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