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