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