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