chiark / gitweb /
exec: optionally apply cgroup attributes to the cgroups we create
[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 (_likely_(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 = NULL, *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         assert(p);
1270
1271         /* Makes every item in the list an absolute path by prepending
1272          * the prefix, if specified and necessary */
1273
1274         if (path_is_absolute(p) || !prefix)
1275                 return strdup(p);
1276
1277         return join(prefix, "/", p, NULL);
1278 }
1279
1280 char *path_make_absolute_cwd(const char *p) {
1281         char *cwd, *r;
1282
1283         assert(p);
1284
1285         /* Similar to path_make_absolute(), but prefixes with the
1286          * current working directory. */
1287
1288         if (path_is_absolute(p))
1289                 return strdup(p);
1290
1291         if (!(cwd = get_current_dir_name()))
1292                 return NULL;
1293
1294         r = path_make_absolute(p, cwd);
1295         free(cwd);
1296
1297         return r;
1298 }
1299
1300 char **strv_path_make_absolute_cwd(char **l) {
1301         char **s;
1302
1303         /* Goes through every item in the string list and makes it
1304          * absolute. This works in place and won't rollback any
1305          * changes on failure. */
1306
1307         STRV_FOREACH(s, l) {
1308                 char *t;
1309
1310                 if (!(t = path_make_absolute_cwd(*s)))
1311                         return NULL;
1312
1313                 free(*s);
1314                 *s = t;
1315         }
1316
1317         return l;
1318 }
1319
1320 char **strv_path_canonicalize(char **l) {
1321         char **s;
1322         unsigned k = 0;
1323         bool enomem = false;
1324
1325         if (strv_isempty(l))
1326                 return l;
1327
1328         /* Goes through every item in the string list and canonicalize
1329          * the path. This works in place and won't rollback any
1330          * changes on failure. */
1331
1332         STRV_FOREACH(s, l) {
1333                 char *t, *u;
1334
1335                 t = path_make_absolute_cwd(*s);
1336                 free(*s);
1337
1338                 if (!t) {
1339                         enomem = true;
1340                         continue;
1341                 }
1342
1343                 errno = 0;
1344                 u = canonicalize_file_name(t);
1345                 free(t);
1346
1347                 if (!u) {
1348                         if (errno == ENOMEM || !errno)
1349                                 enomem = true;
1350
1351                         continue;
1352                 }
1353
1354                 l[k++] = u;
1355         }
1356
1357         l[k] = NULL;
1358
1359         if (enomem)
1360                 return NULL;
1361
1362         return l;
1363 }
1364
1365 char **strv_path_remove_empty(char **l) {
1366         char **f, **t;
1367
1368         if (!l)
1369                 return NULL;
1370
1371         for (f = t = l; *f; f++) {
1372
1373                 if (dir_is_empty(*f) > 0) {
1374                         free(*f);
1375                         continue;
1376                 }
1377
1378                 *(t++) = *f;
1379         }
1380
1381         *t = NULL;
1382         return l;
1383 }
1384
1385 int reset_all_signal_handlers(void) {
1386         int sig;
1387
1388         for (sig = 1; sig < _NSIG; sig++) {
1389                 struct sigaction sa;
1390
1391                 if (sig == SIGKILL || sig == SIGSTOP)
1392                         continue;
1393
1394                 zero(sa);
1395                 sa.sa_handler = SIG_DFL;
1396                 sa.sa_flags = SA_RESTART;
1397
1398                 /* On Linux the first two RT signals are reserved by
1399                  * glibc, and sigaction() will return EINVAL for them. */
1400                 if ((sigaction(sig, &sa, NULL) < 0))
1401                         if (errno != EINVAL)
1402                                 return -errno;
1403         }
1404
1405         return 0;
1406 }
1407
1408 char *strstrip(char *s) {
1409         char *e;
1410
1411         /* Drops trailing whitespace. Modifies the string in
1412          * place. Returns pointer to first non-space character */
1413
1414         s += strspn(s, WHITESPACE);
1415
1416         for (e = strchr(s, 0); e > s; e --)
1417                 if (!strchr(WHITESPACE, e[-1]))
1418                         break;
1419
1420         *e = 0;
1421
1422         return s;
1423 }
1424
1425 char *delete_chars(char *s, const char *bad) {
1426         char *f, *t;
1427
1428         /* Drops all whitespace, regardless where in the string */
1429
1430         for (f = s, t = s; *f; f++) {
1431                 if (strchr(bad, *f))
1432                         continue;
1433
1434                 *(t++) = *f;
1435         }
1436
1437         *t = 0;
1438
1439         return s;
1440 }
1441
1442 bool in_charset(const char *s, const char* charset) {
1443         const char *i;
1444
1445         assert(s);
1446         assert(charset);
1447
1448         for (i = s; *i; i++)
1449                 if (!strchr(charset, *i))
1450                         return false;
1451
1452         return true;
1453 }
1454
1455 char *file_in_same_dir(const char *path, const char *filename) {
1456         char *e, *r;
1457         size_t k;
1458
1459         assert(path);
1460         assert(filename);
1461
1462         /* This removes the last component of path and appends
1463          * filename, unless the latter is absolute anyway or the
1464          * former isn't */
1465
1466         if (path_is_absolute(filename))
1467                 return strdup(filename);
1468
1469         if (!(e = strrchr(path, '/')))
1470                 return strdup(filename);
1471
1472         k = strlen(filename);
1473         if (!(r = new(char, e-path+1+k+1)))
1474                 return NULL;
1475
1476         memcpy(r, path, e-path+1);
1477         memcpy(r+(e-path)+1, filename, k+1);
1478
1479         return r;
1480 }
1481
1482 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1483         struct stat st;
1484
1485         if (label_mkdir(path, mode) >= 0)
1486                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1487                         return -errno;
1488
1489         if (lstat(path, &st) < 0)
1490                 return -errno;
1491
1492         if ((st.st_mode & 0777) != mode ||
1493             st.st_uid != uid ||
1494             st.st_gid != gid ||
1495             !S_ISDIR(st.st_mode)) {
1496                 errno = EEXIST;
1497                 return -errno;
1498         }
1499
1500         return 0;
1501 }
1502
1503
1504 int mkdir_parents(const char *path, mode_t mode) {
1505         const char *p, *e;
1506
1507         assert(path);
1508
1509         /* Creates every parent directory in the path except the last
1510          * component. */
1511
1512         p = path + strspn(path, "/");
1513         for (;;) {
1514                 int r;
1515                 char *t;
1516
1517                 e = p + strcspn(p, "/");
1518                 p = e + strspn(e, "/");
1519
1520                 /* Is this the last component? If so, then we're
1521                  * done */
1522                 if (*p == 0)
1523                         return 0;
1524
1525                 if (!(t = strndup(path, e - path)))
1526                         return -ENOMEM;
1527
1528                 r = label_mkdir(t, mode);
1529                 free(t);
1530
1531                 if (r < 0 && errno != EEXIST)
1532                         return -errno;
1533         }
1534 }
1535
1536 int mkdir_p(const char *path, mode_t mode) {
1537         int r;
1538
1539         /* Like mkdir -p */
1540
1541         if ((r = mkdir_parents(path, mode)) < 0)
1542                 return r;
1543
1544         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1545                 return -errno;
1546
1547         return 0;
1548 }
1549
1550 int rmdir_parents(const char *path, const char *stop) {
1551         size_t l;
1552         int r = 0;
1553
1554         assert(path);
1555         assert(stop);
1556
1557         l = strlen(path);
1558
1559         /* Skip trailing slashes */
1560         while (l > 0 && path[l-1] == '/')
1561                 l--;
1562
1563         while (l > 0) {
1564                 char *t;
1565
1566                 /* Skip last component */
1567                 while (l > 0 && path[l-1] != '/')
1568                         l--;
1569
1570                 /* Skip trailing slashes */
1571                 while (l > 0 && path[l-1] == '/')
1572                         l--;
1573
1574                 if (l <= 0)
1575                         break;
1576
1577                 if (!(t = strndup(path, l)))
1578                         return -ENOMEM;
1579
1580                 if (path_startswith(stop, t)) {
1581                         free(t);
1582                         return 0;
1583                 }
1584
1585                 r = rmdir(t);
1586                 free(t);
1587
1588                 if (r < 0)
1589                         if (errno != ENOENT)
1590                                 return -errno;
1591         }
1592
1593         return 0;
1594 }
1595
1596
1597 char hexchar(int x) {
1598         static const char table[16] = "0123456789abcdef";
1599
1600         return table[x & 15];
1601 }
1602
1603 int unhexchar(char c) {
1604
1605         if (c >= '0' && c <= '9')
1606                 return c - '0';
1607
1608         if (c >= 'a' && c <= 'f')
1609                 return c - 'a' + 10;
1610
1611         if (c >= 'A' && c <= 'F')
1612                 return c - 'A' + 10;
1613
1614         return -1;
1615 }
1616
1617 char octchar(int x) {
1618         return '0' + (x & 7);
1619 }
1620
1621 int unoctchar(char c) {
1622
1623         if (c >= '0' && c <= '7')
1624                 return c - '0';
1625
1626         return -1;
1627 }
1628
1629 char decchar(int x) {
1630         return '0' + (x % 10);
1631 }
1632
1633 int undecchar(char c) {
1634
1635         if (c >= '0' && c <= '9')
1636                 return c - '0';
1637
1638         return -1;
1639 }
1640
1641 char *cescape(const char *s) {
1642         char *r, *t;
1643         const char *f;
1644
1645         assert(s);
1646
1647         /* Does C style string escaping. */
1648
1649         if (!(r = new(char, strlen(s)*4 + 1)))
1650                 return NULL;
1651
1652         for (f = s, t = r; *f; f++)
1653
1654                 switch (*f) {
1655
1656                 case '\a':
1657                         *(t++) = '\\';
1658                         *(t++) = 'a';
1659                         break;
1660                 case '\b':
1661                         *(t++) = '\\';
1662                         *(t++) = 'b';
1663                         break;
1664                 case '\f':
1665                         *(t++) = '\\';
1666                         *(t++) = 'f';
1667                         break;
1668                 case '\n':
1669                         *(t++) = '\\';
1670                         *(t++) = 'n';
1671                         break;
1672                 case '\r':
1673                         *(t++) = '\\';
1674                         *(t++) = 'r';
1675                         break;
1676                 case '\t':
1677                         *(t++) = '\\';
1678                         *(t++) = 't';
1679                         break;
1680                 case '\v':
1681                         *(t++) = '\\';
1682                         *(t++) = 'v';
1683                         break;
1684                 case '\\':
1685                         *(t++) = '\\';
1686                         *(t++) = '\\';
1687                         break;
1688                 case '"':
1689                         *(t++) = '\\';
1690                         *(t++) = '"';
1691                         break;
1692                 case '\'':
1693                         *(t++) = '\\';
1694                         *(t++) = '\'';
1695                         break;
1696
1697                 default:
1698                         /* For special chars we prefer octal over
1699                          * hexadecimal encoding, simply because glib's
1700                          * g_strescape() does the same */
1701                         if ((*f < ' ') || (*f >= 127)) {
1702                                 *(t++) = '\\';
1703                                 *(t++) = octchar((unsigned char) *f >> 6);
1704                                 *(t++) = octchar((unsigned char) *f >> 3);
1705                                 *(t++) = octchar((unsigned char) *f);
1706                         } else
1707                                 *(t++) = *f;
1708                         break;
1709                 }
1710
1711         *t = 0;
1712
1713         return r;
1714 }
1715
1716 char *cunescape_length(const char *s, size_t length) {
1717         char *r, *t;
1718         const char *f;
1719
1720         assert(s);
1721
1722         /* Undoes C style string escaping */
1723
1724         if (!(r = new(char, length+1)))
1725                 return r;
1726
1727         for (f = s, t = r; f < s + length; f++) {
1728
1729                 if (*f != '\\') {
1730                         *(t++) = *f;
1731                         continue;
1732                 }
1733
1734                 f++;
1735
1736                 switch (*f) {
1737
1738                 case 'a':
1739                         *(t++) = '\a';
1740                         break;
1741                 case 'b':
1742                         *(t++) = '\b';
1743                         break;
1744                 case 'f':
1745                         *(t++) = '\f';
1746                         break;
1747                 case 'n':
1748                         *(t++) = '\n';
1749                         break;
1750                 case 'r':
1751                         *(t++) = '\r';
1752                         break;
1753                 case 't':
1754                         *(t++) = '\t';
1755                         break;
1756                 case 'v':
1757                         *(t++) = '\v';
1758                         break;
1759                 case '\\':
1760                         *(t++) = '\\';
1761                         break;
1762                 case '"':
1763                         *(t++) = '"';
1764                         break;
1765                 case '\'':
1766                         *(t++) = '\'';
1767                         break;
1768
1769                 case 's':
1770                         /* This is an extension of the XDG syntax files */
1771                         *(t++) = ' ';
1772                         break;
1773
1774                 case 'x': {
1775                         /* hexadecimal encoding */
1776                         int a, b;
1777
1778                         if ((a = unhexchar(f[1])) < 0 ||
1779                             (b = unhexchar(f[2])) < 0) {
1780                                 /* Invalid escape code, let's take it literal then */
1781                                 *(t++) = '\\';
1782                                 *(t++) = 'x';
1783                         } else {
1784                                 *(t++) = (char) ((a << 4) | b);
1785                                 f += 2;
1786                         }
1787
1788                         break;
1789                 }
1790
1791                 case '0':
1792                 case '1':
1793                 case '2':
1794                 case '3':
1795                 case '4':
1796                 case '5':
1797                 case '6':
1798                 case '7': {
1799                         /* octal encoding */
1800                         int a, b, c;
1801
1802                         if ((a = unoctchar(f[0])) < 0 ||
1803                             (b = unoctchar(f[1])) < 0 ||
1804                             (c = unoctchar(f[2])) < 0) {
1805                                 /* Invalid escape code, let's take it literal then */
1806                                 *(t++) = '\\';
1807                                 *(t++) = f[0];
1808                         } else {
1809                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1810                                 f += 2;
1811                         }
1812
1813                         break;
1814                 }
1815
1816                 case 0:
1817                         /* premature end of string.*/
1818                         *(t++) = '\\';
1819                         goto finish;
1820
1821                 default:
1822                         /* Invalid escape code, let's take it literal then */
1823                         *(t++) = '\\';
1824                         *(t++) = *f;
1825                         break;
1826                 }
1827         }
1828
1829 finish:
1830         *t = 0;
1831         return r;
1832 }
1833
1834 char *cunescape(const char *s) {
1835         return cunescape_length(s, strlen(s));
1836 }
1837
1838 char *xescape(const char *s, const char *bad) {
1839         char *r, *t;
1840         const char *f;
1841
1842         /* Escapes all chars in bad, in addition to \ and all special
1843          * chars, in \xFF style escaping. May be reversed with
1844          * cunescape. */
1845
1846         if (!(r = new(char, strlen(s)*4+1)))
1847                 return NULL;
1848
1849         for (f = s, t = r; *f; f++) {
1850
1851                 if ((*f < ' ') || (*f >= 127) ||
1852                     (*f == '\\') || strchr(bad, *f)) {
1853                         *(t++) = '\\';
1854                         *(t++) = 'x';
1855                         *(t++) = hexchar(*f >> 4);
1856                         *(t++) = hexchar(*f);
1857                 } else
1858                         *(t++) = *f;
1859         }
1860
1861         *t = 0;
1862
1863         return r;
1864 }
1865
1866 char *bus_path_escape(const char *s) {
1867         char *r, *t;
1868         const char *f;
1869
1870         assert(s);
1871
1872         /* Escapes all chars that D-Bus' object path cannot deal
1873          * with. Can be reverse with bus_path_unescape() */
1874
1875         if (!(r = new(char, strlen(s)*3+1)))
1876                 return NULL;
1877
1878         for (f = s, t = r; *f; f++) {
1879
1880                 if (!(*f >= 'A' && *f <= 'Z') &&
1881                     !(*f >= 'a' && *f <= 'z') &&
1882                     !(*f >= '0' && *f <= '9')) {
1883                         *(t++) = '_';
1884                         *(t++) = hexchar(*f >> 4);
1885                         *(t++) = hexchar(*f);
1886                 } else
1887                         *(t++) = *f;
1888         }
1889
1890         *t = 0;
1891
1892         return r;
1893 }
1894
1895 char *bus_path_unescape(const char *f) {
1896         char *r, *t;
1897
1898         assert(f);
1899
1900         if (!(r = strdup(f)))
1901                 return NULL;
1902
1903         for (t = r; *f; f++) {
1904
1905                 if (*f == '_') {
1906                         int a, b;
1907
1908                         if ((a = unhexchar(f[1])) < 0 ||
1909                             (b = unhexchar(f[2])) < 0) {
1910                                 /* Invalid escape code, let's take it literal then */
1911                                 *(t++) = '_';
1912                         } else {
1913                                 *(t++) = (char) ((a << 4) | b);
1914                                 f += 2;
1915                         }
1916                 } else
1917                         *(t++) = *f;
1918         }
1919
1920         *t = 0;
1921
1922         return r;
1923 }
1924
1925 char *path_kill_slashes(char *path) {
1926         char *f, *t;
1927         bool slash = false;
1928
1929         /* Removes redundant inner and trailing slashes. Modifies the
1930          * passed string in-place.
1931          *
1932          * ///foo///bar/ becomes /foo/bar
1933          */
1934
1935         for (f = path, t = path; *f; f++) {
1936
1937                 if (*f == '/') {
1938                         slash = true;
1939                         continue;
1940                 }
1941
1942                 if (slash) {
1943                         slash = false;
1944                         *(t++) = '/';
1945                 }
1946
1947                 *(t++) = *f;
1948         }
1949
1950         /* Special rule, if we are talking of the root directory, a
1951         trailing slash is good */
1952
1953         if (t == path && slash)
1954                 *(t++) = '/';
1955
1956         *t = 0;
1957         return path;
1958 }
1959
1960 bool path_startswith(const char *path, const char *prefix) {
1961         assert(path);
1962         assert(prefix);
1963
1964         if ((path[0] == '/') != (prefix[0] == '/'))
1965                 return false;
1966
1967         for (;;) {
1968                 size_t a, b;
1969
1970                 path += strspn(path, "/");
1971                 prefix += strspn(prefix, "/");
1972
1973                 if (*prefix == 0)
1974                         return true;
1975
1976                 if (*path == 0)
1977                         return false;
1978
1979                 a = strcspn(path, "/");
1980                 b = strcspn(prefix, "/");
1981
1982                 if (a != b)
1983                         return false;
1984
1985                 if (memcmp(path, prefix, a) != 0)
1986                         return false;
1987
1988                 path += a;
1989                 prefix += b;
1990         }
1991 }
1992
1993 bool path_equal(const char *a, const char *b) {
1994         assert(a);
1995         assert(b);
1996
1997         if ((a[0] == '/') != (b[0] == '/'))
1998                 return false;
1999
2000         for (;;) {
2001                 size_t j, k;
2002
2003                 a += strspn(a, "/");
2004                 b += strspn(b, "/");
2005
2006                 if (*a == 0 && *b == 0)
2007                         return true;
2008
2009                 if (*a == 0 || *b == 0)
2010                         return false;
2011
2012                 j = strcspn(a, "/");
2013                 k = strcspn(b, "/");
2014
2015                 if (j != k)
2016                         return false;
2017
2018                 if (memcmp(a, b, j) != 0)
2019                         return false;
2020
2021                 a += j;
2022                 b += k;
2023         }
2024 }
2025
2026 char *ascii_strlower(char *t) {
2027         char *p;
2028
2029         assert(t);
2030
2031         for (p = t; *p; p++)
2032                 if (*p >= 'A' && *p <= 'Z')
2033                         *p = *p - 'A' + 'a';
2034
2035         return t;
2036 }
2037
2038 bool ignore_file(const char *filename) {
2039         assert(filename);
2040
2041         return
2042                 filename[0] == '.' ||
2043                 streq(filename, "lost+found") ||
2044                 streq(filename, "aquota.user") ||
2045                 streq(filename, "aquota.group") ||
2046                 endswith(filename, "~") ||
2047                 endswith(filename, ".rpmnew") ||
2048                 endswith(filename, ".rpmsave") ||
2049                 endswith(filename, ".rpmorig") ||
2050                 endswith(filename, ".dpkg-old") ||
2051                 endswith(filename, ".dpkg-new") ||
2052                 endswith(filename, ".swp");
2053 }
2054
2055 int fd_nonblock(int fd, bool nonblock) {
2056         int flags;
2057
2058         assert(fd >= 0);
2059
2060         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2061                 return -errno;
2062
2063         if (nonblock)
2064                 flags |= O_NONBLOCK;
2065         else
2066                 flags &= ~O_NONBLOCK;
2067
2068         if (fcntl(fd, F_SETFL, flags) < 0)
2069                 return -errno;
2070
2071         return 0;
2072 }
2073
2074 int fd_cloexec(int fd, bool cloexec) {
2075         int flags;
2076
2077         assert(fd >= 0);
2078
2079         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2080                 return -errno;
2081
2082         if (cloexec)
2083                 flags |= FD_CLOEXEC;
2084         else
2085                 flags &= ~FD_CLOEXEC;
2086
2087         if (fcntl(fd, F_SETFD, flags) < 0)
2088                 return -errno;
2089
2090         return 0;
2091 }
2092
2093 int close_all_fds(const int except[], unsigned n_except) {
2094         DIR *d;
2095         struct dirent *de;
2096         int r = 0;
2097
2098         if (!(d = opendir("/proc/self/fd")))
2099                 return -errno;
2100
2101         while ((de = readdir(d))) {
2102                 int fd = -1;
2103
2104                 if (ignore_file(de->d_name))
2105                         continue;
2106
2107                 if (safe_atoi(de->d_name, &fd) < 0)
2108                         /* Let's better ignore this, just in case */
2109                         continue;
2110
2111                 if (fd < 3)
2112                         continue;
2113
2114                 if (fd == dirfd(d))
2115                         continue;
2116
2117                 if (except) {
2118                         bool found;
2119                         unsigned i;
2120
2121                         found = false;
2122                         for (i = 0; i < n_except; i++)
2123                                 if (except[i] == fd) {
2124                                         found = true;
2125                                         break;
2126                                 }
2127
2128                         if (found)
2129                                 continue;
2130                 }
2131
2132                 if (close_nointr(fd) < 0) {
2133                         /* Valgrind has its own FD and doesn't want to have it closed */
2134                         if (errno != EBADF && r == 0)
2135                                 r = -errno;
2136                 }
2137         }
2138
2139         closedir(d);
2140         return r;
2141 }
2142
2143 bool chars_intersect(const char *a, const char *b) {
2144         const char *p;
2145
2146         /* Returns true if any of the chars in a are in b. */
2147         for (p = a; *p; p++)
2148                 if (strchr(b, *p))
2149                         return true;
2150
2151         return false;
2152 }
2153
2154 char *format_timestamp(char *buf, size_t l, usec_t t) {
2155         struct tm tm;
2156         time_t sec;
2157
2158         assert(buf);
2159         assert(l > 0);
2160
2161         if (t <= 0)
2162                 return NULL;
2163
2164         sec = (time_t) (t / USEC_PER_SEC);
2165
2166         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2167                 return NULL;
2168
2169         return buf;
2170 }
2171
2172 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2173         usec_t n, d;
2174
2175         n = now(CLOCK_REALTIME);
2176
2177         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2178                 return NULL;
2179
2180         d = n - t;
2181
2182         if (d >= USEC_PER_YEAR)
2183                 snprintf(buf, l, "%llu years and %llu months ago",
2184                          (unsigned long long) (d / USEC_PER_YEAR),
2185                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2186         else if (d >= USEC_PER_MONTH)
2187                 snprintf(buf, l, "%llu months and %llu days ago",
2188                          (unsigned long long) (d / USEC_PER_MONTH),
2189                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2190         else if (d >= USEC_PER_WEEK)
2191                 snprintf(buf, l, "%llu weeks and %llu days ago",
2192                          (unsigned long long) (d / USEC_PER_WEEK),
2193                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2194         else if (d >= 2*USEC_PER_DAY)
2195                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2196         else if (d >= 25*USEC_PER_HOUR)
2197                 snprintf(buf, l, "1 day and %lluh ago",
2198                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2199         else if (d >= 6*USEC_PER_HOUR)
2200                 snprintf(buf, l, "%lluh ago",
2201                          (unsigned long long) (d / USEC_PER_HOUR));
2202         else if (d >= USEC_PER_HOUR)
2203                 snprintf(buf, l, "%lluh %llumin ago",
2204                          (unsigned long long) (d / USEC_PER_HOUR),
2205                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2206         else if (d >= 5*USEC_PER_MINUTE)
2207                 snprintf(buf, l, "%llumin ago",
2208                          (unsigned long long) (d / USEC_PER_MINUTE));
2209         else if (d >= USEC_PER_MINUTE)
2210                 snprintf(buf, l, "%llumin %llus ago",
2211                          (unsigned long long) (d / USEC_PER_MINUTE),
2212                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2213         else if (d >= USEC_PER_SEC)
2214                 snprintf(buf, l, "%llus ago",
2215                          (unsigned long long) (d / USEC_PER_SEC));
2216         else if (d >= USEC_PER_MSEC)
2217                 snprintf(buf, l, "%llums ago",
2218                          (unsigned long long) (d / USEC_PER_MSEC));
2219         else if (d > 0)
2220                 snprintf(buf, l, "%lluus ago",
2221                          (unsigned long long) d);
2222         else
2223                 snprintf(buf, l, "now");
2224
2225         buf[l-1] = 0;
2226         return buf;
2227 }
2228
2229 char *format_timespan(char *buf, size_t l, usec_t t) {
2230         static const struct {
2231                 const char *suffix;
2232                 usec_t usec;
2233         } table[] = {
2234                 { "w", USEC_PER_WEEK },
2235                 { "d", USEC_PER_DAY },
2236                 { "h", USEC_PER_HOUR },
2237                 { "min", USEC_PER_MINUTE },
2238                 { "s", USEC_PER_SEC },
2239                 { "ms", USEC_PER_MSEC },
2240                 { "us", 1 },
2241         };
2242
2243         unsigned i;
2244         char *p = buf;
2245
2246         assert(buf);
2247         assert(l > 0);
2248
2249         if (t == (usec_t) -1)
2250                 return NULL;
2251
2252         if (t == 0) {
2253                 snprintf(p, l, "0");
2254                 p[l-1] = 0;
2255                 return p;
2256         }
2257
2258         /* The result of this function can be parsed with parse_usec */
2259
2260         for (i = 0; i < ELEMENTSOF(table); i++) {
2261                 int k;
2262                 size_t n;
2263
2264                 if (t < table[i].usec)
2265                         continue;
2266
2267                 if (l <= 1)
2268                         break;
2269
2270                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2271                 n = MIN((size_t) k, l);
2272
2273                 l -= n;
2274                 p += n;
2275
2276                 t %= table[i].usec;
2277         }
2278
2279         *p = 0;
2280
2281         return buf;
2282 }
2283
2284 bool fstype_is_network(const char *fstype) {
2285         static const char * const table[] = {
2286                 "cifs",
2287                 "smbfs",
2288                 "ncpfs",
2289                 "nfs",
2290                 "nfs4",
2291                 "gfs",
2292                 "gfs2"
2293         };
2294
2295         unsigned i;
2296
2297         for (i = 0; i < ELEMENTSOF(table); i++)
2298                 if (streq(table[i], fstype))
2299                         return true;
2300
2301         return false;
2302 }
2303
2304 int chvt(int vt) {
2305         int fd, r = 0;
2306
2307         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2308                 return -errno;
2309
2310         if (vt < 0) {
2311                 int tiocl[2] = {
2312                         TIOCL_GETKMSGREDIRECT,
2313                         0
2314                 };
2315
2316                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2317                         return -errno;
2318
2319                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2320         }
2321
2322         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2323                 r = -errno;
2324
2325         close_nointr_nofail(r);
2326         return r;
2327 }
2328
2329 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2330         struct termios old_termios, new_termios;
2331         char c;
2332         char line[LINE_MAX];
2333
2334         assert(f);
2335         assert(ret);
2336
2337         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2338                 new_termios = old_termios;
2339
2340                 new_termios.c_lflag &= ~ICANON;
2341                 new_termios.c_cc[VMIN] = 1;
2342                 new_termios.c_cc[VTIME] = 0;
2343
2344                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2345                         size_t k;
2346
2347                         k = fread(&c, 1, 1, f);
2348
2349                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2350
2351                         if (k <= 0)
2352                                 return -EIO;
2353
2354                         if (need_nl)
2355                                 *need_nl = c != '\n';
2356
2357                         *ret = c;
2358                         return 0;
2359                 }
2360         }
2361
2362         if (!(fgets(line, sizeof(line), f)))
2363                 return -EIO;
2364
2365         truncate_nl(line);
2366
2367         if (strlen(line) != 1)
2368                 return -EBADMSG;
2369
2370         if (need_nl)
2371                 *need_nl = false;
2372
2373         *ret = line[0];
2374         return 0;
2375 }
2376
2377 int ask(char *ret, const char *replies, const char *text, ...) {
2378         bool on_tty;
2379
2380         assert(ret);
2381         assert(replies);
2382         assert(text);
2383
2384         on_tty = isatty(STDOUT_FILENO);
2385
2386         for (;;) {
2387                 va_list ap;
2388                 char c;
2389                 int r;
2390                 bool need_nl = true;
2391
2392                 if (on_tty)
2393                         fputs("\x1B[1m", stdout);
2394
2395                 va_start(ap, text);
2396                 vprintf(text, ap);
2397                 va_end(ap);
2398
2399                 if (on_tty)
2400                         fputs("\x1B[0m", stdout);
2401
2402                 fflush(stdout);
2403
2404                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2405
2406                         if (r == -EBADMSG) {
2407                                 puts("Bad input, please try again.");
2408                                 continue;
2409                         }
2410
2411                         putchar('\n');
2412                         return r;
2413                 }
2414
2415                 if (need_nl)
2416                         putchar('\n');
2417
2418                 if (strchr(replies, c)) {
2419                         *ret = c;
2420                         return 0;
2421                 }
2422
2423                 puts("Read unexpected character, please try again.");
2424         }
2425 }
2426
2427 int reset_terminal_fd(int fd) {
2428         struct termios termios;
2429         int r = 0;
2430         long arg;
2431
2432         /* Set terminal to some sane defaults */
2433
2434         assert(fd >= 0);
2435
2436         /* We leave locked terminal attributes untouched, so that
2437          * Plymouth may set whatever it wants to set, and we don't
2438          * interfere with that. */
2439
2440         /* Disable exclusive mode, just in case */
2441         ioctl(fd, TIOCNXCL);
2442
2443         /* Enable console unicode mode */
2444         arg = K_UNICODE;
2445         ioctl(fd, KDSKBMODE, &arg);
2446
2447         if (tcgetattr(fd, &termios) < 0) {
2448                 r = -errno;
2449                 goto finish;
2450         }
2451
2452         /* We only reset the stuff that matters to the software. How
2453          * hardware is set up we don't touch assuming that somebody
2454          * else will do that for us */
2455
2456         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2457         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2458         termios.c_oflag |= ONLCR;
2459         termios.c_cflag |= CREAD;
2460         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2461
2462         termios.c_cc[VINTR]    =   03;  /* ^C */
2463         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2464         termios.c_cc[VERASE]   = 0177;
2465         termios.c_cc[VKILL]    =  025;  /* ^X */
2466         termios.c_cc[VEOF]     =   04;  /* ^D */
2467         termios.c_cc[VSTART]   =  021;  /* ^Q */
2468         termios.c_cc[VSTOP]    =  023;  /* ^S */
2469         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2470         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2471         termios.c_cc[VWERASE]  =  027;  /* ^W */
2472         termios.c_cc[VREPRINT] =  022;  /* ^R */
2473         termios.c_cc[VEOL]     =    0;
2474         termios.c_cc[VEOL2]    =    0;
2475
2476         termios.c_cc[VTIME]  = 0;
2477         termios.c_cc[VMIN]   = 1;
2478
2479         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2480                 r = -errno;
2481
2482 finish:
2483         /* Just in case, flush all crap out */
2484         tcflush(fd, TCIOFLUSH);
2485
2486         return r;
2487 }
2488
2489 int reset_terminal(const char *name) {
2490         int fd, r;
2491
2492         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2493         if (fd < 0)
2494                 return fd;
2495
2496         r = reset_terminal_fd(fd);
2497         close_nointr_nofail(fd);
2498
2499         return r;
2500 }
2501
2502 int open_terminal(const char *name, int mode) {
2503         int fd, r;
2504         unsigned c = 0;
2505
2506         /*
2507          * If a TTY is in the process of being closed opening it might
2508          * cause EIO. This is horribly awful, but unlikely to be
2509          * changed in the kernel. Hence we work around this problem by
2510          * retrying a couple of times.
2511          *
2512          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2513          */
2514
2515         for (;;) {
2516                 if ((fd = open(name, mode)) >= 0)
2517                         break;
2518
2519                 if (errno != EIO)
2520                         return -errno;
2521
2522                 if (c >= 20)
2523                         return -errno;
2524
2525                 usleep(50 * USEC_PER_MSEC);
2526                 c++;
2527         }
2528
2529         if (fd < 0)
2530                 return -errno;
2531
2532         if ((r = isatty(fd)) < 0) {
2533                 close_nointr_nofail(fd);
2534                 return -errno;
2535         }
2536
2537         if (!r) {
2538                 close_nointr_nofail(fd);
2539                 return -ENOTTY;
2540         }
2541
2542         return fd;
2543 }
2544
2545 int flush_fd(int fd) {
2546         struct pollfd pollfd;
2547
2548         zero(pollfd);
2549         pollfd.fd = fd;
2550         pollfd.events = POLLIN;
2551
2552         for (;;) {
2553                 char buf[LINE_MAX];
2554                 ssize_t l;
2555                 int r;
2556
2557                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2558
2559                         if (errno == EINTR)
2560                                 continue;
2561
2562                         return -errno;
2563                 }
2564
2565                 if (r == 0)
2566                         return 0;
2567
2568                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2569
2570                         if (errno == EINTR)
2571                                 continue;
2572
2573                         if (errno == EAGAIN)
2574                                 return 0;
2575
2576                         return -errno;
2577                 }
2578
2579                 if (l <= 0)
2580                         return 0;
2581         }
2582 }
2583
2584 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2585         int fd = -1, notify = -1, r, wd = -1;
2586
2587         assert(name);
2588
2589         /* We use inotify to be notified when the tty is closed. We
2590          * create the watch before checking if we can actually acquire
2591          * it, so that we don't lose any event.
2592          *
2593          * Note: strictly speaking this actually watches for the
2594          * device being closed, it does *not* really watch whether a
2595          * tty loses its controlling process. However, unless some
2596          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2597          * its tty otherwise this will not become a problem. As long
2598          * as the administrator makes sure not configure any service
2599          * on the same tty as an untrusted user this should not be a
2600          * problem. (Which he probably should not do anyway.) */
2601
2602         if (!fail && !force) {
2603                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2604                         r = -errno;
2605                         goto fail;
2606                 }
2607
2608                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2609                         r = -errno;
2610                         goto fail;
2611                 }
2612         }
2613
2614         for (;;) {
2615                 if (notify >= 0)
2616                         if ((r = flush_fd(notify)) < 0)
2617                                 goto fail;
2618
2619                 /* We pass here O_NOCTTY only so that we can check the return
2620                  * value TIOCSCTTY and have a reliable way to figure out if we
2621                  * successfully became the controlling process of the tty */
2622                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2623                         return fd;
2624
2625                 /* First, try to get the tty */
2626                 r = ioctl(fd, TIOCSCTTY, force);
2627
2628                 /* Sometimes it makes sense to ignore TIOCSCTTY
2629                  * returning EPERM, i.e. when very likely we already
2630                  * are have this controlling terminal. */
2631                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2632                         r = 0;
2633
2634                 if (r < 0 && (force || fail || errno != EPERM)) {
2635                         r = -errno;
2636                         goto fail;
2637                 }
2638
2639                 if (r >= 0)
2640                         break;
2641
2642                 assert(!fail);
2643                 assert(!force);
2644                 assert(notify >= 0);
2645
2646                 for (;;) {
2647                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2648                         ssize_t l;
2649                         struct inotify_event *e;
2650
2651                         if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2652
2653                                 if (errno == EINTR)
2654                                         continue;
2655
2656                                 r = -errno;
2657                                 goto fail;
2658                         }
2659
2660                         e = (struct inotify_event*) inotify_buffer;
2661
2662                         while (l > 0) {
2663                                 size_t step;
2664
2665                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2666                                         r = -EIO;
2667                                         goto fail;
2668                                 }
2669
2670                                 step = sizeof(struct inotify_event) + e->len;
2671                                 assert(step <= (size_t) l);
2672
2673                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2674                                 l -= step;
2675                         }
2676
2677                         break;
2678                 }
2679
2680                 /* We close the tty fd here since if the old session
2681                  * ended our handle will be dead. It's important that
2682                  * we do this after sleeping, so that we don't enter
2683                  * an endless loop. */
2684                 close_nointr_nofail(fd);
2685         }
2686
2687         if (notify >= 0)
2688                 close_nointr_nofail(notify);
2689
2690         if ((r = reset_terminal_fd(fd)) < 0)
2691                 log_warning("Failed to reset terminal: %s", strerror(-r));
2692
2693         return fd;
2694
2695 fail:
2696         if (fd >= 0)
2697                 close_nointr_nofail(fd);
2698
2699         if (notify >= 0)
2700                 close_nointr_nofail(notify);
2701
2702         return r;
2703 }
2704
2705 int release_terminal(void) {
2706         int r = 0, fd;
2707         struct sigaction sa_old, sa_new;
2708
2709         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2710                 return -errno;
2711
2712         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2713          * by our own TIOCNOTTY */
2714
2715         zero(sa_new);
2716         sa_new.sa_handler = SIG_IGN;
2717         sa_new.sa_flags = SA_RESTART;
2718         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2719
2720         if (ioctl(fd, TIOCNOTTY) < 0)
2721                 r = -errno;
2722
2723         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2724
2725         close_nointr_nofail(fd);
2726         return r;
2727 }
2728
2729 int sigaction_many(const struct sigaction *sa, ...) {
2730         va_list ap;
2731         int r = 0, sig;
2732
2733         va_start(ap, sa);
2734         while ((sig = va_arg(ap, int)) > 0)
2735                 if (sigaction(sig, sa, NULL) < 0)
2736                         r = -errno;
2737         va_end(ap);
2738
2739         return r;
2740 }
2741
2742 int ignore_signals(int sig, ...) {
2743         struct sigaction sa;
2744         va_list ap;
2745         int r = 0;
2746
2747         zero(sa);
2748         sa.sa_handler = SIG_IGN;
2749         sa.sa_flags = SA_RESTART;
2750
2751         if (sigaction(sig, &sa, NULL) < 0)
2752                 r = -errno;
2753
2754         va_start(ap, sig);
2755         while ((sig = va_arg(ap, int)) > 0)
2756                 if (sigaction(sig, &sa, NULL) < 0)
2757                         r = -errno;
2758         va_end(ap);
2759
2760         return r;
2761 }
2762
2763 int default_signals(int sig, ...) {
2764         struct sigaction sa;
2765         va_list ap;
2766         int r = 0;
2767
2768         zero(sa);
2769         sa.sa_handler = SIG_DFL;
2770         sa.sa_flags = SA_RESTART;
2771
2772         if (sigaction(sig, &sa, NULL) < 0)
2773                 r = -errno;
2774
2775         va_start(ap, sig);
2776         while ((sig = va_arg(ap, int)) > 0)
2777                 if (sigaction(sig, &sa, NULL) < 0)
2778                         r = -errno;
2779         va_end(ap);
2780
2781         return r;
2782 }
2783
2784 int close_pipe(int p[]) {
2785         int a = 0, b = 0;
2786
2787         assert(p);
2788
2789         if (p[0] >= 0) {
2790                 a = close_nointr(p[0]);
2791                 p[0] = -1;
2792         }
2793
2794         if (p[1] >= 0) {
2795                 b = close_nointr(p[1]);
2796                 p[1] = -1;
2797         }
2798
2799         return a < 0 ? a : b;
2800 }
2801
2802 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2803         uint8_t *p;
2804         ssize_t n = 0;
2805
2806         assert(fd >= 0);
2807         assert(buf);
2808
2809         p = buf;
2810
2811         while (nbytes > 0) {
2812                 ssize_t k;
2813
2814                 if ((k = read(fd, p, nbytes)) <= 0) {
2815
2816                         if (k < 0 && errno == EINTR)
2817                                 continue;
2818
2819                         if (k < 0 && errno == EAGAIN && do_poll) {
2820                                 struct pollfd pollfd;
2821
2822                                 zero(pollfd);
2823                                 pollfd.fd = fd;
2824                                 pollfd.events = POLLIN;
2825
2826                                 if (poll(&pollfd, 1, -1) < 0) {
2827                                         if (errno == EINTR)
2828                                                 continue;
2829
2830                                         return n > 0 ? n : -errno;
2831                                 }
2832
2833                                 if (pollfd.revents != POLLIN)
2834                                         return n > 0 ? n : -EIO;
2835
2836                                 continue;
2837                         }
2838
2839                         return n > 0 ? n : (k < 0 ? -errno : 0);
2840                 }
2841
2842                 p += k;
2843                 nbytes -= k;
2844                 n += k;
2845         }
2846
2847         return n;
2848 }
2849
2850 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2851         const uint8_t *p;
2852         ssize_t n = 0;
2853
2854         assert(fd >= 0);
2855         assert(buf);
2856
2857         p = buf;
2858
2859         while (nbytes > 0) {
2860                 ssize_t k;
2861
2862                 if ((k = write(fd, p, nbytes)) <= 0) {
2863
2864                         if (k < 0 && errno == EINTR)
2865                                 continue;
2866
2867                         if (k < 0 && errno == EAGAIN && do_poll) {
2868                                 struct pollfd pollfd;
2869
2870                                 zero(pollfd);
2871                                 pollfd.fd = fd;
2872                                 pollfd.events = POLLOUT;
2873
2874                                 if (poll(&pollfd, 1, -1) < 0) {
2875                                         if (errno == EINTR)
2876                                                 continue;
2877
2878                                         return n > 0 ? n : -errno;
2879                                 }
2880
2881                                 if (pollfd.revents != POLLOUT)
2882                                         return n > 0 ? n : -EIO;
2883
2884                                 continue;
2885                         }
2886
2887                         return n > 0 ? n : (k < 0 ? -errno : 0);
2888                 }
2889
2890                 p += k;
2891                 nbytes -= k;
2892                 n += k;
2893         }
2894
2895         return n;
2896 }
2897
2898 int path_is_mount_point(const char *t) {
2899         struct stat a, b;
2900         char *parent;
2901         int r;
2902
2903         if (lstat(t, &a) < 0) {
2904                 if (errno == ENOENT)
2905                         return 0;
2906
2907                 return -errno;
2908         }
2909
2910         if ((r = parent_of_path(t, &parent)) < 0)
2911                 return r;
2912
2913         r = lstat(parent, &b);
2914         free(parent);
2915
2916         if (r < 0)
2917                 return -errno;
2918
2919         return a.st_dev != b.st_dev;
2920 }
2921
2922 int parse_usec(const char *t, usec_t *usec) {
2923         static const struct {
2924                 const char *suffix;
2925                 usec_t usec;
2926         } table[] = {
2927                 { "sec", USEC_PER_SEC },
2928                 { "s", USEC_PER_SEC },
2929                 { "min", USEC_PER_MINUTE },
2930                 { "hr", USEC_PER_HOUR },
2931                 { "h", USEC_PER_HOUR },
2932                 { "d", USEC_PER_DAY },
2933                 { "w", USEC_PER_WEEK },
2934                 { "msec", USEC_PER_MSEC },
2935                 { "ms", USEC_PER_MSEC },
2936                 { "m", USEC_PER_MINUTE },
2937                 { "usec", 1ULL },
2938                 { "us", 1ULL },
2939                 { "", USEC_PER_SEC },
2940         };
2941
2942         const char *p;
2943         usec_t r = 0;
2944
2945         assert(t);
2946         assert(usec);
2947
2948         p = t;
2949         do {
2950                 long long l;
2951                 char *e;
2952                 unsigned i;
2953
2954                 errno = 0;
2955                 l = strtoll(p, &e, 10);
2956
2957                 if (errno != 0)
2958                         return -errno;
2959
2960                 if (l < 0)
2961                         return -ERANGE;
2962
2963                 if (e == p)
2964                         return -EINVAL;
2965
2966                 e += strspn(e, WHITESPACE);
2967
2968                 for (i = 0; i < ELEMENTSOF(table); i++)
2969                         if (startswith(e, table[i].suffix)) {
2970                                 r += (usec_t) l * table[i].usec;
2971                                 p = e + strlen(table[i].suffix);
2972                                 break;
2973                         }
2974
2975                 if (i >= ELEMENTSOF(table))
2976                         return -EINVAL;
2977
2978         } while (*p != 0);
2979
2980         *usec = r;
2981
2982         return 0;
2983 }
2984
2985 int parse_bytes(const char *t, off_t *bytes) {
2986         static const struct {
2987                 const char *suffix;
2988                 off_t factor;
2989         } table[] = {
2990                 { "B", 1 },
2991                 { "K", 1024ULL },
2992                 { "M", 1024ULL*1024ULL },
2993                 { "G", 1024ULL*1024ULL*1024ULL },
2994                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2995                 { "", 1 },
2996         };
2997
2998         const char *p;
2999         off_t r = 0;
3000
3001         assert(t);
3002         assert(bytes);
3003
3004         p = t;
3005         do {
3006                 long long l;
3007                 char *e;
3008                 unsigned i;
3009
3010                 errno = 0;
3011                 l = strtoll(p, &e, 10);
3012
3013                 if (errno != 0)
3014                         return -errno;
3015
3016                 if (l < 0)
3017                         return -ERANGE;
3018
3019                 if (e == p)
3020                         return -EINVAL;
3021
3022                 e += strspn(e, WHITESPACE);
3023
3024                 for (i = 0; i < ELEMENTSOF(table); i++)
3025                         if (startswith(e, table[i].suffix)) {
3026                                 r += (off_t) l * table[i].factor;
3027                                 p = e + strlen(table[i].suffix);
3028                                 break;
3029                         }
3030
3031                 if (i >= ELEMENTSOF(table))
3032                         return -EINVAL;
3033
3034         } while (*p != 0);
3035
3036         *bytes = r;
3037
3038         return 0;
3039 }
3040
3041 int make_stdio(int fd) {
3042         int r, s, t;
3043
3044         assert(fd >= 0);
3045
3046         r = dup2(fd, STDIN_FILENO);
3047         s = dup2(fd, STDOUT_FILENO);
3048         t = dup2(fd, STDERR_FILENO);
3049
3050         if (fd >= 3)
3051                 close_nointr_nofail(fd);
3052
3053         if (r < 0 || s < 0 || t < 0)
3054                 return -errno;
3055
3056         fd_cloexec(STDIN_FILENO, false);
3057         fd_cloexec(STDOUT_FILENO, false);
3058         fd_cloexec(STDERR_FILENO, false);
3059
3060         return 0;
3061 }
3062
3063 int make_null_stdio(void) {
3064         int null_fd;
3065
3066         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3067                 return -errno;
3068
3069         return make_stdio(null_fd);
3070 }
3071
3072 bool is_device_path(const char *path) {
3073
3074         /* Returns true on paths that refer to a device, either in
3075          * sysfs or in /dev */
3076
3077         return
3078                 path_startswith(path, "/dev/") ||
3079                 path_startswith(path, "/sys/");
3080 }
3081
3082 int dir_is_empty(const char *path) {
3083         DIR *d;
3084         int r;
3085         struct dirent buf, *de;
3086
3087         if (!(d = opendir(path)))
3088                 return -errno;
3089
3090         for (;;) {
3091                 if ((r = readdir_r(d, &buf, &de)) > 0) {
3092                         r = -r;
3093                         break;
3094                 }
3095
3096                 if (!de) {
3097                         r = 1;
3098                         break;
3099                 }
3100
3101                 if (!ignore_file(de->d_name)) {
3102                         r = 0;
3103                         break;
3104                 }
3105         }
3106
3107         closedir(d);
3108         return r;
3109 }
3110
3111 unsigned long long random_ull(void) {
3112         int fd;
3113         uint64_t ull;
3114         ssize_t r;
3115
3116         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3117                 goto fallback;
3118
3119         r = loop_read(fd, &ull, sizeof(ull), true);
3120         close_nointr_nofail(fd);
3121
3122         if (r != sizeof(ull))
3123                 goto fallback;
3124
3125         return ull;
3126
3127 fallback:
3128         return random() * RAND_MAX + random();
3129 }
3130
3131 void rename_process(const char name[8]) {
3132         assert(name);
3133
3134         prctl(PR_SET_NAME, name);
3135
3136         /* This is a like a poor man's setproctitle(). The string
3137          * passed should fit in 7 chars (i.e. the length of
3138          * "systemd") */
3139
3140         if (program_invocation_name)
3141                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3142
3143         if (saved_argc > 0) {
3144                 int i;
3145
3146                 if (saved_argv[0])
3147                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3148
3149                 for (i = 1; i < saved_argc; i++) {
3150                         if (!saved_argv[i])
3151                                 break;
3152
3153                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3154                 }
3155         }
3156 }
3157
3158 void sigset_add_many(sigset_t *ss, ...) {
3159         va_list ap;
3160         int sig;
3161
3162         assert(ss);
3163
3164         va_start(ap, ss);
3165         while ((sig = va_arg(ap, int)) > 0)
3166                 assert_se(sigaddset(ss, sig) == 0);
3167         va_end(ap);
3168 }
3169
3170 char* gethostname_malloc(void) {
3171         struct utsname u;
3172
3173         assert_se(uname(&u) >= 0);
3174
3175         if (u.nodename[0])
3176                 return strdup(u.nodename);
3177
3178         return strdup(u.sysname);
3179 }
3180
3181 char* getlogname_malloc(void) {
3182         uid_t uid;
3183         long bufsize;
3184         char *buf, *name;
3185         struct passwd pwbuf, *pw = NULL;
3186         struct stat st;
3187
3188         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3189                 uid = st.st_uid;
3190         else
3191                 uid = getuid();
3192
3193         /* Shortcut things to avoid NSS lookups */
3194         if (uid == 0)
3195                 return strdup("root");
3196
3197         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3198                 bufsize = 4096;
3199
3200         if (!(buf = malloc(bufsize)))
3201                 return NULL;
3202
3203         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3204                 name = strdup(pw->pw_name);
3205                 free(buf);
3206                 return name;
3207         }
3208
3209         free(buf);
3210
3211         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3212                 return NULL;
3213
3214         return name;
3215 }
3216
3217 int getttyname_malloc(int fd, char **r) {
3218         char path[PATH_MAX], *c;
3219         int k;
3220
3221         assert(r);
3222
3223         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3224                 return -k;
3225
3226         char_array_0(path);
3227
3228         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3229                 return -ENOMEM;
3230
3231         *r = c;
3232         return 0;
3233 }
3234
3235 int getttyname_harder(int fd, char **r) {
3236         int k;
3237         char *s;
3238
3239         if ((k = getttyname_malloc(fd, &s)) < 0)
3240                 return k;
3241
3242         if (streq(s, "tty")) {
3243                 free(s);
3244                 return get_ctty(0, NULL, r);
3245         }
3246
3247         *r = s;
3248         return 0;
3249 }
3250
3251 int get_ctty_devnr(pid_t pid, dev_t *d) {
3252         int k;
3253         char line[LINE_MAX], *p, *fn;
3254         unsigned long ttynr;
3255         FILE *f;
3256
3257         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3258                 return -ENOMEM;
3259
3260         f = fopen(fn, "re");
3261         free(fn);
3262         if (!f)
3263                 return -errno;
3264
3265         if (!fgets(line, sizeof(line), f)) {
3266                 k = -errno;
3267                 fclose(f);
3268                 return k;
3269         }
3270
3271         fclose(f);
3272
3273         p = strrchr(line, ')');
3274         if (!p)
3275                 return -EIO;
3276
3277         p++;
3278
3279         if (sscanf(p, " "
3280                    "%*c "  /* state */
3281                    "%*d "  /* ppid */
3282                    "%*d "  /* pgrp */
3283                    "%*d "  /* session */
3284                    "%lu ", /* ttynr */
3285                    &ttynr) != 1)
3286                 return -EIO;
3287
3288         *d = (dev_t) ttynr;
3289         return 0;
3290 }
3291
3292 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3293         int k;
3294         char fn[PATH_MAX], *s, *b, *p;
3295         dev_t devnr;
3296
3297         assert(r);
3298
3299         k = get_ctty_devnr(pid, &devnr);
3300         if (k < 0)
3301                 return k;
3302
3303         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3304         char_array_0(fn);
3305
3306         if ((k = readlink_malloc(fn, &s)) < 0) {
3307
3308                 if (k != -ENOENT)
3309                         return k;
3310
3311                 /* This is an ugly hack */
3312                 if (major(devnr) == 136) {
3313                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3314                                 return -ENOMEM;
3315
3316                         *r = b;
3317                         if (_devnr)
3318                                 *_devnr = devnr;
3319
3320                         return 0;
3321                 }
3322
3323                 /* Probably something like the ptys which have no
3324                  * symlink in /dev/char. Let's return something
3325                  * vaguely useful. */
3326
3327                 if (!(b = strdup(fn + 5)))
3328                         return -ENOMEM;
3329
3330                 *r = b;
3331                 if (_devnr)
3332                         *_devnr = devnr;
3333
3334                 return 0;
3335         }
3336
3337         if (startswith(s, "/dev/"))
3338                 p = s + 5;
3339         else if (startswith(s, "../"))
3340                 p = s + 3;
3341         else
3342                 p = s;
3343
3344         b = strdup(p);
3345         free(s);
3346
3347         if (!b)
3348                 return -ENOMEM;
3349
3350         *r = b;
3351         if (_devnr)
3352                 *_devnr = devnr;
3353
3354         return 0;
3355 }
3356
3357 static int rm_rf_children(int fd, bool only_dirs) {
3358         DIR *d;
3359         int ret = 0;
3360
3361         assert(fd >= 0);
3362
3363         /* This returns the first error we run into, but nevertheless
3364          * tries to go on */
3365
3366         if (!(d = fdopendir(fd))) {
3367                 close_nointr_nofail(fd);
3368
3369                 return errno == ENOENT ? 0 : -errno;
3370         }
3371
3372         for (;;) {
3373                 struct dirent buf, *de;
3374                 bool is_dir;
3375                 int r;
3376
3377                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3378                         if (ret == 0)
3379                                 ret = -r;
3380                         break;
3381                 }
3382
3383                 if (!de)
3384                         break;
3385
3386                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3387                         continue;
3388
3389                 if (de->d_type == DT_UNKNOWN) {
3390                         struct stat st;
3391
3392                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3393                                 if (ret == 0 && errno != ENOENT)
3394                                         ret = -errno;
3395                                 continue;
3396                         }
3397
3398                         is_dir = S_ISDIR(st.st_mode);
3399                 } else
3400                         is_dir = de->d_type == DT_DIR;
3401
3402                 if (is_dir) {
3403                         int subdir_fd;
3404
3405                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3406                                 if (ret == 0 && errno != ENOENT)
3407                                         ret = -errno;
3408                                 continue;
3409                         }
3410
3411                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3412                                 if (ret == 0)
3413                                         ret = r;
3414                         }
3415
3416                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3417                                 if (ret == 0 && errno != ENOENT)
3418                                         ret = -errno;
3419                         }
3420                 } else  if (!only_dirs) {
3421
3422                         if (unlinkat(fd, de->d_name, 0) < 0) {
3423                                 if (ret == 0 && errno != ENOENT)
3424                                         ret = -errno;
3425                         }
3426                 }
3427         }
3428
3429         closedir(d);
3430
3431         return ret;
3432 }
3433
3434 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3435         int fd;
3436         int r;
3437
3438         assert(path);
3439
3440         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3441
3442                 if (errno != ENOTDIR)
3443                         return -errno;
3444
3445                 if (delete_root && !only_dirs)
3446                         if (unlink(path) < 0)
3447                                 return -errno;
3448
3449                 return 0;
3450         }
3451
3452         r = rm_rf_children(fd, only_dirs);
3453
3454         if (delete_root)
3455                 if (rmdir(path) < 0) {
3456                         if (r == 0)
3457                                 r = -errno;
3458                 }
3459
3460         return r;
3461 }
3462
3463 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3464         assert(path);
3465
3466         /* Under the assumption that we are running privileged we
3467          * first change the access mode and only then hand out
3468          * ownership to avoid a window where access is too open. */
3469
3470         if (chmod(path, mode) < 0)
3471                 return -errno;
3472
3473         if (chown(path, uid, gid) < 0)
3474                 return -errno;
3475
3476         return 0;
3477 }
3478
3479 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3480         cpu_set_t *r;
3481         unsigned n = 1024;
3482
3483         /* Allocates the cpuset in the right size */
3484
3485         for (;;) {
3486                 if (!(r = CPU_ALLOC(n)))
3487                         return NULL;
3488
3489                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3490                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3491
3492                         if (ncpus)
3493                                 *ncpus = n;
3494
3495                         return r;
3496                 }
3497
3498                 CPU_FREE(r);
3499
3500                 if (errno != EINVAL)
3501                         return NULL;
3502
3503                 n *= 2;
3504         }
3505 }
3506
3507 void status_vprintf(const char *format, va_list ap) {
3508         char *s = NULL;
3509         int fd = -1;
3510
3511         assert(format);
3512
3513         /* This independent of logging, as status messages are
3514          * optional and go exclusively to the console. */
3515
3516         if (vasprintf(&s, format, ap) < 0)
3517                 goto finish;
3518
3519         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3520                 goto finish;
3521
3522         write(fd, s, strlen(s));
3523
3524 finish:
3525         free(s);
3526
3527         if (fd >= 0)
3528                 close_nointr_nofail(fd);
3529 }
3530
3531 void status_printf(const char *format, ...) {
3532         va_list ap;
3533
3534         assert(format);
3535
3536         va_start(ap, format);
3537         status_vprintf(format, ap);
3538         va_end(ap);
3539 }
3540
3541 void status_welcome(void) {
3542         char *pretty_name = NULL, *ansi_color = NULL;
3543         const char *const_pretty = NULL, *const_color = NULL;
3544         int r;
3545
3546         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3547                                 "PRETTY_NAME", &pretty_name,
3548                                 "ANSI_COLOR", &ansi_color,
3549                                 NULL)) < 0) {
3550
3551                 if (r != -ENOENT)
3552                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3553         }
3554
3555 #if defined(TARGET_FEDORA)
3556         if (!pretty_name) {
3557                 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3558
3559                         if (r != -ENOENT)
3560                                 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3561                 }
3562         }
3563
3564         if (!ansi_color && pretty_name) {
3565
3566                 /* This tries to mimic the color magic the old Red Hat sysinit
3567                  * script did. */
3568
3569                 if (startswith(pretty_name, "Red Hat"))
3570                         const_color = "0;31"; /* Red for RHEL */
3571                 else if (startswith(pretty_name, "Fedora"))
3572                         const_color = "0;34"; /* Blue for Fedora */
3573         }
3574
3575 #elif defined(TARGET_SUSE)
3576
3577         if (!pretty_name) {
3578                 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3579
3580                         if (r != -ENOENT)
3581                                 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3582                 }
3583         }
3584
3585         if (!ansi_color)
3586                 const_color = "0;32"; /* Green for openSUSE */
3587
3588 #elif defined(TARGET_GENTOO)
3589
3590         if (!pretty_name) {
3591                 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3592
3593                         if (r != -ENOENT)
3594                                 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3595                 }
3596         }
3597
3598         if (!ansi_color)
3599                 const_color = "1;34"; /* Light Blue for Gentoo */
3600
3601 #elif defined(TARGET_ALTLINUX)
3602
3603         if (!pretty_name) {
3604                 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3605
3606                         if (r != -ENOENT)
3607                                 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3608                 }
3609         }
3610
3611         if (!ansi_color)
3612                 const_color = "0;36"; /* Cyan for ALTLinux */
3613
3614
3615 #elif defined(TARGET_DEBIAN)
3616
3617         if (!pretty_name) {
3618                 char *version;
3619
3620                 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3621
3622                         if (r != -ENOENT)
3623                                 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3624                 } else {
3625                         pretty_name = strappend("Debian ", version);
3626                         free(version);
3627
3628                         if (!pretty_name)
3629                                 log_warning("Failed to allocate Debian version string.");
3630                 }
3631         }
3632
3633         if (!ansi_color)
3634                 const_color = "1;31"; /* Light Red for Debian */
3635
3636 #elif defined(TARGET_UBUNTU)
3637
3638         if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3639                                 "DISTRIB_DESCRIPTION", &pretty_name,
3640                                 NULL)) < 0) {
3641
3642                 if (r != -ENOENT)
3643                         log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3644         }
3645
3646         if (!ansi_color)
3647                 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3648
3649 #elif defined(TARGET_MANDRIVA)
3650
3651         if (!pretty_name) {
3652                 char *s, *p;
3653
3654                 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3655                         if (r != -ENOENT)
3656                                 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3657                 } else {
3658                         p = strstr(s, " release ");
3659                         if (p) {
3660                                 *p = '\0';
3661                                 p += 9;
3662                                 p[strcspn(p, " ")] = '\0';
3663
3664                                 /* This corresponds to standard rc.sysinit */
3665                                 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3666                                         const_color = "1;36";
3667                                 else
3668                                         log_warning("Failed to allocate Mandriva version string.");
3669                         } else
3670                                 log_warning("Failed to parse /etc/mandriva-release");
3671                         free(s);
3672                 }
3673         }
3674 #elif defined(TARGET_MEEGO)
3675
3676         if (!pretty_name) {
3677                 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3678
3679                         if (r != -ENOENT)
3680                                 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3681                 }
3682         }
3683
3684        if (!ansi_color)
3685                const_color = "1;35"; /* Bright Magenta for MeeGo */
3686 #endif
3687
3688         if (!pretty_name && !const_pretty)
3689                 const_pretty = "Linux";
3690
3691         if (!ansi_color && !const_color)
3692                 const_color = "1";
3693
3694         status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3695                       const_color ? const_color : ansi_color,
3696                       const_pretty ? const_pretty : pretty_name);
3697
3698         free(ansi_color);
3699         free(pretty_name);
3700 }
3701
3702 char *replace_env(const char *format, char **env) {
3703         enum {
3704                 WORD,
3705                 CURLY,
3706                 VARIABLE
3707         } state = WORD;
3708
3709         const char *e, *word = format;
3710         char *r = NULL, *k;
3711
3712         assert(format);
3713
3714         for (e = format; *e; e ++) {
3715
3716                 switch (state) {
3717
3718                 case WORD:
3719                         if (*e == '$')
3720                                 state = CURLY;
3721                         break;
3722
3723                 case CURLY:
3724                         if (*e == '{') {
3725                                 if (!(k = strnappend(r, word, e-word-1)))
3726                                         goto fail;
3727
3728                                 free(r);
3729                                 r = k;
3730
3731                                 word = e-1;
3732                                 state = VARIABLE;
3733
3734                         } else if (*e == '$') {
3735                                 if (!(k = strnappend(r, word, e-word)))
3736                                         goto fail;
3737
3738                                 free(r);
3739                                 r = k;
3740
3741                                 word = e+1;
3742                                 state = WORD;
3743                         } else
3744                                 state = WORD;
3745                         break;
3746
3747                 case VARIABLE:
3748                         if (*e == '}') {
3749                                 const char *t;
3750
3751                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3752                                         t = "";
3753
3754                                 if (!(k = strappend(r, t)))
3755                                         goto fail;
3756
3757                                 free(r);
3758                                 r = k;
3759
3760                                 word = e+1;
3761                                 state = WORD;
3762                         }
3763                         break;
3764                 }
3765         }
3766
3767         if (!(k = strnappend(r, word, e-word)))
3768                 goto fail;
3769
3770         free(r);
3771         return k;
3772
3773 fail:
3774         free(r);
3775         return NULL;
3776 }
3777
3778 char **replace_env_argv(char **argv, char **env) {
3779         char **r, **i;
3780         unsigned k = 0, l = 0;
3781
3782         l = strv_length(argv);
3783
3784         if (!(r = new(char*, l+1)))
3785                 return NULL;
3786
3787         STRV_FOREACH(i, argv) {
3788
3789                 /* If $FOO appears as single word, replace it by the split up variable */
3790                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3791                         char *e;
3792                         char **w, **m;
3793                         unsigned q;
3794
3795                         if ((e = strv_env_get(env, *i+1))) {
3796
3797                                 if (!(m = strv_split_quoted(e))) {
3798                                         r[k] = NULL;
3799                                         strv_free(r);
3800                                         return NULL;
3801                                 }
3802                         } else
3803                                 m = NULL;
3804
3805                         q = strv_length(m);
3806                         l = l + q - 1;
3807
3808                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3809                                 r[k] = NULL;
3810                                 strv_free(r);
3811                                 strv_free(m);
3812                                 return NULL;
3813                         }
3814
3815                         r = w;
3816                         if (m) {
3817                                 memcpy(r + k, m, q * sizeof(char*));
3818                                 free(m);
3819                         }
3820
3821                         k += q;
3822                         continue;
3823                 }
3824
3825                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3826                 if (!(r[k++] = replace_env(*i, env))) {
3827                         strv_free(r);
3828                         return NULL;
3829                 }
3830         }
3831
3832         r[k] = NULL;
3833         return r;
3834 }
3835
3836 int columns(void) {
3837         static __thread int parsed_columns = 0;
3838         const char *e;
3839
3840         if (_likely_(parsed_columns > 0))
3841                 return parsed_columns;
3842
3843         if ((e = getenv("COLUMNS")))
3844                 parsed_columns = atoi(e);
3845
3846         if (parsed_columns <= 0) {
3847                 struct winsize ws;
3848                 zero(ws);
3849
3850                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3851                         parsed_columns = ws.ws_col;
3852         }
3853
3854         if (parsed_columns <= 0)
3855                 parsed_columns = 80;
3856
3857         return parsed_columns;
3858 }
3859
3860 int running_in_chroot(void) {
3861         struct stat a, b;
3862
3863         zero(a);
3864         zero(b);
3865
3866         /* Only works as root */
3867
3868         if (stat("/proc/1/root", &a) < 0)
3869                 return -errno;
3870
3871         if (stat("/", &b) < 0)
3872                 return -errno;
3873
3874         return
3875                 a.st_dev != b.st_dev ||
3876                 a.st_ino != b.st_ino;
3877 }
3878
3879 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3880         size_t l, x;
3881         char *r;
3882
3883         assert(s);
3884         assert(percent <= 100);
3885         assert(length >= 3);
3886
3887         l = strlen(s);
3888
3889         if (l <= 3 || l <= length)
3890                 return strdup(s);
3891
3892         if (!(r = new0(char, length+1)))
3893                 return r;
3894
3895         x = (length * percent) / 100;
3896
3897         if (x > length - 3)
3898                 x = length - 3;
3899
3900         memcpy(r, s, x);
3901         r[x] = '.';
3902         r[x+1] = '.';
3903         r[x+2] = '.';
3904         memcpy(r + x + 3,
3905                s + l - (length - x - 3),
3906                length - x - 3);
3907
3908         return r;
3909 }
3910
3911 int touch(const char *path) {
3912         int fd;
3913
3914         assert(path);
3915
3916         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3917                 return -errno;
3918
3919         close_nointr_nofail(fd);
3920         return 0;
3921 }
3922
3923 char *unquote(const char *s, const char* quotes) {
3924         size_t l;
3925         assert(s);
3926
3927         if ((l = strlen(s)) < 2)
3928                 return strdup(s);
3929
3930         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3931                 return strndup(s+1, l-2);
3932
3933         return strdup(s);
3934 }
3935
3936 char *normalize_env_assignment(const char *s) {
3937         char *name, *value, *p, *r;
3938
3939         p = strchr(s, '=');
3940
3941         if (!p) {
3942                 if (!(r = strdup(s)))
3943                         return NULL;
3944
3945                 return strstrip(r);
3946         }
3947
3948         if (!(name = strndup(s, p - s)))
3949                 return NULL;
3950
3951         if (!(p = strdup(p+1))) {
3952                 free(name);
3953                 return NULL;
3954         }
3955
3956         value = unquote(strstrip(p), QUOTES);
3957         free(p);
3958
3959         if (!value) {
3960                 free(name);
3961                 return NULL;
3962         }
3963
3964         if (asprintf(&r, "%s=%s", name, value) < 0)
3965                 r = NULL;
3966
3967         free(value);
3968         free(name);
3969
3970         return r;
3971 }
3972
3973 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3974         siginfo_t dummy;
3975
3976         assert(pid >= 1);
3977
3978         if (!status)
3979                 status = &dummy;
3980
3981         for (;;) {
3982                 zero(*status);
3983
3984                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3985
3986                         if (errno == EINTR)
3987                                 continue;
3988
3989                         return -errno;
3990                 }
3991
3992                 return 0;
3993         }
3994 }
3995
3996 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3997         int r;
3998         siginfo_t status;
3999
4000         assert(name);
4001         assert(pid > 1);
4002
4003         if ((r = wait_for_terminate(pid, &status)) < 0) {
4004                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4005                 return r;
4006         }
4007
4008         if (status.si_code == CLD_EXITED) {
4009                 if (status.si_status != 0) {
4010                         log_warning("%s failed with error code %i.", name, status.si_status);
4011                         return status.si_status;
4012                 }
4013
4014                 log_debug("%s succeeded.", name);
4015                 return 0;
4016
4017         } else if (status.si_code == CLD_KILLED ||
4018                    status.si_code == CLD_DUMPED) {
4019
4020                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4021                 return -EPROTO;
4022         }
4023
4024         log_warning("%s failed due to unknown reason.", name);
4025         return -EPROTO;
4026
4027 }
4028
4029 void freeze(void) {
4030
4031         /* Make sure nobody waits for us on a socket anymore */
4032         close_all_fds(NULL, 0);
4033
4034         sync();
4035
4036         for (;;)
4037                 pause();
4038 }
4039
4040 bool null_or_empty(struct stat *st) {
4041         assert(st);
4042
4043         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4044                 return true;
4045
4046         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4047                 return true;
4048
4049         return false;
4050 }
4051
4052 int null_or_empty_path(const char *fn) {
4053         struct stat st;
4054
4055         assert(fn);
4056
4057         if (stat(fn, &st) < 0)
4058                 return -errno;
4059
4060         return null_or_empty(&st);
4061 }
4062
4063 DIR *xopendirat(int fd, const char *name, int flags) {
4064         int nfd;
4065         DIR *d;
4066
4067         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4068                 return NULL;
4069
4070         if (!(d = fdopendir(nfd))) {
4071                 close_nointr_nofail(nfd);
4072                 return NULL;
4073         }
4074
4075         return d;
4076 }
4077
4078 int signal_from_string_try_harder(const char *s) {
4079         int signo;
4080         assert(s);
4081
4082         if ((signo = signal_from_string(s)) <= 0)
4083                 if (startswith(s, "SIG"))
4084                         return signal_from_string(s+3);
4085
4086         return signo;
4087 }
4088
4089 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4090
4091         assert(f);
4092         assert(name);
4093         assert(t);
4094
4095         if (!dual_timestamp_is_set(t))
4096                 return;
4097
4098         fprintf(f, "%s=%llu %llu\n",
4099                 name,
4100                 (unsigned long long) t->realtime,
4101                 (unsigned long long) t->monotonic);
4102 }
4103
4104 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4105         unsigned long long a, b;
4106
4107         assert(value);
4108         assert(t);
4109
4110         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4111                 log_debug("Failed to parse finish timestamp value %s", value);
4112         else {
4113                 t->realtime = a;
4114                 t->monotonic = b;
4115         }
4116 }
4117
4118 char *fstab_node_to_udev_node(const char *p) {
4119         char *dn, *t, *u;
4120         int r;
4121
4122         /* FIXME: to follow udev's logic 100% we need to leave valid
4123          * UTF8 chars unescaped */
4124
4125         if (startswith(p, "LABEL=")) {
4126
4127                 if (!(u = unquote(p+6, "\"\'")))
4128                         return NULL;
4129
4130                 t = xescape(u, "/ ");
4131                 free(u);
4132
4133                 if (!t)
4134                         return NULL;
4135
4136                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4137                 free(t);
4138
4139                 if (r < 0)
4140                         return NULL;
4141
4142                 return dn;
4143         }
4144
4145         if (startswith(p, "UUID=")) {
4146
4147                 if (!(u = unquote(p+5, "\"\'")))
4148                         return NULL;
4149
4150                 t = xescape(u, "/ ");
4151                 free(u);
4152
4153                 if (!t)
4154                         return NULL;
4155
4156                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4157                 free(t);
4158
4159                 if (r < 0)
4160                         return NULL;
4161
4162                 return dn;
4163         }
4164
4165         return strdup(p);
4166 }
4167
4168 void filter_environ(const char *prefix) {
4169         int i, j;
4170         assert(prefix);
4171
4172         if (!environ)
4173                 return;
4174
4175         for (i = 0, j = 0; environ[i]; i++) {
4176
4177                 if (startswith(environ[i], prefix))
4178                         continue;
4179
4180                 environ[j++] = environ[i];
4181         }
4182
4183         environ[j] = NULL;
4184 }
4185
4186 bool tty_is_vc(const char *tty) {
4187         assert(tty);
4188
4189         if (startswith(tty, "/dev/"))
4190                 tty += 5;
4191
4192         return vtnr_from_tty(tty) >= 0;
4193 }
4194
4195 int vtnr_from_tty(const char *tty) {
4196         int i, r;
4197
4198         assert(tty);
4199
4200         if (startswith(tty, "/dev/"))
4201                 tty += 5;
4202
4203         if (!startswith(tty, "tty") )
4204                 return -EINVAL;
4205
4206         if (tty[3] < '0' || tty[3] > '9')
4207                 return -EINVAL;
4208
4209         r = safe_atoi(tty+3, &i);
4210         if (r < 0)
4211                 return r;
4212
4213         if (i < 0 || i > 63)
4214                 return -EINVAL;
4215
4216         return i;
4217 }
4218
4219 const char *default_term_for_tty(const char *tty) {
4220         char *active = NULL;
4221         const char *term;
4222
4223         assert(tty);
4224
4225         if (startswith(tty, "/dev/"))
4226                 tty += 5;
4227
4228         /* Resolve where /dev/console is pointing when determining
4229          * TERM */
4230         if (streq(tty, "console"))
4231                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4232                         /* If multiple log outputs are configured the
4233                          * last one is what /dev/console points to */
4234                         if ((tty = strrchr(active, ' ')))
4235                                 tty++;
4236                         else
4237                                 tty = active;
4238                 }
4239
4240         term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4241         free(active);
4242
4243         return term;
4244 }
4245
4246 /* Returns a short identifier for the various VM implementations */
4247 int detect_vm(const char **id) {
4248
4249 #if defined(__i386__) || defined(__x86_64__)
4250
4251         /* Both CPUID and DMI are x86 specific interfaces... */
4252
4253         static const char *const dmi_vendors[] = {
4254                 "/sys/class/dmi/id/sys_vendor",
4255                 "/sys/class/dmi/id/board_vendor",
4256                 "/sys/class/dmi/id/bios_vendor"
4257         };
4258
4259         static const char dmi_vendor_table[] =
4260                 "QEMU\0"                  "qemu\0"
4261                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4262                 "VMware\0"                "vmware\0"
4263                 "VMW\0"                   "vmware\0"
4264                 "Microsoft Corporation\0" "microsoft\0"
4265                 "innotek GmbH\0"          "oracle\0"
4266                 "Xen\0"                   "xen\0"
4267                 "Bochs\0"                 "bochs\0";
4268
4269         static const char cpuid_vendor_table[] =
4270                 "XenVMMXenVMM\0"          "xen\0"
4271                 "KVMKVMKVM\0"             "kvm\0"
4272                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4273                 "VMwareVMware\0"          "vmware\0"
4274                 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4275                 "Microsoft Hv\0"          "microsoft\0";
4276
4277         uint32_t eax, ecx;
4278         union {
4279                 uint32_t sig32[3];
4280                 char text[13];
4281         } sig;
4282         unsigned i;
4283         const char *j, *k;
4284         bool hypervisor;
4285
4286         /* http://lwn.net/Articles/301888/ */
4287         zero(sig);
4288
4289 #if defined (__i386__)
4290 #define REG_a "eax"
4291 #define REG_b "ebx"
4292 #elif defined (__amd64__)
4293 #define REG_a "rax"
4294 #define REG_b "rbx"
4295 #endif
4296
4297         /* First detect whether there is a hypervisor */
4298         eax = 1;
4299         __asm__ __volatile__ (
4300                 /* ebx/rbx is being used for PIC! */
4301                 "  push %%"REG_b"         \n\t"
4302                 "  cpuid                  \n\t"
4303                 "  pop %%"REG_b"          \n\t"
4304
4305                 : "=a" (eax), "=c" (ecx)
4306                 : "0" (eax)
4307         );
4308
4309         hypervisor = !!(ecx & 0x80000000U);
4310
4311         if (hypervisor) {
4312
4313                 /* There is a hypervisor, see what it is */
4314                 eax = 0x40000000U;
4315                 __asm__ __volatile__ (
4316                         /* ebx/rbx is being used for PIC! */
4317                         "  push %%"REG_b"         \n\t"
4318                         "  cpuid                  \n\t"
4319                         "  mov %%ebx, %1          \n\t"
4320                         "  pop %%"REG_b"          \n\t"
4321
4322                         : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4323                         : "0" (eax)
4324                 );
4325
4326                 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4327                         if (streq(sig.text, j)) {
4328
4329                                 if (id)
4330                                         *id = k;
4331
4332                                 return 1;
4333                         }
4334         }
4335
4336         for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4337                 char *s;
4338                 int r;
4339                 const char *found = NULL;
4340
4341                 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4342                         if (r != -ENOENT)
4343                                 return r;
4344
4345                         continue;
4346                 }
4347
4348                 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4349                         if (startswith(s, j))
4350                                 found = k;
4351                 free(s);
4352
4353                 if (found) {
4354                         if (id)
4355                                 *id = found;
4356
4357                         return 1;
4358                 }
4359         }
4360
4361         if (hypervisor) {
4362                 if (id)
4363                         *id = "other";
4364
4365                 return 1;
4366         }
4367
4368 #endif
4369         return 0;
4370 }
4371
4372 int detect_container(const char **id) {
4373         FILE *f;
4374
4375         /* Unfortunately many of these operations require root access
4376          * in one way or another */
4377
4378         if (geteuid() != 0)
4379                 return -EPERM;
4380
4381         if (running_in_chroot() > 0) {
4382
4383                 if (id)
4384                         *id = "chroot";
4385
4386                 return 1;
4387         }
4388
4389         /* /proc/vz exists in container and outside of the container,
4390          * /proc/bc only outside of the container. */
4391         if (access("/proc/vz", F_OK) >= 0 &&
4392             access("/proc/bc", F_OK) < 0) {
4393
4394                 if (id)
4395                         *id = "openvz";
4396
4397                 return 1;
4398         }
4399
4400         if ((f = fopen("/proc/self/cgroup", "re"))) {
4401
4402                 for (;;) {
4403                         char line[LINE_MAX], *p;
4404
4405                         if (!fgets(line, sizeof(line), f))
4406                                 break;
4407
4408                         if (!(p = strchr(strstrip(line), ':')))
4409                                 continue;
4410
4411                         if (strncmp(p, ":ns:", 4))
4412                                 continue;
4413
4414                         if (!streq(p, ":ns:/")) {
4415                                 fclose(f);
4416
4417                                 if (id)
4418                                         *id = "pidns";
4419
4420                                 return 1;
4421                         }
4422                 }
4423
4424                 fclose(f);
4425         }
4426
4427         return 0;
4428 }
4429
4430 /* Returns a short identifier for the various VM/container implementations */
4431 int detect_virtualization(const char **id) {
4432         static __thread const char *cached_id = NULL;
4433         const char *_id;
4434         int r;
4435
4436         if (_likely_(cached_id)) {
4437
4438                 if (cached_id == (const char*) -1)
4439                         return 0;
4440
4441                 if (id)
4442                         *id = cached_id;
4443
4444                 return 1;
4445         }
4446
4447         if ((r = detect_container(&_id)) != 0)
4448                 goto finish;
4449
4450         r = detect_vm(&_id);
4451
4452 finish:
4453         if (r > 0) {
4454                 cached_id = _id;
4455
4456                 if (id)
4457                         *id = _id;
4458         } else if (r == 0)
4459                 cached_id = (const char*) -1;
4460
4461         return r;
4462 }
4463
4464 bool dirent_is_file(struct dirent *de) {
4465         assert(de);
4466
4467         if (ignore_file(de->d_name))
4468                 return false;
4469
4470         if (de->d_type != DT_REG &&
4471             de->d_type != DT_LNK &&
4472             de->d_type != DT_UNKNOWN)
4473                 return false;
4474
4475         return true;
4476 }
4477
4478 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4479         DIR *_d = NULL;
4480         struct dirent *de;
4481         Hashmap *pids = NULL;
4482
4483         assert(directory);
4484
4485         /* Executes all binaries in a directory in parallel and waits
4486          * until all they all finished. */
4487
4488         if (!d) {
4489                 if (!(_d = opendir(directory))) {
4490
4491                         if (errno == ENOENT)
4492                                 return;
4493
4494                         log_error("Failed to enumerate directory %s: %m", directory);
4495                         return;
4496                 }
4497
4498                 d = _d;
4499         }
4500
4501         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4502                 log_error("Failed to allocate set.");
4503                 goto finish;
4504         }
4505
4506         while ((de = readdir(d))) {
4507                 char *path;
4508                 pid_t pid;
4509                 int k;
4510
4511                 if (!dirent_is_file(de))
4512                         continue;
4513
4514                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4515                         log_error("Out of memory");
4516                         continue;
4517                 }
4518
4519                 if ((pid = fork()) < 0) {
4520                         log_error("Failed to fork: %m");
4521                         free(path);
4522                         continue;
4523                 }
4524
4525                 if (pid == 0) {
4526                         char *_argv[2];
4527                         /* Child */
4528
4529                         if (!argv) {
4530                                 _argv[0] = path;
4531                                 _argv[1] = NULL;
4532                                 argv = _argv;
4533                         } else
4534                                 if (!argv[0])
4535                                         argv[0] = path;
4536
4537                         execv(path, argv);
4538
4539                         log_error("Failed to execute %s: %m", path);
4540                         _exit(EXIT_FAILURE);
4541                 }
4542
4543                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4544
4545                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4546                         log_error("Failed to add PID to set: %s", strerror(-k));
4547                         free(path);
4548                 }
4549         }
4550
4551         while (!hashmap_isempty(pids)) {
4552                 siginfo_t si;
4553                 char *path;
4554
4555                 zero(si);
4556                 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4557
4558                         if (errno == EINTR)
4559                                 continue;
4560
4561                         log_error("waitid() failed: %m");
4562                         goto finish;
4563                 }
4564
4565                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4566                         if (!is_clean_exit(si.si_code, si.si_status)) {
4567                                 if (si.si_code == CLD_EXITED)
4568                                         log_error("%s exited with exit status %i.", path, si.si_status);
4569                                 else
4570                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4571                         } else
4572                                 log_debug("%s exited successfully.", path);
4573
4574                         free(path);
4575                 }
4576         }
4577
4578 finish:
4579         if (_d)
4580                 closedir(_d);
4581
4582         if (pids)
4583                 hashmap_free_free(pids);
4584 }
4585
4586 int kill_and_sigcont(pid_t pid, int sig) {
4587         int r;
4588
4589         r = kill(pid, sig) < 0 ? -errno : 0;
4590
4591         if (r >= 0)
4592                 kill(pid, SIGCONT);
4593
4594         return r;
4595 }
4596
4597 bool nulstr_contains(const char*nulstr, const char *needle) {
4598         const char *i;
4599
4600         if (!nulstr)
4601                 return false;
4602
4603         NULSTR_FOREACH(i, nulstr)
4604                 if (streq(i, needle))
4605                         return true;
4606
4607         return false;
4608 }
4609
4610 bool plymouth_running(void) {
4611         return access("/run/plymouth/pid", F_OK) >= 0;
4612 }
4613
4614 void parse_syslog_priority(char **p, int *priority) {
4615         int a = 0, b = 0, c = 0;
4616         int k;
4617
4618         assert(p);
4619         assert(*p);
4620         assert(priority);
4621
4622         if ((*p)[0] != '<')
4623                 return;
4624
4625         if (!strchr(*p, '>'))
4626                 return;
4627
4628         if ((*p)[2] == '>') {
4629                 c = undecchar((*p)[1]);
4630                 k = 3;
4631         } else if ((*p)[3] == '>') {
4632                 b = undecchar((*p)[1]);
4633                 c = undecchar((*p)[2]);
4634                 k = 4;
4635         } else if ((*p)[4] == '>') {
4636                 a = undecchar((*p)[1]);
4637                 b = undecchar((*p)[2]);
4638                 c = undecchar((*p)[3]);
4639                 k = 5;
4640         } else
4641                 return;
4642
4643         if (a < 0 || b < 0 || c < 0)
4644                 return;
4645
4646         *priority = a*100+b*10+c;
4647         *p += k;
4648 }
4649
4650 int have_effective_cap(int value) {
4651         cap_t cap;
4652         cap_flag_value_t fv;
4653         int r;
4654
4655         if (!(cap = cap_get_proc()))
4656                 return -errno;
4657
4658         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4659                 r = -errno;
4660         else
4661                 r = fv == CAP_SET;
4662
4663         cap_free(cap);
4664         return r;
4665 }
4666
4667 char* strshorten(char *s, size_t l) {
4668         assert(s);
4669
4670         if (l < strlen(s))
4671                 s[l] = 0;
4672
4673         return s;
4674 }
4675
4676 static bool hostname_valid_char(char c) {
4677         return
4678                 (c >= 'a' && c <= 'z') ||
4679                 (c >= 'A' && c <= 'Z') ||
4680                 (c >= '0' && c <= '9') ||
4681                 c == '-' ||
4682                 c == '_' ||
4683                 c == '.';
4684 }
4685
4686 bool hostname_is_valid(const char *s) {
4687         const char *p;
4688
4689         if (isempty(s))
4690                 return false;
4691
4692         for (p = s; *p; p++)
4693                 if (!hostname_valid_char(*p))
4694                         return false;
4695
4696         if (p-s > HOST_NAME_MAX)
4697                 return false;
4698
4699         return true;
4700 }
4701
4702 char* hostname_cleanup(char *s) {
4703         char *p, *d;
4704
4705         for (p = s, d = s; *p; p++)
4706                 if ((*p >= 'a' && *p <= 'z') ||
4707                     (*p >= 'A' && *p <= 'Z') ||
4708                     (*p >= '0' && *p <= '9') ||
4709                     *p == '-' ||
4710                     *p == '_' ||
4711                     *p == '.')
4712                         *(d++) = *p;
4713
4714         *d = 0;
4715
4716         strshorten(s, HOST_NAME_MAX);
4717         return s;
4718 }
4719
4720 int pipe_eof(int fd) {
4721         struct pollfd pollfd;
4722         int r;
4723
4724         zero(pollfd);
4725         pollfd.fd = fd;
4726         pollfd.events = POLLIN|POLLHUP;
4727
4728         r = poll(&pollfd, 1, 0);
4729         if (r < 0)
4730                 return -errno;
4731
4732         if (r == 0)
4733                 return 0;
4734
4735         return pollfd.revents & POLLHUP;
4736 }
4737
4738 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4739         FILE *f;
4740         char *t;
4741         const char *fn;
4742         size_t k;
4743         int fd;
4744
4745         assert(path);
4746         assert(_f);
4747         assert(_temp_path);
4748
4749         t = new(char, strlen(path) + 1 + 6 + 1);
4750         if (!t)
4751                 return -ENOMEM;
4752
4753         fn = file_name_from_path(path);
4754         k = fn-path;
4755         memcpy(t, path, k);
4756         t[k] = '.';
4757         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4758
4759         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4760         if (fd < 0) {
4761                 free(t);
4762                 return -errno;
4763         }
4764
4765         f = fdopen(fd, "we");
4766         if (!f) {
4767                 unlink(t);
4768                 free(t);
4769                 return -errno;
4770         }
4771
4772         *_f = f;
4773         *_temp_path = t;
4774
4775         return 0;
4776 }
4777
4778 int terminal_vhangup_fd(int fd) {
4779         assert(fd >= 0);
4780
4781         if (ioctl(fd, TIOCVHANGUP) < 0)
4782                 return -errno;
4783
4784         return 0;
4785 }
4786
4787 int terminal_vhangup(const char *name) {
4788         int fd, r;
4789
4790         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4791         if (fd < 0)
4792                 return fd;
4793
4794         r = terminal_vhangup_fd(fd);
4795         close_nointr_nofail(fd);
4796
4797         return r;
4798 }
4799
4800 int vt_disallocate(const char *name) {
4801         int fd, r;
4802         unsigned u;
4803
4804         /* Deallocate the VT if possible. If not possible
4805          * (i.e. because it is the active one), at least clear it
4806          * entirely (including the scrollback buffer) */
4807
4808         if (!startswith(name, "/dev/"))
4809                 return -EINVAL;
4810
4811         if (!tty_is_vc(name)) {
4812                 /* So this is not a VT. I guess we cannot deallocate
4813                  * it then. But let's at least clear the screen */
4814
4815                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4816                 if (fd < 0)
4817                         return fd;
4818
4819                 loop_write(fd,
4820                            "\033[r"    /* clear scrolling region */
4821                            "\033[H"    /* move home */
4822                            "\033[2J",  /* clear screen */
4823                            10, false);
4824                 close_nointr_nofail(fd);
4825
4826                 return 0;
4827         }
4828
4829         if (!startswith(name, "/dev/tty"))
4830                 return -EINVAL;
4831
4832         r = safe_atou(name+8, &u);
4833         if (r < 0)
4834                 return r;
4835
4836         if (u <= 0)
4837                 return -EINVAL;
4838
4839         /* Try to deallocate */
4840         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4841         if (fd < 0)
4842                 return fd;
4843
4844         r = ioctl(fd, VT_DISALLOCATE, u);
4845         close_nointr_nofail(fd);
4846
4847         if (r >= 0)
4848                 return 0;
4849
4850         if (errno != EBUSY)
4851                 return -errno;
4852
4853         /* Couldn't deallocate, so let's clear it fully with
4854          * scrollback */
4855         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4856         if (fd < 0)
4857                 return fd;
4858
4859         loop_write(fd,
4860                    "\033[r"   /* clear scrolling region */
4861                    "\033[H"   /* move home */
4862                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4863                    10, false);
4864         close_nointr_nofail(fd);
4865
4866         return 0;
4867 }
4868
4869
4870 static int file_is_conf(const struct dirent *d, const char *suffix) {
4871         assert(d);
4872
4873         if (ignore_file(d->d_name))
4874                 return 0;
4875
4876         if (d->d_type != DT_REG &&
4877             d->d_type != DT_LNK &&
4878             d->d_type != DT_UNKNOWN)
4879                 return 0;
4880
4881         return endswith(d->d_name, suffix);
4882 }
4883
4884 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4885         DIR *dir;
4886         struct dirent buffer, *de;
4887         int r = 0;
4888
4889         dir = opendir(path);
4890         if (!dir) {
4891                 if (errno == ENOENT)
4892                         return 0;
4893                 return -errno;
4894         }
4895
4896         for (;;) {
4897                 int k;
4898                 char *p, *f;
4899
4900                 k = readdir_r(dir, &buffer, &de);
4901                 if (k != 0) {
4902                         r = -k;
4903                         goto finish;
4904                 }
4905
4906                 if (!de)
4907                         break;
4908
4909                 if (!file_is_conf(de, suffix))
4910                         continue;
4911
4912                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4913                         r = -ENOMEM;
4914                         goto finish;
4915                 }
4916
4917                 f = canonicalize_file_name(p);
4918                 if (!f) {
4919                         log_error("Failed to canonicalize file name '%s': %m", p);
4920                         free(p);
4921                         continue;
4922                 }
4923                 free(p);
4924
4925                 log_debug("found: %s\n", f);
4926                 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4927                         free(f);
4928         }
4929
4930 finish:
4931         closedir(dir);
4932         return r;
4933 }
4934
4935 static int base_cmp(const void *a, const void *b) {
4936         const char *s1, *s2;
4937
4938         s1 = *(char * const *)a;
4939         s2 = *(char * const *)b;
4940         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4941 }
4942
4943 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4944         Hashmap *fh = NULL;
4945         char **dirs = NULL;
4946         char **files = NULL;
4947         char **p;
4948         va_list ap;
4949         int r = 0;
4950
4951         va_start(ap, dir);
4952         dirs = strv_new_ap(dir, ap);
4953         va_end(ap);
4954         if (!dirs) {
4955                 r = -ENOMEM;
4956                 goto finish;
4957         }
4958         if (!strv_path_canonicalize(dirs)) {
4959                 r = -ENOMEM;
4960                 goto finish;
4961         }
4962         if (!strv_uniq(dirs)) {
4963                 r = -ENOMEM;
4964                 goto finish;
4965         }
4966
4967         fh = hashmap_new(string_hash_func, string_compare_func);
4968         if (!fh) {
4969                 r = -ENOMEM;
4970                 goto finish;
4971         }
4972
4973         STRV_FOREACH(p, dirs) {
4974                 if (files_add(fh, *p, suffix) < 0) {
4975                         log_error("Failed to search for files.");
4976                         r = -EINVAL;
4977                         goto finish;
4978                 }
4979         }
4980
4981         files = hashmap_get_strv(fh);
4982         if (files == NULL) {
4983                 log_error("Failed to compose list of files.");
4984                 r = -ENOMEM;
4985                 goto finish;
4986         }
4987
4988         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4989
4990 finish:
4991         strv_free(dirs);
4992         hashmap_free(fh);
4993         *strv = files;
4994         return r;
4995 }
4996
4997 int hwclock_is_localtime(void) {
4998         FILE *f;
4999         bool local = false;
5000
5001         /*
5002          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5003          *   # /etc/adjtime
5004          *   0.0 0 0
5005          *   0
5006          *   UTC
5007          */
5008         f = fopen("/etc/adjtime", "re");
5009         if (f) {
5010                 char line[LINE_MAX];
5011                 bool b;
5012
5013                 b = fgets(line, sizeof(line), f) &&
5014                         fgets(line, sizeof(line), f) &&
5015                         fgets(line, sizeof(line), f);
5016
5017                 fclose(f);
5018
5019                 if (!b)
5020                         return -EIO;
5021
5022
5023                 truncate_nl(line);
5024                 local = streq(line, "LOCAL");
5025
5026         } else if (errno != -ENOENT)
5027                 return -errno;
5028
5029         return local;
5030 }
5031
5032 int hwclock_apply_localtime_delta(int *min) {
5033         const struct timeval *tv_null = NULL;
5034         struct timespec ts;
5035         struct tm *tm;
5036         int minuteswest;
5037         struct timezone tz;
5038
5039         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5040         assert_se(tm = localtime(&ts.tv_sec));
5041         minuteswest = tm->tm_gmtoff / 60;
5042
5043         tz.tz_minuteswest = -minuteswest;
5044         tz.tz_dsttime = 0; /* DST_NONE*/
5045
5046         /*
5047          * If the hardware clock does not run in UTC, but in local time:
5048          * The very first time we set the kernel's timezone, it will warp
5049          * the clock so that it runs in UTC instead of local time.
5050          */
5051         if (settimeofday(tv_null, &tz) < 0)
5052                 return -errno;
5053         if (min)
5054                 *min = minuteswest;
5055         return 0;
5056 }
5057
5058 int hwclock_reset_localtime_delta(void) {
5059         const struct timeval *tv_null = NULL;
5060         struct timezone tz;
5061
5062         tz.tz_minuteswest = 0;
5063         tz.tz_dsttime = 0; /* DST_NONE*/
5064
5065         if (settimeofday(tv_null, &tz) < 0)
5066                 return -errno;
5067
5068         return 0;
5069 }
5070
5071 int hwclock_get_time(struct tm *tm) {
5072         int fd;
5073         int err = 0;
5074
5075         assert(tm);
5076
5077         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5078         if (fd < 0)
5079                 return -errno;
5080
5081         /* This leaves the timezone fields of struct tm
5082          * uninitialized! */
5083         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5084                 err = -errno;
5085
5086         /* We don't now daylight saving, so we reset this in order not
5087          * to confused mktime(). */
5088         tm->tm_isdst = -1;
5089
5090         close_nointr_nofail(fd);
5091
5092         return err;
5093 }
5094
5095 int hwclock_set_time(const struct tm *tm) {
5096         int fd;
5097         int err = 0;
5098
5099         assert(tm);
5100
5101         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5102         if (fd < 0)
5103                 return -errno;
5104
5105         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5106                 err = -errno;
5107
5108         close_nointr_nofail(fd);
5109
5110         return err;
5111 }
5112
5113 int copy_file(const char *from, const char *to) {
5114         int r, fdf, fdt;
5115
5116         assert(from);
5117         assert(to);
5118
5119         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5120         if (fdf < 0)
5121                 return -errno;
5122
5123         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5124         if (fdt < 0) {
5125                 close_nointr_nofail(fdf);
5126                 return -errno;
5127         }
5128
5129         for (;;) {
5130                 char buf[PIPE_BUF];
5131                 ssize_t n, k;
5132
5133                 n = read(fdf, buf, sizeof(buf));
5134                 if (n < 0) {
5135                         r = -errno;
5136
5137                         close_nointr_nofail(fdf);
5138                         close_nointr(fdt);
5139                         unlink(to);
5140
5141                         return r;
5142                 }
5143
5144                 if (n == 0)
5145                         break;
5146
5147                 errno = 0;
5148                 k = loop_write(fdt, buf, n, false);
5149                 if (n != k) {
5150                         r = k < 0 ? k : (errno ? -errno : -EIO);
5151
5152                         close_nointr_nofail(fdf);
5153                         close_nointr(fdt);
5154
5155                         unlink(to);
5156                         return r;
5157                 }
5158         }
5159
5160         close_nointr_nofail(fdf);
5161         r = close_nointr(fdt);
5162
5163         if (r < 0) {
5164                 unlink(to);
5165                 return r;
5166         }
5167
5168         return 0;
5169 }
5170
5171 int symlink_or_copy(const char *from, const char *to) {
5172         char *pf = NULL, *pt = NULL;
5173         struct stat a, b;
5174         int r;
5175
5176         assert(from);
5177         assert(to);
5178
5179         if (parent_of_path(from, &pf) < 0 ||
5180             parent_of_path(to, &pt) < 0) {
5181                 r = -ENOMEM;
5182                 goto finish;
5183         }
5184
5185         if (stat(pf, &a) < 0 ||
5186             stat(pt, &b) < 0) {
5187                 r = -errno;
5188                 goto finish;
5189         }
5190
5191         if (a.st_dev != b.st_dev) {
5192                 free(pf);
5193                 free(pt);
5194
5195                 return copy_file(from, to);
5196         }
5197
5198         if (symlink(from, to) < 0) {
5199                 r = -errno;
5200                 goto finish;
5201         }
5202
5203         r = 0;
5204
5205 finish:
5206         free(pf);
5207         free(pt);
5208
5209         return r;
5210 }
5211
5212 int symlink_or_copy_atomic(const char *from, const char *to) {
5213         char *t, *x;
5214         const char *fn;
5215         size_t k;
5216         unsigned long long ull;
5217         unsigned i;
5218         int r;
5219
5220         assert(from);
5221         assert(to);
5222
5223         t = new(char, strlen(to) + 1 + 16 + 1);
5224         if (!t)
5225                 return -ENOMEM;
5226
5227         fn = file_name_from_path(to);
5228         k = fn-to;
5229         memcpy(t, to, k);
5230         t[k] = '.';
5231         x = stpcpy(t+k+1, fn);
5232
5233         ull = random_ull();
5234         for (i = 0; i < 16; i++) {
5235                 *(x++) = hexchar(ull & 0xF);
5236                 ull >>= 4;
5237         }
5238
5239         *x = 0;
5240
5241         r = symlink_or_copy(from, t);
5242         if (r < 0) {
5243                 unlink(t);
5244                 free(t);
5245                 return r;
5246         }
5247
5248         if (rename(t, to) < 0) {
5249                 r = -errno;
5250                 unlink(t);
5251                 free(t);
5252                 return r;
5253         }
5254
5255         free(t);
5256         return r;
5257 }
5258
5259 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5260         char *p, *s;
5261         uint32_t u;
5262         int r;
5263
5264         assert(pid >= 1);
5265         assert(id);
5266
5267         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5268                 return -ENOENT;
5269
5270         if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5271                 return -ENOMEM;
5272
5273         r = read_one_line_file(p, &s);
5274         free(p);
5275         if (r < 0)
5276                 return r;
5277
5278         r = safe_atou32(s, &u);
5279         free(s);
5280
5281         if (r < 0)
5282                 return r;
5283
5284         if (u == (uint32_t) -1 || u <= 0)
5285                 return -ENOENT;
5286
5287         *id = u;
5288         return 0;
5289 }
5290
5291 bool display_is_local(const char *display) {
5292         assert(display);
5293
5294         return
5295                 display[0] == ':' &&
5296                 display[1] >= '0' &&
5297                 display[1] <= '9';
5298 }
5299
5300 int socket_from_display(const char *display, char **path) {
5301         size_t k;
5302         char *f, *c;
5303
5304         assert(display);
5305         assert(path);
5306
5307         if (!display_is_local(display))
5308                 return -EINVAL;
5309
5310         k = strspn(display+1, "0123456789");
5311
5312         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5313         if (!f)
5314                 return -ENOMEM;
5315
5316         c = stpcpy(f, "/tmp/.X11-unix/X");
5317         memcpy(c, display+1, k);
5318         c[k] = 0;
5319
5320         *path = f;
5321
5322         return 0;
5323 }
5324
5325 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5326         struct passwd *p;
5327         uid_t u;
5328
5329         assert(username);
5330         assert(*username);
5331
5332         /* We enforce some special rules for uid=0: in order to avoid
5333          * NSS lookups for root we hardcode its data. */
5334
5335         if (streq(*username, "root") || streq(*username, "0")) {
5336                 *username = "root";
5337
5338                 if (uid)
5339                         *uid = 0;
5340
5341                 if (gid)
5342                         *gid = 0;
5343
5344                 if (home)
5345                         *home = "/root";
5346                 return 0;
5347         }
5348
5349         if (parse_uid(*username, &u) >= 0) {
5350                 errno = 0;
5351                 p = getpwuid(u);
5352
5353                 /* If there are multiple users with the same id, make
5354                  * sure to leave $USER to the configured value instead
5355                  * of the first occurrence in the database. However if
5356                  * the uid was configured by a numeric uid, then let's
5357                  * pick the real username from /etc/passwd. */
5358                 if (p)
5359                         *username = p->pw_name;
5360         } else {
5361                 errno = 0;
5362                 p = getpwnam(*username);
5363         }
5364
5365         if (!p)
5366                 return errno != 0 ? -errno : -ESRCH;
5367
5368         if (uid)
5369                 *uid = p->pw_uid;
5370
5371         if (gid)
5372                 *gid = p->pw_gid;
5373
5374         if (home)
5375                 *home = p->pw_dir;
5376
5377         return 0;
5378 }
5379
5380 int get_group_creds(const char **groupname, gid_t *gid) {
5381         struct group *g;
5382         gid_t id;
5383
5384         assert(groupname);
5385
5386         /* We enforce some special rules for gid=0: in order to avoid
5387          * NSS lookups for root we hardcode its data. */
5388
5389         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5390                 *groupname = "root";
5391
5392                 if (gid)
5393                         *gid = 0;
5394
5395                 return 0;
5396         }
5397
5398         if (parse_gid(*groupname, &id) >= 0) {
5399                 errno = 0;
5400                 g = getgrgid(id);
5401
5402                 if (g)
5403                         *groupname = g->gr_name;
5404         } else {
5405                 errno = 0;
5406                 g = getgrnam(*groupname);
5407         }
5408
5409         if (!g)
5410                 return errno != 0 ? -errno : -ESRCH;
5411
5412         if (gid)
5413                 *gid = g->gr_gid;
5414
5415         return 0;
5416 }
5417
5418 int glob_exists(const char *path) {
5419         glob_t g;
5420         int r, k;
5421
5422         assert(path);
5423
5424         zero(g);
5425         errno = 0;
5426         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5427
5428         if (k == GLOB_NOMATCH)
5429                 r = 0;
5430         else if (k == GLOB_NOSPACE)
5431                 r = -ENOMEM;
5432         else if (k == 0)
5433                 r = !strv_isempty(g.gl_pathv);
5434         else
5435                 r = errno ? -errno : -EIO;
5436
5437         globfree(&g);
5438
5439         return r;
5440 }
5441
5442 int dirent_ensure_type(DIR *d, struct dirent *de) {
5443         struct stat st;
5444
5445         assert(d);
5446         assert(de);
5447
5448         if (de->d_type != DT_UNKNOWN)
5449                 return 0;
5450
5451         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5452                 return -errno;
5453
5454         de->d_type =
5455                 S_ISREG(st.st_mode)  ? DT_REG  :
5456                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5457                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5458                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5459                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5460                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5461                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5462                                        DT_UNKNOWN;
5463
5464         return 0;
5465 }
5466
5467 int in_search_path(const char *path, char **search) {
5468         char **i, *parent;
5469         int r;
5470
5471         r = parent_of_path(path, &parent);
5472         if (r < 0)
5473                 return r;
5474
5475         r = 0;
5476
5477         STRV_FOREACH(i, search) {
5478                 if (path_equal(parent, *i)) {
5479                         r = 1;
5480                         break;
5481                 }
5482         }
5483
5484         free(parent);
5485
5486         return r;
5487 }
5488
5489 int get_files_in_directory(const char *path, char ***list) {
5490         DIR *d;
5491         int r = 0;
5492         unsigned n = 0;
5493         char **l = NULL;
5494
5495         assert(path);
5496
5497         /* Returns all files in a directory in *list, and the number
5498          * of files as return value. If list is NULL returns only the
5499          * number */
5500
5501         d = opendir(path);
5502         for (;;) {
5503                 struct dirent buffer, *de;
5504                 int k;
5505
5506                 k = readdir_r(d, &buffer, &de);
5507                 if (k != 0) {
5508                         r = -k;
5509                         goto finish;
5510                 }
5511
5512                 if (!de)
5513                         break;
5514
5515                 dirent_ensure_type(d, de);
5516
5517                 if (!dirent_is_file(de))
5518                         continue;
5519
5520                 if (list) {
5521                         if ((unsigned) r >= n) {
5522                                 char **t;
5523
5524                                 n = MAX(16, 2*r);
5525                                 t = realloc(l, sizeof(char*) * n);
5526                                 if (!t) {
5527                                         r = -ENOMEM;
5528                                         goto finish;
5529                                 }
5530
5531                                 l = t;
5532                         }
5533
5534                         assert((unsigned) r < n);
5535
5536                         l[r] = strdup(de->d_name);
5537                         if (!l[r]) {
5538                                 r = -ENOMEM;
5539                                 goto finish;
5540                         }
5541
5542                         l[++r] = NULL;
5543                 } else
5544                         r++;
5545         }
5546
5547 finish:
5548         if (d)
5549                 closedir(d);
5550
5551         if (r >= 0) {
5552                 if (list)
5553                         *list = l;
5554         } else
5555                 strv_free(l);
5556
5557         return r;
5558 }
5559
5560 char *join(const char *x, ...) {
5561         va_list ap;
5562         size_t l;
5563         char *r, *p;
5564
5565         va_start(ap, x);
5566
5567         if (x) {
5568                 l = strlen(x);
5569
5570                 for (;;) {
5571                         const char *t;
5572
5573                         t = va_arg(ap, const char *);
5574                         if (!t)
5575                                 break;
5576
5577                         l += strlen(t);
5578                 }
5579         } else
5580                 l = 0;
5581
5582         va_end(ap);
5583
5584         r = new(char, l+1);
5585         if (!r)
5586                 return NULL;
5587
5588         if (x) {
5589                 p = stpcpy(r, x);
5590
5591                 va_start(ap, x);
5592
5593                 for (;;) {
5594                         const char *t;
5595
5596                         t = va_arg(ap, const char *);
5597                         if (!t)
5598                                 break;
5599
5600                         p = stpcpy(p, t);
5601                 }
5602         } else
5603                 r[0] = 0;
5604
5605         return r;
5606 }
5607
5608 bool is_main_thread(void) {
5609         static __thread int cached = 0;
5610
5611         if (_unlikely_(cached == 0))
5612                 cached = getpid() == gettid() ? 1 : -1;
5613
5614         return cached > 0;
5615 }
5616
5617 static const char *const ioprio_class_table[] = {
5618         [IOPRIO_CLASS_NONE] = "none",
5619         [IOPRIO_CLASS_RT] = "realtime",
5620         [IOPRIO_CLASS_BE] = "best-effort",
5621         [IOPRIO_CLASS_IDLE] = "idle"
5622 };
5623
5624 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5625
5626 static const char *const sigchld_code_table[] = {
5627         [CLD_EXITED] = "exited",
5628         [CLD_KILLED] = "killed",
5629         [CLD_DUMPED] = "dumped",
5630         [CLD_TRAPPED] = "trapped",
5631         [CLD_STOPPED] = "stopped",
5632         [CLD_CONTINUED] = "continued",
5633 };
5634
5635 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5636
5637 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5638         [LOG_FAC(LOG_KERN)] = "kern",
5639         [LOG_FAC(LOG_USER)] = "user",
5640         [LOG_FAC(LOG_MAIL)] = "mail",
5641         [LOG_FAC(LOG_DAEMON)] = "daemon",
5642         [LOG_FAC(LOG_AUTH)] = "auth",
5643         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5644         [LOG_FAC(LOG_LPR)] = "lpr",
5645         [LOG_FAC(LOG_NEWS)] = "news",
5646         [LOG_FAC(LOG_UUCP)] = "uucp",
5647         [LOG_FAC(LOG_CRON)] = "cron",
5648         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5649         [LOG_FAC(LOG_FTP)] = "ftp",
5650         [LOG_FAC(LOG_LOCAL0)] = "local0",
5651         [LOG_FAC(LOG_LOCAL1)] = "local1",
5652         [LOG_FAC(LOG_LOCAL2)] = "local2",
5653         [LOG_FAC(LOG_LOCAL3)] = "local3",
5654         [LOG_FAC(LOG_LOCAL4)] = "local4",
5655         [LOG_FAC(LOG_LOCAL5)] = "local5",
5656         [LOG_FAC(LOG_LOCAL6)] = "local6",
5657         [LOG_FAC(LOG_LOCAL7)] = "local7"
5658 };
5659
5660 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5661
5662 static const char *const log_level_table[] = {
5663         [LOG_EMERG] = "emerg",
5664         [LOG_ALERT] = "alert",
5665         [LOG_CRIT] = "crit",
5666         [LOG_ERR] = "err",
5667         [LOG_WARNING] = "warning",
5668         [LOG_NOTICE] = "notice",
5669         [LOG_INFO] = "info",
5670         [LOG_DEBUG] = "debug"
5671 };
5672
5673 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5674
5675 static const char* const sched_policy_table[] = {
5676         [SCHED_OTHER] = "other",
5677         [SCHED_BATCH] = "batch",
5678         [SCHED_IDLE] = "idle",
5679         [SCHED_FIFO] = "fifo",
5680         [SCHED_RR] = "rr"
5681 };
5682
5683 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5684
5685 static const char* const rlimit_table[] = {
5686         [RLIMIT_CPU] = "LimitCPU",
5687         [RLIMIT_FSIZE] = "LimitFSIZE",
5688         [RLIMIT_DATA] = "LimitDATA",
5689         [RLIMIT_STACK] = "LimitSTACK",
5690         [RLIMIT_CORE] = "LimitCORE",
5691         [RLIMIT_RSS] = "LimitRSS",
5692         [RLIMIT_NOFILE] = "LimitNOFILE",
5693         [RLIMIT_AS] = "LimitAS",
5694         [RLIMIT_NPROC] = "LimitNPROC",
5695         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5696         [RLIMIT_LOCKS] = "LimitLOCKS",
5697         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5698         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5699         [RLIMIT_NICE] = "LimitNICE",
5700         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5701         [RLIMIT_RTTIME] = "LimitRTTIME"
5702 };
5703
5704 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5705
5706 static const char* const ip_tos_table[] = {
5707         [IPTOS_LOWDELAY] = "low-delay",
5708         [IPTOS_THROUGHPUT] = "throughput",
5709         [IPTOS_RELIABILITY] = "reliability",
5710         [IPTOS_LOWCOST] = "low-cost",
5711 };
5712
5713 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5714
5715 static const char *const signal_table[] = {
5716         [SIGHUP] = "HUP",
5717         [SIGINT] = "INT",
5718         [SIGQUIT] = "QUIT",
5719         [SIGILL] = "ILL",
5720         [SIGTRAP] = "TRAP",
5721         [SIGABRT] = "ABRT",
5722         [SIGBUS] = "BUS",
5723         [SIGFPE] = "FPE",
5724         [SIGKILL] = "KILL",
5725         [SIGUSR1] = "USR1",
5726         [SIGSEGV] = "SEGV",
5727         [SIGUSR2] = "USR2",
5728         [SIGPIPE] = "PIPE",
5729         [SIGALRM] = "ALRM",
5730         [SIGTERM] = "TERM",
5731 #ifdef SIGSTKFLT
5732         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5733 #endif
5734         [SIGCHLD] = "CHLD",
5735         [SIGCONT] = "CONT",
5736         [SIGSTOP] = "STOP",
5737         [SIGTSTP] = "TSTP",
5738         [SIGTTIN] = "TTIN",
5739         [SIGTTOU] = "TTOU",
5740         [SIGURG] = "URG",
5741         [SIGXCPU] = "XCPU",
5742         [SIGXFSZ] = "XFSZ",
5743         [SIGVTALRM] = "VTALRM",
5744         [SIGPROF] = "PROF",
5745         [SIGWINCH] = "WINCH",
5746         [SIGIO] = "IO",
5747         [SIGPWR] = "PWR",
5748         [SIGSYS] = "SYS"
5749 };
5750
5751 DEFINE_STRING_TABLE_LOOKUP(signal, int);