chiark / gitweb /
manager: drop all pending jobs when isolating
[elogind.git] / src / 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 General Public License as published by
10   the Free Software Foundation; either version 2 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   General Public License for more details.
17
18   You should have received a copy of the GNU 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/capability.h>
54
55 #include "macro.h"
56 #include "util.h"
57 #include "ioprio.h"
58 #include "missing.h"
59 #include "log.h"
60 #include "strv.h"
61 #include "label.h"
62 #include "exit-status.h"
63 #include "hashmap.h"
64
65 size_t page_size(void) {
66         static __thread size_t pgsz = 0;
67         long r;
68
69         if (pgsz)
70                 return pgsz;
71
72         assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
73
74         pgsz = (size_t) r;
75
76         return pgsz;
77 }
78
79 bool streq_ptr(const char *a, const char *b) {
80
81         /* Like streq(), but tries to make sense of NULL pointers */
82
83         if (a && b)
84                 return streq(a, b);
85
86         if (!a && !b)
87                 return true;
88
89         return false;
90 }
91
92 usec_t now(clockid_t clock_id) {
93         struct timespec ts;
94
95         assert_se(clock_gettime(clock_id, &ts) == 0);
96
97         return timespec_load(&ts);
98 }
99
100 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
101         assert(ts);
102
103         ts->realtime = now(CLOCK_REALTIME);
104         ts->monotonic = now(CLOCK_MONOTONIC);
105
106         return ts;
107 }
108
109 usec_t timespec_load(const struct timespec *ts) {
110         assert(ts);
111
112         return
113                 (usec_t) ts->tv_sec * USEC_PER_SEC +
114                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
115 }
116
117 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
118         assert(ts);
119
120         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
121         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
122
123         return ts;
124 }
125
126 usec_t timeval_load(const struct timeval *tv) {
127         assert(tv);
128
129         return
130                 (usec_t) tv->tv_sec * USEC_PER_SEC +
131                 (usec_t) tv->tv_usec;
132 }
133
134 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
135         assert(tv);
136
137         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
138         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
139
140         return tv;
141 }
142
143 bool endswith(const char *s, const char *postfix) {
144         size_t sl, pl;
145
146         assert(s);
147         assert(postfix);
148
149         sl = strlen(s);
150         pl = strlen(postfix);
151
152         if (pl == 0)
153                 return true;
154
155         if (sl < pl)
156                 return false;
157
158         return memcmp(s + sl - pl, postfix, pl) == 0;
159 }
160
161 bool startswith(const char *s, const char *prefix) {
162         size_t sl, pl;
163
164         assert(s);
165         assert(prefix);
166
167         sl = strlen(s);
168         pl = strlen(prefix);
169
170         if (pl == 0)
171                 return true;
172
173         if (sl < pl)
174                 return false;
175
176         return memcmp(s, prefix, pl) == 0;
177 }
178
179 bool startswith_no_case(const char *s, const char *prefix) {
180         size_t sl, pl;
181         unsigned i;
182
183         assert(s);
184         assert(prefix);
185
186         sl = strlen(s);
187         pl = strlen(prefix);
188
189         if (pl == 0)
190                 return true;
191
192         if (sl < pl)
193                 return false;
194
195         for(i = 0; i < pl; ++i) {
196                 if (tolower(s[i]) != tolower(prefix[i]))
197                         return false;
198         }
199
200         return true;
201 }
202
203 bool first_word(const char *s, const char *word) {
204         size_t sl, wl;
205
206         assert(s);
207         assert(word);
208
209         sl = strlen(s);
210         wl = strlen(word);
211
212         if (sl < wl)
213                 return false;
214
215         if (wl == 0)
216                 return true;
217
218         if (memcmp(s, word, wl) != 0)
219                 return false;
220
221         return s[wl] == 0 ||
222                 strchr(WHITESPACE, s[wl]);
223 }
224
225 int close_nointr(int fd) {
226         assert(fd >= 0);
227
228         for (;;) {
229                 int r;
230
231                 if ((r = close(fd)) >= 0)
232                         return r;
233
234                 if (errno != EINTR)
235                         return r;
236         }
237 }
238
239 void close_nointr_nofail(int fd) {
240         int saved_errno = errno;
241
242         /* like close_nointr() but cannot fail, and guarantees errno
243          * is unchanged */
244
245         assert_se(close_nointr(fd) == 0);
246
247         errno = saved_errno;
248 }
249
250 void close_many(const int fds[], unsigned n_fd) {
251         unsigned i;
252
253         for (i = 0; i < n_fd; i++)
254                 close_nointr_nofail(fds[i]);
255 }
256
257 int parse_boolean(const char *v) {
258         assert(v);
259
260         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
261                 return 1;
262         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
263                 return 0;
264
265         return -EINVAL;
266 }
267
268 int parse_pid(const char *s, pid_t* ret_pid) {
269         unsigned long ul = 0;
270         pid_t pid;
271         int r;
272
273         assert(s);
274         assert(ret_pid);
275
276         if ((r = safe_atolu(s, &ul)) < 0)
277                 return r;
278
279         pid = (pid_t) ul;
280
281         if ((unsigned long) pid != ul)
282                 return -ERANGE;
283
284         if (pid <= 0)
285                 return -ERANGE;
286
287         *ret_pid = pid;
288         return 0;
289 }
290
291 int safe_atou(const char *s, unsigned *ret_u) {
292         char *x = NULL;
293         unsigned long l;
294
295         assert(s);
296         assert(ret_u);
297
298         errno = 0;
299         l = strtoul(s, &x, 0);
300
301         if (!x || *x || errno)
302                 return errno ? -errno : -EINVAL;
303
304         if ((unsigned long) (unsigned) l != l)
305                 return -ERANGE;
306
307         *ret_u = (unsigned) l;
308         return 0;
309 }
310
311 int safe_atoi(const char *s, int *ret_i) {
312         char *x = NULL;
313         long l;
314
315         assert(s);
316         assert(ret_i);
317
318         errno = 0;
319         l = strtol(s, &x, 0);
320
321         if (!x || *x || errno)
322                 return errno ? -errno : -EINVAL;
323
324         if ((long) (int) l != l)
325                 return -ERANGE;
326
327         *ret_i = (int) l;
328         return 0;
329 }
330
331 int safe_atollu(const char *s, long long unsigned *ret_llu) {
332         char *x = NULL;
333         unsigned long long l;
334
335         assert(s);
336         assert(ret_llu);
337
338         errno = 0;
339         l = strtoull(s, &x, 0);
340
341         if (!x || *x || errno)
342                 return errno ? -errno : -EINVAL;
343
344         *ret_llu = l;
345         return 0;
346 }
347
348 int safe_atolli(const char *s, long long int *ret_lli) {
349         char *x = NULL;
350         long long l;
351
352         assert(s);
353         assert(ret_lli);
354
355         errno = 0;
356         l = strtoll(s, &x, 0);
357
358         if (!x || *x || errno)
359                 return errno ? -errno : -EINVAL;
360
361         *ret_lli = l;
362         return 0;
363 }
364
365 /* Split a string into words. */
366 char *split(const char *c, size_t *l, const char *separator, char **state) {
367         char *current;
368
369         current = *state ? *state : (char*) c;
370
371         if (!*current || *c == 0)
372                 return NULL;
373
374         current += strspn(current, separator);
375         *l = strcspn(current, separator);
376         *state = current+*l;
377
378         return (char*) current;
379 }
380
381 /* Split a string into words, but consider strings enclosed in '' and
382  * "" as words even if they include spaces. */
383 char *split_quoted(const char *c, size_t *l, char **state) {
384         char *current, *e;
385         bool escaped = false;
386
387         current = *state ? *state : (char*) c;
388
389         if (!*current || *c == 0)
390                 return NULL;
391
392         current += strspn(current, WHITESPACE);
393
394         if (*current == '\'') {
395                 current ++;
396
397                 for (e = current; *e; e++) {
398                         if (escaped)
399                                 escaped = false;
400                         else if (*e == '\\')
401                                 escaped = true;
402                         else if (*e == '\'')
403                                 break;
404                 }
405
406                 *l = e-current;
407                 *state = *e == 0 ? e : e+1;
408         } else if (*current == '\"') {
409                 current ++;
410
411                 for (e = current; *e; e++) {
412                         if (escaped)
413                                 escaped = false;
414                         else if (*e == '\\')
415                                 escaped = true;
416                         else if (*e == '\"')
417                                 break;
418                 }
419
420                 *l = e-current;
421                 *state = *e == 0 ? e : e+1;
422         } else {
423                 for (e = current; *e; e++) {
424                         if (escaped)
425                                 escaped = false;
426                         else if (*e == '\\')
427                                 escaped = true;
428                         else if (strchr(WHITESPACE, *e))
429                                 break;
430                 }
431                 *l = e-current;
432                 *state = e;
433         }
434
435         return (char*) current;
436 }
437
438 char **split_path_and_make_absolute(const char *p) {
439         char **l;
440         assert(p);
441
442         if (!(l = strv_split(p, ":")))
443                 return NULL;
444
445         if (!strv_path_make_absolute_cwd(l)) {
446                 strv_free(l);
447                 return NULL;
448         }
449
450         return l;
451 }
452
453 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
454         int r;
455         FILE *f;
456         char fn[PATH_MAX], line[LINE_MAX], *p;
457         long unsigned ppid;
458
459         assert(pid >= 0);
460         assert(_ppid);
461
462         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
463         fn[sizeof(fn)-1] = 0;
464
465         if (!(f = fopen(fn, "r")))
466                 return -errno;
467
468         if (!(fgets(line, sizeof(line), f))) {
469                 r = -errno;
470                 fclose(f);
471                 return r;
472         }
473
474         fclose(f);
475
476         /* Let's skip the pid and comm fields. The latter is enclosed
477          * in () but does not escape any () in its value, so let's
478          * skip over it manually */
479
480         if (!(p = strrchr(line, ')')))
481                 return -EIO;
482
483         p++;
484
485         if (sscanf(p, " "
486                    "%*c "  /* state */
487                    "%lu ", /* ppid */
488                    &ppid) != 1)
489                 return -EIO;
490
491         if ((long unsigned) (pid_t) ppid != ppid)
492                 return -ERANGE;
493
494         *_ppid = (pid_t) ppid;
495
496         return 0;
497 }
498
499 int write_one_line_file(const char *fn, const char *line) {
500         FILE *f;
501         int r;
502
503         assert(fn);
504         assert(line);
505
506         if (!(f = fopen(fn, "we")))
507                 return -errno;
508
509         if (fputs(line, f) < 0) {
510                 r = -errno;
511                 goto finish;
512         }
513
514         if (!endswith(line, "\n"))
515                 fputc('\n', f);
516
517         fflush(f);
518
519         if (ferror(f)) {
520                 if (errno != 0)
521                         r = -errno;
522                 else
523                         r = -EIO;
524         } else
525                 r = 0;
526
527 finish:
528         fclose(f);
529         return r;
530 }
531
532 int read_one_line_file(const char *fn, char **line) {
533         FILE *f;
534         int r;
535         char t[LINE_MAX], *c;
536
537         assert(fn);
538         assert(line);
539
540         if (!(f = fopen(fn, "re")))
541                 return -errno;
542
543         if (!(fgets(t, sizeof(t), f))) {
544                 r = -errno;
545                 goto finish;
546         }
547
548         if (!(c = strdup(t))) {
549                 r = -ENOMEM;
550                 goto finish;
551         }
552
553         *line = c;
554         r = 0;
555
556 finish:
557         fclose(f);
558         return r;
559 }
560
561 int read_full_file(const char *fn, char **contents) {
562         FILE *f;
563         int r;
564         size_t n, l;
565         char *buf = NULL;
566         struct stat st;
567
568         if (!(f = fopen(fn, "re")))
569                 return -errno;
570
571         if (fstat(fileno(f), &st) < 0) {
572                 r = -errno;
573                 goto finish;
574         }
575
576         n = st.st_size > 0 ? st.st_size : LINE_MAX;
577         l = 0;
578
579         for (;;) {
580                 char *t;
581                 size_t k;
582
583                 if (!(t = realloc(buf, n+1))) {
584                         r = -ENOMEM;
585                         goto finish;
586                 }
587
588                 buf = t;
589                 k = fread(buf + l, 1, n - l, f);
590
591                 if (k <= 0) {
592                         if (ferror(f)) {
593                                 r = -errno;
594                                 goto finish;
595                         }
596
597                         break;
598                 }
599
600                 l += k;
601                 n *= 2;
602
603                 /* Safety check */
604                 if (n > 4*1024*1024) {
605                         r = -E2BIG;
606                         goto finish;
607                 }
608         }
609
610         if (buf)
611                 buf[l] = 0;
612         else if (!(buf = calloc(1, 1))) {
613                 r = -errno;
614                 goto finish;
615         }
616
617         *contents = buf;
618         buf = NULL;
619
620         r = 0;
621
622 finish:
623         fclose(f);
624         free(buf);
625
626         return r;
627 }
628
629 int parse_env_file(
630                 const char *fname,
631                 const char *separator, ...) {
632
633         int r = 0;
634         char *contents, *p;
635
636         assert(fname);
637         assert(separator);
638
639         if ((r = read_full_file(fname, &contents)) < 0)
640                 return r;
641
642         p = contents;
643         for (;;) {
644                 const char *key = NULL;
645
646                 p += strspn(p, separator);
647                 p += strspn(p, WHITESPACE);
648
649                 if (!*p)
650                         break;
651
652                 if (!strchr(COMMENTS, *p)) {
653                         va_list ap;
654                         char **value;
655
656                         va_start(ap, separator);
657                         while ((key = va_arg(ap, char *))) {
658                                 size_t n;
659                                 char *v;
660
661                                 value = va_arg(ap, char **);
662
663                                 n = strlen(key);
664                                 if (strncmp(p, key, n) != 0 ||
665                                     p[n] != '=')
666                                         continue;
667
668                                 p += n + 1;
669                                 n = strcspn(p, separator);
670
671                                 if (n >= 2 &&
672                                     strchr(QUOTES, p[0]) &&
673                                     p[n-1] == p[0])
674                                         v = strndup(p+1, n-2);
675                                 else
676                                         v = strndup(p, n);
677
678                                 if (!v) {
679                                         r = -ENOMEM;
680                                         va_end(ap);
681                                         goto fail;
682                                 }
683
684                                 if (v[0] == '\0') {
685                                         /* return empty value strings as NULL */
686                                         free(v);
687                                         v = NULL;
688                                 }
689
690                                 free(*value);
691                                 *value = v;
692
693                                 p += n;
694
695                                 r ++;
696                                 break;
697                         }
698                         va_end(ap);
699                 }
700
701                 if (!key)
702                         p += strcspn(p, separator);
703         }
704
705 fail:
706         free(contents);
707         return r;
708 }
709
710 int load_env_file(
711                 const char *fname,
712                 char ***rl) {
713
714         FILE *f;
715         char **m = 0;
716         int r;
717
718         assert(fname);
719         assert(rl);
720
721         if (!(f = fopen(fname, "re")))
722                 return -errno;
723
724         while (!feof(f)) {
725                 char l[LINE_MAX], *p, *u;
726                 char **t;
727
728                 if (!fgets(l, sizeof(l), f)) {
729                         if (feof(f))
730                                 break;
731
732                         r = -errno;
733                         goto finish;
734                 }
735
736                 p = strstrip(l);
737
738                 if (!*p)
739                         continue;
740
741                 if (strchr(COMMENTS, *p))
742                         continue;
743
744                 if (!(u = normalize_env_assignment(p))) {
745                         log_error("Out of memory");
746                         r = -ENOMEM;
747                         goto finish;
748                 }
749
750                 t = strv_append(m, u);
751                 free(u);
752
753                 if (!t) {
754                         log_error("Out of memory");
755                         r = -ENOMEM;
756                         goto finish;
757                 }
758
759                 strv_free(m);
760                 m = t;
761         }
762
763         r = 0;
764
765         *rl = m;
766         m = NULL;
767
768 finish:
769         if (f)
770                 fclose(f);
771
772         strv_free(m);
773
774         return r;
775 }
776
777 char *truncate_nl(char *s) {
778         assert(s);
779
780         s[strcspn(s, NEWLINE)] = 0;
781         return s;
782 }
783
784 int get_process_name(pid_t pid, char **name) {
785         char *p;
786         int r;
787
788         assert(pid >= 1);
789         assert(name);
790
791         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
792                 return -ENOMEM;
793
794         r = read_one_line_file(p, name);
795         free(p);
796
797         if (r < 0)
798                 return r;
799
800         truncate_nl(*name);
801         return 0;
802 }
803
804 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
805         char *p, *r, *k;
806         int c;
807         bool space = false;
808         size_t left;
809         FILE *f;
810
811         assert(pid >= 1);
812         assert(max_length > 0);
813         assert(line);
814
815         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
816                 return -ENOMEM;
817
818         f = fopen(p, "r");
819         free(p);
820
821         if (!f)
822                 return -errno;
823
824         if (!(r = new(char, max_length))) {
825                 fclose(f);
826                 return -ENOMEM;
827         }
828
829         k = r;
830         left = max_length;
831         while ((c = getc(f)) != EOF) {
832
833                 if (isprint(c)) {
834                         if (space) {
835                                 if (left <= 4)
836                                         break;
837
838                                 *(k++) = ' ';
839                                 left--;
840                                 space = false;
841                         }
842
843                         if (left <= 4)
844                                 break;
845
846                         *(k++) = (char) c;
847                         left--;
848                 }  else
849                         space = true;
850         }
851
852         if (left <= 4) {
853                 size_t n = MIN(left-1, 3U);
854                 memcpy(k, "...", n);
855                 k[n] = 0;
856         } else
857                 *k = 0;
858
859         fclose(f);
860
861         /* Kernel threads have no argv[] */
862         if (r[0] == 0) {
863                 char *t;
864                 int h;
865
866                 free(r);
867
868                 if ((h = get_process_name(pid, &t)) < 0)
869                         return h;
870
871                 h = asprintf(&r, "[%s]", t);
872                 free(t);
873
874                 if (h < 0)
875                         return -ENOMEM;
876         }
877
878         *line = r;
879         return 0;
880 }
881
882 char *strnappend(const char *s, const char *suffix, size_t b) {
883         size_t a;
884         char *r;
885
886         if (!s && !suffix)
887                 return strdup("");
888
889         if (!s)
890                 return strndup(suffix, b);
891
892         if (!suffix)
893                 return strdup(s);
894
895         assert(s);
896         assert(suffix);
897
898         a = strlen(s);
899
900         if (!(r = new(char, a+b+1)))
901                 return NULL;
902
903         memcpy(r, s, a);
904         memcpy(r+a, suffix, b);
905         r[a+b] = 0;
906
907         return r;
908 }
909
910 char *strappend(const char *s, const char *suffix) {
911         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
912 }
913
914 int readlink_malloc(const char *p, char **r) {
915         size_t l = 100;
916
917         assert(p);
918         assert(r);
919
920         for (;;) {
921                 char *c;
922                 ssize_t n;
923
924                 if (!(c = new(char, l)))
925                         return -ENOMEM;
926
927                 if ((n = readlink(p, c, l-1)) < 0) {
928                         int ret = -errno;
929                         free(c);
930                         return ret;
931                 }
932
933                 if ((size_t) n < l-1) {
934                         c[n] = 0;
935                         *r = c;
936                         return 0;
937                 }
938
939                 free(c);
940                 l *= 2;
941         }
942 }
943
944 int readlink_and_make_absolute(const char *p, char **r) {
945         char *target, *k;
946         int j;
947
948         assert(p);
949         assert(r);
950
951         if ((j = readlink_malloc(p, &target)) < 0)
952                 return j;
953
954         k = file_in_same_dir(p, target);
955         free(target);
956
957         if (!k)
958                 return -ENOMEM;
959
960         *r = k;
961         return 0;
962 }
963
964 int parent_of_path(const char *path, char **_r) {
965         const char *e, *a = NULL, *b = NULL, *p;
966         char *r;
967         bool slash = false;
968
969         assert(path);
970         assert(_r);
971
972         if (!*path)
973                 return -EINVAL;
974
975         for (e = path; *e; e++) {
976
977                 if (!slash && *e == '/') {
978                         a = b;
979                         b = e;
980                         slash = true;
981                 } else if (slash && *e != '/')
982                         slash = false;
983         }
984
985         if (*(e-1) == '/')
986                 p = a;
987         else
988                 p = b;
989
990         if (!p)
991                 return -EINVAL;
992
993         if (p == path)
994                 r = strdup("/");
995         else
996                 r = strndup(path, p-path);
997
998         if (!r)
999                 return -ENOMEM;
1000
1001         *_r = r;
1002         return 0;
1003 }
1004
1005
1006 char *file_name_from_path(const char *p) {
1007         char *r;
1008
1009         assert(p);
1010
1011         if ((r = strrchr(p, '/')))
1012                 return r + 1;
1013
1014         return (char*) p;
1015 }
1016
1017 bool path_is_absolute(const char *p) {
1018         assert(p);
1019
1020         return p[0] == '/';
1021 }
1022
1023 bool is_path(const char *p) {
1024
1025         return !!strchr(p, '/');
1026 }
1027
1028 char *path_make_absolute(const char *p, const char *prefix) {
1029         char *r;
1030
1031         assert(p);
1032
1033         /* Makes every item in the list an absolute path by prepending
1034          * the prefix, if specified and necessary */
1035
1036         if (path_is_absolute(p) || !prefix)
1037                 return strdup(p);
1038
1039         if (asprintf(&r, "%s/%s", prefix, p) < 0)
1040                 return NULL;
1041
1042         return r;
1043 }
1044
1045 char *path_make_absolute_cwd(const char *p) {
1046         char *cwd, *r;
1047
1048         assert(p);
1049
1050         /* Similar to path_make_absolute(), but prefixes with the
1051          * current working directory. */
1052
1053         if (path_is_absolute(p))
1054                 return strdup(p);
1055
1056         if (!(cwd = get_current_dir_name()))
1057                 return NULL;
1058
1059         r = path_make_absolute(p, cwd);
1060         free(cwd);
1061
1062         return r;
1063 }
1064
1065 char **strv_path_make_absolute_cwd(char **l) {
1066         char **s;
1067
1068         /* Goes through every item in the string list and makes it
1069          * absolute. This works in place and won't rollback any
1070          * changes on failure. */
1071
1072         STRV_FOREACH(s, l) {
1073                 char *t;
1074
1075                 if (!(t = path_make_absolute_cwd(*s)))
1076                         return NULL;
1077
1078                 free(*s);
1079                 *s = t;
1080         }
1081
1082         return l;
1083 }
1084
1085 char **strv_path_canonicalize(char **l) {
1086         char **s;
1087         unsigned k = 0;
1088         bool enomem = false;
1089
1090         if (strv_isempty(l))
1091                 return l;
1092
1093         /* Goes through every item in the string list and canonicalize
1094          * the path. This works in place and won't rollback any
1095          * changes on failure. */
1096
1097         STRV_FOREACH(s, l) {
1098                 char *t, *u;
1099
1100                 t = path_make_absolute_cwd(*s);
1101                 free(*s);
1102
1103                 if (!t) {
1104                         enomem = true;
1105                         continue;
1106                 }
1107
1108                 errno = 0;
1109                 u = canonicalize_file_name(t);
1110                 free(t);
1111
1112                 if (!u) {
1113                         if (errno == ENOMEM || !errno)
1114                                 enomem = true;
1115
1116                         continue;
1117                 }
1118
1119                 l[k++] = u;
1120         }
1121
1122         l[k] = NULL;
1123
1124         if (enomem)
1125                 return NULL;
1126
1127         return l;
1128 }
1129
1130 int reset_all_signal_handlers(void) {
1131         int sig;
1132
1133         for (sig = 1; sig < _NSIG; sig++) {
1134                 struct sigaction sa;
1135
1136                 if (sig == SIGKILL || sig == SIGSTOP)
1137                         continue;
1138
1139                 zero(sa);
1140                 sa.sa_handler = SIG_DFL;
1141                 sa.sa_flags = SA_RESTART;
1142
1143                 /* On Linux the first two RT signals are reserved by
1144                  * glibc, and sigaction() will return EINVAL for them. */
1145                 if ((sigaction(sig, &sa, NULL) < 0))
1146                         if (errno != EINVAL)
1147                                 return -errno;
1148         }
1149
1150         return 0;
1151 }
1152
1153 char *strstrip(char *s) {
1154         char *e, *l = NULL;
1155
1156         /* Drops trailing whitespace. Modifies the string in
1157          * place. Returns pointer to first non-space character */
1158
1159         s += strspn(s, WHITESPACE);
1160
1161         for (e = s; *e; e++)
1162                 if (!strchr(WHITESPACE, *e))
1163                         l = e;
1164
1165         if (l)
1166                 *(l+1) = 0;
1167         else
1168                 *s = 0;
1169
1170         return s;
1171 }
1172
1173 char *delete_chars(char *s, const char *bad) {
1174         char *f, *t;
1175
1176         /* Drops all whitespace, regardless where in the string */
1177
1178         for (f = s, t = s; *f; f++) {
1179                 if (strchr(bad, *f))
1180                         continue;
1181
1182                 *(t++) = *f;
1183         }
1184
1185         *t = 0;
1186
1187         return s;
1188 }
1189
1190 char *file_in_same_dir(const char *path, const char *filename) {
1191         char *e, *r;
1192         size_t k;
1193
1194         assert(path);
1195         assert(filename);
1196
1197         /* This removes the last component of path and appends
1198          * filename, unless the latter is absolute anyway or the
1199          * former isn't */
1200
1201         if (path_is_absolute(filename))
1202                 return strdup(filename);
1203
1204         if (!(e = strrchr(path, '/')))
1205                 return strdup(filename);
1206
1207         k = strlen(filename);
1208         if (!(r = new(char, e-path+1+k+1)))
1209                 return NULL;
1210
1211         memcpy(r, path, e-path+1);
1212         memcpy(r+(e-path)+1, filename, k+1);
1213
1214         return r;
1215 }
1216
1217 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1218         struct stat st;
1219
1220         if (label_mkdir(path, mode) >= 0)
1221                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1222                         return -errno;
1223
1224         if (lstat(path, &st) < 0)
1225                 return -errno;
1226
1227         if ((st.st_mode & 0777) != mode ||
1228             st.st_uid != uid ||
1229             st.st_gid != gid ||
1230             !S_ISDIR(st.st_mode)) {
1231                 errno = EEXIST;
1232                 return -errno;
1233         }
1234
1235         return 0;
1236 }
1237
1238
1239 int mkdir_parents(const char *path, mode_t mode) {
1240         const char *p, *e;
1241
1242         assert(path);
1243
1244         /* Creates every parent directory in the path except the last
1245          * component. */
1246
1247         p = path + strspn(path, "/");
1248         for (;;) {
1249                 int r;
1250                 char *t;
1251
1252                 e = p + strcspn(p, "/");
1253                 p = e + strspn(e, "/");
1254
1255                 /* Is this the last component? If so, then we're
1256                  * done */
1257                 if (*p == 0)
1258                         return 0;
1259
1260                 if (!(t = strndup(path, e - path)))
1261                         return -ENOMEM;
1262
1263                 r = label_mkdir(t, mode);
1264                 free(t);
1265
1266                 if (r < 0 && errno != EEXIST)
1267                         return -errno;
1268         }
1269 }
1270
1271 int mkdir_p(const char *path, mode_t mode) {
1272         int r;
1273
1274         /* Like mkdir -p */
1275
1276         if ((r = mkdir_parents(path, mode)) < 0)
1277                 return r;
1278
1279         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1280                 return -errno;
1281
1282         return 0;
1283 }
1284
1285 int rmdir_parents(const char *path, const char *stop) {
1286         size_t l;
1287         int r = 0;
1288
1289         assert(path);
1290         assert(stop);
1291
1292         l = strlen(path);
1293
1294         /* Skip trailing slashes */
1295         while (l > 0 && path[l-1] == '/')
1296                 l--;
1297
1298         while (l > 0) {
1299                 char *t;
1300
1301                 /* Skip last component */
1302                 while (l > 0 && path[l-1] != '/')
1303                         l--;
1304
1305                 /* Skip trailing slashes */
1306                 while (l > 0 && path[l-1] == '/')
1307                         l--;
1308
1309                 if (l <= 0)
1310                         break;
1311
1312                 if (!(t = strndup(path, l)))
1313                         return -ENOMEM;
1314
1315                 if (path_startswith(stop, t)) {
1316                         free(t);
1317                         return 0;
1318                 }
1319
1320                 r = rmdir(t);
1321                 free(t);
1322
1323                 if (r < 0)
1324                         if (errno != ENOENT)
1325                                 return -errno;
1326         }
1327
1328         return 0;
1329 }
1330
1331
1332 char hexchar(int x) {
1333         static const char table[16] = "0123456789abcdef";
1334
1335         return table[x & 15];
1336 }
1337
1338 int unhexchar(char c) {
1339
1340         if (c >= '0' && c <= '9')
1341                 return c - '0';
1342
1343         if (c >= 'a' && c <= 'f')
1344                 return c - 'a' + 10;
1345
1346         if (c >= 'A' && c <= 'F')
1347                 return c - 'A' + 10;
1348
1349         return -1;
1350 }
1351
1352 char octchar(int x) {
1353         return '0' + (x & 7);
1354 }
1355
1356 int unoctchar(char c) {
1357
1358         if (c >= '0' && c <= '7')
1359                 return c - '0';
1360
1361         return -1;
1362 }
1363
1364 char decchar(int x) {
1365         return '0' + (x % 10);
1366 }
1367
1368 int undecchar(char c) {
1369
1370         if (c >= '0' && c <= '9')
1371                 return c - '0';
1372
1373         return -1;
1374 }
1375
1376 char *cescape(const char *s) {
1377         char *r, *t;
1378         const char *f;
1379
1380         assert(s);
1381
1382         /* Does C style string escaping. */
1383
1384         if (!(r = new(char, strlen(s)*4 + 1)))
1385                 return NULL;
1386
1387         for (f = s, t = r; *f; f++)
1388
1389                 switch (*f) {
1390
1391                 case '\a':
1392                         *(t++) = '\\';
1393                         *(t++) = 'a';
1394                         break;
1395                 case '\b':
1396                         *(t++) = '\\';
1397                         *(t++) = 'b';
1398                         break;
1399                 case '\f':
1400                         *(t++) = '\\';
1401                         *(t++) = 'f';
1402                         break;
1403                 case '\n':
1404                         *(t++) = '\\';
1405                         *(t++) = 'n';
1406                         break;
1407                 case '\r':
1408                         *(t++) = '\\';
1409                         *(t++) = 'r';
1410                         break;
1411                 case '\t':
1412                         *(t++) = '\\';
1413                         *(t++) = 't';
1414                         break;
1415                 case '\v':
1416                         *(t++) = '\\';
1417                         *(t++) = 'v';
1418                         break;
1419                 case '\\':
1420                         *(t++) = '\\';
1421                         *(t++) = '\\';
1422                         break;
1423                 case '"':
1424                         *(t++) = '\\';
1425                         *(t++) = '"';
1426                         break;
1427                 case '\'':
1428                         *(t++) = '\\';
1429                         *(t++) = '\'';
1430                         break;
1431
1432                 default:
1433                         /* For special chars we prefer octal over
1434                          * hexadecimal encoding, simply because glib's
1435                          * g_strescape() does the same */
1436                         if ((*f < ' ') || (*f >= 127)) {
1437                                 *(t++) = '\\';
1438                                 *(t++) = octchar((unsigned char) *f >> 6);
1439                                 *(t++) = octchar((unsigned char) *f >> 3);
1440                                 *(t++) = octchar((unsigned char) *f);
1441                         } else
1442                                 *(t++) = *f;
1443                         break;
1444                 }
1445
1446         *t = 0;
1447
1448         return r;
1449 }
1450
1451 char *cunescape_length(const char *s, size_t length) {
1452         char *r, *t;
1453         const char *f;
1454
1455         assert(s);
1456
1457         /* Undoes C style string escaping */
1458
1459         if (!(r = new(char, length+1)))
1460                 return r;
1461
1462         for (f = s, t = r; f < s + length; f++) {
1463
1464                 if (*f != '\\') {
1465                         *(t++) = *f;
1466                         continue;
1467                 }
1468
1469                 f++;
1470
1471                 switch (*f) {
1472
1473                 case 'a':
1474                         *(t++) = '\a';
1475                         break;
1476                 case 'b':
1477                         *(t++) = '\b';
1478                         break;
1479                 case 'f':
1480                         *(t++) = '\f';
1481                         break;
1482                 case 'n':
1483                         *(t++) = '\n';
1484                         break;
1485                 case 'r':
1486                         *(t++) = '\r';
1487                         break;
1488                 case 't':
1489                         *(t++) = '\t';
1490                         break;
1491                 case 'v':
1492                         *(t++) = '\v';
1493                         break;
1494                 case '\\':
1495                         *(t++) = '\\';
1496                         break;
1497                 case '"':
1498                         *(t++) = '"';
1499                         break;
1500                 case '\'':
1501                         *(t++) = '\'';
1502                         break;
1503
1504                 case 's':
1505                         /* This is an extension of the XDG syntax files */
1506                         *(t++) = ' ';
1507                         break;
1508
1509                 case 'x': {
1510                         /* hexadecimal encoding */
1511                         int a, b;
1512
1513                         if ((a = unhexchar(f[1])) < 0 ||
1514                             (b = unhexchar(f[2])) < 0) {
1515                                 /* Invalid escape code, let's take it literal then */
1516                                 *(t++) = '\\';
1517                                 *(t++) = 'x';
1518                         } else {
1519                                 *(t++) = (char) ((a << 4) | b);
1520                                 f += 2;
1521                         }
1522
1523                         break;
1524                 }
1525
1526                 case '0':
1527                 case '1':
1528                 case '2':
1529                 case '3':
1530                 case '4':
1531                 case '5':
1532                 case '6':
1533                 case '7': {
1534                         /* octal encoding */
1535                         int a, b, c;
1536
1537                         if ((a = unoctchar(f[0])) < 0 ||
1538                             (b = unoctchar(f[1])) < 0 ||
1539                             (c = unoctchar(f[2])) < 0) {
1540                                 /* Invalid escape code, let's take it literal then */
1541                                 *(t++) = '\\';
1542                                 *(t++) = f[0];
1543                         } else {
1544                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1545                                 f += 2;
1546                         }
1547
1548                         break;
1549                 }
1550
1551                 case 0:
1552                         /* premature end of string.*/
1553                         *(t++) = '\\';
1554                         goto finish;
1555
1556                 default:
1557                         /* Invalid escape code, let's take it literal then */
1558                         *(t++) = '\\';
1559                         *(t++) = *f;
1560                         break;
1561                 }
1562         }
1563
1564 finish:
1565         *t = 0;
1566         return r;
1567 }
1568
1569 char *cunescape(const char *s) {
1570         return cunescape_length(s, strlen(s));
1571 }
1572
1573 char *xescape(const char *s, const char *bad) {
1574         char *r, *t;
1575         const char *f;
1576
1577         /* Escapes all chars in bad, in addition to \ and all special
1578          * chars, in \xFF style escaping. May be reversed with
1579          * cunescape. */
1580
1581         if (!(r = new(char, strlen(s)*4+1)))
1582                 return NULL;
1583
1584         for (f = s, t = r; *f; f++) {
1585
1586                 if ((*f < ' ') || (*f >= 127) ||
1587                     (*f == '\\') || strchr(bad, *f)) {
1588                         *(t++) = '\\';
1589                         *(t++) = 'x';
1590                         *(t++) = hexchar(*f >> 4);
1591                         *(t++) = hexchar(*f);
1592                 } else
1593                         *(t++) = *f;
1594         }
1595
1596         *t = 0;
1597
1598         return r;
1599 }
1600
1601 char *bus_path_escape(const char *s) {
1602         char *r, *t;
1603         const char *f;
1604
1605         assert(s);
1606
1607         /* Escapes all chars that D-Bus' object path cannot deal
1608          * with. Can be reverse with bus_path_unescape() */
1609
1610         if (!(r = new(char, strlen(s)*3+1)))
1611                 return NULL;
1612
1613         for (f = s, t = r; *f; f++) {
1614
1615                 if (!(*f >= 'A' && *f <= 'Z') &&
1616                     !(*f >= 'a' && *f <= 'z') &&
1617                     !(*f >= '0' && *f <= '9')) {
1618                         *(t++) = '_';
1619                         *(t++) = hexchar(*f >> 4);
1620                         *(t++) = hexchar(*f);
1621                 } else
1622                         *(t++) = *f;
1623         }
1624
1625         *t = 0;
1626
1627         return r;
1628 }
1629
1630 char *bus_path_unescape(const char *f) {
1631         char *r, *t;
1632
1633         assert(f);
1634
1635         if (!(r = strdup(f)))
1636                 return NULL;
1637
1638         for (t = r; *f; f++) {
1639
1640                 if (*f == '_') {
1641                         int a, b;
1642
1643                         if ((a = unhexchar(f[1])) < 0 ||
1644                             (b = unhexchar(f[2])) < 0) {
1645                                 /* Invalid escape code, let's take it literal then */
1646                                 *(t++) = '_';
1647                         } else {
1648                                 *(t++) = (char) ((a << 4) | b);
1649                                 f += 2;
1650                         }
1651                 } else
1652                         *(t++) = *f;
1653         }
1654
1655         *t = 0;
1656
1657         return r;
1658 }
1659
1660 char *path_kill_slashes(char *path) {
1661         char *f, *t;
1662         bool slash = false;
1663
1664         /* Removes redundant inner and trailing slashes. Modifies the
1665          * passed string in-place.
1666          *
1667          * ///foo///bar/ becomes /foo/bar
1668          */
1669
1670         for (f = path, t = path; *f; f++) {
1671
1672                 if (*f == '/') {
1673                         slash = true;
1674                         continue;
1675                 }
1676
1677                 if (slash) {
1678                         slash = false;
1679                         *(t++) = '/';
1680                 }
1681
1682                 *(t++) = *f;
1683         }
1684
1685         /* Special rule, if we are talking of the root directory, a
1686         trailing slash is good */
1687
1688         if (t == path && slash)
1689                 *(t++) = '/';
1690
1691         *t = 0;
1692         return path;
1693 }
1694
1695 bool path_startswith(const char *path, const char *prefix) {
1696         assert(path);
1697         assert(prefix);
1698
1699         if ((path[0] == '/') != (prefix[0] == '/'))
1700                 return false;
1701
1702         for (;;) {
1703                 size_t a, b;
1704
1705                 path += strspn(path, "/");
1706                 prefix += strspn(prefix, "/");
1707
1708                 if (*prefix == 0)
1709                         return true;
1710
1711                 if (*path == 0)
1712                         return false;
1713
1714                 a = strcspn(path, "/");
1715                 b = strcspn(prefix, "/");
1716
1717                 if (a != b)
1718                         return false;
1719
1720                 if (memcmp(path, prefix, a) != 0)
1721                         return false;
1722
1723                 path += a;
1724                 prefix += b;
1725         }
1726 }
1727
1728 bool path_equal(const char *a, const char *b) {
1729         assert(a);
1730         assert(b);
1731
1732         if ((a[0] == '/') != (b[0] == '/'))
1733                 return false;
1734
1735         for (;;) {
1736                 size_t j, k;
1737
1738                 a += strspn(a, "/");
1739                 b += strspn(b, "/");
1740
1741                 if (*a == 0 && *b == 0)
1742                         return true;
1743
1744                 if (*a == 0 || *b == 0)
1745                         return false;
1746
1747                 j = strcspn(a, "/");
1748                 k = strcspn(b, "/");
1749
1750                 if (j != k)
1751                         return false;
1752
1753                 if (memcmp(a, b, j) != 0)
1754                         return false;
1755
1756                 a += j;
1757                 b += k;
1758         }
1759 }
1760
1761 char *ascii_strlower(char *t) {
1762         char *p;
1763
1764         assert(t);
1765
1766         for (p = t; *p; p++)
1767                 if (*p >= 'A' && *p <= 'Z')
1768                         *p = *p - 'A' + 'a';
1769
1770         return t;
1771 }
1772
1773 bool ignore_file(const char *filename) {
1774         assert(filename);
1775
1776         return
1777                 filename[0] == '.' ||
1778                 streq(filename, "lost+found") ||
1779                 streq(filename, "aquota.user") ||
1780                 streq(filename, "aquota.group") ||
1781                 endswith(filename, "~") ||
1782                 endswith(filename, ".rpmnew") ||
1783                 endswith(filename, ".rpmsave") ||
1784                 endswith(filename, ".rpmorig") ||
1785                 endswith(filename, ".dpkg-old") ||
1786                 endswith(filename, ".dpkg-new") ||
1787                 endswith(filename, ".swp");
1788 }
1789
1790 int fd_nonblock(int fd, bool nonblock) {
1791         int flags;
1792
1793         assert(fd >= 0);
1794
1795         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1796                 return -errno;
1797
1798         if (nonblock)
1799                 flags |= O_NONBLOCK;
1800         else
1801                 flags &= ~O_NONBLOCK;
1802
1803         if (fcntl(fd, F_SETFL, flags) < 0)
1804                 return -errno;
1805
1806         return 0;
1807 }
1808
1809 int fd_cloexec(int fd, bool cloexec) {
1810         int flags;
1811
1812         assert(fd >= 0);
1813
1814         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1815                 return -errno;
1816
1817         if (cloexec)
1818                 flags |= FD_CLOEXEC;
1819         else
1820                 flags &= ~FD_CLOEXEC;
1821
1822         if (fcntl(fd, F_SETFD, flags) < 0)
1823                 return -errno;
1824
1825         return 0;
1826 }
1827
1828 int close_all_fds(const int except[], unsigned n_except) {
1829         DIR *d;
1830         struct dirent *de;
1831         int r = 0;
1832
1833         if (!(d = opendir("/proc/self/fd")))
1834                 return -errno;
1835
1836         while ((de = readdir(d))) {
1837                 int fd = -1;
1838
1839                 if (ignore_file(de->d_name))
1840                         continue;
1841
1842                 if (safe_atoi(de->d_name, &fd) < 0)
1843                         /* Let's better ignore this, just in case */
1844                         continue;
1845
1846                 if (fd < 3)
1847                         continue;
1848
1849                 if (fd == dirfd(d))
1850                         continue;
1851
1852                 if (except) {
1853                         bool found;
1854                         unsigned i;
1855
1856                         found = false;
1857                         for (i = 0; i < n_except; i++)
1858                                 if (except[i] == fd) {
1859                                         found = true;
1860                                         break;
1861                                 }
1862
1863                         if (found)
1864                                 continue;
1865                 }
1866
1867                 if (close_nointr(fd) < 0) {
1868                         /* Valgrind has its own FD and doesn't want to have it closed */
1869                         if (errno != EBADF && r == 0)
1870                                 r = -errno;
1871                 }
1872         }
1873
1874         closedir(d);
1875         return r;
1876 }
1877
1878 bool chars_intersect(const char *a, const char *b) {
1879         const char *p;
1880
1881         /* Returns true if any of the chars in a are in b. */
1882         for (p = a; *p; p++)
1883                 if (strchr(b, *p))
1884                         return true;
1885
1886         return false;
1887 }
1888
1889 char *format_timestamp(char *buf, size_t l, usec_t t) {
1890         struct tm tm;
1891         time_t sec;
1892
1893         assert(buf);
1894         assert(l > 0);
1895
1896         if (t <= 0)
1897                 return NULL;
1898
1899         sec = (time_t) (t / USEC_PER_SEC);
1900
1901         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1902                 return NULL;
1903
1904         return buf;
1905 }
1906
1907 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1908         usec_t n, d;
1909
1910         n = now(CLOCK_REALTIME);
1911
1912         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1913                 return NULL;
1914
1915         d = n - t;
1916
1917         if (d >= USEC_PER_YEAR)
1918                 snprintf(buf, l, "%llu years and %llu months ago",
1919                          (unsigned long long) (d / USEC_PER_YEAR),
1920                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1921         else if (d >= USEC_PER_MONTH)
1922                 snprintf(buf, l, "%llu months and %llu days ago",
1923                          (unsigned long long) (d / USEC_PER_MONTH),
1924                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1925         else if (d >= USEC_PER_WEEK)
1926                 snprintf(buf, l, "%llu weeks and %llu days ago",
1927                          (unsigned long long) (d / USEC_PER_WEEK),
1928                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1929         else if (d >= 2*USEC_PER_DAY)
1930                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1931         else if (d >= 25*USEC_PER_HOUR)
1932                 snprintf(buf, l, "1 day and %lluh ago",
1933                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1934         else if (d >= 6*USEC_PER_HOUR)
1935                 snprintf(buf, l, "%lluh ago",
1936                          (unsigned long long) (d / USEC_PER_HOUR));
1937         else if (d >= USEC_PER_HOUR)
1938                 snprintf(buf, l, "%lluh %llumin ago",
1939                          (unsigned long long) (d / USEC_PER_HOUR),
1940                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1941         else if (d >= 5*USEC_PER_MINUTE)
1942                 snprintf(buf, l, "%llumin ago",
1943                          (unsigned long long) (d / USEC_PER_MINUTE));
1944         else if (d >= USEC_PER_MINUTE)
1945                 snprintf(buf, l, "%llumin %llus ago",
1946                          (unsigned long long) (d / USEC_PER_MINUTE),
1947                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1948         else if (d >= USEC_PER_SEC)
1949                 snprintf(buf, l, "%llus ago",
1950                          (unsigned long long) (d / USEC_PER_SEC));
1951         else if (d >= USEC_PER_MSEC)
1952                 snprintf(buf, l, "%llums ago",
1953                          (unsigned long long) (d / USEC_PER_MSEC));
1954         else if (d > 0)
1955                 snprintf(buf, l, "%lluus ago",
1956                          (unsigned long long) d);
1957         else
1958                 snprintf(buf, l, "now");
1959
1960         buf[l-1] = 0;
1961         return buf;
1962 }
1963
1964 char *format_timespan(char *buf, size_t l, usec_t t) {
1965         static const struct {
1966                 const char *suffix;
1967                 usec_t usec;
1968         } table[] = {
1969                 { "w", USEC_PER_WEEK },
1970                 { "d", USEC_PER_DAY },
1971                 { "h", USEC_PER_HOUR },
1972                 { "min", USEC_PER_MINUTE },
1973                 { "s", USEC_PER_SEC },
1974                 { "ms", USEC_PER_MSEC },
1975                 { "us", 1 },
1976         };
1977
1978         unsigned i;
1979         char *p = buf;
1980
1981         assert(buf);
1982         assert(l > 0);
1983
1984         if (t == (usec_t) -1)
1985                 return NULL;
1986
1987         if (t == 0) {
1988                 snprintf(p, l, "0");
1989                 p[l-1] = 0;
1990                 return p;
1991         }
1992
1993         /* The result of this function can be parsed with parse_usec */
1994
1995         for (i = 0; i < ELEMENTSOF(table); i++) {
1996                 int k;
1997                 size_t n;
1998
1999                 if (t < table[i].usec)
2000                         continue;
2001
2002                 if (l <= 1)
2003                         break;
2004
2005                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2006                 n = MIN((size_t) k, l);
2007
2008                 l -= n;
2009                 p += n;
2010
2011                 t %= table[i].usec;
2012         }
2013
2014         *p = 0;
2015
2016         return buf;
2017 }
2018
2019 bool fstype_is_network(const char *fstype) {
2020         static const char * const table[] = {
2021                 "cifs",
2022                 "smbfs",
2023                 "ncpfs",
2024                 "nfs",
2025                 "nfs4",
2026                 "gfs",
2027                 "gfs2"
2028         };
2029
2030         unsigned i;
2031
2032         for (i = 0; i < ELEMENTSOF(table); i++)
2033                 if (streq(table[i], fstype))
2034                         return true;
2035
2036         return false;
2037 }
2038
2039 int chvt(int vt) {
2040         int fd, r = 0;
2041
2042         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2043                 return -errno;
2044
2045         if (vt < 0) {
2046                 int tiocl[2] = {
2047                         TIOCL_GETKMSGREDIRECT,
2048                         0
2049                 };
2050
2051                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2052                         return -errno;
2053
2054                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2055         }
2056
2057         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2058                 r = -errno;
2059
2060         close_nointr_nofail(r);
2061         return r;
2062 }
2063
2064 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2065         struct termios old_termios, new_termios;
2066         char c;
2067         char line[LINE_MAX];
2068
2069         assert(f);
2070         assert(ret);
2071
2072         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2073                 new_termios = old_termios;
2074
2075                 new_termios.c_lflag &= ~ICANON;
2076                 new_termios.c_cc[VMIN] = 1;
2077                 new_termios.c_cc[VTIME] = 0;
2078
2079                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2080                         size_t k;
2081
2082                         k = fread(&c, 1, 1, f);
2083
2084                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2085
2086                         if (k <= 0)
2087                                 return -EIO;
2088
2089                         if (need_nl)
2090                                 *need_nl = c != '\n';
2091
2092                         *ret = c;
2093                         return 0;
2094                 }
2095         }
2096
2097         if (!(fgets(line, sizeof(line), f)))
2098                 return -EIO;
2099
2100         truncate_nl(line);
2101
2102         if (strlen(line) != 1)
2103                 return -EBADMSG;
2104
2105         if (need_nl)
2106                 *need_nl = false;
2107
2108         *ret = line[0];
2109         return 0;
2110 }
2111
2112 int ask(char *ret, const char *replies, const char *text, ...) {
2113         bool on_tty;
2114
2115         assert(ret);
2116         assert(replies);
2117         assert(text);
2118
2119         on_tty = isatty(STDOUT_FILENO);
2120
2121         for (;;) {
2122                 va_list ap;
2123                 char c;
2124                 int r;
2125                 bool need_nl = true;
2126
2127                 if (on_tty)
2128                         fputs("\x1B[1m", stdout);
2129
2130                 va_start(ap, text);
2131                 vprintf(text, ap);
2132                 va_end(ap);
2133
2134                 if (on_tty)
2135                         fputs("\x1B[0m", stdout);
2136
2137                 fflush(stdout);
2138
2139                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2140
2141                         if (r == -EBADMSG) {
2142                                 puts("Bad input, please try again.");
2143                                 continue;
2144                         }
2145
2146                         putchar('\n');
2147                         return r;
2148                 }
2149
2150                 if (need_nl)
2151                         putchar('\n');
2152
2153                 if (strchr(replies, c)) {
2154                         *ret = c;
2155                         return 0;
2156                 }
2157
2158                 puts("Read unexpected character, please try again.");
2159         }
2160 }
2161
2162 int reset_terminal(int fd) {
2163         struct termios termios;
2164         int r = 0;
2165         long arg;
2166
2167         /* Set terminal to some sane defaults */
2168
2169         assert(fd >= 0);
2170
2171         /* We leave locked terminal attributes untouched, so that
2172          * Plymouth may set whatever it wants to set, and we don't
2173          * interfere with that. */
2174
2175         /* Disable exclusive mode, just in case */
2176         ioctl(fd, TIOCNXCL);
2177
2178         /* Enable console unicode mode */
2179         arg = K_UNICODE;
2180         ioctl(fd, KDSKBMODE, &arg);
2181
2182         if (tcgetattr(fd, &termios) < 0) {
2183                 r = -errno;
2184                 goto finish;
2185         }
2186
2187         /* We only reset the stuff that matters to the software. How
2188          * hardware is set up we don't touch assuming that somebody
2189          * else will do that for us */
2190
2191         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2192         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2193         termios.c_oflag |= ONLCR;
2194         termios.c_cflag |= CREAD;
2195         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2196
2197         termios.c_cc[VINTR]    =   03;  /* ^C */
2198         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2199         termios.c_cc[VERASE]   = 0177;
2200         termios.c_cc[VKILL]    =  025;  /* ^X */
2201         termios.c_cc[VEOF]     =   04;  /* ^D */
2202         termios.c_cc[VSTART]   =  021;  /* ^Q */
2203         termios.c_cc[VSTOP]    =  023;  /* ^S */
2204         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2205         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2206         termios.c_cc[VWERASE]  =  027;  /* ^W */
2207         termios.c_cc[VREPRINT] =  022;  /* ^R */
2208         termios.c_cc[VEOL]     =    0;
2209         termios.c_cc[VEOL2]    =    0;
2210
2211         termios.c_cc[VTIME]  = 0;
2212         termios.c_cc[VMIN]   = 1;
2213
2214         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2215                 r = -errno;
2216
2217 finish:
2218         /* Just in case, flush all crap out */
2219         tcflush(fd, TCIOFLUSH);
2220
2221         return r;
2222 }
2223
2224 int open_terminal(const char *name, int mode) {
2225         int fd, r;
2226         unsigned c = 0;
2227
2228         /*
2229          * If a TTY is in the process of being closed opening it might
2230          * cause EIO. This is horribly awful, but unlikely to be
2231          * changed in the kernel. Hence we work around this problem by
2232          * retrying a couple of times.
2233          *
2234          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2235          */
2236
2237         for (;;) {
2238                 if ((fd = open(name, mode)) >= 0)
2239                         break;
2240
2241                 if (errno != EIO)
2242                         return -errno;
2243
2244                 if (c >= 20)
2245                         return -errno;
2246
2247                 usleep(50 * USEC_PER_MSEC);
2248                 c++;
2249         }
2250
2251         if (fd < 0)
2252                 return -errno;
2253
2254         if ((r = isatty(fd)) < 0) {
2255                 close_nointr_nofail(fd);
2256                 return -errno;
2257         }
2258
2259         if (!r) {
2260                 close_nointr_nofail(fd);
2261                 return -ENOTTY;
2262         }
2263
2264         return fd;
2265 }
2266
2267 int flush_fd(int fd) {
2268         struct pollfd pollfd;
2269
2270         zero(pollfd);
2271         pollfd.fd = fd;
2272         pollfd.events = POLLIN;
2273
2274         for (;;) {
2275                 char buf[LINE_MAX];
2276                 ssize_t l;
2277                 int r;
2278
2279                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2280
2281                         if (errno == EINTR)
2282                                 continue;
2283
2284                         return -errno;
2285                 }
2286
2287                 if (r == 0)
2288                         return 0;
2289
2290                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2291
2292                         if (errno == EINTR)
2293                                 continue;
2294
2295                         if (errno == EAGAIN)
2296                                 return 0;
2297
2298                         return -errno;
2299                 }
2300
2301                 if (l <= 0)
2302                         return 0;
2303         }
2304 }
2305
2306 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2307         int fd = -1, notify = -1, r, wd = -1;
2308
2309         assert(name);
2310
2311         /* We use inotify to be notified when the tty is closed. We
2312          * create the watch before checking if we can actually acquire
2313          * it, so that we don't lose any event.
2314          *
2315          * Note: strictly speaking this actually watches for the
2316          * device being closed, it does *not* really watch whether a
2317          * tty loses its controlling process. However, unless some
2318          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2319          * its tty otherwise this will not become a problem. As long
2320          * as the administrator makes sure not configure any service
2321          * on the same tty as an untrusted user this should not be a
2322          * problem. (Which he probably should not do anyway.) */
2323
2324         if (!fail && !force) {
2325                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2326                         r = -errno;
2327                         goto fail;
2328                 }
2329
2330                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2331                         r = -errno;
2332                         goto fail;
2333                 }
2334         }
2335
2336         for (;;) {
2337                 if (notify >= 0)
2338                         if ((r = flush_fd(notify)) < 0)
2339                                 goto fail;
2340
2341                 /* We pass here O_NOCTTY only so that we can check the return
2342                  * value TIOCSCTTY and have a reliable way to figure out if we
2343                  * successfully became the controlling process of the tty */
2344                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2345                         return -errno;
2346
2347                 /* First, try to get the tty */
2348                 r = ioctl(fd, TIOCSCTTY, force);
2349
2350                 /* Sometimes it makes sense to ignore TIOCSCTTY
2351                  * returning EPERM, i.e. when very likely we already
2352                  * are have this controlling terminal. */
2353                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2354                         r = 0;
2355
2356                 if (r < 0 && (force || fail || errno != EPERM)) {
2357                         r = -errno;
2358                         goto fail;
2359                 }
2360
2361                 if (r >= 0)
2362                         break;
2363
2364                 assert(!fail);
2365                 assert(!force);
2366                 assert(notify >= 0);
2367
2368                 for (;;) {
2369                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2370                         ssize_t l;
2371                         struct inotify_event *e;
2372
2373                         if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2374
2375                                 if (errno == EINTR)
2376                                         continue;
2377
2378                                 r = -errno;
2379                                 goto fail;
2380                         }
2381
2382                         e = (struct inotify_event*) inotify_buffer;
2383
2384                         while (l > 0) {
2385                                 size_t step;
2386
2387                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2388                                         r = -EIO;
2389                                         goto fail;
2390                                 }
2391
2392                                 step = sizeof(struct inotify_event) + e->len;
2393                                 assert(step <= (size_t) l);
2394
2395                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2396                                 l -= step;
2397                         }
2398
2399                         break;
2400                 }
2401
2402                 /* We close the tty fd here since if the old session
2403                  * ended our handle will be dead. It's important that
2404                  * we do this after sleeping, so that we don't enter
2405                  * an endless loop. */
2406                 close_nointr_nofail(fd);
2407         }
2408
2409         if (notify >= 0)
2410                 close_nointr_nofail(notify);
2411
2412         if ((r = reset_terminal(fd)) < 0)
2413                 log_warning("Failed to reset terminal: %s", strerror(-r));
2414
2415         return fd;
2416
2417 fail:
2418         if (fd >= 0)
2419                 close_nointr_nofail(fd);
2420
2421         if (notify >= 0)
2422                 close_nointr_nofail(notify);
2423
2424         return r;
2425 }
2426
2427 int release_terminal(void) {
2428         int r = 0, fd;
2429         struct sigaction sa_old, sa_new;
2430
2431         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2432                 return -errno;
2433
2434         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2435          * by our own TIOCNOTTY */
2436
2437         zero(sa_new);
2438         sa_new.sa_handler = SIG_IGN;
2439         sa_new.sa_flags = SA_RESTART;
2440         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2441
2442         if (ioctl(fd, TIOCNOTTY) < 0)
2443                 r = -errno;
2444
2445         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2446
2447         close_nointr_nofail(fd);
2448         return r;
2449 }
2450
2451 int sigaction_many(const struct sigaction *sa, ...) {
2452         va_list ap;
2453         int r = 0, sig;
2454
2455         va_start(ap, sa);
2456         while ((sig = va_arg(ap, int)) > 0)
2457                 if (sigaction(sig, sa, NULL) < 0)
2458                         r = -errno;
2459         va_end(ap);
2460
2461         return r;
2462 }
2463
2464 int ignore_signals(int sig, ...) {
2465         struct sigaction sa;
2466         va_list ap;
2467         int r = 0;
2468
2469         zero(sa);
2470         sa.sa_handler = SIG_IGN;
2471         sa.sa_flags = SA_RESTART;
2472
2473         if (sigaction(sig, &sa, NULL) < 0)
2474                 r = -errno;
2475
2476         va_start(ap, sig);
2477         while ((sig = va_arg(ap, int)) > 0)
2478                 if (sigaction(sig, &sa, NULL) < 0)
2479                         r = -errno;
2480         va_end(ap);
2481
2482         return r;
2483 }
2484
2485 int default_signals(int sig, ...) {
2486         struct sigaction sa;
2487         va_list ap;
2488         int r = 0;
2489
2490         zero(sa);
2491         sa.sa_handler = SIG_DFL;
2492         sa.sa_flags = SA_RESTART;
2493
2494         if (sigaction(sig, &sa, NULL) < 0)
2495                 r = -errno;
2496
2497         va_start(ap, sig);
2498         while ((sig = va_arg(ap, int)) > 0)
2499                 if (sigaction(sig, &sa, NULL) < 0)
2500                         r = -errno;
2501         va_end(ap);
2502
2503         return r;
2504 }
2505
2506 int close_pipe(int p[]) {
2507         int a = 0, b = 0;
2508
2509         assert(p);
2510
2511         if (p[0] >= 0) {
2512                 a = close_nointr(p[0]);
2513                 p[0] = -1;
2514         }
2515
2516         if (p[1] >= 0) {
2517                 b = close_nointr(p[1]);
2518                 p[1] = -1;
2519         }
2520
2521         return a < 0 ? a : b;
2522 }
2523
2524 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2525         uint8_t *p;
2526         ssize_t n = 0;
2527
2528         assert(fd >= 0);
2529         assert(buf);
2530
2531         p = buf;
2532
2533         while (nbytes > 0) {
2534                 ssize_t k;
2535
2536                 if ((k = read(fd, p, nbytes)) <= 0) {
2537
2538                         if (k < 0 && errno == EINTR)
2539                                 continue;
2540
2541                         if (k < 0 && errno == EAGAIN && do_poll) {
2542                                 struct pollfd pollfd;
2543
2544                                 zero(pollfd);
2545                                 pollfd.fd = fd;
2546                                 pollfd.events = POLLIN;
2547
2548                                 if (poll(&pollfd, 1, -1) < 0) {
2549                                         if (errno == EINTR)
2550                                                 continue;
2551
2552                                         return n > 0 ? n : -errno;
2553                                 }
2554
2555                                 if (pollfd.revents != POLLIN)
2556                                         return n > 0 ? n : -EIO;
2557
2558                                 continue;
2559                         }
2560
2561                         return n > 0 ? n : (k < 0 ? -errno : 0);
2562                 }
2563
2564                 p += k;
2565                 nbytes -= k;
2566                 n += k;
2567         }
2568
2569         return n;
2570 }
2571
2572 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2573         const uint8_t *p;
2574         ssize_t n = 0;
2575
2576         assert(fd >= 0);
2577         assert(buf);
2578
2579         p = buf;
2580
2581         while (nbytes > 0) {
2582                 ssize_t k;
2583
2584                 if ((k = write(fd, p, nbytes)) <= 0) {
2585
2586                         if (k < 0 && errno == EINTR)
2587                                 continue;
2588
2589                         if (k < 0 && errno == EAGAIN && do_poll) {
2590                                 struct pollfd pollfd;
2591
2592                                 zero(pollfd);
2593                                 pollfd.fd = fd;
2594                                 pollfd.events = POLLOUT;
2595
2596                                 if (poll(&pollfd, 1, -1) < 0) {
2597                                         if (errno == EINTR)
2598                                                 continue;
2599
2600                                         return n > 0 ? n : -errno;
2601                                 }
2602
2603                                 if (pollfd.revents != POLLOUT)
2604                                         return n > 0 ? n : -EIO;
2605
2606                                 continue;
2607                         }
2608
2609                         return n > 0 ? n : (k < 0 ? -errno : 0);
2610                 }
2611
2612                 p += k;
2613                 nbytes -= k;
2614                 n += k;
2615         }
2616
2617         return n;
2618 }
2619
2620 int path_is_mount_point(const char *t) {
2621         struct stat a, b;
2622         char *parent;
2623         int r;
2624
2625         if (lstat(t, &a) < 0) {
2626                 if (errno == ENOENT)
2627                         return 0;
2628
2629                 return -errno;
2630         }
2631
2632         if ((r = parent_of_path(t, &parent)) < 0)
2633                 return r;
2634
2635         r = lstat(parent, &b);
2636         free(parent);
2637
2638         if (r < 0)
2639                 return -errno;
2640
2641         return a.st_dev != b.st_dev;
2642 }
2643
2644 int parse_usec(const char *t, usec_t *usec) {
2645         static const struct {
2646                 const char *suffix;
2647                 usec_t usec;
2648         } table[] = {
2649                 { "sec", USEC_PER_SEC },
2650                 { "s", USEC_PER_SEC },
2651                 { "min", USEC_PER_MINUTE },
2652                 { "hr", USEC_PER_HOUR },
2653                 { "h", USEC_PER_HOUR },
2654                 { "d", USEC_PER_DAY },
2655                 { "w", USEC_PER_WEEK },
2656                 { "msec", USEC_PER_MSEC },
2657                 { "ms", USEC_PER_MSEC },
2658                 { "m", USEC_PER_MINUTE },
2659                 { "usec", 1ULL },
2660                 { "us", 1ULL },
2661                 { "", USEC_PER_SEC },
2662         };
2663
2664         const char *p;
2665         usec_t r = 0;
2666
2667         assert(t);
2668         assert(usec);
2669
2670         p = t;
2671         do {
2672                 long long l;
2673                 char *e;
2674                 unsigned i;
2675
2676                 errno = 0;
2677                 l = strtoll(p, &e, 10);
2678
2679                 if (errno != 0)
2680                         return -errno;
2681
2682                 if (l < 0)
2683                         return -ERANGE;
2684
2685                 if (e == p)
2686                         return -EINVAL;
2687
2688                 e += strspn(e, WHITESPACE);
2689
2690                 for (i = 0; i < ELEMENTSOF(table); i++)
2691                         if (startswith(e, table[i].suffix)) {
2692                                 r += (usec_t) l * table[i].usec;
2693                                 p = e + strlen(table[i].suffix);
2694                                 break;
2695                         }
2696
2697                 if (i >= ELEMENTSOF(table))
2698                         return -EINVAL;
2699
2700         } while (*p != 0);
2701
2702         *usec = r;
2703
2704         return 0;
2705 }
2706
2707 int make_stdio(int fd) {
2708         int r, s, t;
2709
2710         assert(fd >= 0);
2711
2712         r = dup2(fd, STDIN_FILENO);
2713         s = dup2(fd, STDOUT_FILENO);
2714         t = dup2(fd, STDERR_FILENO);
2715
2716         if (fd >= 3)
2717                 close_nointr_nofail(fd);
2718
2719         if (r < 0 || s < 0 || t < 0)
2720                 return -errno;
2721
2722         return 0;
2723 }
2724
2725 int make_null_stdio(void) {
2726         int null_fd;
2727
2728         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2729                 return -errno;
2730
2731         return make_stdio(null_fd);
2732 }
2733
2734 bool is_device_path(const char *path) {
2735
2736         /* Returns true on paths that refer to a device, either in
2737          * sysfs or in /dev */
2738
2739         return
2740                 path_startswith(path, "/dev/") ||
2741                 path_startswith(path, "/sys/");
2742 }
2743
2744 int dir_is_empty(const char *path) {
2745         DIR *d;
2746         int r;
2747         struct dirent buf, *de;
2748
2749         if (!(d = opendir(path)))
2750                 return -errno;
2751
2752         for (;;) {
2753                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2754                         r = -r;
2755                         break;
2756                 }
2757
2758                 if (!de) {
2759                         r = 1;
2760                         break;
2761                 }
2762
2763                 if (!ignore_file(de->d_name)) {
2764                         r = 0;
2765                         break;
2766                 }
2767         }
2768
2769         closedir(d);
2770         return r;
2771 }
2772
2773 unsigned long long random_ull(void) {
2774         int fd;
2775         uint64_t ull;
2776         ssize_t r;
2777
2778         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2779                 goto fallback;
2780
2781         r = loop_read(fd, &ull, sizeof(ull), true);
2782         close_nointr_nofail(fd);
2783
2784         if (r != sizeof(ull))
2785                 goto fallback;
2786
2787         return ull;
2788
2789 fallback:
2790         return random() * RAND_MAX + random();
2791 }
2792
2793 void rename_process(const char name[8]) {
2794         assert(name);
2795
2796         prctl(PR_SET_NAME, name);
2797
2798         /* This is a like a poor man's setproctitle(). The string
2799          * passed should fit in 7 chars (i.e. the length of
2800          * "systemd") */
2801
2802         if (program_invocation_name)
2803                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2804 }
2805
2806 void sigset_add_many(sigset_t *ss, ...) {
2807         va_list ap;
2808         int sig;
2809
2810         assert(ss);
2811
2812         va_start(ap, ss);
2813         while ((sig = va_arg(ap, int)) > 0)
2814                 assert_se(sigaddset(ss, sig) == 0);
2815         va_end(ap);
2816 }
2817
2818 char* gethostname_malloc(void) {
2819         struct utsname u;
2820
2821         assert_se(uname(&u) >= 0);
2822
2823         if (u.nodename[0])
2824                 return strdup(u.nodename);
2825
2826         return strdup(u.sysname);
2827 }
2828
2829 char* getlogname_malloc(void) {
2830         uid_t uid;
2831         long bufsize;
2832         char *buf, *name;
2833         struct passwd pwbuf, *pw = NULL;
2834         struct stat st;
2835
2836         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2837                 uid = st.st_uid;
2838         else
2839                 uid = getuid();
2840
2841         /* Shortcut things to avoid NSS lookups */
2842         if (uid == 0)
2843                 return strdup("root");
2844
2845         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2846                 bufsize = 4096;
2847
2848         if (!(buf = malloc(bufsize)))
2849                 return NULL;
2850
2851         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2852                 name = strdup(pw->pw_name);
2853                 free(buf);
2854                 return name;
2855         }
2856
2857         free(buf);
2858
2859         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2860                 return NULL;
2861
2862         return name;
2863 }
2864
2865 int getttyname_malloc(int fd, char **r) {
2866         char path[PATH_MAX], *c;
2867         int k;
2868
2869         assert(r);
2870
2871         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2872                 return -k;
2873
2874         char_array_0(path);
2875
2876         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2877                 return -ENOMEM;
2878
2879         *r = c;
2880         return 0;
2881 }
2882
2883 int getttyname_harder(int fd, char **r) {
2884         int k;
2885         char *s;
2886
2887         if ((k = getttyname_malloc(fd, &s)) < 0)
2888                 return k;
2889
2890         if (streq(s, "tty")) {
2891                 free(s);
2892                 return get_ctty(r, NULL);
2893         }
2894
2895         *r = s;
2896         return 0;
2897 }
2898
2899 int get_ctty_devnr(dev_t *d) {
2900         int k;
2901         char line[LINE_MAX], *p;
2902         unsigned long ttynr;
2903         FILE *f;
2904
2905         if (!(f = fopen("/proc/self/stat", "r")))
2906                 return -errno;
2907
2908         if (!(fgets(line, sizeof(line), f))) {
2909                 k = -errno;
2910                 fclose(f);
2911                 return k;
2912         }
2913
2914         fclose(f);
2915
2916         if (!(p = strrchr(line, ')')))
2917                 return -EIO;
2918
2919         p++;
2920
2921         if (sscanf(p, " "
2922                    "%*c "  /* state */
2923                    "%*d "  /* ppid */
2924                    "%*d "  /* pgrp */
2925                    "%*d "  /* session */
2926                    "%lu ", /* ttynr */
2927                    &ttynr) != 1)
2928                 return -EIO;
2929
2930         *d = (dev_t) ttynr;
2931         return 0;
2932 }
2933
2934 int get_ctty(char **r, dev_t *_devnr) {
2935         int k;
2936         char fn[PATH_MAX], *s, *b, *p;
2937         dev_t devnr;
2938
2939         assert(r);
2940
2941         if ((k = get_ctty_devnr(&devnr)) < 0)
2942                 return k;
2943
2944         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2945         char_array_0(fn);
2946
2947         if ((k = readlink_malloc(fn, &s)) < 0) {
2948
2949                 if (k != -ENOENT)
2950                         return k;
2951
2952                 /* This is an ugly hack */
2953                 if (major(devnr) == 136) {
2954                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2955                                 return -ENOMEM;
2956
2957                         *r = b;
2958                         if (_devnr)
2959                                 *_devnr = devnr;
2960
2961                         return 0;
2962                 }
2963
2964                 /* Probably something like the ptys which have no
2965                  * symlink in /dev/char. Let's return something
2966                  * vaguely useful. */
2967
2968                 if (!(b = strdup(fn + 5)))
2969                         return -ENOMEM;
2970
2971                 *r = b;
2972                 if (_devnr)
2973                         *_devnr = devnr;
2974
2975                 return 0;
2976         }
2977
2978         if (startswith(s, "/dev/"))
2979                 p = s + 5;
2980         else if (startswith(s, "../"))
2981                 p = s + 3;
2982         else
2983                 p = s;
2984
2985         b = strdup(p);
2986         free(s);
2987
2988         if (!b)
2989                 return -ENOMEM;
2990
2991         *r = b;
2992         if (_devnr)
2993                 *_devnr = devnr;
2994
2995         return 0;
2996 }
2997
2998 static int rm_rf_children(int fd, bool only_dirs) {
2999         DIR *d;
3000         int ret = 0;
3001
3002         assert(fd >= 0);
3003
3004         /* This returns the first error we run into, but nevertheless
3005          * tries to go on */
3006
3007         if (!(d = fdopendir(fd))) {
3008                 close_nointr_nofail(fd);
3009
3010                 return errno == ENOENT ? 0 : -errno;
3011         }
3012
3013         for (;;) {
3014                 struct dirent buf, *de;
3015                 bool is_dir;
3016                 int r;
3017
3018                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3019                         if (ret == 0)
3020                                 ret = -r;
3021                         break;
3022                 }
3023
3024                 if (!de)
3025                         break;
3026
3027                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3028                         continue;
3029
3030                 if (de->d_type == DT_UNKNOWN) {
3031                         struct stat st;
3032
3033                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3034                                 if (ret == 0 && errno != ENOENT)
3035                                         ret = -errno;
3036                                 continue;
3037                         }
3038
3039                         is_dir = S_ISDIR(st.st_mode);
3040                 } else
3041                         is_dir = de->d_type == DT_DIR;
3042
3043                 if (is_dir) {
3044                         int subdir_fd;
3045
3046                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3047                                 if (ret == 0 && errno != ENOENT)
3048                                         ret = -errno;
3049                                 continue;
3050                         }
3051
3052                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3053                                 if (ret == 0)
3054                                         ret = r;
3055                         }
3056
3057                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3058                                 if (ret == 0 && errno != ENOENT)
3059                                         ret = -errno;
3060                         }
3061                 } else  if (!only_dirs) {
3062
3063                         if (unlinkat(fd, de->d_name, 0) < 0) {
3064                                 if (ret == 0 && errno != ENOENT)
3065                                         ret = -errno;
3066                         }
3067                 }
3068         }
3069
3070         closedir(d);
3071
3072         return ret;
3073 }
3074
3075 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3076         int fd;
3077         int r;
3078
3079         assert(path);
3080
3081         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3082
3083                 if (errno != ENOTDIR)
3084                         return -errno;
3085
3086                 if (delete_root && !only_dirs)
3087                         if (unlink(path) < 0)
3088                                 return -errno;
3089
3090                 return 0;
3091         }
3092
3093         r = rm_rf_children(fd, only_dirs);
3094
3095         if (delete_root)
3096                 if (rmdir(path) < 0) {
3097                         if (r == 0)
3098                                 r = -errno;
3099                 }
3100
3101         return r;
3102 }
3103
3104 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3105         assert(path);
3106
3107         /* Under the assumption that we are running privileged we
3108          * first change the access mode and only then hand out
3109          * ownership to avoid a window where access is too open. */
3110
3111         if (chmod(path, mode) < 0)
3112                 return -errno;
3113
3114         if (chown(path, uid, gid) < 0)
3115                 return -errno;
3116
3117         return 0;
3118 }
3119
3120 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3121         cpu_set_t *r;
3122         unsigned n = 1024;
3123
3124         /* Allocates the cpuset in the right size */
3125
3126         for (;;) {
3127                 if (!(r = CPU_ALLOC(n)))
3128                         return NULL;
3129
3130                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3131                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3132
3133                         if (ncpus)
3134                                 *ncpus = n;
3135
3136                         return r;
3137                 }
3138
3139                 CPU_FREE(r);
3140
3141                 if (errno != EINVAL)
3142                         return NULL;
3143
3144                 n *= 2;
3145         }
3146 }
3147
3148 void status_vprintf(const char *format, va_list ap) {
3149         char *s = NULL;
3150         int fd = -1;
3151
3152         assert(format);
3153
3154         /* This independent of logging, as status messages are
3155          * optional and go exclusively to the console. */
3156
3157         if (vasprintf(&s, format, ap) < 0)
3158                 goto finish;
3159
3160         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3161                 goto finish;
3162
3163         write(fd, s, strlen(s));
3164
3165 finish:
3166         free(s);
3167
3168         if (fd >= 0)
3169                 close_nointr_nofail(fd);
3170 }
3171
3172 void status_printf(const char *format, ...) {
3173         va_list ap;
3174
3175         assert(format);
3176
3177         va_start(ap, format);
3178         status_vprintf(format, ap);
3179         va_end(ap);
3180 }
3181
3182 void status_welcome(void) {
3183         char *pretty_name = NULL, *ansi_color = NULL;
3184         const char *const_pretty = NULL, *const_color = NULL;
3185         int r;
3186
3187         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3188                                 "PRETTY_NAME", &pretty_name,
3189                                 "ANSI_COLOR", &ansi_color,
3190                                 NULL)) < 0) {
3191
3192                 if (r != -ENOENT)
3193                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3194         }
3195
3196 #if defined(TARGET_FEDORA)
3197         if (!pretty_name) {
3198                 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3199
3200                         if (r != -ENOENT)
3201                                 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3202                 } else
3203                         truncate_nl(pretty_name);
3204         }
3205
3206         if (!ansi_color && pretty_name) {
3207
3208                 /* This tries to mimic the color magic the old Red Hat sysinit
3209                  * script did. */
3210
3211                 if (startswith(pretty_name, "Red Hat"))
3212                         const_color = "0;31"; /* Red for RHEL */
3213                 else if (startswith(pretty_name, "Fedora"))
3214                         const_color = "0;34"; /* Blue for Fedora */
3215         }
3216
3217 #elif defined(TARGET_SUSE)
3218
3219         if (!pretty_name) {
3220                 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3221
3222                         if (r != -ENOENT)
3223                                 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3224                 } else
3225                         truncate_nl(pretty_name);
3226         }
3227
3228         if (!ansi_color)
3229                 const_color = "0;32"; /* Green for openSUSE */
3230
3231 #elif defined(TARGET_GENTOO)
3232
3233         if (!pretty_name) {
3234                 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3235
3236                         if (r != -ENOENT)
3237                                 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3238                 } else
3239                         truncate_nl(pretty_name);
3240         }
3241
3242         if (!ansi_color)
3243                 const_color = "1;34"; /* Light Blue for Gentoo */
3244
3245 #elif defined(TARGET_ALTLINUX)
3246
3247         if (!pretty_name) {
3248                 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3249
3250                         if (r != -ENOENT)
3251                                 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3252                 } else
3253                         truncate_nl(pretty_name);
3254         }
3255
3256         if (!ansi_color)
3257                 const_color = "0;36"; /* Cyan for ALTLinux */
3258
3259
3260 #elif defined(TARGET_DEBIAN)
3261
3262         if (!pretty_name) {
3263                 char *version;
3264
3265                 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3266
3267                         if (r != -ENOENT)
3268                                 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3269                 } else {
3270                         truncate_nl(version);
3271                         pretty_name = strappend("Debian ", version);
3272                         free(version);
3273
3274                         if (!pretty_name)
3275                                 log_warning("Failed to allocate Debian version string.");
3276                 }
3277         }
3278
3279         if (!ansi_color)
3280                 const_color = "1;31"; /* Light Red for Debian */
3281
3282 #elif defined(TARGET_UBUNTU)
3283
3284         if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3285                                 "DISTRIB_DESCRIPTION", &pretty_name,
3286                                 NULL)) < 0) {
3287
3288                 if (r != -ENOENT)
3289                         log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3290         }
3291
3292         if (!ansi_color)
3293                 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3294
3295 #elif defined(TARGET_MANDRIVA)
3296
3297         if (!pretty_name) {
3298                 char *s, *p;
3299
3300                 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3301                         if (r != -ENOENT)
3302                                 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3303                 } else {
3304                         p = strstr(s, " release ");
3305                         if (p) {
3306                                 *p = '\0';
3307                                 p += 9;
3308                                 p[strcspn(p, " ")] = '\0';
3309
3310                                 /* This corresponds to standard rc.sysinit */
3311                                 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3312                                         const_color = "1;36";
3313                                 else
3314                                         log_warning("Failed to allocate Mandriva version string.");
3315                         } else
3316                                 log_warning("Failed to parse /etc/mandriva-release");
3317                         free(s);
3318                 }
3319         }
3320
3321 #endif
3322
3323         if (!pretty_name && !const_pretty)
3324                 const_pretty = "Linux";
3325
3326         if (!ansi_color && !const_color)
3327                 const_color = "1";
3328
3329         status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3330                       const_color ? const_color : ansi_color,
3331                       const_pretty ? const_pretty : pretty_name);
3332
3333         free(ansi_color);
3334         free(pretty_name);
3335 }
3336
3337 char *replace_env(const char *format, char **env) {
3338         enum {
3339                 WORD,
3340                 CURLY,
3341                 VARIABLE
3342         } state = WORD;
3343
3344         const char *e, *word = format;
3345         char *r = NULL, *k;
3346
3347         assert(format);
3348
3349         for (e = format; *e; e ++) {
3350
3351                 switch (state) {
3352
3353                 case WORD:
3354                         if (*e == '$')
3355                                 state = CURLY;
3356                         break;
3357
3358                 case CURLY:
3359                         if (*e == '{') {
3360                                 if (!(k = strnappend(r, word, e-word-1)))
3361                                         goto fail;
3362
3363                                 free(r);
3364                                 r = k;
3365
3366                                 word = e-1;
3367                                 state = VARIABLE;
3368
3369                         } else if (*e == '$') {
3370                                 if (!(k = strnappend(r, word, e-word)))
3371                                         goto fail;
3372
3373                                 free(r);
3374                                 r = k;
3375
3376                                 word = e+1;
3377                                 state = WORD;
3378                         } else
3379                                 state = WORD;
3380                         break;
3381
3382                 case VARIABLE:
3383                         if (*e == '}') {
3384                                 const char *t;
3385
3386                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3387                                         t = "";
3388
3389                                 if (!(k = strappend(r, t)))
3390                                         goto fail;
3391
3392                                 free(r);
3393                                 r = k;
3394
3395                                 word = e+1;
3396                                 state = WORD;
3397                         }
3398                         break;
3399                 }
3400         }
3401
3402         if (!(k = strnappend(r, word, e-word)))
3403                 goto fail;
3404
3405         free(r);
3406         return k;
3407
3408 fail:
3409         free(r);
3410         return NULL;
3411 }
3412
3413 char **replace_env_argv(char **argv, char **env) {
3414         char **r, **i;
3415         unsigned k = 0, l = 0;
3416
3417         l = strv_length(argv);
3418
3419         if (!(r = new(char*, l+1)))
3420                 return NULL;
3421
3422         STRV_FOREACH(i, argv) {
3423
3424                 /* If $FOO appears as single word, replace it by the split up variable */
3425                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3426                         char *e;
3427                         char **w, **m;
3428                         unsigned q;
3429
3430                         if ((e = strv_env_get(env, *i+1))) {
3431
3432                                 if (!(m = strv_split_quoted(e))) {
3433                                         r[k] = NULL;
3434                                         strv_free(r);
3435                                         return NULL;
3436                                 }
3437                         } else
3438                                 m = NULL;
3439
3440                         q = strv_length(m);
3441                         l = l + q - 1;
3442
3443                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3444                                 r[k] = NULL;
3445                                 strv_free(r);
3446                                 strv_free(m);
3447                                 return NULL;
3448                         }
3449
3450                         r = w;
3451                         if (m) {
3452                                 memcpy(r + k, m, q * sizeof(char*));
3453                                 free(m);
3454                         }
3455
3456                         k += q;
3457                         continue;
3458                 }
3459
3460                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3461                 if (!(r[k++] = replace_env(*i, env))) {
3462                         strv_free(r);
3463                         return NULL;
3464                 }
3465         }
3466
3467         r[k] = NULL;
3468         return r;
3469 }
3470
3471 int columns(void) {
3472         static __thread int parsed_columns = 0;
3473         const char *e;
3474
3475         if (parsed_columns > 0)
3476                 return parsed_columns;
3477
3478         if ((e = getenv("COLUMNS")))
3479                 parsed_columns = atoi(e);
3480
3481         if (parsed_columns <= 0) {
3482                 struct winsize ws;
3483                 zero(ws);
3484
3485                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3486                         parsed_columns = ws.ws_col;
3487         }
3488
3489         if (parsed_columns <= 0)
3490                 parsed_columns = 80;
3491
3492         return parsed_columns;
3493 }
3494
3495 int running_in_chroot(void) {
3496         struct stat a, b;
3497
3498         zero(a);
3499         zero(b);
3500
3501         /* Only works as root */
3502
3503         if (stat("/proc/1/root", &a) < 0)
3504                 return -errno;
3505
3506         if (stat("/", &b) < 0)
3507                 return -errno;
3508
3509         return
3510                 a.st_dev != b.st_dev ||
3511                 a.st_ino != b.st_ino;
3512 }
3513
3514 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3515         size_t l, x;
3516         char *r;
3517
3518         assert(s);
3519         assert(percent <= 100);
3520         assert(length >= 3);
3521
3522         l = strlen(s);
3523
3524         if (l <= 3 || l <= length)
3525                 return strdup(s);
3526
3527         if (!(r = new0(char, length+1)))
3528                 return r;
3529
3530         x = (length * percent) / 100;
3531
3532         if (x > length - 3)
3533                 x = length - 3;
3534
3535         memcpy(r, s, x);
3536         r[x] = '.';
3537         r[x+1] = '.';
3538         r[x+2] = '.';
3539         memcpy(r + x + 3,
3540                s + l - (length - x - 3),
3541                length - x - 3);
3542
3543         return r;
3544 }
3545
3546 int touch(const char *path) {
3547         int fd;
3548
3549         assert(path);
3550
3551         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3552                 return -errno;
3553
3554         close_nointr_nofail(fd);
3555         return 0;
3556 }
3557
3558 char *unquote(const char *s, const char* quotes) {
3559         size_t l;
3560         assert(s);
3561
3562         if ((l = strlen(s)) < 2)
3563                 return strdup(s);
3564
3565         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3566                 return strndup(s+1, l-2);
3567
3568         return strdup(s);
3569 }
3570
3571 char *normalize_env_assignment(const char *s) {
3572         char *name, *value, *p, *r;
3573
3574         p = strchr(s, '=');
3575
3576         if (!p) {
3577                 if (!(r = strdup(s)))
3578                         return NULL;
3579
3580                 return strstrip(r);
3581         }
3582
3583         if (!(name = strndup(s, p - s)))
3584                 return NULL;
3585
3586         if (!(p = strdup(p+1))) {
3587                 free(name);
3588                 return NULL;
3589         }
3590
3591         value = unquote(strstrip(p), QUOTES);
3592         free(p);
3593
3594         if (!value) {
3595                 free(name);
3596                 return NULL;
3597         }
3598
3599         if (asprintf(&r, "%s=%s", name, value) < 0)
3600                 r = NULL;
3601
3602         free(value);
3603         free(name);
3604
3605         return r;
3606 }
3607
3608 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3609         assert(pid >= 1);
3610         assert(status);
3611
3612         for (;;) {
3613                 zero(*status);
3614
3615                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3616
3617                         if (errno == EINTR)
3618                                 continue;
3619
3620                         return -errno;
3621                 }
3622
3623                 return 0;
3624         }
3625 }
3626
3627 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3628         int r;
3629         siginfo_t status;
3630
3631         assert(name);
3632         assert(pid > 1);
3633
3634         if ((r = wait_for_terminate(pid, &status)) < 0) {
3635                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3636                 return r;
3637         }
3638
3639         if (status.si_code == CLD_EXITED) {
3640                 if (status.si_status != 0) {
3641                         log_warning("%s failed with error code %i.", name, status.si_status);
3642                         return status.si_status;
3643                 }
3644
3645                 log_debug("%s succeeded.", name);
3646                 return 0;
3647
3648         } else if (status.si_code == CLD_KILLED ||
3649                    status.si_code == CLD_DUMPED) {
3650
3651                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3652                 return -EPROTO;
3653         }
3654
3655         log_warning("%s failed due to unknown reason.", name);
3656         return -EPROTO;
3657
3658 }
3659
3660 void freeze(void) {
3661
3662         /* Make sure nobody waits for us on a socket anymore */
3663         close_all_fds(NULL, 0);
3664
3665         sync();
3666
3667         for (;;)
3668                 pause();
3669 }
3670
3671 bool null_or_empty(struct stat *st) {
3672         assert(st);
3673
3674         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3675                 return true;
3676
3677         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3678                 return true;
3679
3680         return false;
3681 }
3682
3683 DIR *xopendirat(int fd, const char *name, int flags) {
3684         int nfd;
3685         DIR *d;
3686
3687         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3688                 return NULL;
3689
3690         if (!(d = fdopendir(nfd))) {
3691                 close_nointr_nofail(nfd);
3692                 return NULL;
3693         }
3694
3695         return d;
3696 }
3697
3698 int signal_from_string_try_harder(const char *s) {
3699         int signo;
3700         assert(s);
3701
3702         if ((signo = signal_from_string(s)) <= 0)
3703                 if (startswith(s, "SIG"))
3704                         return signal_from_string(s+3);
3705
3706         return signo;
3707 }
3708
3709 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3710
3711         assert(f);
3712         assert(name);
3713         assert(t);
3714
3715         if (!dual_timestamp_is_set(t))
3716                 return;
3717
3718         fprintf(f, "%s=%llu %llu\n",
3719                 name,
3720                 (unsigned long long) t->realtime,
3721                 (unsigned long long) t->monotonic);
3722 }
3723
3724 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3725         unsigned long long a, b;
3726
3727         assert(value);
3728         assert(t);
3729
3730         if (sscanf(value, "%lli %llu", &a, &b) != 2)
3731                 log_debug("Failed to parse finish timestamp value %s", value);
3732         else {
3733                 t->realtime = a;
3734                 t->monotonic = b;
3735         }
3736 }
3737
3738 char *fstab_node_to_udev_node(const char *p) {
3739         char *dn, *t, *u;
3740         int r;
3741
3742         /* FIXME: to follow udev's logic 100% we need to leave valid
3743          * UTF8 chars unescaped */
3744
3745         if (startswith(p, "LABEL=")) {
3746
3747                 if (!(u = unquote(p+6, "\"\'")))
3748                         return NULL;
3749
3750                 t = xescape(u, "/ ");
3751                 free(u);
3752
3753                 if (!t)
3754                         return NULL;
3755
3756                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3757                 free(t);
3758
3759                 if (r < 0)
3760                         return NULL;
3761
3762                 return dn;
3763         }
3764
3765         if (startswith(p, "UUID=")) {
3766
3767                 if (!(u = unquote(p+5, "\"\'")))
3768                         return NULL;
3769
3770                 t = xescape(u, "/ ");
3771                 free(u);
3772
3773                 if (!t)
3774                         return NULL;
3775
3776                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3777                 free(t);
3778
3779                 if (r < 0)
3780                         return NULL;
3781
3782                 return dn;
3783         }
3784
3785         return strdup(p);
3786 }
3787
3788 void filter_environ(const char *prefix) {
3789         int i, j;
3790         assert(prefix);
3791
3792         if (!environ)
3793                 return;
3794
3795         for (i = 0, j = 0; environ[i]; i++) {
3796
3797                 if (startswith(environ[i], prefix))
3798                         continue;
3799
3800                 environ[j++] = environ[i];
3801         }
3802
3803         environ[j] = NULL;
3804 }
3805
3806 bool tty_is_vc(const char *tty) {
3807         assert(tty);
3808
3809         if (startswith(tty, "/dev/"))
3810                 tty += 5;
3811
3812         return startswith(tty, "tty") &&
3813                 tty[3] >= '0' && tty[3] <= '9';
3814 }
3815
3816 const char *default_term_for_tty(const char *tty) {
3817         char *active = NULL;
3818         const char *term;
3819
3820         assert(tty);
3821
3822         if (startswith(tty, "/dev/"))
3823                 tty += 5;
3824
3825         /* Resolve where /dev/console is pointing when determining
3826          * TERM */
3827         if (streq(tty, "console"))
3828                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3829                         truncate_nl(active);
3830
3831                         /* If multiple log outputs are configured the
3832                          * last one is what /dev/console points to */
3833                         if ((tty = strrchr(active, ' ')))
3834                                 tty++;
3835                         else
3836                                 tty = active;
3837                 }
3838
3839         term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3840         free(active);
3841
3842         return term;
3843 }
3844
3845 /* Returns a short identifier for the various VM implementations */
3846 int detect_vm(const char **id) {
3847
3848 #if defined(__i386__) || defined(__x86_64__)
3849
3850         /* Both CPUID and DMI are x86 specific interfaces... */
3851
3852         static const char *const dmi_vendors[] = {
3853                 "/sys/class/dmi/id/sys_vendor",
3854                 "/sys/class/dmi/id/board_vendor",
3855                 "/sys/class/dmi/id/bios_vendor"
3856         };
3857
3858         static const char dmi_vendor_table[] =
3859                 "QEMU\0"                  "qemu\0"
3860                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3861                 "VMware\0"                "vmware\0"
3862                 "VMW\0"                   "vmware\0"
3863                 "Microsoft Corporation\0" "microsoft\0"
3864                 "innotek GmbH\0"          "oracle\0"
3865                 "Xen\0"                   "xen\0"
3866                 "Bochs\0"                 "bochs\0";
3867
3868         static const char cpuid_vendor_table[] =
3869                 "XenVMMXenVMM\0"          "xen\0"
3870                 "KVMKVMKVM\0"             "kvm\0"
3871                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3872                 "VMwareVMware\0"          "vmware\0"
3873                 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3874                 "Microsoft Hv\0"          "microsoft\0";
3875
3876         uint32_t eax, ecx;
3877         union {
3878                 uint32_t sig32[3];
3879                 char text[13];
3880         } sig;
3881         unsigned i;
3882         const char *j, *k;
3883         bool hypervisor;
3884
3885         /* http://lwn.net/Articles/301888/ */
3886         zero(sig);
3887
3888 #if defined (__i386__)
3889 #define REG_a "eax"
3890 #define REG_b "ebx"
3891 #elif defined (__amd64__)
3892 #define REG_a "rax"
3893 #define REG_b "rbx"
3894 #endif
3895
3896         /* First detect whether there is a hypervisor */
3897         eax = 1;
3898         __asm__ __volatile__ (
3899                 /* ebx/rbx is being used for PIC! */
3900                 "  push %%"REG_b"         \n\t"
3901                 "  cpuid                  \n\t"
3902                 "  pop %%"REG_b"          \n\t"
3903
3904                 : "=a" (eax), "=c" (ecx)
3905                 : "0" (eax)
3906         );
3907
3908         hypervisor = !!(ecx & ecx & 0x80000000U);
3909
3910         if (hypervisor) {
3911
3912                 /* There is a hypervisor, see what it is */
3913                 eax = 0x40000000U;
3914                 __asm__ __volatile__ (
3915                         /* ebx/rbx is being used for PIC! */
3916                         "  push %%"REG_b"         \n\t"
3917                         "  cpuid                  \n\t"
3918                         "  mov %%ebx, %1          \n\t"
3919                         "  pop %%"REG_b"          \n\t"
3920
3921                         : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3922                         : "0" (eax)
3923                 );
3924
3925                 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3926                         if (streq(sig.text, j)) {
3927
3928                                 if (id)
3929                                         *id = k;
3930
3931                                 return 1;
3932                         }
3933         }
3934
3935         for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3936                 char *s;
3937                 int r;
3938                 const char *found = NULL;
3939
3940                 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3941                         if (r != -ENOENT)
3942                                 return r;
3943
3944                         continue;
3945                 }
3946
3947                 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3948                         if (startswith(s, j))
3949                                 found = k;
3950                 free(s);
3951
3952                 if (found) {
3953                         if (id)
3954                                 *id = found;
3955
3956                         return 1;
3957                 }
3958         }
3959
3960         if (hypervisor) {
3961                 if (id)
3962                         *id = "other";
3963
3964                 return 1;
3965         }
3966
3967 #endif
3968         return 0;
3969 }
3970
3971 int detect_container(const char **id) {
3972         FILE *f;
3973
3974         /* Unfortunately many of these operations require root access
3975          * in one way or another */
3976
3977         if (geteuid() != 0)
3978                 return -EPERM;
3979
3980         if (running_in_chroot() > 0) {
3981
3982                 if (id)
3983                         *id = "chroot";
3984
3985                 return 1;
3986         }
3987
3988         /* /proc/vz exists in container and outside of the container,
3989          * /proc/bc only outside of the container. */
3990         if (access("/proc/vz", F_OK) >= 0 &&
3991             access("/proc/bc", F_OK) < 0) {
3992
3993                 if (id)
3994                         *id = "openvz";
3995
3996                 return 1;
3997         }
3998
3999         if ((f = fopen("/proc/self/cgroup", "r"))) {
4000
4001                 for (;;) {
4002                         char line[LINE_MAX], *p;
4003
4004                         if (!fgets(line, sizeof(line), f))
4005                                 break;
4006
4007                         if (!(p = strchr(strstrip(line), ':')))
4008                                 continue;
4009
4010                         if (strncmp(p, ":ns:", 4))
4011                                 continue;
4012
4013                         if (!streq(p, ":ns:/")) {
4014                                 fclose(f);
4015
4016                                 if (id)
4017                                         *id = "pidns";
4018
4019                                 return 1;
4020                         }
4021                 }
4022
4023                 fclose(f);
4024         }
4025
4026         return 0;
4027 }
4028
4029 /* Returns a short identifier for the various VM/container implementations */
4030 int detect_virtualization(const char **id) {
4031         static __thread const char *cached_id = NULL;
4032         const char *_id;
4033         int r;
4034
4035         if (cached_id) {
4036
4037                 if (cached_id == (const char*) -1)
4038                         return 0;
4039
4040                 if (id)
4041                         *id = cached_id;
4042
4043                 return 1;
4044         }
4045
4046         if ((r = detect_container(&_id)) != 0)
4047                 goto finish;
4048
4049         r = detect_vm(&_id);
4050
4051 finish:
4052         if (r > 0) {
4053                 cached_id = _id;
4054
4055                 if (id)
4056                         *id = _id;
4057         } else if (r == 0)
4058                 cached_id = (const char*) -1;
4059
4060         return r;
4061 }
4062
4063 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4064         DIR *_d = NULL;
4065         struct dirent *de;
4066         Hashmap *pids = NULL;
4067
4068         assert(directory);
4069
4070         /* Executes all binaries in a directory in parallel and waits
4071          * until all they all finished. */
4072
4073         if (!d) {
4074                 if (!(_d = opendir(directory))) {
4075
4076                         if (errno == ENOENT)
4077                                 return;
4078
4079                         log_error("Failed to enumerate directory %s: %m", directory);
4080                         return;
4081                 }
4082
4083                 d = _d;
4084         }
4085
4086         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4087                 log_error("Failed to allocate set.");
4088                 goto finish;
4089         }
4090
4091         while ((de = readdir(d))) {
4092                 char *path;
4093                 pid_t pid;
4094                 int k;
4095
4096                 if (ignore_file(de->d_name))
4097                         continue;
4098
4099                 if (de->d_type != DT_REG &&
4100                     de->d_type != DT_LNK &&
4101                     de->d_type != DT_UNKNOWN)
4102                         continue;
4103
4104                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4105                         log_error("Out of memory");
4106                         continue;
4107                 }
4108
4109                 if ((pid = fork()) < 0) {
4110                         log_error("Failed to fork: %m");
4111                         free(path);
4112                         continue;
4113                 }
4114
4115                 if (pid == 0) {
4116                         char *_argv[2];
4117                         /* Child */
4118
4119                         if (!argv) {
4120                                 _argv[0] = path;
4121                                 _argv[1] = NULL;
4122                                 argv = _argv;
4123                         } else
4124                                 if (!argv[0])
4125                                         argv[0] = path;
4126
4127                         execv(path, argv);
4128
4129                         log_error("Failed to execute %s: %m", path);
4130                         _exit(EXIT_FAILURE);
4131                 }
4132
4133                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4134
4135                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4136                         log_error("Failed to add PID to set: %s", strerror(-k));
4137                         free(path);
4138                 }
4139         }
4140
4141         while (!hashmap_isempty(pids)) {
4142                 siginfo_t si;
4143                 char *path;
4144
4145                 zero(si);
4146                 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4147
4148                         if (errno == EINTR)
4149                                 continue;
4150
4151                         log_error("waitid() failed: %m");
4152                         goto finish;
4153                 }
4154
4155                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4156                         if (!is_clean_exit(si.si_code, si.si_status)) {
4157                                 if (si.si_code == CLD_EXITED)
4158                                         log_error("%s exited with exit status %i.", path, si.si_status);
4159                                 else
4160                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4161                         } else
4162                                 log_debug("%s exited successfully.", path);
4163
4164                         free(path);
4165                 }
4166         }
4167
4168 finish:
4169         if (_d)
4170                 closedir(_d);
4171
4172         if (pids)
4173                 hashmap_free_free(pids);
4174 }
4175
4176 int kill_and_sigcont(pid_t pid, int sig) {
4177         int r;
4178
4179         r = kill(pid, sig) < 0 ? -errno : 0;
4180
4181         if (r >= 0)
4182                 kill(pid, SIGCONT);
4183
4184         return r;
4185 }
4186
4187 bool nulstr_contains(const char*nulstr, const char *needle) {
4188         const char *i;
4189
4190         if (!nulstr)
4191                 return false;
4192
4193         NULSTR_FOREACH(i, nulstr)
4194                 if (streq(i, needle))
4195                         return true;
4196
4197         return false;
4198 }
4199
4200 bool plymouth_running(void) {
4201         return access("/run/plymouth/pid", F_OK) >= 0;
4202 }
4203
4204 void parse_syslog_priority(char **p, int *priority) {
4205         int a = 0, b = 0, c = 0;
4206         int k;
4207
4208         assert(p);
4209         assert(*p);
4210         assert(priority);
4211
4212         if ((*p)[0] != '<')
4213                 return;
4214
4215         if (!strchr(*p, '>'))
4216                 return;
4217
4218         if ((*p)[2] == '>') {
4219                 c = undecchar((*p)[1]);
4220                 k = 3;
4221         } else if ((*p)[3] == '>') {
4222                 b = undecchar((*p)[1]);
4223                 c = undecchar((*p)[2]);
4224                 k = 4;
4225         } else if ((*p)[4] == '>') {
4226                 a = undecchar((*p)[1]);
4227                 b = undecchar((*p)[2]);
4228                 c = undecchar((*p)[3]);
4229                 k = 5;
4230         } else
4231                 return;
4232
4233         if (a < 0 || b < 0 || c < 0)
4234                 return;
4235
4236         *priority = a*100+b*10+c;
4237         *p += k;
4238 }
4239
4240 int have_effective_cap(int value) {
4241         cap_t cap;
4242         cap_flag_value_t fv;
4243         int r;
4244
4245         if (!(cap = cap_get_proc()))
4246                 return -errno;
4247
4248         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4249                 r = -errno;
4250         else
4251                 r = fv == CAP_SET;
4252
4253         cap_free(cap);
4254         return r;
4255 }
4256
4257 static const char *const ioprio_class_table[] = {
4258         [IOPRIO_CLASS_NONE] = "none",
4259         [IOPRIO_CLASS_RT] = "realtime",
4260         [IOPRIO_CLASS_BE] = "best-effort",
4261         [IOPRIO_CLASS_IDLE] = "idle"
4262 };
4263
4264 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4265
4266 static const char *const sigchld_code_table[] = {
4267         [CLD_EXITED] = "exited",
4268         [CLD_KILLED] = "killed",
4269         [CLD_DUMPED] = "dumped",
4270         [CLD_TRAPPED] = "trapped",
4271         [CLD_STOPPED] = "stopped",
4272         [CLD_CONTINUED] = "continued",
4273 };
4274
4275 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4276
4277 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4278         [LOG_FAC(LOG_KERN)] = "kern",
4279         [LOG_FAC(LOG_USER)] = "user",
4280         [LOG_FAC(LOG_MAIL)] = "mail",
4281         [LOG_FAC(LOG_DAEMON)] = "daemon",
4282         [LOG_FAC(LOG_AUTH)] = "auth",
4283         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4284         [LOG_FAC(LOG_LPR)] = "lpr",
4285         [LOG_FAC(LOG_NEWS)] = "news",
4286         [LOG_FAC(LOG_UUCP)] = "uucp",
4287         [LOG_FAC(LOG_CRON)] = "cron",
4288         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4289         [LOG_FAC(LOG_FTP)] = "ftp",
4290         [LOG_FAC(LOG_LOCAL0)] = "local0",
4291         [LOG_FAC(LOG_LOCAL1)] = "local1",
4292         [LOG_FAC(LOG_LOCAL2)] = "local2",
4293         [LOG_FAC(LOG_LOCAL3)] = "local3",
4294         [LOG_FAC(LOG_LOCAL4)] = "local4",
4295         [LOG_FAC(LOG_LOCAL5)] = "local5",
4296         [LOG_FAC(LOG_LOCAL6)] = "local6",
4297         [LOG_FAC(LOG_LOCAL7)] = "local7"
4298 };
4299
4300 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4301
4302 static const char *const log_level_table[] = {
4303         [LOG_EMERG] = "emerg",
4304         [LOG_ALERT] = "alert",
4305         [LOG_CRIT] = "crit",
4306         [LOG_ERR] = "err",
4307         [LOG_WARNING] = "warning",
4308         [LOG_NOTICE] = "notice",
4309         [LOG_INFO] = "info",
4310         [LOG_DEBUG] = "debug"
4311 };
4312
4313 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4314
4315 static const char* const sched_policy_table[] = {
4316         [SCHED_OTHER] = "other",
4317         [SCHED_BATCH] = "batch",
4318         [SCHED_IDLE] = "idle",
4319         [SCHED_FIFO] = "fifo",
4320         [SCHED_RR] = "rr"
4321 };
4322
4323 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4324
4325 static const char* const rlimit_table[] = {
4326         [RLIMIT_CPU] = "LimitCPU",
4327         [RLIMIT_FSIZE] = "LimitFSIZE",
4328         [RLIMIT_DATA] = "LimitDATA",
4329         [RLIMIT_STACK] = "LimitSTACK",
4330         [RLIMIT_CORE] = "LimitCORE",
4331         [RLIMIT_RSS] = "LimitRSS",
4332         [RLIMIT_NOFILE] = "LimitNOFILE",
4333         [RLIMIT_AS] = "LimitAS",
4334         [RLIMIT_NPROC] = "LimitNPROC",
4335         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4336         [RLIMIT_LOCKS] = "LimitLOCKS",
4337         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4338         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4339         [RLIMIT_NICE] = "LimitNICE",
4340         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4341         [RLIMIT_RTTIME] = "LimitRTTIME"
4342 };
4343
4344 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4345
4346 static const char* const ip_tos_table[] = {
4347         [IPTOS_LOWDELAY] = "low-delay",
4348         [IPTOS_THROUGHPUT] = "throughput",
4349         [IPTOS_RELIABILITY] = "reliability",
4350         [IPTOS_LOWCOST] = "low-cost",
4351 };
4352
4353 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4354
4355 static const char *const signal_table[] = {
4356         [SIGHUP] = "HUP",
4357         [SIGINT] = "INT",
4358         [SIGQUIT] = "QUIT",
4359         [SIGILL] = "ILL",
4360         [SIGTRAP] = "TRAP",
4361         [SIGABRT] = "ABRT",
4362         [SIGBUS] = "BUS",
4363         [SIGFPE] = "FPE",
4364         [SIGKILL] = "KILL",
4365         [SIGUSR1] = "USR1",
4366         [SIGSEGV] = "SEGV",
4367         [SIGUSR2] = "USR2",
4368         [SIGPIPE] = "PIPE",
4369         [SIGALRM] = "ALRM",
4370         [SIGTERM] = "TERM",
4371 #ifdef SIGSTKFLT
4372         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4373 #endif
4374         [SIGCHLD] = "CHLD",
4375         [SIGCONT] = "CONT",
4376         [SIGSTOP] = "STOP",
4377         [SIGTSTP] = "TSTP",
4378         [SIGTTIN] = "TTIN",
4379         [SIGTTOU] = "TTOU",
4380         [SIGURG] = "URG",
4381         [SIGXCPU] = "XCPU",
4382         [SIGXFSZ] = "XFSZ",
4383         [SIGVTALRM] = "VTALRM",
4384         [SIGPROF] = "PROF",
4385         [SIGWINCH] = "WINCH",
4386         [SIGIO] = "IO",
4387         [SIGPWR] = "PWR",
4388         [SIGSYS] = "SYS"
4389 };
4390
4391 DEFINE_STRING_TABLE_LOOKUP(signal, int);