chiark / gitweb /
59c1417b44615443d5a360339acc3171c5cd1e56
[elogind.git] / src / shared / util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <syslog.h>
30 #include <sched.h>
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <dirent.h>
37 #include <sys/ioctl.h>
38 #include <linux/vt.h>
39 #include <linux/tiocl.h>
40 #include <termios.h>
41 #include <stdarg.h>
42 #include <sys/inotify.h>
43 #include <sys/poll.h>
44 #include <libgen.h>
45 #include <ctype.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
48 #include <pwd.h>
49 #include <netinet/ip.h>
50 #include <linux/kd.h>
51 #include <dlfcn.h>
52 #include <sys/wait.h>
53 #include <sys/time.h>
54 #include <glob.h>
55 #include <grp.h>
56 #include <sys/mman.h>
57 #include <sys/vfs.h>
58 #include <linux/magic.h>
59
60 #include "macro.h"
61 #include "util.h"
62 #include "ioprio.h"
63 #include "missing.h"
64 #include "log.h"
65 #include "strv.h"
66 #include "label.h"
67 #include "path-util.h"
68 #include "exit-status.h"
69 #include "hashmap.h"
70
71 int saved_argc = 0;
72 char **saved_argv = NULL;
73
74 size_t page_size(void) {
75         static __thread size_t pgsz = 0;
76         long r;
77
78         if (_likely_(pgsz > 0))
79                 return pgsz;
80
81         r = sysconf(_SC_PAGESIZE);
82         assert(r > 0);
83
84         pgsz = (size_t) r;
85         return pgsz;
86 }
87
88 bool streq_ptr(const char *a, const char *b) {
89
90         /* Like streq(), but tries to make sense of NULL pointers */
91
92         if (a && b)
93                 return streq(a, b);
94
95         if (!a && !b)
96                 return true;
97
98         return false;
99 }
100
101 usec_t now(clockid_t clock_id) {
102         struct timespec ts;
103
104         assert_se(clock_gettime(clock_id, &ts) == 0);
105
106         return timespec_load(&ts);
107 }
108
109 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
110         assert(ts);
111
112         ts->realtime = now(CLOCK_REALTIME);
113         ts->monotonic = now(CLOCK_MONOTONIC);
114
115         return ts;
116 }
117
118 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
119         int64_t delta;
120         assert(ts);
121
122         ts->realtime = u;
123
124         if (u == 0)
125                 ts->monotonic = 0;
126         else {
127                 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
128
129                 ts->monotonic = now(CLOCK_MONOTONIC);
130
131                 if ((int64_t) ts->monotonic > delta)
132                         ts->monotonic -= delta;
133                 else
134                         ts->monotonic = 0;
135         }
136
137         return ts;
138 }
139
140 usec_t timespec_load(const struct timespec *ts) {
141         assert(ts);
142
143         return
144                 (usec_t) ts->tv_sec * USEC_PER_SEC +
145                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
146 }
147
148 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
149         assert(ts);
150
151         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
152         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
153
154         return ts;
155 }
156
157 usec_t timeval_load(const struct timeval *tv) {
158         assert(tv);
159
160         return
161                 (usec_t) tv->tv_sec * USEC_PER_SEC +
162                 (usec_t) tv->tv_usec;
163 }
164
165 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
166         assert(tv);
167
168         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
169         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
170
171         return tv;
172 }
173
174 bool endswith(const char *s, const char *postfix) {
175         size_t sl, pl;
176
177         assert(s);
178         assert(postfix);
179
180         sl = strlen(s);
181         pl = strlen(postfix);
182
183         if (pl == 0)
184                 return true;
185
186         if (sl < pl)
187                 return false;
188
189         return memcmp(s + sl - pl, postfix, pl) == 0;
190 }
191
192 bool startswith(const char *s, const char *prefix) {
193         size_t sl, pl;
194
195         assert(s);
196         assert(prefix);
197
198         sl = strlen(s);
199         pl = strlen(prefix);
200
201         if (pl == 0)
202                 return true;
203
204         if (sl < pl)
205                 return false;
206
207         return memcmp(s, prefix, pl) == 0;
208 }
209
210 bool startswith_no_case(const char *s, const char *prefix) {
211         size_t sl, pl;
212         unsigned i;
213
214         assert(s);
215         assert(prefix);
216
217         sl = strlen(s);
218         pl = strlen(prefix);
219
220         if (pl == 0)
221                 return true;
222
223         if (sl < pl)
224                 return false;
225
226         for(i = 0; i < pl; ++i)
227                 if (tolower(s[i]) != tolower(prefix[i]))
228                         return false;
229
230         return true;
231 }
232
233 bool first_word(const char *s, const char *word) {
234         size_t sl, wl;
235
236         assert(s);
237         assert(word);
238
239         sl = strlen(s);
240         wl = strlen(word);
241
242         if (sl < wl)
243                 return false;
244
245         if (wl == 0)
246                 return true;
247
248         if (memcmp(s, word, wl) != 0)
249                 return false;
250
251         return s[wl] == 0 ||
252                 strchr(WHITESPACE, s[wl]);
253 }
254
255 int close_nointr(int fd) {
256         assert(fd >= 0);
257
258         for (;;) {
259                 int r;
260
261                 r = close(fd);
262                 if (r >= 0)
263                         return r;
264
265                 if (errno != EINTR)
266                         return -errno;
267         }
268 }
269
270 void close_nointr_nofail(int fd) {
271         int saved_errno = errno;
272
273         /* like close_nointr() but cannot fail, and guarantees errno
274          * is unchanged */
275
276         assert_se(close_nointr(fd) == 0);
277
278         errno = saved_errno;
279 }
280
281 void close_many(const int fds[], unsigned n_fd) {
282         unsigned i;
283
284         for (i = 0; i < n_fd; i++)
285                 close_nointr_nofail(fds[i]);
286 }
287
288 int parse_boolean(const char *v) {
289         assert(v);
290
291         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
292                 return 1;
293         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
294                 return 0;
295
296         return -EINVAL;
297 }
298
299 int parse_pid(const char *s, pid_t* ret_pid) {
300         unsigned long ul = 0;
301         pid_t pid;
302         int r;
303
304         assert(s);
305         assert(ret_pid);
306
307         r = safe_atolu(s, &ul);
308         if (r < 0)
309                 return r;
310
311         pid = (pid_t) ul;
312
313         if ((unsigned long) pid != ul)
314                 return -ERANGE;
315
316         if (pid <= 0)
317                 return -ERANGE;
318
319         *ret_pid = pid;
320         return 0;
321 }
322
323 int parse_uid(const char *s, uid_t* ret_uid) {
324         unsigned long ul = 0;
325         uid_t uid;
326         int r;
327
328         assert(s);
329         assert(ret_uid);
330
331         r = safe_atolu(s, &ul);
332         if (r < 0)
333                 return r;
334
335         uid = (uid_t) ul;
336
337         if ((unsigned long) uid != ul)
338                 return -ERANGE;
339
340         *ret_uid = uid;
341         return 0;
342 }
343
344 int safe_atou(const char *s, unsigned *ret_u) {
345         char *x = NULL;
346         unsigned long l;
347
348         assert(s);
349         assert(ret_u);
350
351         errno = 0;
352         l = strtoul(s, &x, 0);
353
354         if (!x || *x || errno)
355                 return errno ? -errno : -EINVAL;
356
357         if ((unsigned long) (unsigned) l != l)
358                 return -ERANGE;
359
360         *ret_u = (unsigned) l;
361         return 0;
362 }
363
364 int safe_atoi(const char *s, int *ret_i) {
365         char *x = NULL;
366         long l;
367
368         assert(s);
369         assert(ret_i);
370
371         errno = 0;
372         l = strtol(s, &x, 0);
373
374         if (!x || *x || errno)
375                 return errno ? -errno : -EINVAL;
376
377         if ((long) (int) l != l)
378                 return -ERANGE;
379
380         *ret_i = (int) l;
381         return 0;
382 }
383
384 int safe_atollu(const char *s, long long unsigned *ret_llu) {
385         char *x = NULL;
386         unsigned long long l;
387
388         assert(s);
389         assert(ret_llu);
390
391         errno = 0;
392         l = strtoull(s, &x, 0);
393
394         if (!x || *x || errno)
395                 return errno ? -errno : -EINVAL;
396
397         *ret_llu = l;
398         return 0;
399 }
400
401 int safe_atolli(const char *s, long long int *ret_lli) {
402         char *x = NULL;
403         long long l;
404
405         assert(s);
406         assert(ret_lli);
407
408         errno = 0;
409         l = strtoll(s, &x, 0);
410
411         if (!x || *x || errno)
412                 return errno ? -errno : -EINVAL;
413
414         *ret_lli = l;
415         return 0;
416 }
417
418 /* Split a string into words. */
419 char *split(const char *c, size_t *l, const char *separator, char **state) {
420         char *current;
421
422         current = *state ? *state : (char*) c;
423
424         if (!*current || *c == 0)
425                 return NULL;
426
427         current += strspn(current, separator);
428         *l = strcspn(current, separator);
429         *state = current+*l;
430
431         return (char*) current;
432 }
433
434 /* Split a string into words, but consider strings enclosed in '' and
435  * "" as words even if they include spaces. */
436 char *split_quoted(const char *c, size_t *l, char **state) {
437         char *current, *e;
438         bool escaped = false;
439
440         current = *state ? *state : (char*) c;
441
442         if (!*current || *c == 0)
443                 return NULL;
444
445         current += strspn(current, WHITESPACE);
446
447         if (*current == '\'') {
448                 current ++;
449
450                 for (e = current; *e; e++) {
451                         if (escaped)
452                                 escaped = false;
453                         else if (*e == '\\')
454                                 escaped = true;
455                         else if (*e == '\'')
456                                 break;
457                 }
458
459                 *l = e-current;
460                 *state = *e == 0 ? e : e+1;
461         } else if (*current == '\"') {
462                 current ++;
463
464                 for (e = current; *e; e++) {
465                         if (escaped)
466                                 escaped = false;
467                         else if (*e == '\\')
468                                 escaped = true;
469                         else if (*e == '\"')
470                                 break;
471                 }
472
473                 *l = e-current;
474                 *state = *e == 0 ? e : e+1;
475         } else {
476                 for (e = current; *e; e++) {
477                         if (escaped)
478                                 escaped = false;
479                         else if (*e == '\\')
480                                 escaped = true;
481                         else if (strchr(WHITESPACE, *e))
482                                 break;
483                 }
484                 *l = e-current;
485                 *state = e;
486         }
487
488         return (char*) current;
489 }
490
491 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
492         int r;
493         _cleanup_fclose_ FILE *f = NULL;
494         char fn[PATH_MAX], line[LINE_MAX], *p;
495         long unsigned ppid;
496
497         assert(pid > 0);
498         assert(_ppid);
499
500         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
501         char_array_0(fn);
502
503         f = fopen(fn, "re");
504         if (!f)
505                 return -errno;
506
507         if (!fgets(line, sizeof(line), f)) {
508                 r = feof(f) ? -EIO : -errno;
509                 fclose(f);
510                 return r;
511         }
512
513         /* Let's skip the pid and comm fields. The latter is enclosed
514          * in () but does not escape any () in its value, so let's
515          * skip over it manually */
516
517         p = strrchr(line, ')');
518         if (!p)
519                 return -EIO;
520
521         p++;
522
523         if (sscanf(p, " "
524                    "%*c "  /* state */
525                    "%lu ", /* ppid */
526                    &ppid) != 1)
527                 return -EIO;
528
529         if ((long unsigned) (pid_t) ppid != ppid)
530                 return -ERANGE;
531
532         *_ppid = (pid_t) ppid;
533
534         return 0;
535 }
536
537 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
538         _cleanup_fclose_ FILE *f = NULL;
539         char fn[PATH_MAX], line[LINE_MAX], *p;
540
541         assert(pid > 0);
542         assert(st);
543
544         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
545         char_array_0(fn);
546
547         f = fopen(fn, "re");
548         if (!f)
549                 return -errno;
550
551         if (!fgets(line, sizeof(line), f)) {
552                 if (ferror(f))
553                         return -errno;
554
555                 return -EIO;
556         }
557
558         /* Let's skip the pid and comm fields. The latter is enclosed
559          * in () but does not escape any () in its value, so let's
560          * skip over it manually */
561
562         p = strrchr(line, ')');
563         if (!p)
564                 return -EIO;
565
566         p++;
567
568         if (sscanf(p, " "
569                    "%*c "  /* state */
570                    "%*d "  /* ppid */
571                    "%*d "  /* pgrp */
572                    "%*d "  /* session */
573                    "%*d "  /* tty_nr */
574                    "%*d "  /* tpgid */
575                    "%*u "  /* flags */
576                    "%*u "  /* minflt */
577                    "%*u "  /* cminflt */
578                    "%*u "  /* majflt */
579                    "%*u "  /* cmajflt */
580                    "%*u "  /* utime */
581                    "%*u "  /* stime */
582                    "%*d "  /* cutime */
583                    "%*d "  /* cstime */
584                    "%*d "  /* priority */
585                    "%*d "  /* nice */
586                    "%*d "  /* num_threads */
587                    "%*d "  /* itrealvalue */
588                    "%llu "  /* starttime */,
589                    st) != 1)
590                 return -EIO;
591
592         return 0;
593 }
594
595 int write_one_line_file(const char *fn, const char *line) {
596         _cleanup_fclose_ FILE *f = NULL;
597
598         assert(fn);
599         assert(line);
600
601         f = fopen(fn, "we");
602         if (!f)
603                 return -errno;
604
605         errno = 0;
606         if (fputs(line, f) < 0)
607                 return errno ? -errno : -EIO;
608
609         if (!endswith(line, "\n"))
610                 fputc('\n', f);
611
612         fflush(f);
613
614         if (ferror(f))
615                 return errno ? -errno : -EIO;
616
617         return 0;
618 }
619
620 int fchmod_umask(int fd, mode_t m) {
621         mode_t u;
622         int r;
623
624         u = umask(0777);
625         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
626         umask(u);
627
628         return r;
629 }
630
631 int write_one_line_file_atomic(const char *fn, const char *line) {
632         FILE *f;
633         int r;
634         char *p;
635
636         assert(fn);
637         assert(line);
638
639         r = fopen_temporary(fn, &f, &p);
640         if (r < 0)
641                 return r;
642
643         fchmod_umask(fileno(f), 0644);
644
645         errno = 0;
646         if (fputs(line, f) < 0) {
647                 r = -errno;
648                 goto finish;
649         }
650
651         if (!endswith(line, "\n"))
652                 fputc('\n', f);
653
654         fflush(f);
655
656         if (ferror(f)) {
657                 if (errno != 0)
658                         r = -errno;
659                 else
660                         r = -EIO;
661         } else {
662                 if (rename(p, fn) < 0)
663                         r = -errno;
664                 else
665                         r = 0;
666         }
667
668 finish:
669         if (r < 0)
670                 unlink(p);
671
672         fclose(f);
673         free(p);
674
675         return r;
676 }
677
678 int read_one_line_file(const char *fn, char **line) {
679         _cleanup_fclose_ FILE *f = NULL;
680         char t[LINE_MAX], *c;
681
682         assert(fn);
683         assert(line);
684
685         f = fopen(fn, "re");
686         if (!f)
687                 return -errno;
688
689         if (!fgets(t, sizeof(t), f)) {
690
691                 if (ferror(f))
692                         return errno ? -errno : -EIO;
693
694                 t[0] = 0;
695         }
696
697         c = strdup(t);
698         if (!c)
699                 return -ENOMEM;
700         truncate_nl(c);
701
702         *line = c;
703         return 0;
704 }
705
706 int read_full_file(const char *fn, char **contents, size_t *size) {
707         _cleanup_fclose_ FILE *f = NULL;
708         size_t n, l;
709         _cleanup_free_ char *buf = NULL;
710         struct stat st;
711
712         f = fopen(fn, "re");
713         if (!f)
714                 return -errno;
715
716         if (fstat(fileno(f), &st) < 0)
717                 return -errno;
718
719         /* Safety check */
720         if (st.st_size > 4*1024*1024)
721                 return -E2BIG;
722
723         n = st.st_size > 0 ? st.st_size : LINE_MAX;
724         l = 0;
725
726         for (;;) {
727                 char *t;
728                 size_t k;
729
730                 t = realloc(buf, n+1);
731                 if (!t)
732                         return -ENOMEM;
733
734                 buf = t;
735                 k = fread(buf + l, 1, n - l, f);
736
737                 if (k <= 0) {
738                         if (ferror(f))
739                                 return -errno;
740
741                         break;
742                 }
743
744                 l += k;
745                 n *= 2;
746
747                 /* Safety check */
748                 if (n > 4*1024*1024)
749                         return -E2BIG;
750         }
751
752         buf[l] = 0;
753         *contents = buf;
754         buf = NULL;
755
756         if (size)
757                 *size = l;
758
759         return 0;
760 }
761
762 int parse_env_file(
763                 const char *fname,
764                 const char *separator, ...) {
765
766         int r = 0;
767         char *contents = NULL, *p;
768
769         assert(fname);
770         assert(separator);
771
772         if ((r = read_full_file(fname, &contents, NULL)) < 0)
773                 return r;
774
775         p = contents;
776         for (;;) {
777                 const char *key = NULL;
778
779                 p += strspn(p, separator);
780                 p += strspn(p, WHITESPACE);
781
782                 if (!*p)
783                         break;
784
785                 if (!strchr(COMMENTS, *p)) {
786                         va_list ap;
787                         char **value;
788
789                         va_start(ap, separator);
790                         while ((key = va_arg(ap, char *))) {
791                                 size_t n;
792                                 char *v;
793
794                                 value = va_arg(ap, char **);
795
796                                 n = strlen(key);
797                                 if (strncmp(p, key, n) != 0 ||
798                                     p[n] != '=')
799                                         continue;
800
801                                 p += n + 1;
802                                 n = strcspn(p, separator);
803
804                                 if (n >= 2 &&
805                                     strchr(QUOTES, p[0]) &&
806                                     p[n-1] == p[0])
807                                         v = strndup(p+1, n-2);
808                                 else
809                                         v = strndup(p, n);
810
811                                 if (!v) {
812                                         r = -ENOMEM;
813                                         va_end(ap);
814                                         goto fail;
815                                 }
816
817                                 if (v[0] == '\0') {
818                                         /* return empty value strings as NULL */
819                                         free(v);
820                                         v = NULL;
821                                 }
822
823                                 free(*value);
824                                 *value = v;
825
826                                 p += n;
827
828                                 r ++;
829                                 break;
830                         }
831                         va_end(ap);
832                 }
833
834                 if (!key)
835                         p += strcspn(p, separator);
836         }
837
838 fail:
839         free(contents);
840         return r;
841 }
842
843 int load_env_file(
844                 const char *fname,
845                 char ***rl) {
846
847         FILE *f;
848         char **m = NULL;
849         int r;
850
851         assert(fname);
852         assert(rl);
853
854         if (!(f = fopen(fname, "re")))
855                 return -errno;
856
857         while (!feof(f)) {
858                 char l[LINE_MAX], *p, *u;
859                 char **t;
860
861                 if (!fgets(l, sizeof(l), f)) {
862                         if (feof(f))
863                                 break;
864
865                         r = -errno;
866                         goto finish;
867                 }
868
869                 p = strstrip(l);
870
871                 if (!*p)
872                         continue;
873
874                 if (strchr(COMMENTS, *p))
875                         continue;
876
877                 if (!(u = normalize_env_assignment(p))) {
878                         r = log_oom();
879                         goto finish;
880                 }
881
882                 t = strv_append(m, u);
883                 free(u);
884
885                 if (!t) {
886                         r = log_oom();
887                         goto finish;
888                 }
889
890                 strv_free(m);
891                 m = t;
892         }
893
894         r = 0;
895
896         *rl = m;
897         m = NULL;
898
899 finish:
900         if (f)
901                 fclose(f);
902
903         strv_free(m);
904
905         return r;
906 }
907
908 int write_env_file(const char *fname, char **l) {
909         char **i, *p;
910         FILE *f;
911         int r;
912
913         r = fopen_temporary(fname, &f, &p);
914         if (r < 0)
915                 return r;
916
917         fchmod_umask(fileno(f), 0644);
918
919         errno = 0;
920         STRV_FOREACH(i, l) {
921                 fputs(*i, f);
922                 fputc('\n', f);
923         }
924
925         fflush(f);
926
927         if (ferror(f)) {
928                 if (errno != 0)
929                         r = -errno;
930                 else
931                         r = -EIO;
932         } else {
933                 if (rename(p, fname) < 0)
934                         r = -errno;
935                 else
936                         r = 0;
937         }
938
939         if (r < 0)
940                 unlink(p);
941
942         fclose(f);
943         free(p);
944
945         return r;
946 }
947
948 char *truncate_nl(char *s) {
949         assert(s);
950
951         s[strcspn(s, NEWLINE)] = 0;
952         return s;
953 }
954
955 int get_process_comm(pid_t pid, char **name) {
956         int r;
957
958         assert(name);
959
960         if (pid == 0)
961                 r = read_one_line_file("/proc/self/comm", name);
962         else {
963                 char *p;
964                 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
965                         return -ENOMEM;
966
967                 r = read_one_line_file(p, name);
968                 free(p);
969         }
970
971         return r;
972 }
973
974 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
975         char *r, *k;
976         int c;
977         bool space = false;
978         size_t left;
979         FILE *f;
980
981         assert(max_length > 0);
982         assert(line);
983
984         if (pid == 0)
985                 f = fopen("/proc/self/cmdline", "re");
986         else {
987                 char *p;
988                 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
989                         return -ENOMEM;
990
991                 f = fopen(p, "re");
992                 free(p);
993         }
994
995         if (!f)
996                 return -errno;
997
998         r = new(char, max_length);
999         if (!r) {
1000                 fclose(f);
1001                 return -ENOMEM;
1002         }
1003
1004         k = r;
1005         left = max_length;
1006         while ((c = getc(f)) != EOF) {
1007
1008                 if (isprint(c)) {
1009                         if (space) {
1010                                 if (left <= 4)
1011                                         break;
1012
1013                                 *(k++) = ' ';
1014                                 left--;
1015                                 space = false;
1016                         }
1017
1018                         if (left <= 4)
1019                                 break;
1020
1021                         *(k++) = (char) c;
1022                         left--;
1023                 }  else
1024                         space = true;
1025         }
1026
1027         if (left <= 4) {
1028                 size_t n = MIN(left-1, 3U);
1029                 memcpy(k, "...", n);
1030                 k[n] = 0;
1031         } else
1032                 *k = 0;
1033
1034         fclose(f);
1035
1036         /* Kernel threads have no argv[] */
1037         if (r[0] == 0) {
1038                 char *t;
1039                 int h;
1040
1041                 free(r);
1042
1043                 if (!comm_fallback)
1044                         return -ENOENT;
1045
1046                 h = get_process_comm(pid, &t);
1047                 if (h < 0)
1048                         return h;
1049
1050                 r = strjoin("[", t, "]", NULL);
1051                 free(t);
1052
1053                 if (!r)
1054                         return -ENOMEM;
1055         }
1056
1057         *line = r;
1058         return 0;
1059 }
1060
1061 int is_kernel_thread(pid_t pid) {
1062         char *p;
1063         size_t count;
1064         char c;
1065         bool eof;
1066         FILE *f;
1067
1068         if (pid == 0)
1069                 return 0;
1070
1071         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1072                 return -ENOMEM;
1073
1074         f = fopen(p, "re");
1075         free(p);
1076
1077         if (!f)
1078                 return -errno;
1079
1080         count = fread(&c, 1, 1, f);
1081         eof = feof(f);
1082         fclose(f);
1083
1084         /* Kernel threads have an empty cmdline */
1085
1086         if (count <= 0)
1087                 return eof ? 1 : -errno;
1088
1089         return 0;
1090 }
1091
1092 int get_process_exe(pid_t pid, char **name) {
1093         int r;
1094
1095         assert(name);
1096
1097         if (pid == 0)
1098                 r = readlink_malloc("/proc/self/exe", name);
1099         else {
1100                 char *p;
1101                 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1102                         return -ENOMEM;
1103
1104                 r = readlink_malloc(p, name);
1105                 free(p);
1106         }
1107
1108         return r;
1109 }
1110
1111 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1112         char *p;
1113         FILE *f;
1114         int r;
1115
1116         assert(uid);
1117
1118         if (pid == 0)
1119                 return getuid();
1120
1121         if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1122                 return -ENOMEM;
1123
1124         f = fopen(p, "re");
1125         free(p);
1126
1127         if (!f)
1128                 return -errno;
1129
1130         while (!feof(f)) {
1131                 char line[LINE_MAX], *l;
1132
1133                 if (!fgets(line, sizeof(line), f)) {
1134                         if (feof(f))
1135                                 break;
1136
1137                         r = -errno;
1138                         goto finish;
1139                 }
1140
1141                 l = strstrip(line);
1142
1143                 if (startswith(l, field)) {
1144                         l += strlen(field);
1145                         l += strspn(l, WHITESPACE);
1146
1147                         l[strcspn(l, WHITESPACE)] = 0;
1148
1149                         r = parse_uid(l, uid);
1150                         goto finish;
1151                 }
1152         }
1153
1154         r = -EIO;
1155
1156 finish:
1157         fclose(f);
1158
1159         return r;
1160 }
1161
1162 int get_process_uid(pid_t pid, uid_t *uid) {
1163         return get_process_id(pid, "Uid:", uid);
1164 }
1165
1166 int get_process_gid(pid_t pid, gid_t *gid) {
1167         return get_process_id(pid, "Gid:", gid);
1168 }
1169
1170 char *strnappend(const char *s, const char *suffix, size_t b) {
1171         size_t a;
1172         char *r;
1173
1174         if (!s && !suffix)
1175                 return strdup("");
1176
1177         if (!s)
1178                 return strndup(suffix, b);
1179
1180         if (!suffix)
1181                 return strdup(s);
1182
1183         assert(s);
1184         assert(suffix);
1185
1186         a = strlen(s);
1187
1188         if (!(r = new(char, a+b+1)))
1189                 return NULL;
1190
1191         memcpy(r, s, a);
1192         memcpy(r+a, suffix, b);
1193         r[a+b] = 0;
1194
1195         return r;
1196 }
1197
1198 char *strappend(const char *s, const char *suffix) {
1199         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1200 }
1201
1202 int readlink_malloc(const char *p, char **r) {
1203         size_t l = 100;
1204
1205         assert(p);
1206         assert(r);
1207
1208         for (;;) {
1209                 char *c;
1210                 ssize_t n;
1211
1212                 if (!(c = new(char, l)))
1213                         return -ENOMEM;
1214
1215                 if ((n = readlink(p, c, l-1)) < 0) {
1216                         int ret = -errno;
1217                         free(c);
1218                         return ret;
1219                 }
1220
1221                 if ((size_t) n < l-1) {
1222                         c[n] = 0;
1223                         *r = c;
1224                         return 0;
1225                 }
1226
1227                 free(c);
1228                 l *= 2;
1229         }
1230 }
1231
1232 int readlink_and_make_absolute(const char *p, char **r) {
1233         char *target, *k;
1234         int j;
1235
1236         assert(p);
1237         assert(r);
1238
1239         if ((j = readlink_malloc(p, &target)) < 0)
1240                 return j;
1241
1242         k = file_in_same_dir(p, target);
1243         free(target);
1244
1245         if (!k)
1246                 return -ENOMEM;
1247
1248         *r = k;
1249         return 0;
1250 }
1251
1252 int readlink_and_canonicalize(const char *p, char **r) {
1253         char *t, *s;
1254         int j;
1255
1256         assert(p);
1257         assert(r);
1258
1259         j = readlink_and_make_absolute(p, &t);
1260         if (j < 0)
1261                 return j;
1262
1263         s = canonicalize_file_name(t);
1264         if (s) {
1265                 free(t);
1266                 *r = s;
1267         } else
1268                 *r = t;
1269
1270         path_kill_slashes(*r);
1271
1272         return 0;
1273 }
1274
1275 int reset_all_signal_handlers(void) {
1276         int sig;
1277
1278         for (sig = 1; sig < _NSIG; sig++) {
1279                 struct sigaction sa;
1280
1281                 if (sig == SIGKILL || sig == SIGSTOP)
1282                         continue;
1283
1284                 zero(sa);
1285                 sa.sa_handler = SIG_DFL;
1286                 sa.sa_flags = SA_RESTART;
1287
1288                 /* On Linux the first two RT signals are reserved by
1289                  * glibc, and sigaction() will return EINVAL for them. */
1290                 if ((sigaction(sig, &sa, NULL) < 0))
1291                         if (errno != EINVAL)
1292                                 return -errno;
1293         }
1294
1295         return 0;
1296 }
1297
1298 char *strstrip(char *s) {
1299         char *e;
1300
1301         /* Drops trailing whitespace. Modifies the string in
1302          * place. Returns pointer to first non-space character */
1303
1304         s += strspn(s, WHITESPACE);
1305
1306         for (e = strchr(s, 0); e > s; e --)
1307                 if (!strchr(WHITESPACE, e[-1]))
1308                         break;
1309
1310         *e = 0;
1311
1312         return s;
1313 }
1314
1315 char *delete_chars(char *s, const char *bad) {
1316         char *f, *t;
1317
1318         /* Drops all whitespace, regardless where in the string */
1319
1320         for (f = s, t = s; *f; f++) {
1321                 if (strchr(bad, *f))
1322                         continue;
1323
1324                 *(t++) = *f;
1325         }
1326
1327         *t = 0;
1328
1329         return s;
1330 }
1331
1332 bool in_charset(const char *s, const char* charset) {
1333         const char *i;
1334
1335         assert(s);
1336         assert(charset);
1337
1338         for (i = s; *i; i++)
1339                 if (!strchr(charset, *i))
1340                         return false;
1341
1342         return true;
1343 }
1344
1345 char *file_in_same_dir(const char *path, const char *filename) {
1346         char *e, *r;
1347         size_t k;
1348
1349         assert(path);
1350         assert(filename);
1351
1352         /* This removes the last component of path and appends
1353          * filename, unless the latter is absolute anyway or the
1354          * former isn't */
1355
1356         if (path_is_absolute(filename))
1357                 return strdup(filename);
1358
1359         if (!(e = strrchr(path, '/')))
1360                 return strdup(filename);
1361
1362         k = strlen(filename);
1363         if (!(r = new(char, e-path+1+k+1)))
1364                 return NULL;
1365
1366         memcpy(r, path, e-path+1);
1367         memcpy(r+(e-path)+1, filename, k+1);
1368
1369         return r;
1370 }
1371
1372 int rmdir_parents(const char *path, const char *stop) {
1373         size_t l;
1374         int r = 0;
1375
1376         assert(path);
1377         assert(stop);
1378
1379         l = strlen(path);
1380
1381         /* Skip trailing slashes */
1382         while (l > 0 && path[l-1] == '/')
1383                 l--;
1384
1385         while (l > 0) {
1386                 char *t;
1387
1388                 /* Skip last component */
1389                 while (l > 0 && path[l-1] != '/')
1390                         l--;
1391
1392                 /* Skip trailing slashes */
1393                 while (l > 0 && path[l-1] == '/')
1394                         l--;
1395
1396                 if (l <= 0)
1397                         break;
1398
1399                 if (!(t = strndup(path, l)))
1400                         return -ENOMEM;
1401
1402                 if (path_startswith(stop, t)) {
1403                         free(t);
1404                         return 0;
1405                 }
1406
1407                 r = rmdir(t);
1408                 free(t);
1409
1410                 if (r < 0)
1411                         if (errno != ENOENT)
1412                                 return -errno;
1413         }
1414
1415         return 0;
1416 }
1417
1418
1419 char hexchar(int x) {
1420         static const char table[16] = "0123456789abcdef";
1421
1422         return table[x & 15];
1423 }
1424
1425 int unhexchar(char c) {
1426
1427         if (c >= '0' && c <= '9')
1428                 return c - '0';
1429
1430         if (c >= 'a' && c <= 'f')
1431                 return c - 'a' + 10;
1432
1433         if (c >= 'A' && c <= 'F')
1434                 return c - 'A' + 10;
1435
1436         return -1;
1437 }
1438
1439 char octchar(int x) {
1440         return '0' + (x & 7);
1441 }
1442
1443 int unoctchar(char c) {
1444
1445         if (c >= '0' && c <= '7')
1446                 return c - '0';
1447
1448         return -1;
1449 }
1450
1451 char decchar(int x) {
1452         return '0' + (x % 10);
1453 }
1454
1455 int undecchar(char c) {
1456
1457         if (c >= '0' && c <= '9')
1458                 return c - '0';
1459
1460         return -1;
1461 }
1462
1463 char *cescape(const char *s) {
1464         char *r, *t;
1465         const char *f;
1466
1467         assert(s);
1468
1469         /* Does C style string escaping. */
1470
1471         r = new(char, strlen(s)*4 + 1);
1472         if (!r)
1473                 return NULL;
1474
1475         for (f = s, t = r; *f; f++)
1476
1477                 switch (*f) {
1478
1479                 case '\a':
1480                         *(t++) = '\\';
1481                         *(t++) = 'a';
1482                         break;
1483                 case '\b':
1484                         *(t++) = '\\';
1485                         *(t++) = 'b';
1486                         break;
1487                 case '\f':
1488                         *(t++) = '\\';
1489                         *(t++) = 'f';
1490                         break;
1491                 case '\n':
1492                         *(t++) = '\\';
1493                         *(t++) = 'n';
1494                         break;
1495                 case '\r':
1496                         *(t++) = '\\';
1497                         *(t++) = 'r';
1498                         break;
1499                 case '\t':
1500                         *(t++) = '\\';
1501                         *(t++) = 't';
1502                         break;
1503                 case '\v':
1504                         *(t++) = '\\';
1505                         *(t++) = 'v';
1506                         break;
1507                 case '\\':
1508                         *(t++) = '\\';
1509                         *(t++) = '\\';
1510                         break;
1511                 case '"':
1512                         *(t++) = '\\';
1513                         *(t++) = '"';
1514                         break;
1515                 case '\'':
1516                         *(t++) = '\\';
1517                         *(t++) = '\'';
1518                         break;
1519
1520                 default:
1521                         /* For special chars we prefer octal over
1522                          * hexadecimal encoding, simply because glib's
1523                          * g_strescape() does the same */
1524                         if ((*f < ' ') || (*f >= 127)) {
1525                                 *(t++) = '\\';
1526                                 *(t++) = octchar((unsigned char) *f >> 6);
1527                                 *(t++) = octchar((unsigned char) *f >> 3);
1528                                 *(t++) = octchar((unsigned char) *f);
1529                         } else
1530                                 *(t++) = *f;
1531                         break;
1532                 }
1533
1534         *t = 0;
1535
1536         return r;
1537 }
1538
1539 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1540         char *r, *t;
1541         const char *f;
1542         size_t pl;
1543
1544         assert(s);
1545
1546         /* Undoes C style string escaping, and optionally prefixes it. */
1547
1548         pl = prefix ? strlen(prefix) : 0;
1549
1550         r = new(char, pl+length+1);
1551         if (!r)
1552                 return r;
1553
1554         if (prefix)
1555                 memcpy(r, prefix, pl);
1556
1557         for (f = s, t = r + pl; f < s + length; f++) {
1558
1559                 if (*f != '\\') {
1560                         *(t++) = *f;
1561                         continue;
1562                 }
1563
1564                 f++;
1565
1566                 switch (*f) {
1567
1568                 case 'a':
1569                         *(t++) = '\a';
1570                         break;
1571                 case 'b':
1572                         *(t++) = '\b';
1573                         break;
1574                 case 'f':
1575                         *(t++) = '\f';
1576                         break;
1577                 case 'n':
1578                         *(t++) = '\n';
1579                         break;
1580                 case 'r':
1581                         *(t++) = '\r';
1582                         break;
1583                 case 't':
1584                         *(t++) = '\t';
1585                         break;
1586                 case 'v':
1587                         *(t++) = '\v';
1588                         break;
1589                 case '\\':
1590                         *(t++) = '\\';
1591                         break;
1592                 case '"':
1593                         *(t++) = '"';
1594                         break;
1595                 case '\'':
1596                         *(t++) = '\'';
1597                         break;
1598
1599                 case 's':
1600                         /* This is an extension of the XDG syntax files */
1601                         *(t++) = ' ';
1602                         break;
1603
1604                 case 'x': {
1605                         /* hexadecimal encoding */
1606                         int a, b;
1607
1608                         a = unhexchar(f[1]);
1609                         b = unhexchar(f[2]);
1610
1611                         if (a < 0 || b < 0) {
1612                                 /* Invalid escape code, let's take it literal then */
1613                                 *(t++) = '\\';
1614                                 *(t++) = 'x';
1615                         } else {
1616                                 *(t++) = (char) ((a << 4) | b);
1617                                 f += 2;
1618                         }
1619
1620                         break;
1621                 }
1622
1623                 case '0':
1624                 case '1':
1625                 case '2':
1626                 case '3':
1627                 case '4':
1628                 case '5':
1629                 case '6':
1630                 case '7': {
1631                         /* octal encoding */
1632                         int a, b, c;
1633
1634                         a = unoctchar(f[0]);
1635                         b = unoctchar(f[1]);
1636                         c = unoctchar(f[2]);
1637
1638                         if (a < 0 || b < 0 || c < 0) {
1639                                 /* Invalid escape code, let's take it literal then */
1640                                 *(t++) = '\\';
1641                                 *(t++) = f[0];
1642                         } else {
1643                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1644                                 f += 2;
1645                         }
1646
1647                         break;
1648                 }
1649
1650                 case 0:
1651                         /* premature end of string.*/
1652                         *(t++) = '\\';
1653                         goto finish;
1654
1655                 default:
1656                         /* Invalid escape code, let's take it literal then */
1657                         *(t++) = '\\';
1658                         *(t++) = *f;
1659                         break;
1660                 }
1661         }
1662
1663 finish:
1664         *t = 0;
1665         return r;
1666 }
1667
1668 char *cunescape_length(const char *s, size_t length) {
1669         return cunescape_length_with_prefix(s, length, NULL);
1670 }
1671
1672 char *cunescape(const char *s) {
1673         assert(s);
1674
1675         return cunescape_length(s, strlen(s));
1676 }
1677
1678 char *xescape(const char *s, const char *bad) {
1679         char *r, *t;
1680         const char *f;
1681
1682         /* Escapes all chars in bad, in addition to \ and all special
1683          * chars, in \xFF style escaping. May be reversed with
1684          * cunescape. */
1685
1686         if (!(r = new(char, strlen(s)*4+1)))
1687                 return NULL;
1688
1689         for (f = s, t = r; *f; f++) {
1690
1691                 if ((*f < ' ') || (*f >= 127) ||
1692                     (*f == '\\') || strchr(bad, *f)) {
1693                         *(t++) = '\\';
1694                         *(t++) = 'x';
1695                         *(t++) = hexchar(*f >> 4);
1696                         *(t++) = hexchar(*f);
1697                 } else
1698                         *(t++) = *f;
1699         }
1700
1701         *t = 0;
1702
1703         return r;
1704 }
1705
1706 char *bus_path_escape(const char *s) {
1707         char *r, *t;
1708         const char *f;
1709
1710         assert(s);
1711
1712         /* Escapes all chars that D-Bus' object path cannot deal
1713          * with. Can be reverse with bus_path_unescape() */
1714
1715         if (!(r = new(char, strlen(s)*3+1)))
1716                 return NULL;
1717
1718         for (f = s, t = r; *f; f++) {
1719
1720                 if (!(*f >= 'A' && *f <= 'Z') &&
1721                     !(*f >= 'a' && *f <= 'z') &&
1722                     !(*f >= '0' && *f <= '9')) {
1723                         *(t++) = '_';
1724                         *(t++) = hexchar(*f >> 4);
1725                         *(t++) = hexchar(*f);
1726                 } else
1727                         *(t++) = *f;
1728         }
1729
1730         *t = 0;
1731
1732         return r;
1733 }
1734
1735 char *bus_path_unescape(const char *f) {
1736         char *r, *t;
1737
1738         assert(f);
1739
1740         if (!(r = strdup(f)))
1741                 return NULL;
1742
1743         for (t = r; *f; f++) {
1744
1745                 if (*f == '_') {
1746                         int a, b;
1747
1748                         if ((a = unhexchar(f[1])) < 0 ||
1749                             (b = unhexchar(f[2])) < 0) {
1750                                 /* Invalid escape code, let's take it literal then */
1751                                 *(t++) = '_';
1752                         } else {
1753                                 *(t++) = (char) ((a << 4) | b);
1754                                 f += 2;
1755                         }
1756                 } else
1757                         *(t++) = *f;
1758         }
1759
1760         *t = 0;
1761
1762         return r;
1763 }
1764
1765 char *ascii_strlower(char *t) {
1766         char *p;
1767
1768         assert(t);
1769
1770         for (p = t; *p; p++)
1771                 if (*p >= 'A' && *p <= 'Z')
1772                         *p = *p - 'A' + 'a';
1773
1774         return t;
1775 }
1776
1777 static bool ignore_file_allow_backup(const char *filename) {
1778         assert(filename);
1779
1780         return
1781                 filename[0] == '.' ||
1782                 streq(filename, "lost+found") ||
1783                 streq(filename, "aquota.user") ||
1784                 streq(filename, "aquota.group") ||
1785                 endswith(filename, ".rpmnew") ||
1786                 endswith(filename, ".rpmsave") ||
1787                 endswith(filename, ".rpmorig") ||
1788                 endswith(filename, ".dpkg-old") ||
1789                 endswith(filename, ".dpkg-new") ||
1790                 endswith(filename, ".swp");
1791 }
1792
1793 bool ignore_file(const char *filename) {
1794         assert(filename);
1795
1796         if (endswith(filename, "~"))
1797                 return false;
1798
1799         return ignore_file_allow_backup(filename);
1800 }
1801
1802 int fd_nonblock(int fd, bool nonblock) {
1803         int flags;
1804
1805         assert(fd >= 0);
1806
1807         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1808                 return -errno;
1809
1810         if (nonblock)
1811                 flags |= O_NONBLOCK;
1812         else
1813                 flags &= ~O_NONBLOCK;
1814
1815         if (fcntl(fd, F_SETFL, flags) < 0)
1816                 return -errno;
1817
1818         return 0;
1819 }
1820
1821 int fd_cloexec(int fd, bool cloexec) {
1822         int flags;
1823
1824         assert(fd >= 0);
1825
1826         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1827                 return -errno;
1828
1829         if (cloexec)
1830                 flags |= FD_CLOEXEC;
1831         else
1832                 flags &= ~FD_CLOEXEC;
1833
1834         if (fcntl(fd, F_SETFD, flags) < 0)
1835                 return -errno;
1836
1837         return 0;
1838 }
1839
1840 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1841         unsigned i;
1842
1843         assert(n_fdset == 0 || fdset);
1844
1845         for (i = 0; i < n_fdset; i++)
1846                 if (fdset[i] == fd)
1847                         return true;
1848
1849         return false;
1850 }
1851
1852 int close_all_fds(const int except[], unsigned n_except) {
1853         DIR *d;
1854         struct dirent *de;
1855         int r = 0;
1856
1857         assert(n_except == 0 || except);
1858
1859         d = opendir("/proc/self/fd");
1860         if (!d) {
1861                 int fd;
1862                 struct rlimit rl;
1863
1864                 /* When /proc isn't available (for example in chroots)
1865                  * the fallback is brute forcing through the fd
1866                  * table */
1867
1868                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1869                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1870
1871                         if (fd_in_set(fd, except, n_except))
1872                                 continue;
1873
1874                         if (close_nointr(fd) < 0)
1875                                 if (errno != EBADF && r == 0)
1876                                         r = -errno;
1877                 }
1878
1879                 return r;
1880         }
1881
1882         while ((de = readdir(d))) {
1883                 int fd = -1;
1884
1885                 if (ignore_file(de->d_name))
1886                         continue;
1887
1888                 if (safe_atoi(de->d_name, &fd) < 0)
1889                         /* Let's better ignore this, just in case */
1890                         continue;
1891
1892                 if (fd < 3)
1893                         continue;
1894
1895                 if (fd == dirfd(d))
1896                         continue;
1897
1898                 if (fd_in_set(fd, except, n_except))
1899                         continue;
1900
1901                 if (close_nointr(fd) < 0) {
1902                         /* Valgrind has its own FD and doesn't want to have it closed */
1903                         if (errno != EBADF && r == 0)
1904                                 r = -errno;
1905                 }
1906         }
1907
1908         closedir(d);
1909         return r;
1910 }
1911
1912 bool chars_intersect(const char *a, const char *b) {
1913         const char *p;
1914
1915         /* Returns true if any of the chars in a are in b. */
1916         for (p = a; *p; p++)
1917                 if (strchr(b, *p))
1918                         return true;
1919
1920         return false;
1921 }
1922
1923 char *format_timestamp(char *buf, size_t l, usec_t t) {
1924         struct tm tm;
1925         time_t sec;
1926
1927         assert(buf);
1928         assert(l > 0);
1929
1930         if (t <= 0)
1931                 return NULL;
1932
1933         sec = (time_t) (t / USEC_PER_SEC);
1934
1935         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1936                 return NULL;
1937
1938         return buf;
1939 }
1940
1941 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1942         usec_t n, d;
1943
1944         n = now(CLOCK_REALTIME);
1945
1946         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1947                 return NULL;
1948
1949         d = n - t;
1950
1951         if (d >= USEC_PER_YEAR)
1952                 snprintf(buf, l, "%llu years and %llu months ago",
1953                          (unsigned long long) (d / USEC_PER_YEAR),
1954                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1955         else if (d >= USEC_PER_MONTH)
1956                 snprintf(buf, l, "%llu months and %llu days ago",
1957                          (unsigned long long) (d / USEC_PER_MONTH),
1958                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1959         else if (d >= USEC_PER_WEEK)
1960                 snprintf(buf, l, "%llu weeks and %llu days ago",
1961                          (unsigned long long) (d / USEC_PER_WEEK),
1962                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1963         else if (d >= 2*USEC_PER_DAY)
1964                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1965         else if (d >= 25*USEC_PER_HOUR)
1966                 snprintf(buf, l, "1 day and %lluh ago",
1967                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1968         else if (d >= 6*USEC_PER_HOUR)
1969                 snprintf(buf, l, "%lluh ago",
1970                          (unsigned long long) (d / USEC_PER_HOUR));
1971         else if (d >= USEC_PER_HOUR)
1972                 snprintf(buf, l, "%lluh %llumin ago",
1973                          (unsigned long long) (d / USEC_PER_HOUR),
1974                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1975         else if (d >= 5*USEC_PER_MINUTE)
1976                 snprintf(buf, l, "%llumin ago",
1977                          (unsigned long long) (d / USEC_PER_MINUTE));
1978         else if (d >= USEC_PER_MINUTE)
1979                 snprintf(buf, l, "%llumin %llus ago",
1980                          (unsigned long long) (d / USEC_PER_MINUTE),
1981                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1982         else if (d >= USEC_PER_SEC)
1983                 snprintf(buf, l, "%llus ago",
1984                          (unsigned long long) (d / USEC_PER_SEC));
1985         else if (d >= USEC_PER_MSEC)
1986                 snprintf(buf, l, "%llums ago",
1987                          (unsigned long long) (d / USEC_PER_MSEC));
1988         else if (d > 0)
1989                 snprintf(buf, l, "%lluus ago",
1990                          (unsigned long long) d);
1991         else
1992                 snprintf(buf, l, "now");
1993
1994         buf[l-1] = 0;
1995         return buf;
1996 }
1997
1998 char *format_timespan(char *buf, size_t l, usec_t t) {
1999         static const struct {
2000                 const char *suffix;
2001                 usec_t usec;
2002         } table[] = {
2003                 { "w", USEC_PER_WEEK },
2004                 { "d", USEC_PER_DAY },
2005                 { "h", USEC_PER_HOUR },
2006                 { "min", USEC_PER_MINUTE },
2007                 { "s", USEC_PER_SEC },
2008                 { "ms", USEC_PER_MSEC },
2009                 { "us", 1 },
2010         };
2011
2012         unsigned i;
2013         char *p = buf;
2014
2015         assert(buf);
2016         assert(l > 0);
2017
2018         if (t == (usec_t) -1)
2019                 return NULL;
2020
2021         if (t == 0) {
2022                 snprintf(p, l, "0");
2023                 p[l-1] = 0;
2024                 return p;
2025         }
2026
2027         /* The result of this function can be parsed with parse_usec */
2028
2029         for (i = 0; i < ELEMENTSOF(table); i++) {
2030                 int k;
2031                 size_t n;
2032
2033                 if (t < table[i].usec)
2034                         continue;
2035
2036                 if (l <= 1)
2037                         break;
2038
2039                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2040                 n = MIN((size_t) k, l);
2041
2042                 l -= n;
2043                 p += n;
2044
2045                 t %= table[i].usec;
2046         }
2047
2048         *p = 0;
2049
2050         return buf;
2051 }
2052
2053 bool fstype_is_network(const char *fstype) {
2054         static const char table[] =
2055                 "cifs\0"
2056                 "smbfs\0"
2057                 "ncpfs\0"
2058                 "nfs\0"
2059                 "nfs4\0"
2060                 "gfs\0"
2061                 "gfs2\0";
2062
2063         return nulstr_contains(table, fstype);
2064 }
2065
2066 int chvt(int vt) {
2067         _cleanup_close_ int fd;
2068
2069         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2070         if (fd < 0)
2071                 return -errno;
2072
2073         if (vt < 0) {
2074                 int tiocl[2] = {
2075                         TIOCL_GETKMSGREDIRECT,
2076                         0
2077                 };
2078
2079                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2080                         return -errno;
2081
2082                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2083         }
2084
2085         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2086                 return -errno;
2087
2088         return 0;
2089 }
2090
2091 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2092         struct termios old_termios, new_termios;
2093         char c;
2094         char line[LINE_MAX];
2095
2096         assert(f);
2097         assert(ret);
2098
2099         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2100                 new_termios = old_termios;
2101
2102                 new_termios.c_lflag &= ~ICANON;
2103                 new_termios.c_cc[VMIN] = 1;
2104                 new_termios.c_cc[VTIME] = 0;
2105
2106                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2107                         size_t k;
2108
2109                         if (t != (usec_t) -1) {
2110                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2111                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2112                                         return -ETIMEDOUT;
2113                                 }
2114                         }
2115
2116                         k = fread(&c, 1, 1, f);
2117
2118                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2119
2120                         if (k <= 0)
2121                                 return -EIO;
2122
2123                         if (need_nl)
2124                                 *need_nl = c != '\n';
2125
2126                         *ret = c;
2127                         return 0;
2128                 }
2129         }
2130
2131         if (t != (usec_t) -1)
2132                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2133                         return -ETIMEDOUT;
2134
2135         if (!fgets(line, sizeof(line), f))
2136                 return -EIO;
2137
2138         truncate_nl(line);
2139
2140         if (strlen(line) != 1)
2141                 return -EBADMSG;
2142
2143         if (need_nl)
2144                 *need_nl = false;
2145
2146         *ret = line[0];
2147         return 0;
2148 }
2149
2150 int ask(char *ret, const char *replies, const char *text, ...) {
2151         bool on_tty;
2152
2153         assert(ret);
2154         assert(replies);
2155         assert(text);
2156
2157         on_tty = isatty(STDOUT_FILENO);
2158
2159         for (;;) {
2160                 va_list ap;
2161                 char c;
2162                 int r;
2163                 bool need_nl = true;
2164
2165                 if (on_tty)
2166                         fputs(ANSI_HIGHLIGHT_ON, stdout);
2167
2168                 va_start(ap, text);
2169                 vprintf(text, ap);
2170                 va_end(ap);
2171
2172                 if (on_tty)
2173                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
2174
2175                 fflush(stdout);
2176
2177                 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2178                 if (r < 0) {
2179
2180                         if (r == -EBADMSG) {
2181                                 puts("Bad input, please try again.");
2182                                 continue;
2183                         }
2184
2185                         putchar('\n');
2186                         return r;
2187                 }
2188
2189                 if (need_nl)
2190                         putchar('\n');
2191
2192                 if (strchr(replies, c)) {
2193                         *ret = c;
2194                         return 0;
2195                 }
2196
2197                 puts("Read unexpected character, please try again.");
2198         }
2199 }
2200
2201 int reset_terminal_fd(int fd, bool switch_to_text) {
2202         struct termios termios;
2203         int r = 0;
2204
2205         /* Set terminal to some sane defaults */
2206
2207         assert(fd >= 0);
2208
2209         /* We leave locked terminal attributes untouched, so that
2210          * Plymouth may set whatever it wants to set, and we don't
2211          * interfere with that. */
2212
2213         /* Disable exclusive mode, just in case */
2214         ioctl(fd, TIOCNXCL);
2215
2216         /* Switch to text mode */
2217         if (switch_to_text)
2218                 ioctl(fd, KDSETMODE, KD_TEXT);
2219
2220         /* Enable console unicode mode */
2221         ioctl(fd, KDSKBMODE, K_UNICODE);
2222
2223         if (tcgetattr(fd, &termios) < 0) {
2224                 r = -errno;
2225                 goto finish;
2226         }
2227
2228         /* We only reset the stuff that matters to the software. How
2229          * hardware is set up we don't touch assuming that somebody
2230          * else will do that for us */
2231
2232         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2233         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2234         termios.c_oflag |= ONLCR;
2235         termios.c_cflag |= CREAD;
2236         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2237
2238         termios.c_cc[VINTR]    =   03;  /* ^C */
2239         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2240         termios.c_cc[VERASE]   = 0177;
2241         termios.c_cc[VKILL]    =  025;  /* ^X */
2242         termios.c_cc[VEOF]     =   04;  /* ^D */
2243         termios.c_cc[VSTART]   =  021;  /* ^Q */
2244         termios.c_cc[VSTOP]    =  023;  /* ^S */
2245         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2246         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2247         termios.c_cc[VWERASE]  =  027;  /* ^W */
2248         termios.c_cc[VREPRINT] =  022;  /* ^R */
2249         termios.c_cc[VEOL]     =    0;
2250         termios.c_cc[VEOL2]    =    0;
2251
2252         termios.c_cc[VTIME]  = 0;
2253         termios.c_cc[VMIN]   = 1;
2254
2255         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2256                 r = -errno;
2257
2258 finish:
2259         /* Just in case, flush all crap out */
2260         tcflush(fd, TCIOFLUSH);
2261
2262         return r;
2263 }
2264
2265 int reset_terminal(const char *name) {
2266         int fd, r;
2267
2268         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2269         if (fd < 0)
2270                 return fd;
2271
2272         r = reset_terminal_fd(fd, true);
2273         close_nointr_nofail(fd);
2274
2275         return r;
2276 }
2277
2278 int open_terminal(const char *name, int mode) {
2279         int fd, r;
2280         unsigned c = 0;
2281
2282         /*
2283          * If a TTY is in the process of being closed opening it might
2284          * cause EIO. This is horribly awful, but unlikely to be
2285          * changed in the kernel. Hence we work around this problem by
2286          * retrying a couple of times.
2287          *
2288          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2289          */
2290
2291         for (;;) {
2292                 fd = open(name, mode);
2293                 if (fd >= 0)
2294                         break;
2295
2296                 if (errno != EIO)
2297                         return -errno;
2298
2299                 /* Max 1s in total */
2300                 if (c >= 20)
2301                         return -errno;
2302
2303                 usleep(50 * USEC_PER_MSEC);
2304                 c++;
2305         }
2306
2307         if (fd < 0)
2308                 return -errno;
2309
2310         r = isatty(fd);
2311         if (r < 0) {
2312                 close_nointr_nofail(fd);
2313                 return -errno;
2314         }
2315
2316         if (!r) {
2317                 close_nointr_nofail(fd);
2318                 return -ENOTTY;
2319         }
2320
2321         return fd;
2322 }
2323
2324 int flush_fd(int fd) {
2325         struct pollfd pollfd;
2326
2327         zero(pollfd);
2328         pollfd.fd = fd;
2329         pollfd.events = POLLIN;
2330
2331         for (;;) {
2332                 char buf[LINE_MAX];
2333                 ssize_t l;
2334                 int r;
2335
2336                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2337
2338                         if (errno == EINTR)
2339                                 continue;
2340
2341                         return -errno;
2342                 }
2343
2344                 if (r == 0)
2345                         return 0;
2346
2347                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2348
2349                         if (errno == EINTR)
2350                                 continue;
2351
2352                         if (errno == EAGAIN)
2353                                 return 0;
2354
2355                         return -errno;
2356                 }
2357
2358                 if (l <= 0)
2359                         return 0;
2360         }
2361 }
2362
2363 int acquire_terminal(
2364                 const char *name,
2365                 bool fail,
2366                 bool force,
2367                 bool ignore_tiocstty_eperm,
2368                 usec_t timeout) {
2369
2370         int fd = -1, notify = -1, r = 0, wd = -1;
2371         usec_t ts = 0;
2372         struct sigaction sa_old, sa_new;
2373
2374         assert(name);
2375
2376         /* We use inotify to be notified when the tty is closed. We
2377          * create the watch before checking if we can actually acquire
2378          * it, so that we don't lose any event.
2379          *
2380          * Note: strictly speaking this actually watches for the
2381          * device being closed, it does *not* really watch whether a
2382          * tty loses its controlling process. However, unless some
2383          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2384          * its tty otherwise this will not become a problem. As long
2385          * as the administrator makes sure not configure any service
2386          * on the same tty as an untrusted user this should not be a
2387          * problem. (Which he probably should not do anyway.) */
2388
2389         if (timeout != (usec_t) -1)
2390                 ts = now(CLOCK_MONOTONIC);
2391
2392         if (!fail && !force) {
2393                 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2394                 if (notify < 0) {
2395                         r = -errno;
2396                         goto fail;
2397                 }
2398
2399                 wd = inotify_add_watch(notify, name, IN_CLOSE);
2400                 if (wd < 0) {
2401                         r = -errno;
2402                         goto fail;
2403                 }
2404         }
2405
2406         for (;;) {
2407                 if (notify >= 0) {
2408                         r = flush_fd(notify);
2409                         if (r < 0)
2410                                 goto fail;
2411                 }
2412
2413                 /* We pass here O_NOCTTY only so that we can check the return
2414                  * value TIOCSCTTY and have a reliable way to figure out if we
2415                  * successfully became the controlling process of the tty */
2416                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2417                 if (fd < 0)
2418                         return fd;
2419
2420                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2421                  * if we already own the tty. */
2422                 zero(sa_new);
2423                 sa_new.sa_handler = SIG_IGN;
2424                 sa_new.sa_flags = SA_RESTART;
2425                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2426
2427                 /* First, try to get the tty */
2428                 if (ioctl(fd, TIOCSCTTY, force) < 0)
2429                         r = -errno;
2430
2431                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2432
2433                 /* Sometimes it makes sense to ignore TIOCSCTTY
2434                  * returning EPERM, i.e. when very likely we already
2435                  * are have this controlling terminal. */
2436                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2437                         r = 0;
2438
2439                 if (r < 0 && (force || fail || r != -EPERM)) {
2440                         goto fail;
2441                 }
2442
2443                 if (r >= 0)
2444                         break;
2445
2446                 assert(!fail);
2447                 assert(!force);
2448                 assert(notify >= 0);
2449
2450                 for (;;) {
2451                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2452                         ssize_t l;
2453                         struct inotify_event *e;
2454
2455                         if (timeout != (usec_t) -1) {
2456                                 usec_t n;
2457
2458                                 n = now(CLOCK_MONOTONIC);
2459                                 if (ts + timeout < n) {
2460                                         r = -ETIMEDOUT;
2461                                         goto fail;
2462                                 }
2463
2464                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2465                                 if (r < 0)
2466                                         goto fail;
2467
2468                                 if (r == 0) {
2469                                         r = -ETIMEDOUT;
2470                                         goto fail;
2471                                 }
2472                         }
2473
2474                         l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2475                         if (l < 0) {
2476
2477                                 if (errno == EINTR || errno == EAGAIN)
2478                                         continue;
2479
2480                                 r = -errno;
2481                                 goto fail;
2482                         }
2483
2484                         e = (struct inotify_event*) inotify_buffer;
2485
2486                         while (l > 0) {
2487                                 size_t step;
2488
2489                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2490                                         r = -EIO;
2491                                         goto fail;
2492                                 }
2493
2494                                 step = sizeof(struct inotify_event) + e->len;
2495                                 assert(step <= (size_t) l);
2496
2497                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2498                                 l -= step;
2499                         }
2500
2501                         break;
2502                 }
2503
2504                 /* We close the tty fd here since if the old session
2505                  * ended our handle will be dead. It's important that
2506                  * we do this after sleeping, so that we don't enter
2507                  * an endless loop. */
2508                 close_nointr_nofail(fd);
2509         }
2510
2511         if (notify >= 0)
2512                 close_nointr_nofail(notify);
2513
2514         r = reset_terminal_fd(fd, true);
2515         if (r < 0)
2516                 log_warning("Failed to reset terminal: %s", strerror(-r));
2517
2518         return fd;
2519
2520 fail:
2521         if (fd >= 0)
2522                 close_nointr_nofail(fd);
2523
2524         if (notify >= 0)
2525                 close_nointr_nofail(notify);
2526
2527         return r;
2528 }
2529
2530 int release_terminal(void) {
2531         int r = 0, fd;
2532         struct sigaction sa_old, sa_new;
2533
2534         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2535                 return -errno;
2536
2537         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2538          * by our own TIOCNOTTY */
2539
2540         zero(sa_new);
2541         sa_new.sa_handler = SIG_IGN;
2542         sa_new.sa_flags = SA_RESTART;
2543         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2544
2545         if (ioctl(fd, TIOCNOTTY) < 0)
2546                 r = -errno;
2547
2548         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2549
2550         close_nointr_nofail(fd);
2551         return r;
2552 }
2553
2554 int sigaction_many(const struct sigaction *sa, ...) {
2555         va_list ap;
2556         int r = 0, sig;
2557
2558         va_start(ap, sa);
2559         while ((sig = va_arg(ap, int)) > 0)
2560                 if (sigaction(sig, sa, NULL) < 0)
2561                         r = -errno;
2562         va_end(ap);
2563
2564         return r;
2565 }
2566
2567 int ignore_signals(int sig, ...) {
2568         struct sigaction sa;
2569         va_list ap;
2570         int r = 0;
2571
2572         zero(sa);
2573         sa.sa_handler = SIG_IGN;
2574         sa.sa_flags = SA_RESTART;
2575
2576         if (sigaction(sig, &sa, NULL) < 0)
2577                 r = -errno;
2578
2579         va_start(ap, sig);
2580         while ((sig = va_arg(ap, int)) > 0)
2581                 if (sigaction(sig, &sa, NULL) < 0)
2582                         r = -errno;
2583         va_end(ap);
2584
2585         return r;
2586 }
2587
2588 int default_signals(int sig, ...) {
2589         struct sigaction sa;
2590         va_list ap;
2591         int r = 0;
2592
2593         zero(sa);
2594         sa.sa_handler = SIG_DFL;
2595         sa.sa_flags = SA_RESTART;
2596
2597         if (sigaction(sig, &sa, NULL) < 0)
2598                 r = -errno;
2599
2600         va_start(ap, sig);
2601         while ((sig = va_arg(ap, int)) > 0)
2602                 if (sigaction(sig, &sa, NULL) < 0)
2603                         r = -errno;
2604         va_end(ap);
2605
2606         return r;
2607 }
2608
2609 int close_pipe(int p[]) {
2610         int a = 0, b = 0;
2611
2612         assert(p);
2613
2614         if (p[0] >= 0) {
2615                 a = close_nointr(p[0]);
2616                 p[0] = -1;
2617         }
2618
2619         if (p[1] >= 0) {
2620                 b = close_nointr(p[1]);
2621                 p[1] = -1;
2622         }
2623
2624         return a < 0 ? a : b;
2625 }
2626
2627 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2628         uint8_t *p;
2629         ssize_t n = 0;
2630
2631         assert(fd >= 0);
2632         assert(buf);
2633
2634         p = buf;
2635
2636         while (nbytes > 0) {
2637                 ssize_t k;
2638
2639                 if ((k = read(fd, p, nbytes)) <= 0) {
2640
2641                         if (k < 0 && errno == EINTR)
2642                                 continue;
2643
2644                         if (k < 0 && errno == EAGAIN && do_poll) {
2645                                 struct pollfd pollfd;
2646
2647                                 zero(pollfd);
2648                                 pollfd.fd = fd;
2649                                 pollfd.events = POLLIN;
2650
2651                                 if (poll(&pollfd, 1, -1) < 0) {
2652                                         if (errno == EINTR)
2653                                                 continue;
2654
2655                                         return n > 0 ? n : -errno;
2656                                 }
2657
2658                                 if (pollfd.revents != POLLIN)
2659                                         return n > 0 ? n : -EIO;
2660
2661                                 continue;
2662                         }
2663
2664                         return n > 0 ? n : (k < 0 ? -errno : 0);
2665                 }
2666
2667                 p += k;
2668                 nbytes -= k;
2669                 n += k;
2670         }
2671
2672         return n;
2673 }
2674
2675 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2676         const uint8_t *p;
2677         ssize_t n = 0;
2678
2679         assert(fd >= 0);
2680         assert(buf);
2681
2682         p = buf;
2683
2684         while (nbytes > 0) {
2685                 ssize_t k;
2686
2687                 k = write(fd, p, nbytes);
2688                 if (k <= 0) {
2689
2690                         if (k < 0 && errno == EINTR)
2691                                 continue;
2692
2693                         if (k < 0 && errno == EAGAIN && do_poll) {
2694                                 struct pollfd pollfd;
2695
2696                                 zero(pollfd);
2697                                 pollfd.fd = fd;
2698                                 pollfd.events = POLLOUT;
2699
2700                                 if (poll(&pollfd, 1, -1) < 0) {
2701                                         if (errno == EINTR)
2702                                                 continue;
2703
2704                                         return n > 0 ? n : -errno;
2705                                 }
2706
2707                                 if (pollfd.revents != POLLOUT)
2708                                         return n > 0 ? n : -EIO;
2709
2710                                 continue;
2711                         }
2712
2713                         return n > 0 ? n : (k < 0 ? -errno : 0);
2714                 }
2715
2716                 p += k;
2717                 nbytes -= k;
2718                 n += k;
2719         }
2720
2721         return n;
2722 }
2723
2724 int parse_usec(const char *t, usec_t *usec) {
2725         static const struct {
2726                 const char *suffix;
2727                 usec_t usec;
2728         } table[] = {
2729                 { "sec", USEC_PER_SEC },
2730                 { "s", USEC_PER_SEC },
2731                 { "min", USEC_PER_MINUTE },
2732                 { "hr", USEC_PER_HOUR },
2733                 { "h", USEC_PER_HOUR },
2734                 { "d", USEC_PER_DAY },
2735                 { "w", USEC_PER_WEEK },
2736                 { "msec", USEC_PER_MSEC },
2737                 { "ms", USEC_PER_MSEC },
2738                 { "m", USEC_PER_MINUTE },
2739                 { "usec", 1ULL },
2740                 { "us", 1ULL },
2741                 { "", USEC_PER_SEC }, /* default is sec */
2742         };
2743
2744         const char *p;
2745         usec_t r = 0;
2746
2747         assert(t);
2748         assert(usec);
2749
2750         p = t;
2751         do {
2752                 long long l;
2753                 char *e;
2754                 unsigned i;
2755
2756                 errno = 0;
2757                 l = strtoll(p, &e, 10);
2758
2759                 if (errno != 0)
2760                         return -errno;
2761
2762                 if (l < 0)
2763                         return -ERANGE;
2764
2765                 if (e == p)
2766                         return -EINVAL;
2767
2768                 e += strspn(e, WHITESPACE);
2769
2770                 for (i = 0; i < ELEMENTSOF(table); i++)
2771                         if (startswith(e, table[i].suffix)) {
2772                                 r += (usec_t) l * table[i].usec;
2773                                 p = e + strlen(table[i].suffix);
2774                                 break;
2775                         }
2776
2777                 if (i >= ELEMENTSOF(table))
2778                         return -EINVAL;
2779
2780         } while (*p != 0);
2781
2782         *usec = r;
2783
2784         return 0;
2785 }
2786
2787 int parse_nsec(const char *t, nsec_t *nsec) {
2788         static const struct {
2789                 const char *suffix;
2790                 nsec_t nsec;
2791         } table[] = {
2792                 { "sec", NSEC_PER_SEC },
2793                 { "s", NSEC_PER_SEC },
2794                 { "min", NSEC_PER_MINUTE },
2795                 { "hr", NSEC_PER_HOUR },
2796                 { "h", NSEC_PER_HOUR },
2797                 { "d", NSEC_PER_DAY },
2798                 { "w", NSEC_PER_WEEK },
2799                 { "msec", NSEC_PER_MSEC },
2800                 { "ms", NSEC_PER_MSEC },
2801                 { "m", NSEC_PER_MINUTE },
2802                 { "usec", NSEC_PER_USEC },
2803                 { "us", NSEC_PER_USEC },
2804                 { "nsec", 1ULL },
2805                 { "ns", 1ULL },
2806                 { "", 1ULL }, /* default is nsec */
2807         };
2808
2809         const char *p;
2810         nsec_t r = 0;
2811
2812         assert(t);
2813         assert(nsec);
2814
2815         p = t;
2816         do {
2817                 long long l;
2818                 char *e;
2819                 unsigned i;
2820
2821                 errno = 0;
2822                 l = strtoll(p, &e, 10);
2823
2824                 if (errno != 0)
2825                         return -errno;
2826
2827                 if (l < 0)
2828                         return -ERANGE;
2829
2830                 if (e == p)
2831                         return -EINVAL;
2832
2833                 e += strspn(e, WHITESPACE);
2834
2835                 for (i = 0; i < ELEMENTSOF(table); i++)
2836                         if (startswith(e, table[i].suffix)) {
2837                                 r += (nsec_t) l * table[i].nsec;
2838                                 p = e + strlen(table[i].suffix);
2839                                 break;
2840                         }
2841
2842                 if (i >= ELEMENTSOF(table))
2843                         return -EINVAL;
2844
2845         } while (*p != 0);
2846
2847         *nsec = r;
2848
2849         return 0;
2850 }
2851
2852 int parse_bytes(const char *t, off_t *bytes) {
2853         static const struct {
2854                 const char *suffix;
2855                 off_t factor;
2856         } table[] = {
2857                 { "B", 1 },
2858                 { "K", 1024ULL },
2859                 { "M", 1024ULL*1024ULL },
2860                 { "G", 1024ULL*1024ULL*1024ULL },
2861                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2862                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2863                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2864                 { "", 1 },
2865         };
2866
2867         const char *p;
2868         off_t r = 0;
2869
2870         assert(t);
2871         assert(bytes);
2872
2873         p = t;
2874         do {
2875                 long long l;
2876                 char *e;
2877                 unsigned i;
2878
2879                 errno = 0;
2880                 l = strtoll(p, &e, 10);
2881
2882                 if (errno != 0)
2883                         return -errno;
2884
2885                 if (l < 0)
2886                         return -ERANGE;
2887
2888                 if (e == p)
2889                         return -EINVAL;
2890
2891                 e += strspn(e, WHITESPACE);
2892
2893                 for (i = 0; i < ELEMENTSOF(table); i++)
2894                         if (startswith(e, table[i].suffix)) {
2895                                 r += (off_t) l * table[i].factor;
2896                                 p = e + strlen(table[i].suffix);
2897                                 break;
2898                         }
2899
2900                 if (i >= ELEMENTSOF(table))
2901                         return -EINVAL;
2902
2903         } while (*p != 0);
2904
2905         *bytes = r;
2906
2907         return 0;
2908 }
2909
2910 int make_stdio(int fd) {
2911         int r, s, t;
2912
2913         assert(fd >= 0);
2914
2915         r = dup3(fd, STDIN_FILENO, 0);
2916         s = dup3(fd, STDOUT_FILENO, 0);
2917         t = dup3(fd, STDERR_FILENO, 0);
2918
2919         if (fd >= 3)
2920                 close_nointr_nofail(fd);
2921
2922         if (r < 0 || s < 0 || t < 0)
2923                 return -errno;
2924
2925         /* We rely here that the new fd has O_CLOEXEC not set */
2926
2927         return 0;
2928 }
2929
2930 int make_null_stdio(void) {
2931         int null_fd;
2932
2933         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2934         if (null_fd < 0)
2935                 return -errno;
2936
2937         return make_stdio(null_fd);
2938 }
2939
2940 bool is_device_path(const char *path) {
2941
2942         /* Returns true on paths that refer to a device, either in
2943          * sysfs or in /dev */
2944
2945         return
2946                 path_startswith(path, "/dev/") ||
2947                 path_startswith(path, "/sys/");
2948 }
2949
2950 int dir_is_empty(const char *path) {
2951         _cleanup_closedir_ DIR *d;
2952         int r;
2953
2954         d = opendir(path);
2955         if (!d)
2956                 return -errno;
2957
2958         for (;;) {
2959                 struct dirent buf, *de;
2960
2961                 r = readdir_r(d, &buf, &de);
2962                 if (r > 0)
2963                         return -r;
2964
2965                 if (!de)
2966                         return 1;
2967
2968                 if (!ignore_file(de->d_name))
2969                         return 0;
2970         }
2971 }
2972
2973 unsigned long long random_ull(void) {
2974         _cleanup_close_ int fd;
2975         uint64_t ull;
2976         ssize_t r;
2977
2978         fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2979         if (fd < 0)
2980                 goto fallback;
2981
2982         r = loop_read(fd, &ull, sizeof(ull), true);
2983         if (r != sizeof(ull))
2984                 goto fallback;
2985
2986         return ull;
2987
2988 fallback:
2989         return random() * RAND_MAX + random();
2990 }
2991
2992 void rename_process(const char name[8]) {
2993         assert(name);
2994
2995         /* This is a like a poor man's setproctitle(). It changes the
2996          * comm field, argv[0], and also the glibc's internally used
2997          * name of the process. For the first one a limit of 16 chars
2998          * applies, to the second one usually one of 10 (i.e. length
2999          * of "/sbin/init"), to the third one one of 7 (i.e. length of
3000          * "systemd"). If you pass a longer string it will be
3001          * truncated */
3002
3003         prctl(PR_SET_NAME, name);
3004
3005         if (program_invocation_name)
3006                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3007
3008         if (saved_argc > 0) {
3009                 int i;
3010
3011                 if (saved_argv[0])
3012                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3013
3014                 for (i = 1; i < saved_argc; i++) {
3015                         if (!saved_argv[i])
3016                                 break;
3017
3018                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3019                 }
3020         }
3021 }
3022
3023 void sigset_add_many(sigset_t *ss, ...) {
3024         va_list ap;
3025         int sig;
3026
3027         assert(ss);
3028
3029         va_start(ap, ss);
3030         while ((sig = va_arg(ap, int)) > 0)
3031                 assert_se(sigaddset(ss, sig) == 0);
3032         va_end(ap);
3033 }
3034
3035 char* gethostname_malloc(void) {
3036         struct utsname u;
3037
3038         assert_se(uname(&u) >= 0);
3039
3040         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3041                 return strdup(u.nodename);
3042
3043         return strdup(u.sysname);
3044 }
3045
3046 bool hostname_is_set(void) {
3047         struct utsname u;
3048
3049         assert_se(uname(&u) >= 0);
3050
3051         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3052 }
3053
3054 static char *lookup_uid(uid_t uid) {
3055         long bufsize;
3056         char *name;
3057         _cleanup_free_ char *buf = NULL;
3058         struct passwd pwbuf, *pw = NULL;
3059
3060         /* Shortcut things to avoid NSS lookups */
3061         if (uid == 0)
3062                 return strdup("root");
3063
3064         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3065         if (bufsize <= 0)
3066                 bufsize = 4096;
3067
3068         buf = malloc(bufsize);
3069         if (!buf)
3070                 return NULL;
3071
3072         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3073                 return strdup(pw->pw_name);
3074
3075         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3076                 return NULL;
3077
3078         return name;
3079 }
3080
3081 char* getlogname_malloc(void) {
3082         uid_t uid;
3083         struct stat st;
3084
3085         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3086                 uid = st.st_uid;
3087         else
3088                 uid = getuid();
3089
3090         return lookup_uid(uid);
3091 }
3092
3093 char *getusername_malloc(void) {
3094         const char *e;
3095
3096         e = getenv("USER");
3097         if (e)
3098                 return strdup(e);
3099
3100         return lookup_uid(getuid());
3101 }
3102
3103 int getttyname_malloc(int fd, char **r) {
3104         char path[PATH_MAX], *c;
3105         int k;
3106
3107         assert(r);
3108
3109         k = ttyname_r(fd, path, sizeof(path));
3110         if (k != 0)
3111                 return -k;
3112
3113         char_array_0(path);
3114
3115         c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3116         if (!c)
3117                 return -ENOMEM;
3118
3119         *r = c;
3120         return 0;
3121 }
3122
3123 int getttyname_harder(int fd, char **r) {
3124         int k;
3125         char *s;
3126
3127         k = getttyname_malloc(fd, &s);
3128         if (k < 0)
3129                 return k;
3130
3131         if (streq(s, "tty")) {
3132                 free(s);
3133                 return get_ctty(0, NULL, r);
3134         }
3135
3136         *r = s;
3137         return 0;
3138 }
3139
3140 int get_ctty_devnr(pid_t pid, dev_t *d) {
3141         int k;
3142         char line[LINE_MAX], *p, *fn;
3143         unsigned long ttynr;
3144         FILE *f;
3145
3146         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3147                 return -ENOMEM;
3148
3149         f = fopen(fn, "re");
3150         free(fn);
3151         if (!f)
3152                 return -errno;
3153
3154         if (!fgets(line, sizeof(line), f)) {
3155                 k = feof(f) ? -EIO : -errno;
3156                 fclose(f);
3157                 return k;
3158         }
3159
3160         fclose(f);
3161
3162         p = strrchr(line, ')');
3163         if (!p)
3164                 return -EIO;
3165
3166         p++;
3167
3168         if (sscanf(p, " "
3169                    "%*c "  /* state */
3170                    "%*d "  /* ppid */
3171                    "%*d "  /* pgrp */
3172                    "%*d "  /* session */
3173                    "%lu ", /* ttynr */
3174                    &ttynr) != 1)
3175                 return -EIO;
3176
3177         *d = (dev_t) ttynr;
3178         return 0;
3179 }
3180
3181 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3182         int k;
3183         char fn[PATH_MAX], *s, *b, *p;
3184         dev_t devnr;
3185
3186         assert(r);
3187
3188         k = get_ctty_devnr(pid, &devnr);
3189         if (k < 0)
3190                 return k;
3191
3192         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3193         char_array_0(fn);
3194
3195         if ((k = readlink_malloc(fn, &s)) < 0) {
3196
3197                 if (k != -ENOENT)
3198                         return k;
3199
3200                 /* This is an ugly hack */
3201                 if (major(devnr) == 136) {
3202                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3203                                 return -ENOMEM;
3204
3205                         *r = b;
3206                         if (_devnr)
3207                                 *_devnr = devnr;
3208
3209                         return 0;
3210                 }
3211
3212                 /* Probably something like the ptys which have no
3213                  * symlink in /dev/char. Let's return something
3214                  * vaguely useful. */
3215
3216                 if (!(b = strdup(fn + 5)))
3217                         return -ENOMEM;
3218
3219                 *r = b;
3220                 if (_devnr)
3221                         *_devnr = devnr;
3222
3223                 return 0;
3224         }
3225
3226         if (startswith(s, "/dev/"))
3227                 p = s + 5;
3228         else if (startswith(s, "../"))
3229                 p = s + 3;
3230         else
3231                 p = s;
3232
3233         b = strdup(p);
3234         free(s);
3235
3236         if (!b)
3237                 return -ENOMEM;
3238
3239         *r = b;
3240         if (_devnr)
3241                 *_devnr = devnr;
3242
3243         return 0;
3244 }
3245
3246 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3247         DIR *d;
3248         int ret = 0;
3249
3250         assert(fd >= 0);
3251
3252         /* This returns the first error we run into, but nevertheless
3253          * tries to go on. This closes the passed fd. */
3254
3255         d = fdopendir(fd);
3256         if (!d) {
3257                 close_nointr_nofail(fd);
3258
3259                 return errno == ENOENT ? 0 : -errno;
3260         }
3261
3262         for (;;) {
3263                 struct dirent buf, *de;
3264                 bool is_dir, keep_around;
3265                 struct stat st;
3266                 int r;
3267
3268                 r = readdir_r(d, &buf, &de);
3269                 if (r != 0 && ret == 0) {
3270                         ret = -r;
3271                         break;
3272                 }
3273
3274                 if (!de)
3275                         break;
3276
3277                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3278                         continue;
3279
3280                 if (de->d_type == DT_UNKNOWN ||
3281                     honour_sticky ||
3282                     (de->d_type == DT_DIR && root_dev)) {
3283                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3284                                 if (ret == 0 && errno != ENOENT)
3285                                         ret = -errno;
3286                                 continue;
3287                         }
3288
3289                         is_dir = S_ISDIR(st.st_mode);
3290                         keep_around =
3291                                 honour_sticky &&
3292                                 (st.st_uid == 0 || st.st_uid == getuid()) &&
3293                                 (st.st_mode & S_ISVTX);
3294                 } else {
3295                         is_dir = de->d_type == DT_DIR;
3296                         keep_around = false;
3297                 }
3298
3299                 if (is_dir) {
3300                         int subdir_fd;
3301
3302                         /* if root_dev is set, remove subdirectories only, if device is same as dir */
3303                         if (root_dev && st.st_dev != root_dev->st_dev)
3304                                 continue;
3305
3306                         subdir_fd = openat(fd, de->d_name,
3307                                            O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3308                         if (subdir_fd < 0) {
3309                                 if (ret == 0 && errno != ENOENT)
3310                                         ret = -errno;
3311                                 continue;
3312                         }
3313
3314                         r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3315                         if (r < 0 && ret == 0)
3316                                 ret = r;
3317
3318                         if (!keep_around)
3319                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3320                                         if (ret == 0 && errno != ENOENT)
3321                                                 ret = -errno;
3322                                 }
3323
3324                 } else if (!only_dirs && !keep_around) {
3325
3326                         if (unlinkat(fd, de->d_name, 0) < 0) {
3327                                 if (ret == 0 && errno != ENOENT)
3328                                         ret = -errno;
3329                         }
3330                 }
3331         }
3332
3333         closedir(d);
3334
3335         return ret;
3336 }
3337
3338 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3339         struct statfs s;
3340
3341         assert(fd >= 0);
3342
3343         if (fstatfs(fd, &s) < 0) {
3344                 close_nointr_nofail(fd);
3345                 return -errno;
3346         }
3347
3348         /* We refuse to clean disk file systems with this call. This
3349          * is extra paranoia just to be sure we never ever remove
3350          * non-state data */
3351
3352         if (s.f_type != TMPFS_MAGIC &&
3353             s.f_type != RAMFS_MAGIC) {
3354                 log_error("Attempted to remove disk file system, and we can't allow that.");
3355                 close_nointr_nofail(fd);
3356                 return -EPERM;
3357         }
3358
3359         return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3360 }
3361
3362 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3363         int fd, r;
3364         struct statfs s;
3365
3366         assert(path);
3367
3368         /* We refuse to clean the root file system with this
3369          * call. This is extra paranoia to never cause a really
3370          * seriously broken system. */
3371         if (path_equal(path, "/")) {
3372                 log_error("Attempted to remove entire root file system, and we can't allow that.");
3373                 return -EPERM;
3374         }
3375
3376         fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3377         if (fd < 0) {
3378
3379                 if (errno != ENOTDIR)
3380                         return -errno;
3381
3382                 if (!dangerous) {
3383                         if (statfs(path, &s) < 0)
3384                                 return -errno;
3385
3386                         if (s.f_type != TMPFS_MAGIC &&
3387                             s.f_type != RAMFS_MAGIC) {
3388                                 log_error("Attempted to remove disk file system, and we can't allow that.");
3389                                 return -EPERM;
3390                         }
3391                 }
3392
3393                 if (delete_root && !only_dirs)
3394                         if (unlink(path) < 0 && errno != ENOENT)
3395                                 return -errno;
3396
3397                 return 0;
3398         }
3399
3400         if (!dangerous) {
3401                 if (fstatfs(fd, &s) < 0) {
3402                         close_nointr_nofail(fd);
3403                         return -errno;
3404                 }
3405
3406                 if (s.f_type != TMPFS_MAGIC &&
3407                     s.f_type != RAMFS_MAGIC) {
3408                         log_error("Attempted to remove disk file system, and we can't allow that.");
3409                         close_nointr_nofail(fd);
3410                         return -EPERM;
3411                 }
3412         }
3413
3414         r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3415         if (delete_root) {
3416
3417                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3418                         return r;
3419
3420                 if (rmdir(path) < 0 && errno != ENOENT) {
3421                         if (r == 0)
3422                                 r = -errno;
3423                 }
3424         }
3425
3426         return r;
3427 }
3428
3429 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3430         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3431 }
3432
3433 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3434         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3435 }
3436
3437 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3438         assert(path);
3439
3440         /* Under the assumption that we are running privileged we
3441          * first change the access mode and only then hand out
3442          * ownership to avoid a window where access is too open. */
3443
3444         if (mode != (mode_t) -1)
3445                 if (chmod(path, mode) < 0)
3446                         return -errno;
3447
3448         if (uid != (uid_t) -1 || gid != (gid_t) -1)
3449                 if (chown(path, uid, gid) < 0)
3450                         return -errno;
3451
3452         return 0;
3453 }
3454
3455 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3456         assert(fd >= 0);
3457
3458         /* Under the assumption that we are running privileged we
3459          * first change the access mode and only then hand out
3460          * ownership to avoid a window where access is too open. */
3461
3462         if (fchmod(fd, mode) < 0)
3463                 return -errno;
3464
3465         if (fchown(fd, uid, gid) < 0)
3466                 return -errno;
3467
3468         return 0;
3469 }
3470
3471 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3472         cpu_set_t *r;
3473         unsigned n = 1024;
3474
3475         /* Allocates the cpuset in the right size */
3476
3477         for (;;) {
3478                 if (!(r = CPU_ALLOC(n)))
3479                         return NULL;
3480
3481                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3482                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3483
3484                         if (ncpus)
3485                                 *ncpus = n;
3486
3487                         return r;
3488                 }
3489
3490                 CPU_FREE(r);
3491
3492                 if (errno != EINVAL)
3493                         return NULL;
3494
3495                 n *= 2;
3496         }
3497 }
3498
3499 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3500         static const char status_indent[] = "         "; /* "[" STATUS "] " */
3501         _cleanup_free_ char *s = NULL;
3502         _cleanup_close_ int fd = -1;
3503         struct iovec iovec[5];
3504         int n = 0;
3505
3506         assert(format);
3507
3508         /* This is independent of logging, as status messages are
3509          * optional and go exclusively to the console. */
3510
3511         if (vasprintf(&s, format, ap) < 0)
3512                 return log_oom();
3513
3514         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3515         if (fd < 0)
3516                 return fd;
3517
3518         if (ellipse) {
3519                 char *e;
3520                 size_t emax, sl;
3521                 int c;
3522
3523                 c = fd_columns(fd);
3524                 if (c <= 0)
3525                         c = 80;
3526
3527                 sl = status ? sizeof(status_indent)-1 : 0;
3528
3529                 emax = c - sl - 1;
3530                 if (emax < 3)
3531                         emax = 3;
3532
3533                 e = ellipsize(s, emax, 75);
3534                 if (e) {
3535                         free(s);
3536                         s = e;
3537                 }
3538         }
3539
3540         zero(iovec);
3541
3542         if (status) {
3543                 if (!isempty(status)) {
3544                         IOVEC_SET_STRING(iovec[n++], "[");
3545                         IOVEC_SET_STRING(iovec[n++], status);
3546                         IOVEC_SET_STRING(iovec[n++], "] ");
3547                 } else
3548                         IOVEC_SET_STRING(iovec[n++], status_indent);
3549         }
3550
3551         IOVEC_SET_STRING(iovec[n++], s);
3552         IOVEC_SET_STRING(iovec[n++], "\n");
3553
3554         if (writev(fd, iovec, n) < 0)
3555                 return -errno;
3556
3557         return 0;
3558 }
3559
3560 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3561         va_list ap;
3562         int r;
3563
3564         assert(format);
3565
3566         va_start(ap, format);
3567         r = status_vprintf(status, ellipse, format, ap);
3568         va_end(ap);
3569
3570         return r;
3571 }
3572
3573 int status_welcome(void) {
3574         int r;
3575         _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3576
3577         r = parse_env_file("/etc/os-release", NEWLINE,
3578                            "PRETTY_NAME", &pretty_name,
3579                            "ANSI_COLOR", &ansi_color,
3580                            NULL);
3581         if (r < 0 && r != -ENOENT)
3582                 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3583
3584         return status_printf(NULL, false,
3585                              "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3586                              isempty(ansi_color) ? "1" : ansi_color,
3587                              isempty(pretty_name) ? "Linux" : pretty_name);
3588 }
3589
3590 char *replace_env(const char *format, char **env) {
3591         enum {
3592                 WORD,
3593                 CURLY,
3594                 VARIABLE
3595         } state = WORD;
3596
3597         const char *e, *word = format;
3598         char *r = NULL, *k;
3599
3600         assert(format);
3601
3602         for (e = format; *e; e ++) {
3603
3604                 switch (state) {
3605
3606                 case WORD:
3607                         if (*e == '$')
3608                                 state = CURLY;
3609                         break;
3610
3611                 case CURLY:
3612                         if (*e == '{') {
3613                                 if (!(k = strnappend(r, word, e-word-1)))
3614                                         goto fail;
3615
3616                                 free(r);
3617                                 r = k;
3618
3619                                 word = e-1;
3620                                 state = VARIABLE;
3621
3622                         } else if (*e == '$') {
3623                                 if (!(k = strnappend(r, word, e-word)))
3624                                         goto fail;
3625
3626                                 free(r);
3627                                 r = k;
3628
3629                                 word = e+1;
3630                                 state = WORD;
3631                         } else
3632                                 state = WORD;
3633                         break;
3634
3635                 case VARIABLE:
3636                         if (*e == '}') {
3637                                 const char *t;
3638
3639                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3640                                         t = "";
3641
3642                                 if (!(k = strappend(r, t)))
3643                                         goto fail;
3644
3645                                 free(r);
3646                                 r = k;
3647
3648                                 word = e+1;
3649                                 state = WORD;
3650                         }
3651                         break;
3652                 }
3653         }
3654
3655         if (!(k = strnappend(r, word, e-word)))
3656                 goto fail;
3657
3658         free(r);
3659         return k;
3660
3661 fail:
3662         free(r);
3663         return NULL;
3664 }
3665
3666 char **replace_env_argv(char **argv, char **env) {
3667         char **r, **i;
3668         unsigned k = 0, l = 0;
3669
3670         l = strv_length(argv);
3671
3672         if (!(r = new(char*, l+1)))
3673                 return NULL;
3674
3675         STRV_FOREACH(i, argv) {
3676
3677                 /* If $FOO appears as single word, replace it by the split up variable */
3678                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3679                         char *e;
3680                         char **w, **m;
3681                         unsigned q;
3682
3683                         if ((e = strv_env_get(env, *i+1))) {
3684
3685                                 if (!(m = strv_split_quoted(e))) {
3686                                         r[k] = NULL;
3687                                         strv_free(r);
3688                                         return NULL;
3689                                 }
3690                         } else
3691                                 m = NULL;
3692
3693                         q = strv_length(m);
3694                         l = l + q - 1;
3695
3696                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3697                                 r[k] = NULL;
3698                                 strv_free(r);
3699                                 strv_free(m);
3700                                 return NULL;
3701                         }
3702
3703                         r = w;
3704                         if (m) {
3705                                 memcpy(r + k, m, q * sizeof(char*));
3706                                 free(m);
3707                         }
3708
3709                         k += q;
3710                         continue;
3711                 }
3712
3713                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3714                 if (!(r[k++] = replace_env(*i, env))) {
3715                         strv_free(r);
3716                         return NULL;
3717                 }
3718         }
3719
3720         r[k] = NULL;
3721         return r;
3722 }
3723
3724 int fd_columns(int fd) {
3725         struct winsize ws;
3726         zero(ws);
3727
3728         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3729                 return -errno;
3730
3731         if (ws.ws_col <= 0)
3732                 return -EIO;
3733
3734         return ws.ws_col;
3735 }
3736
3737 static unsigned columns_cached(bool cached) {
3738         static __thread int parsed_columns = 0, env_columns = -1;
3739         const char *e;
3740
3741         if (_likely_(parsed_columns > 0 && cached))
3742                 return parsed_columns;
3743
3744         if (_unlikely_(env_columns == -1)) {
3745                 e = getenv("COLUMNS");
3746                 if (e)
3747                         env_columns = atoi(e);
3748                 else
3749                         env_columns = 0;
3750         }
3751
3752         if (env_columns > 0) {
3753                 parsed_columns = env_columns;
3754                 return parsed_columns;
3755         }
3756
3757         if (parsed_columns <= 0 || !cached)
3758                 parsed_columns = fd_columns(STDOUT_FILENO);
3759
3760         if (parsed_columns <= 0)
3761                 parsed_columns = 80;
3762
3763         return parsed_columns;
3764 }
3765
3766 unsigned columns(void) {
3767         return columns_cached(true);
3768 }
3769
3770 unsigned columns_uncached(void) {
3771         return columns_cached(false);
3772 }
3773
3774 int fd_lines(int fd) {
3775         struct winsize ws;
3776         zero(ws);
3777
3778         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3779                 return -errno;
3780
3781         if (ws.ws_row <= 0)
3782                 return -EIO;
3783
3784         return ws.ws_row;
3785 }
3786
3787 unsigned lines(void) {
3788         static __thread int parsed_lines = 0;
3789         const char *e;
3790
3791         if (_likely_(parsed_lines > 0))
3792                 return parsed_lines;
3793
3794         e = getenv("LINES");
3795         if (e)
3796                 parsed_lines = atoi(e);
3797
3798         if (parsed_lines <= 0)
3799                 parsed_lines = fd_lines(STDOUT_FILENO);
3800
3801         if (parsed_lines <= 0)
3802                 parsed_lines = 25;
3803
3804         return parsed_lines;
3805 }
3806
3807 int running_in_chroot(void) {
3808         struct stat a, b;
3809
3810         zero(a);
3811         zero(b);
3812
3813         /* Only works as root */
3814
3815         if (stat("/proc/1/root", &a) < 0)
3816                 return -errno;
3817
3818         if (stat("/", &b) < 0)
3819                 return -errno;
3820
3821         return
3822                 a.st_dev != b.st_dev ||
3823                 a.st_ino != b.st_ino;
3824 }
3825
3826 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3827         size_t x;
3828         char *r;
3829
3830         assert(s);
3831         assert(percent <= 100);
3832         assert(new_length >= 3);
3833
3834         if (old_length <= 3 || old_length <= new_length)
3835                 return strndup(s, old_length);
3836
3837         r = new0(char, new_length+1);
3838         if (!r)
3839                 return r;
3840
3841         x = (new_length * percent) / 100;
3842
3843         if (x > new_length - 3)
3844                 x = new_length - 3;
3845
3846         memcpy(r, s, x);
3847         r[x] = '.';
3848         r[x+1] = '.';
3849         r[x+2] = '.';
3850         memcpy(r + x + 3,
3851                s + old_length - (new_length - x - 3),
3852                new_length - x - 3);
3853
3854         return r;
3855 }
3856
3857 char *ellipsize(const char *s, size_t length, unsigned percent) {
3858         return ellipsize_mem(s, strlen(s), length, percent);
3859 }
3860
3861 int touch(const char *path) {
3862         int fd;
3863
3864         assert(path);
3865
3866         /* This just opens the file for writing, ensuring it
3867          * exists. It doesn't call utimensat() the way /usr/bin/touch
3868          * does it. */
3869
3870         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3871         if (fd < 0)
3872                 return -errno;
3873
3874         close_nointr_nofail(fd);
3875         return 0;
3876 }
3877
3878 char *unquote(const char *s, const char* quotes) {
3879         size_t l;
3880         assert(s);
3881
3882         /* This is rather stupid, simply removes the heading and
3883          * trailing quotes if there is one. Doesn't care about
3884          * escaping or anything. */
3885
3886         l = strlen(s);
3887         if (l < 2)
3888                 return strdup(s);
3889
3890         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3891                 return strndup(s+1, l-2);
3892
3893         return strdup(s);
3894 }
3895
3896 char *normalize_env_assignment(const char *s) {
3897         char *name, *value, *p, *r;
3898
3899         p = strchr(s, '=');
3900
3901         if (!p) {
3902                 if (!(r = strdup(s)))
3903                         return NULL;
3904
3905                 return strstrip(r);
3906         }
3907
3908         if (!(name = strndup(s, p - s)))
3909                 return NULL;
3910
3911         if (!(p = strdup(p+1))) {
3912                 free(name);
3913                 return NULL;
3914         }
3915
3916         value = unquote(strstrip(p), QUOTES);
3917         free(p);
3918
3919         if (!value) {
3920                 free(name);
3921                 return NULL;
3922         }
3923
3924         if (asprintf(&r, "%s=%s", name, value) < 0)
3925                 r = NULL;
3926
3927         free(value);
3928         free(name);
3929
3930         return r;
3931 }
3932
3933 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3934         siginfo_t dummy;
3935
3936         assert(pid >= 1);
3937
3938         if (!status)
3939                 status = &dummy;
3940
3941         for (;;) {
3942                 zero(*status);
3943
3944                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3945
3946                         if (errno == EINTR)
3947                                 continue;
3948
3949                         return -errno;
3950                 }
3951
3952                 return 0;
3953         }
3954 }
3955
3956 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3957         int r;
3958         siginfo_t status;
3959
3960         assert(name);
3961         assert(pid > 1);
3962
3963         r = wait_for_terminate(pid, &status);
3964         if (r < 0) {
3965                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3966                 return r;
3967         }
3968
3969         if (status.si_code == CLD_EXITED) {
3970                 if (status.si_status != 0) {
3971                         log_warning("%s failed with error code %i.", name, status.si_status);
3972                         return status.si_status;
3973                 }
3974
3975                 log_debug("%s succeeded.", name);
3976                 return 0;
3977
3978         } else if (status.si_code == CLD_KILLED ||
3979                    status.si_code == CLD_DUMPED) {
3980
3981                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3982                 return -EPROTO;
3983         }
3984
3985         log_warning("%s failed due to unknown reason.", name);
3986         return -EPROTO;
3987 }
3988
3989 _noreturn_ void freeze(void) {
3990
3991         /* Make sure nobody waits for us on a socket anymore */
3992         close_all_fds(NULL, 0);
3993
3994         sync();
3995
3996         for (;;)
3997                 pause();
3998 }
3999
4000 bool null_or_empty(struct stat *st) {
4001         assert(st);
4002
4003         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4004                 return true;
4005
4006         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4007                 return true;
4008
4009         return false;
4010 }
4011
4012 int null_or_empty_path(const char *fn) {
4013         struct stat st;
4014
4015         assert(fn);
4016
4017         if (stat(fn, &st) < 0)
4018                 return -errno;
4019
4020         return null_or_empty(&st);
4021 }
4022
4023 DIR *xopendirat(int fd, const char *name, int flags) {
4024         int nfd;
4025         DIR *d;
4026
4027         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4028         if (nfd < 0)
4029                 return NULL;
4030
4031         d = fdopendir(nfd);
4032         if (!d) {
4033                 close_nointr_nofail(nfd);
4034                 return NULL;
4035         }
4036
4037         return d;
4038 }
4039
4040 int signal_from_string_try_harder(const char *s) {
4041         int signo;
4042         assert(s);
4043
4044         signo = signal_from_string(s);
4045         if (signo <= 0)
4046                 if (startswith(s, "SIG"))
4047                         return signal_from_string(s+3);
4048
4049         return signo;
4050 }
4051
4052 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4053
4054         assert(f);
4055         assert(name);
4056         assert(t);
4057
4058         if (!dual_timestamp_is_set(t))
4059                 return;
4060
4061         fprintf(f, "%s=%llu %llu\n",
4062                 name,
4063                 (unsigned long long) t->realtime,
4064                 (unsigned long long) t->monotonic);
4065 }
4066
4067 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4068         unsigned long long a, b;
4069
4070         assert(value);
4071         assert(t);
4072
4073         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4074                 log_debug("Failed to parse finish timestamp value %s", value);
4075         else {
4076                 t->realtime = a;
4077                 t->monotonic = b;
4078         }
4079 }
4080
4081 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4082         char *dn, *t, *u;
4083         int r;
4084
4085         /* FIXME: to follow udev's logic 100% we need to leave valid
4086          * UTF8 chars unescaped */
4087
4088         u = unquote(tagvalue, "\"\'");
4089         if (u == NULL)
4090                 return NULL;
4091
4092         t = xescape(u, "/ ");
4093         free(u);
4094
4095         if (t == NULL)
4096                 return NULL;
4097
4098         r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4099         free(t);
4100
4101         if (r < 0)
4102                 return NULL;
4103
4104         return dn;
4105 }
4106
4107 char *fstab_node_to_udev_node(const char *p) {
4108         assert(p);
4109
4110         if (startswith(p, "LABEL="))
4111                 return tag_to_udev_node(p+6, "label");
4112
4113         if (startswith(p, "UUID="))
4114                 return tag_to_udev_node(p+5, "uuid");
4115
4116         if (startswith(p, "PARTUUID="))
4117                 return tag_to_udev_node(p+9, "partuuid");
4118
4119         if (startswith(p, "PARTLABEL="))
4120                 return tag_to_udev_node(p+10, "partlabel");
4121
4122         return strdup(p);
4123 }
4124
4125 bool tty_is_vc(const char *tty) {
4126         assert(tty);
4127
4128         if (startswith(tty, "/dev/"))
4129                 tty += 5;
4130
4131         return vtnr_from_tty(tty) >= 0;
4132 }
4133
4134 bool tty_is_console(const char *tty) {
4135         assert(tty);
4136
4137         if (startswith(tty, "/dev/"))
4138                 tty += 5;
4139
4140         return streq(tty, "console");
4141 }
4142
4143 int vtnr_from_tty(const char *tty) {
4144         int i, r;
4145
4146         assert(tty);
4147
4148         if (startswith(tty, "/dev/"))
4149                 tty += 5;
4150
4151         if (!startswith(tty, "tty") )
4152                 return -EINVAL;
4153
4154         if (tty[3] < '0' || tty[3] > '9')
4155                 return -EINVAL;
4156
4157         r = safe_atoi(tty+3, &i);
4158         if (r < 0)
4159                 return r;
4160
4161         if (i < 0 || i > 63)
4162                 return -EINVAL;
4163
4164         return i;
4165 }
4166
4167 bool tty_is_vc_resolve(const char *tty) {
4168         char *active = NULL;
4169         bool b;
4170
4171         assert(tty);
4172
4173         if (startswith(tty, "/dev/"))
4174                 tty += 5;
4175
4176         /* Resolve where /dev/console is pointing to, if /sys is
4177          * actually ours (i.e. not read-only-mounted which is a sign
4178          * for container setups) */
4179         if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4180                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4181                         /* If multiple log outputs are configured the
4182                          * last one is what /dev/console points to */
4183                         tty = strrchr(active, ' ');
4184                         if (tty)
4185                                 tty++;
4186                         else
4187                                 tty = active;
4188                 }
4189
4190         b = tty_is_vc(tty);
4191         free(active);
4192
4193         return b;
4194 }
4195
4196 const char *default_term_for_tty(const char *tty) {
4197         assert(tty);
4198
4199         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4200 }
4201
4202 bool dirent_is_file(const struct dirent *de) {
4203         assert(de);
4204
4205         if (ignore_file(de->d_name))
4206                 return false;
4207
4208         if (de->d_type != DT_REG &&
4209             de->d_type != DT_LNK &&
4210             de->d_type != DT_UNKNOWN)
4211                 return false;
4212
4213         return true;
4214 }
4215
4216 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4217         assert(de);
4218
4219         if (de->d_type != DT_REG &&
4220             de->d_type != DT_LNK &&
4221             de->d_type != DT_UNKNOWN)
4222                 return false;
4223
4224         if (ignore_file_allow_backup(de->d_name))
4225                 return false;
4226
4227         return endswith(de->d_name, suffix);
4228 }
4229
4230 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4231         DIR *_d = NULL;
4232         struct dirent *de;
4233         Hashmap *pids = NULL;
4234
4235         assert(directory);
4236
4237         /* Executes all binaries in a directory in parallel and waits
4238          * until all they all finished. */
4239
4240         if (!d) {
4241                 if (!(_d = opendir(directory))) {
4242
4243                         if (errno == ENOENT)
4244                                 return;
4245
4246                         log_error("Failed to enumerate directory %s: %m", directory);
4247                         return;
4248                 }
4249
4250                 d = _d;
4251         }
4252
4253         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4254                 log_error("Failed to allocate set.");
4255                 goto finish;
4256         }
4257
4258         while ((de = readdir(d))) {
4259                 char *path;
4260                 pid_t pid;
4261                 int k;
4262
4263                 if (!dirent_is_file(de))
4264                         continue;
4265
4266                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4267                         log_oom();
4268                         continue;
4269                 }
4270
4271                 if ((pid = fork()) < 0) {
4272                         log_error("Failed to fork: %m");
4273                         free(path);
4274                         continue;
4275                 }
4276
4277                 if (pid == 0) {
4278                         char *_argv[2];
4279                         /* Child */
4280
4281                         if (!argv) {
4282                                 _argv[0] = path;
4283                                 _argv[1] = NULL;
4284                                 argv = _argv;
4285                         } else
4286                                 argv[0] = path;
4287
4288                         execv(path, argv);
4289
4290                         log_error("Failed to execute %s: %m", path);
4291                         _exit(EXIT_FAILURE);
4292                 }
4293
4294                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4295
4296                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4297                         log_error("Failed to add PID to set: %s", strerror(-k));
4298                         free(path);
4299                 }
4300         }
4301
4302         while (!hashmap_isempty(pids)) {
4303                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4304                 siginfo_t si;
4305                 char *path;
4306
4307                 zero(si);
4308                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4309
4310                         if (errno == EINTR)
4311                                 continue;
4312
4313                         log_error("waitid() failed: %m");
4314                         goto finish;
4315                 }
4316
4317                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4318                         if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4319                                 if (si.si_code == CLD_EXITED)
4320                                         log_error("%s exited with exit status %i.", path, si.si_status);
4321                                 else
4322                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4323                         } else
4324                                 log_debug("%s exited successfully.", path);
4325
4326                         free(path);
4327                 }
4328         }
4329
4330 finish:
4331         if (_d)
4332                 closedir(_d);
4333
4334         if (pids)
4335                 hashmap_free_free(pids);
4336 }
4337
4338 int kill_and_sigcont(pid_t pid, int sig) {
4339         int r;
4340
4341         r = kill(pid, sig) < 0 ? -errno : 0;
4342
4343         if (r >= 0)
4344                 kill(pid, SIGCONT);
4345
4346         return r;
4347 }
4348
4349 bool nulstr_contains(const char*nulstr, const char *needle) {
4350         const char *i;
4351
4352         if (!nulstr)
4353                 return false;
4354
4355         NULSTR_FOREACH(i, nulstr)
4356                 if (streq(i, needle))
4357                         return true;
4358
4359         return false;
4360 }
4361
4362 bool plymouth_running(void) {
4363         return access("/run/plymouth/pid", F_OK) >= 0;
4364 }
4365
4366 char* strshorten(char *s, size_t l) {
4367         assert(s);
4368
4369         if (l < strlen(s))
4370                 s[l] = 0;
4371
4372         return s;
4373 }
4374
4375 static bool hostname_valid_char(char c) {
4376         return
4377                 (c >= 'a' && c <= 'z') ||
4378                 (c >= 'A' && c <= 'Z') ||
4379                 (c >= '0' && c <= '9') ||
4380                 c == '-' ||
4381                 c == '_' ||
4382                 c == '.';
4383 }
4384
4385 bool hostname_is_valid(const char *s) {
4386         const char *p;
4387
4388         if (isempty(s))
4389                 return false;
4390
4391         for (p = s; *p; p++)
4392                 if (!hostname_valid_char(*p))
4393                         return false;
4394
4395         if (p-s > HOST_NAME_MAX)
4396                 return false;
4397
4398         return true;
4399 }
4400
4401 char* hostname_cleanup(char *s) {
4402         char *p, *d;
4403
4404         for (p = s, d = s; *p; p++)
4405                 if ((*p >= 'a' && *p <= 'z') ||
4406                     (*p >= 'A' && *p <= 'Z') ||
4407                     (*p >= '0' && *p <= '9') ||
4408                     *p == '-' ||
4409                     *p == '_' ||
4410                     *p == '.')
4411                         *(d++) = *p;
4412
4413         *d = 0;
4414
4415         strshorten(s, HOST_NAME_MAX);
4416         return s;
4417 }
4418
4419 int pipe_eof(int fd) {
4420         struct pollfd pollfd;
4421         int r;
4422
4423         zero(pollfd);
4424         pollfd.fd = fd;
4425         pollfd.events = POLLIN|POLLHUP;
4426
4427         r = poll(&pollfd, 1, 0);
4428         if (r < 0)
4429                 return -errno;
4430
4431         if (r == 0)
4432                 return 0;
4433
4434         return pollfd.revents & POLLHUP;
4435 }
4436
4437 int fd_wait_for_event(int fd, int event, usec_t t) {
4438         struct pollfd pollfd;
4439         int r;
4440
4441         zero(pollfd);
4442         pollfd.fd = fd;
4443         pollfd.events = event;
4444
4445         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4446         if (r < 0)
4447                 return -errno;
4448
4449         if (r == 0)
4450                 return 0;
4451
4452         return pollfd.revents;
4453 }
4454
4455 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4456         FILE *f;
4457         char *t;
4458         const char *fn;
4459         size_t k;
4460         int fd;
4461
4462         assert(path);
4463         assert(_f);
4464         assert(_temp_path);
4465
4466         t = new(char, strlen(path) + 1 + 6 + 1);
4467         if (!t)
4468                 return -ENOMEM;
4469
4470         fn = path_get_file_name(path);
4471         k = fn-path;
4472         memcpy(t, path, k);
4473         t[k] = '.';
4474         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4475
4476         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4477         if (fd < 0) {
4478                 free(t);
4479                 return -errno;
4480         }
4481
4482         f = fdopen(fd, "we");
4483         if (!f) {
4484                 unlink(t);
4485                 free(t);
4486                 return -errno;
4487         }
4488
4489         *_f = f;
4490         *_temp_path = t;
4491
4492         return 0;
4493 }
4494
4495 int terminal_vhangup_fd(int fd) {
4496         assert(fd >= 0);
4497
4498         if (ioctl(fd, TIOCVHANGUP) < 0)
4499                 return -errno;
4500
4501         return 0;
4502 }
4503
4504 int terminal_vhangup(const char *name) {
4505         int fd, r;
4506
4507         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4508         if (fd < 0)
4509                 return fd;
4510
4511         r = terminal_vhangup_fd(fd);
4512         close_nointr_nofail(fd);
4513
4514         return r;
4515 }
4516
4517 int vt_disallocate(const char *name) {
4518         int fd, r;
4519         unsigned u;
4520
4521         /* Deallocate the VT if possible. If not possible
4522          * (i.e. because it is the active one), at least clear it
4523          * entirely (including the scrollback buffer) */
4524
4525         if (!startswith(name, "/dev/"))
4526                 return -EINVAL;
4527
4528         if (!tty_is_vc(name)) {
4529                 /* So this is not a VT. I guess we cannot deallocate
4530                  * it then. But let's at least clear the screen */
4531
4532                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4533                 if (fd < 0)
4534                         return fd;
4535
4536                 loop_write(fd,
4537                            "\033[r"    /* clear scrolling region */
4538                            "\033[H"    /* move home */
4539                            "\033[2J",  /* clear screen */
4540                            10, false);
4541                 close_nointr_nofail(fd);
4542
4543                 return 0;
4544         }
4545
4546         if (!startswith(name, "/dev/tty"))
4547                 return -EINVAL;
4548
4549         r = safe_atou(name+8, &u);
4550         if (r < 0)
4551                 return r;
4552
4553         if (u <= 0)
4554                 return -EINVAL;
4555
4556         /* Try to deallocate */
4557         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4558         if (fd < 0)
4559                 return fd;
4560
4561         r = ioctl(fd, VT_DISALLOCATE, u);
4562         close_nointr_nofail(fd);
4563
4564         if (r >= 0)
4565                 return 0;
4566
4567         if (errno != EBUSY)
4568                 return -errno;
4569
4570         /* Couldn't deallocate, so let's clear it fully with
4571          * scrollback */
4572         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4573         if (fd < 0)
4574                 return fd;
4575
4576         loop_write(fd,
4577                    "\033[r"   /* clear scrolling region */
4578                    "\033[H"   /* move home */
4579                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4580                    10, false);
4581         close_nointr_nofail(fd);
4582
4583         return 0;
4584 }
4585
4586 int copy_file(const char *from, const char *to) {
4587         int r, fdf, fdt;
4588
4589         assert(from);
4590         assert(to);
4591
4592         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4593         if (fdf < 0)
4594                 return -errno;
4595
4596         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4597         if (fdt < 0) {
4598                 close_nointr_nofail(fdf);
4599                 return -errno;
4600         }
4601
4602         for (;;) {
4603                 char buf[PIPE_BUF];
4604                 ssize_t n, k;
4605
4606                 n = read(fdf, buf, sizeof(buf));
4607                 if (n < 0) {
4608                         r = -errno;
4609
4610                         close_nointr_nofail(fdf);
4611                         close_nointr(fdt);
4612                         unlink(to);
4613
4614                         return r;
4615                 }
4616
4617                 if (n == 0)
4618                         break;
4619
4620                 errno = 0;
4621                 k = loop_write(fdt, buf, n, false);
4622                 if (n != k) {
4623                         r = k < 0 ? k : (errno ? -errno : -EIO);
4624
4625                         close_nointr_nofail(fdf);
4626                         close_nointr(fdt);
4627
4628                         unlink(to);
4629                         return r;
4630                 }
4631         }
4632
4633         close_nointr_nofail(fdf);
4634         r = close_nointr(fdt);
4635
4636         if (r < 0) {
4637                 unlink(to);
4638                 return r;
4639         }
4640
4641         return 0;
4642 }
4643
4644 int symlink_atomic(const char *from, const char *to) {
4645         char *x;
4646         _cleanup_free_ char *t;
4647         const char *fn;
4648         size_t k;
4649         unsigned long long ull;
4650         unsigned i;
4651         int r;
4652
4653         assert(from);
4654         assert(to);
4655
4656         t = new(char, strlen(to) + 1 + 16 + 1);
4657         if (!t)
4658                 return -ENOMEM;
4659
4660         fn = path_get_file_name(to);
4661         k = fn-to;
4662         memcpy(t, to, k);
4663         t[k] = '.';
4664         x = stpcpy(t+k+1, fn);
4665
4666         ull = random_ull();
4667         for (i = 0; i < 16; i++) {
4668                 *(x++) = hexchar(ull & 0xF);
4669                 ull >>= 4;
4670         }
4671
4672         *x = 0;
4673
4674         if (symlink(from, t) < 0)
4675                 return -errno;
4676
4677         if (rename(t, to) < 0) {
4678                 r = -errno;
4679                 unlink(t);
4680                 return r;
4681         }
4682
4683         return 0;
4684 }
4685
4686 bool display_is_local(const char *display) {
4687         assert(display);
4688
4689         return
4690                 display[0] == ':' &&
4691                 display[1] >= '0' &&
4692                 display[1] <= '9';
4693 }
4694
4695 int socket_from_display(const char *display, char **path) {
4696         size_t k;
4697         char *f, *c;
4698
4699         assert(display);
4700         assert(path);
4701
4702         if (!display_is_local(display))
4703                 return -EINVAL;
4704
4705         k = strspn(display+1, "0123456789");
4706
4707         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4708         if (!f)
4709                 return -ENOMEM;
4710
4711         c = stpcpy(f, "/tmp/.X11-unix/X");
4712         memcpy(c, display+1, k);
4713         c[k] = 0;
4714
4715         *path = f;
4716
4717         return 0;
4718 }
4719
4720 int get_user_creds(
4721                 const char **username,
4722                 uid_t *uid, gid_t *gid,
4723                 const char **home,
4724                 const char **shell) {
4725
4726         struct passwd *p;
4727         uid_t u;
4728
4729         assert(username);
4730         assert(*username);
4731
4732         /* We enforce some special rules for uid=0: in order to avoid
4733          * NSS lookups for root we hardcode its data. */
4734
4735         if (streq(*username, "root") || streq(*username, "0")) {
4736                 *username = "root";
4737
4738                 if (uid)
4739                         *uid = 0;
4740
4741                 if (gid)
4742                         *gid = 0;
4743
4744                 if (home)
4745                         *home = "/root";
4746
4747                 if (shell)
4748                         *shell = "/bin/sh";
4749
4750                 return 0;
4751         }
4752
4753         if (parse_uid(*username, &u) >= 0) {
4754                 errno = 0;
4755                 p = getpwuid(u);
4756
4757                 /* If there are multiple users with the same id, make
4758                  * sure to leave $USER to the configured value instead
4759                  * of the first occurrence in the database. However if
4760                  * the uid was configured by a numeric uid, then let's
4761                  * pick the real username from /etc/passwd. */
4762                 if (p)
4763                         *username = p->pw_name;
4764         } else {
4765                 errno = 0;
4766                 p = getpwnam(*username);
4767         }
4768
4769         if (!p)
4770                 return errno != 0 ? -errno : -ESRCH;
4771
4772         if (uid)
4773                 *uid = p->pw_uid;
4774
4775         if (gid)
4776                 *gid = p->pw_gid;
4777
4778         if (home)
4779                 *home = p->pw_dir;
4780
4781         if (shell)
4782                 *shell = p->pw_shell;
4783
4784         return 0;
4785 }
4786
4787 int get_group_creds(const char **groupname, gid_t *gid) {
4788         struct group *g;
4789         gid_t id;
4790
4791         assert(groupname);
4792
4793         /* We enforce some special rules for gid=0: in order to avoid
4794          * NSS lookups for root we hardcode its data. */
4795
4796         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4797                 *groupname = "root";
4798
4799                 if (gid)
4800                         *gid = 0;
4801
4802                 return 0;
4803         }
4804
4805         if (parse_gid(*groupname, &id) >= 0) {
4806                 errno = 0;
4807                 g = getgrgid(id);
4808
4809                 if (g)
4810                         *groupname = g->gr_name;
4811         } else {
4812                 errno = 0;
4813                 g = getgrnam(*groupname);
4814         }
4815
4816         if (!g)
4817                 return errno != 0 ? -errno : -ESRCH;
4818
4819         if (gid)
4820                 *gid = g->gr_gid;
4821
4822         return 0;
4823 }
4824
4825 int in_group(const char *name) {
4826         gid_t gid, *gids;
4827         int ngroups_max, r, i;
4828
4829         r = get_group_creds(&name, &gid);
4830         if (r < 0)
4831                 return r;
4832
4833         if (getgid() == gid)
4834                 return 1;
4835
4836         if (getegid() == gid)
4837                 return 1;
4838
4839         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4840         assert(ngroups_max > 0);
4841
4842         gids = alloca(sizeof(gid_t) * ngroups_max);
4843
4844         r = getgroups(ngroups_max, gids);
4845         if (r < 0)
4846                 return -errno;
4847
4848         for (i = 0; i < r; i++)
4849                 if (gids[i] == gid)
4850                         return 1;
4851
4852         return 0;
4853 }
4854
4855 int glob_exists(const char *path) {
4856         glob_t g;
4857         int r, k;
4858
4859         assert(path);
4860
4861         zero(g);
4862         errno = 0;
4863         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4864
4865         if (k == GLOB_NOMATCH)
4866                 r = 0;
4867         else if (k == GLOB_NOSPACE)
4868                 r = -ENOMEM;
4869         else if (k == 0)
4870                 r = !strv_isempty(g.gl_pathv);
4871         else
4872                 r = errno ? -errno : -EIO;
4873
4874         globfree(&g);
4875
4876         return r;
4877 }
4878
4879 int dirent_ensure_type(DIR *d, struct dirent *de) {
4880         struct stat st;
4881
4882         assert(d);
4883         assert(de);
4884
4885         if (de->d_type != DT_UNKNOWN)
4886                 return 0;
4887
4888         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4889                 return -errno;
4890
4891         de->d_type =
4892                 S_ISREG(st.st_mode)  ? DT_REG  :
4893                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4894                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4895                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4896                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4897                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4898                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4899                                        DT_UNKNOWN;
4900
4901         return 0;
4902 }
4903
4904 int in_search_path(const char *path, char **search) {
4905         char **i, *parent;
4906         int r;
4907
4908         r = path_get_parent(path, &parent);
4909         if (r < 0)
4910                 return r;
4911
4912         r = 0;
4913
4914         STRV_FOREACH(i, search) {
4915                 if (path_equal(parent, *i)) {
4916                         r = 1;
4917                         break;
4918                 }
4919         }
4920
4921         free(parent);
4922
4923         return r;
4924 }
4925
4926 int get_files_in_directory(const char *path, char ***list) {
4927         DIR *d;
4928         int r = 0;
4929         unsigned n = 0;
4930         char **l = NULL;
4931
4932         assert(path);
4933
4934         /* Returns all files in a directory in *list, and the number
4935          * of files as return value. If list is NULL returns only the
4936          * number */
4937
4938         d = opendir(path);
4939         if (!d)
4940                 return -errno;
4941
4942         for (;;) {
4943                 struct dirent buffer, *de;
4944                 int k;
4945
4946                 k = readdir_r(d, &buffer, &de);
4947                 if (k != 0) {
4948                         r = -k;
4949                         goto finish;
4950                 }
4951
4952                 if (!de)
4953                         break;
4954
4955                 dirent_ensure_type(d, de);
4956
4957                 if (!dirent_is_file(de))
4958                         continue;
4959
4960                 if (list) {
4961                         if ((unsigned) r >= n) {
4962                                 char **t;
4963
4964                                 n = MAX(16, 2*r);
4965                                 t = realloc(l, sizeof(char*) * n);
4966                                 if (!t) {
4967                                         r = -ENOMEM;
4968                                         goto finish;
4969                                 }
4970
4971                                 l = t;
4972                         }
4973
4974                         assert((unsigned) r < n);
4975
4976                         l[r] = strdup(de->d_name);
4977                         if (!l[r]) {
4978                                 r = -ENOMEM;
4979                                 goto finish;
4980                         }
4981
4982                         l[++r] = NULL;
4983                 } else
4984                         r++;
4985         }
4986
4987 finish:
4988         if (d)
4989                 closedir(d);
4990
4991         if (r >= 0) {
4992                 if (list)
4993                         *list = l;
4994         } else
4995                 strv_free(l);
4996
4997         return r;
4998 }
4999
5000 char *strjoin(const char *x, ...) {
5001         va_list ap;
5002         size_t l;
5003         char *r, *p;
5004
5005         va_start(ap, x);
5006
5007         if (x) {
5008                 l = strlen(x);
5009
5010                 for (;;) {
5011                         const char *t;
5012
5013                         t = va_arg(ap, const char *);
5014                         if (!t)
5015                                 break;
5016
5017                         l += strlen(t);
5018                 }
5019         } else
5020                 l = 0;
5021
5022         va_end(ap);
5023
5024         r = new(char, l+1);
5025         if (!r)
5026                 return NULL;
5027
5028         if (x) {
5029                 p = stpcpy(r, x);
5030
5031                 va_start(ap, x);
5032
5033                 for (;;) {
5034                         const char *t;
5035
5036                         t = va_arg(ap, const char *);
5037                         if (!t)
5038                                 break;
5039
5040                         p = stpcpy(p, t);
5041                 }
5042
5043                 va_end(ap);
5044         } else
5045                 r[0] = 0;
5046
5047         return r;
5048 }
5049
5050 bool is_main_thread(void) {
5051         static __thread int cached = 0;
5052
5053         if (_unlikely_(cached == 0))
5054                 cached = getpid() == gettid() ? 1 : -1;
5055
5056         return cached > 0;
5057 }
5058
5059 int block_get_whole_disk(dev_t d, dev_t *ret) {
5060         char *p, *s;
5061         int r;
5062         unsigned n, m;
5063
5064         assert(ret);
5065
5066         /* If it has a queue this is good enough for us */
5067         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5068                 return -ENOMEM;
5069
5070         r = access(p, F_OK);
5071         free(p);
5072
5073         if (r >= 0) {
5074                 *ret = d;
5075                 return 0;
5076         }
5077
5078         /* If it is a partition find the originating device */
5079         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5080                 return -ENOMEM;
5081
5082         r = access(p, F_OK);
5083         free(p);
5084
5085         if (r < 0)
5086                 return -ENOENT;
5087
5088         /* Get parent dev_t */
5089         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5090                 return -ENOMEM;
5091
5092         r = read_one_line_file(p, &s);
5093         free(p);
5094
5095         if (r < 0)
5096                 return r;
5097
5098         r = sscanf(s, "%u:%u", &m, &n);
5099         free(s);
5100
5101         if (r != 2)
5102                 return -EINVAL;
5103
5104         /* Only return this if it is really good enough for us. */
5105         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5106                 return -ENOMEM;
5107
5108         r = access(p, F_OK);
5109         free(p);
5110
5111         if (r >= 0) {
5112                 *ret = makedev(m, n);
5113                 return 0;
5114         }
5115
5116         return -ENOENT;
5117 }
5118
5119 int file_is_priv_sticky(const char *p) {
5120         struct stat st;
5121
5122         assert(p);
5123
5124         if (lstat(p, &st) < 0)
5125                 return -errno;
5126
5127         return
5128                 (st.st_uid == 0 || st.st_uid == getuid()) &&
5129                 (st.st_mode & S_ISVTX);
5130 }
5131
5132 static const char *const ioprio_class_table[] = {
5133         [IOPRIO_CLASS_NONE] = "none",
5134         [IOPRIO_CLASS_RT] = "realtime",
5135         [IOPRIO_CLASS_BE] = "best-effort",
5136         [IOPRIO_CLASS_IDLE] = "idle"
5137 };
5138
5139 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5140
5141 static const char *const sigchld_code_table[] = {
5142         [CLD_EXITED] = "exited",
5143         [CLD_KILLED] = "killed",
5144         [CLD_DUMPED] = "dumped",
5145         [CLD_TRAPPED] = "trapped",
5146         [CLD_STOPPED] = "stopped",
5147         [CLD_CONTINUED] = "continued",
5148 };
5149
5150 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5151
5152 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5153         [LOG_FAC(LOG_KERN)] = "kern",
5154         [LOG_FAC(LOG_USER)] = "user",
5155         [LOG_FAC(LOG_MAIL)] = "mail",
5156         [LOG_FAC(LOG_DAEMON)] = "daemon",
5157         [LOG_FAC(LOG_AUTH)] = "auth",
5158         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5159         [LOG_FAC(LOG_LPR)] = "lpr",
5160         [LOG_FAC(LOG_NEWS)] = "news",
5161         [LOG_FAC(LOG_UUCP)] = "uucp",
5162         [LOG_FAC(LOG_CRON)] = "cron",
5163         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5164         [LOG_FAC(LOG_FTP)] = "ftp",
5165         [LOG_FAC(LOG_LOCAL0)] = "local0",
5166         [LOG_FAC(LOG_LOCAL1)] = "local1",
5167         [LOG_FAC(LOG_LOCAL2)] = "local2",
5168         [LOG_FAC(LOG_LOCAL3)] = "local3",
5169         [LOG_FAC(LOG_LOCAL4)] = "local4",
5170         [LOG_FAC(LOG_LOCAL5)] = "local5",
5171         [LOG_FAC(LOG_LOCAL6)] = "local6",
5172         [LOG_FAC(LOG_LOCAL7)] = "local7"
5173 };
5174
5175 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5176
5177 static const char *const log_level_table[] = {
5178         [LOG_EMERG] = "emerg",
5179         [LOG_ALERT] = "alert",
5180         [LOG_CRIT] = "crit",
5181         [LOG_ERR] = "err",
5182         [LOG_WARNING] = "warning",
5183         [LOG_NOTICE] = "notice",
5184         [LOG_INFO] = "info",
5185         [LOG_DEBUG] = "debug"
5186 };
5187
5188 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5189
5190 static const char* const sched_policy_table[] = {
5191         [SCHED_OTHER] = "other",
5192         [SCHED_BATCH] = "batch",
5193         [SCHED_IDLE] = "idle",
5194         [SCHED_FIFO] = "fifo",
5195         [SCHED_RR] = "rr"
5196 };
5197
5198 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5199
5200 static const char* const rlimit_table[] = {
5201         [RLIMIT_CPU] = "LimitCPU",
5202         [RLIMIT_FSIZE] = "LimitFSIZE",
5203         [RLIMIT_DATA] = "LimitDATA",
5204         [RLIMIT_STACK] = "LimitSTACK",
5205         [RLIMIT_CORE] = "LimitCORE",
5206         [RLIMIT_RSS] = "LimitRSS",
5207         [RLIMIT_NOFILE] = "LimitNOFILE",
5208         [RLIMIT_AS] = "LimitAS",
5209         [RLIMIT_NPROC] = "LimitNPROC",
5210         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5211         [RLIMIT_LOCKS] = "LimitLOCKS",
5212         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5213         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5214         [RLIMIT_NICE] = "LimitNICE",
5215         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5216         [RLIMIT_RTTIME] = "LimitRTTIME"
5217 };
5218
5219 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5220
5221 static const char* const ip_tos_table[] = {
5222         [IPTOS_LOWDELAY] = "low-delay",
5223         [IPTOS_THROUGHPUT] = "throughput",
5224         [IPTOS_RELIABILITY] = "reliability",
5225         [IPTOS_LOWCOST] = "low-cost",
5226 };
5227
5228 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5229
5230 static const char *const __signal_table[] = {
5231         [SIGHUP] = "HUP",
5232         [SIGINT] = "INT",
5233         [SIGQUIT] = "QUIT",
5234         [SIGILL] = "ILL",
5235         [SIGTRAP] = "TRAP",
5236         [SIGABRT] = "ABRT",
5237         [SIGBUS] = "BUS",
5238         [SIGFPE] = "FPE",
5239         [SIGKILL] = "KILL",
5240         [SIGUSR1] = "USR1",
5241         [SIGSEGV] = "SEGV",
5242         [SIGUSR2] = "USR2",
5243         [SIGPIPE] = "PIPE",
5244         [SIGALRM] = "ALRM",
5245         [SIGTERM] = "TERM",
5246 #ifdef SIGSTKFLT
5247         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5248 #endif
5249         [SIGCHLD] = "CHLD",
5250         [SIGCONT] = "CONT",
5251         [SIGSTOP] = "STOP",
5252         [SIGTSTP] = "TSTP",
5253         [SIGTTIN] = "TTIN",
5254         [SIGTTOU] = "TTOU",
5255         [SIGURG] = "URG",
5256         [SIGXCPU] = "XCPU",
5257         [SIGXFSZ] = "XFSZ",
5258         [SIGVTALRM] = "VTALRM",
5259         [SIGPROF] = "PROF",
5260         [SIGWINCH] = "WINCH",
5261         [SIGIO] = "IO",
5262         [SIGPWR] = "PWR",
5263         [SIGSYS] = "SYS"
5264 };
5265
5266 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5267
5268 const char *signal_to_string(int signo) {
5269         static __thread char buf[12];
5270         const char *name;
5271
5272         name = __signal_to_string(signo);
5273         if (name)
5274                 return name;
5275
5276         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5277                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5278         else
5279                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5280         char_array_0(buf);
5281         return buf;
5282 }
5283
5284 int signal_from_string(const char *s) {
5285         int signo;
5286         int offset = 0;
5287         unsigned u;
5288
5289         signo =__signal_from_string(s);
5290         if (signo > 0)
5291                 return signo;
5292
5293         if (startswith(s, "RTMIN+")) {
5294                 s += 6;
5295                 offset = SIGRTMIN;
5296         }
5297         if (safe_atou(s, &u) >= 0) {
5298                 signo = (int) u + offset;
5299                 if (signo > 0 && signo < _NSIG)
5300                         return signo;
5301         }
5302         return -1;
5303 }
5304
5305 bool kexec_loaded(void) {
5306        bool loaded = false;
5307        char *s;
5308
5309        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5310                if (s[0] == '1')
5311                        loaded = true;
5312                free(s);
5313        }
5314        return loaded;
5315 }
5316
5317 int strdup_or_null(const char *a, char **b) {
5318         char *c;
5319
5320         assert(b);
5321
5322         if (!a) {
5323                 *b = NULL;
5324                 return 0;
5325         }
5326
5327         c = strdup(a);
5328         if (!c)
5329                 return -ENOMEM;
5330
5331         *b = c;
5332         return 0;
5333 }
5334
5335 int prot_from_flags(int flags) {
5336
5337         switch (flags & O_ACCMODE) {
5338
5339         case O_RDONLY:
5340                 return PROT_READ;
5341
5342         case O_WRONLY:
5343                 return PROT_WRITE;
5344
5345         case O_RDWR:
5346                 return PROT_READ|PROT_WRITE;
5347
5348         default:
5349                 return -EINVAL;
5350         }
5351 }
5352
5353 char *format_bytes(char *buf, size_t l, off_t t) {
5354         unsigned i;
5355
5356         static const struct {
5357                 const char *suffix;
5358                 off_t factor;
5359         } table[] = {
5360                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5361                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5362                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5363                 { "G", 1024ULL*1024ULL*1024ULL },
5364                 { "M", 1024ULL*1024ULL },
5365                 { "K", 1024ULL },
5366         };
5367
5368         for (i = 0; i < ELEMENTSOF(table); i++) {
5369
5370                 if (t >= table[i].factor) {
5371                         snprintf(buf, l,
5372                                  "%llu.%llu%s",
5373                                  (unsigned long long) (t / table[i].factor),
5374                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5375                                  table[i].suffix);
5376
5377                         goto finish;
5378                 }
5379         }
5380
5381         snprintf(buf, l, "%lluB", (unsigned long long) t);
5382
5383 finish:
5384         buf[l-1] = 0;
5385         return buf;
5386
5387 }
5388
5389 void* memdup(const void *p, size_t l) {
5390         void *r;
5391
5392         assert(p);
5393
5394         r = malloc(l);
5395         if (!r)
5396                 return NULL;
5397
5398         memcpy(r, p, l);
5399         return r;
5400 }
5401
5402 int fd_inc_sndbuf(int fd, size_t n) {
5403         int r, value;
5404         socklen_t l = sizeof(value);
5405
5406         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5407         if (r >= 0 &&
5408             l == sizeof(value) &&
5409             (size_t) value >= n*2)
5410                 return 0;
5411
5412         value = (int) n;
5413         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5414         if (r < 0)
5415                 return -errno;
5416
5417         return 1;
5418 }
5419
5420 int fd_inc_rcvbuf(int fd, size_t n) {
5421         int r, value;
5422         socklen_t l = sizeof(value);
5423
5424         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5425         if (r >= 0 &&
5426             l == sizeof(value) &&
5427             (size_t) value >= n*2)
5428                 return 0;
5429
5430         value = (int) n;
5431         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5432         if (r < 0)
5433                 return -errno;
5434
5435         return 1;
5436 }
5437
5438 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5439         pid_t parent_pid, agent_pid;
5440         int fd;
5441         bool stdout_is_tty, stderr_is_tty;
5442         unsigned n, i;
5443         va_list ap;
5444         char **l;
5445
5446         assert(pid);
5447         assert(path);
5448
5449         parent_pid = getpid();
5450
5451         /* Spawns a temporary TTY agent, making sure it goes away when
5452          * we go away */
5453
5454         agent_pid = fork();
5455         if (agent_pid < 0)
5456                 return -errno;
5457
5458         if (agent_pid != 0) {
5459                 *pid = agent_pid;
5460                 return 0;
5461         }
5462
5463         /* In the child:
5464          *
5465          * Make sure the agent goes away when the parent dies */
5466         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5467                 _exit(EXIT_FAILURE);
5468
5469         /* Check whether our parent died before we were able
5470          * to set the death signal */
5471         if (getppid() != parent_pid)
5472                 _exit(EXIT_SUCCESS);
5473
5474         /* Don't leak fds to the agent */
5475         close_all_fds(except, n_except);
5476
5477         stdout_is_tty = isatty(STDOUT_FILENO);
5478         stderr_is_tty = isatty(STDERR_FILENO);
5479
5480         if (!stdout_is_tty || !stderr_is_tty) {
5481                 /* Detach from stdout/stderr. and reopen
5482                  * /dev/tty for them. This is important to
5483                  * ensure that when systemctl is started via
5484                  * popen() or a similar call that expects to
5485                  * read EOF we actually do generate EOF and
5486                  * not delay this indefinitely by because we
5487                  * keep an unused copy of stdin around. */
5488                 fd = open("/dev/tty", O_WRONLY);
5489                 if (fd < 0) {
5490                         log_error("Failed to open /dev/tty: %m");
5491                         _exit(EXIT_FAILURE);
5492                 }
5493
5494                 if (!stdout_is_tty)
5495                         dup2(fd, STDOUT_FILENO);
5496
5497                 if (!stderr_is_tty)
5498                         dup2(fd, STDERR_FILENO);
5499
5500                 if (fd > 2)
5501                         close(fd);
5502         }
5503
5504         /* Count arguments */
5505         va_start(ap, path);
5506         for (n = 0; va_arg(ap, char*); n++)
5507                 ;
5508         va_end(ap);
5509
5510         /* Allocate strv */
5511         l = alloca(sizeof(char *) * (n + 1));
5512
5513         /* Fill in arguments */
5514         va_start(ap, path);
5515         for (i = 0; i <= n; i++)
5516                 l[i] = va_arg(ap, char*);
5517         va_end(ap);
5518
5519         execv(path, l);
5520         _exit(EXIT_FAILURE);
5521 }
5522
5523 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5524         struct rlimit highest, fixed;
5525
5526         assert(rlim);
5527
5528         if (setrlimit(resource, rlim) >= 0)
5529                 return 0;
5530
5531         if (errno != EPERM)
5532                 return -errno;
5533
5534         /* So we failed to set the desired setrlimit, then let's try
5535          * to get as close as we can */
5536         assert_se(getrlimit(resource, &highest) == 0);
5537
5538         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5539         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5540
5541         if (setrlimit(resource, &fixed) < 0)
5542                 return -errno;
5543
5544         return 0;
5545 }
5546
5547 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5548         char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5549         int r;
5550         FILE *f;
5551         bool done = false;
5552         size_t l;
5553
5554         assert(field);
5555         assert(_value);
5556
5557         if (pid == 0)
5558                 pid = getpid();
5559
5560         snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5561         char_array_0(path);
5562
5563         f = fopen(path, "re");
5564         if (!f)
5565                 return -errno;
5566
5567         l = strlen(field);
5568         r = 0;
5569
5570         do {
5571                 char line[LINE_MAX];
5572                 unsigned i;
5573
5574                 for (i = 0; i < sizeof(line)-1; i++) {
5575                         int c;
5576
5577                         c = getc(f);
5578                         if (_unlikely_(c == EOF)) {
5579                                 done = true;
5580                                 break;
5581                         } else if (c == 0)
5582                                 break;
5583
5584                         line[i] = c;
5585                 }
5586                 line[i] = 0;
5587
5588                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5589                         value = strdup(line + l + 1);
5590                         if (!value) {
5591                                 r = -ENOMEM;
5592                                 break;
5593                         }
5594
5595                         r = 1;
5596                         break;
5597                 }
5598
5599         } while (!done);
5600
5601         fclose(f);
5602
5603         if (r >= 0)
5604                 *_value = value;
5605
5606         return r;
5607 }
5608
5609 int can_sleep(const char *type) {
5610         char *w, *state;
5611         size_t l, k;
5612         int r;
5613         _cleanup_free_ char *p = NULL;
5614
5615         assert(type);
5616
5617         r = read_one_line_file("/sys/power/state", &p);
5618         if (r < 0)
5619                 return r == -ENOENT ? 0 : r;
5620
5621         k = strlen(type);
5622         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5623                 if (l == k && memcmp(w, type, l) == 0)
5624                         return true;
5625
5626         return false;
5627 }
5628
5629 bool is_valid_documentation_url(const char *url) {
5630         assert(url);
5631
5632         if (startswith(url, "http://") && url[7])
5633                 return true;
5634
5635         if (startswith(url, "https://") && url[8])
5636                 return true;
5637
5638         if (startswith(url, "file:") && url[5])
5639                 return true;
5640
5641         if (startswith(url, "info:") && url[5])
5642                 return true;
5643
5644         if (startswith(url, "man:") && url[4])
5645                 return true;
5646
5647         return false;
5648 }
5649
5650 bool in_initrd(void) {
5651         static __thread int saved = -1;
5652         struct statfs s;
5653
5654         if (saved >= 0)
5655                 return saved;
5656
5657         /* We make two checks here:
5658          *
5659          * 1. the flag file /etc/initrd-release must exist
5660          * 2. the root file system must be a memory file system
5661          *
5662          * The second check is extra paranoia, since misdetecting an
5663          * initrd can have bad bad consequences due the initrd
5664          * emptying when transititioning to the main systemd.
5665          */
5666
5667         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5668                 statfs("/", &s) >= 0 &&
5669                 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5670
5671         return saved;
5672 }
5673
5674 void warn_melody(void) {
5675         _cleanup_close_ int fd = -1;
5676
5677         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5678         if (fd < 0)
5679                 return;
5680
5681         /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5682
5683         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5684         usleep(125*USEC_PER_MSEC);
5685
5686         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5687         usleep(125*USEC_PER_MSEC);
5688
5689         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5690         usleep(125*USEC_PER_MSEC);
5691
5692         ioctl(fd, KIOCSOUND, 0);
5693 }
5694
5695 int make_console_stdio(void) {
5696         int fd, r;
5697
5698         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5699
5700         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5701         if (fd < 0) {
5702                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5703                 return fd;
5704         }
5705
5706         r = make_stdio(fd);
5707         if (r < 0) {
5708                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5709                 return r;
5710         }
5711
5712         return 0;
5713 }
5714
5715 int get_home_dir(char **_h) {
5716         char *h;
5717         const char *e;
5718         uid_t u;
5719         struct passwd *p;
5720
5721         assert(_h);
5722
5723         /* Take the user specified one */
5724         e = getenv("HOME");
5725         if (e) {
5726                 h = strdup(e);
5727                 if (!h)
5728                         return -ENOMEM;
5729
5730                 *_h = h;
5731                 return 0;
5732         }
5733
5734         /* Hardcode home directory for root to avoid NSS */
5735         u = getuid();
5736         if (u == 0) {
5737                 h = strdup("/root");
5738                 if (!h)
5739                         return -ENOMEM;
5740
5741                 *_h = h;
5742                 return 0;
5743         }
5744
5745         /* Check the database... */
5746         errno = 0;
5747         p = getpwuid(u);
5748         if (!p)
5749                 return errno ? -errno : -ESRCH;
5750
5751         if (!path_is_absolute(p->pw_dir))
5752                 return -EINVAL;
5753
5754         h = strdup(p->pw_dir);
5755         if (!h)
5756                 return -ENOMEM;
5757
5758         *_h = h;
5759         return 0;
5760 }
5761
5762 int get_shell(char **_sh) {
5763         char *sh;
5764         const char *e;
5765         uid_t u;
5766         struct passwd *p;
5767
5768         assert(_sh);
5769
5770         /* Take the user specified one */
5771         e = getenv("SHELL");
5772         if (e) {
5773                 sh = strdup(e);
5774                 if (!sh)
5775                         return -ENOMEM;
5776
5777                 *_sh = sh;
5778                 return 0;
5779         }
5780
5781         /* Hardcode home directory for root to avoid NSS */
5782         u = getuid();
5783         if (u == 0) {
5784                 sh = strdup("/bin/sh");
5785                 if (!sh)
5786                         return -ENOMEM;
5787
5788                 *_sh = sh;
5789                 return 0;
5790         }
5791
5792         /* Check the database... */
5793         errno = 0;
5794         p = getpwuid(u);
5795         if (!p)
5796                 return errno ? -errno : -ESRCH;
5797
5798         if (!path_is_absolute(p->pw_shell))
5799                 return -EINVAL;
5800
5801         sh = strdup(p->pw_shell);
5802         if (!sh)
5803                 return -ENOMEM;
5804
5805         *_sh = sh;
5806         return 0;
5807 }
5808
5809 void freep(void *p) {
5810         free(*(void**) p);
5811 }
5812
5813 void fclosep(FILE **f) {
5814         if (*f)
5815                 fclose(*f);
5816 }
5817
5818 void closep(int *fd) {
5819         if (*fd >= 0)
5820                 close_nointr_nofail(*fd);
5821 }
5822
5823 void closedirp(DIR **d) {
5824         if (*d)
5825                 closedir(*d);
5826 }
5827
5828 void umaskp(mode_t *u) {
5829         umask(*u);
5830 }