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