chiark / gitweb /
execute: optionally ignore return status of invoked commands
[elogind.git] / src / util.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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
51 #include "macro.h"
52 #include "util.h"
53 #include "ioprio.h"
54 #include "missing.h"
55 #include "log.h"
56 #include "strv.h"
57
58 bool streq_ptr(const char *a, const char *b) {
59
60         /* Like streq(), but tries to make sense of NULL pointers */
61
62         if (a && b)
63                 return streq(a, b);
64
65         if (!a && !b)
66                 return true;
67
68         return false;
69 }
70
71 usec_t now(clockid_t clock_id) {
72         struct timespec ts;
73
74         assert_se(clock_gettime(clock_id, &ts) == 0);
75
76         return timespec_load(&ts);
77 }
78
79 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
80         assert(ts);
81
82         ts->realtime = now(CLOCK_REALTIME);
83         ts->monotonic = now(CLOCK_MONOTONIC);
84
85         return ts;
86 }
87
88 usec_t timespec_load(const struct timespec *ts) {
89         assert(ts);
90
91         return
92                 (usec_t) ts->tv_sec * USEC_PER_SEC +
93                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
94 }
95
96 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
97         assert(ts);
98
99         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
100         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
101
102         return ts;
103 }
104
105 usec_t timeval_load(const struct timeval *tv) {
106         assert(tv);
107
108         return
109                 (usec_t) tv->tv_sec * USEC_PER_SEC +
110                 (usec_t) tv->tv_usec;
111 }
112
113 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
114         assert(tv);
115
116         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
117         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
118
119         return tv;
120 }
121
122 bool endswith(const char *s, const char *postfix) {
123         size_t sl, pl;
124
125         assert(s);
126         assert(postfix);
127
128         sl = strlen(s);
129         pl = strlen(postfix);
130
131         if (pl == 0)
132                 return true;
133
134         if (sl < pl)
135                 return false;
136
137         return memcmp(s + sl - pl, postfix, pl) == 0;
138 }
139
140 bool startswith(const char *s, const char *prefix) {
141         size_t sl, pl;
142
143         assert(s);
144         assert(prefix);
145
146         sl = strlen(s);
147         pl = strlen(prefix);
148
149         if (pl == 0)
150                 return true;
151
152         if (sl < pl)
153                 return false;
154
155         return memcmp(s, prefix, pl) == 0;
156 }
157
158 bool startswith_no_case(const char *s, const char *prefix) {
159         size_t sl, pl;
160         unsigned i;
161
162         assert(s);
163         assert(prefix);
164
165         sl = strlen(s);
166         pl = strlen(prefix);
167
168         if (pl == 0)
169                 return true;
170
171         if (sl < pl)
172                 return false;
173
174         for(i = 0; i < pl; ++i) {
175                 if (tolower(s[i]) != tolower(prefix[i]))
176                         return false;
177         }
178
179         return true;
180 }
181
182 bool first_word(const char *s, const char *word) {
183         size_t sl, wl;
184
185         assert(s);
186         assert(word);
187
188         sl = strlen(s);
189         wl = strlen(word);
190
191         if (sl < wl)
192                 return false;
193
194         if (wl == 0)
195                 return true;
196
197         if (memcmp(s, word, wl) != 0)
198                 return false;
199
200         return s[wl] == 0 ||
201                 strchr(WHITESPACE, s[wl]);
202 }
203
204 int close_nointr(int fd) {
205         assert(fd >= 0);
206
207         for (;;) {
208                 int r;
209
210                 if ((r = close(fd)) >= 0)
211                         return r;
212
213                 if (errno != EINTR)
214                         return r;
215         }
216 }
217
218 void close_nointr_nofail(int fd) {
219         int saved_errno = errno;
220
221         /* like close_nointr() but cannot fail, and guarantees errno
222          * is unchanged */
223
224         assert_se(close_nointr(fd) == 0);
225
226         errno = saved_errno;
227 }
228
229 void close_many(const int fds[], unsigned n_fd) {
230         unsigned i;
231
232         for (i = 0; i < n_fd; i++)
233                 close_nointr_nofail(fds[i]);
234 }
235
236 int parse_boolean(const char *v) {
237         assert(v);
238
239         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
240                 return 1;
241         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
242                 return 0;
243
244         return -EINVAL;
245 }
246
247 int parse_pid(const char *s, pid_t* ret_pid) {
248         unsigned long ul;
249         pid_t pid;
250         int r;
251
252         assert(s);
253         assert(ret_pid);
254
255         if ((r = safe_atolu(s, &ul)) < 0)
256                 return r;
257
258         pid = (pid_t) ul;
259
260         if ((unsigned long) pid != ul)
261                 return -ERANGE;
262
263         if (pid <= 0)
264                 return -ERANGE;
265
266         *ret_pid = pid;
267         return 0;
268 }
269
270 int safe_atou(const char *s, unsigned *ret_u) {
271         char *x = NULL;
272         unsigned long l;
273
274         assert(s);
275         assert(ret_u);
276
277         errno = 0;
278         l = strtoul(s, &x, 0);
279
280         if (!x || *x || errno)
281                 return errno ? -errno : -EINVAL;
282
283         if ((unsigned long) (unsigned) l != l)
284                 return -ERANGE;
285
286         *ret_u = (unsigned) l;
287         return 0;
288 }
289
290 int safe_atoi(const char *s, int *ret_i) {
291         char *x = NULL;
292         long l;
293
294         assert(s);
295         assert(ret_i);
296
297         errno = 0;
298         l = strtol(s, &x, 0);
299
300         if (!x || *x || errno)
301                 return errno ? -errno : -EINVAL;
302
303         if ((long) (int) l != l)
304                 return -ERANGE;
305
306         *ret_i = (int) l;
307         return 0;
308 }
309
310 int safe_atollu(const char *s, long long unsigned *ret_llu) {
311         char *x = NULL;
312         unsigned long long l;
313
314         assert(s);
315         assert(ret_llu);
316
317         errno = 0;
318         l = strtoull(s, &x, 0);
319
320         if (!x || *x || errno)
321                 return errno ? -errno : -EINVAL;
322
323         *ret_llu = l;
324         return 0;
325 }
326
327 int safe_atolli(const char *s, long long int *ret_lli) {
328         char *x = NULL;
329         long long l;
330
331         assert(s);
332         assert(ret_lli);
333
334         errno = 0;
335         l = strtoll(s, &x, 0);
336
337         if (!x || *x || errno)
338                 return errno ? -errno : -EINVAL;
339
340         *ret_lli = l;
341         return 0;
342 }
343
344 /* Split a string into words. */
345 char *split(const char *c, size_t *l, const char *separator, char **state) {
346         char *current;
347
348         current = *state ? *state : (char*) c;
349
350         if (!*current || *c == 0)
351                 return NULL;
352
353         current += strspn(current, separator);
354         *l = strcspn(current, separator);
355         *state = current+*l;
356
357         return (char*) current;
358 }
359
360 /* Split a string into words, but consider strings enclosed in '' and
361  * "" as words even if they include spaces. */
362 char *split_quoted(const char *c, size_t *l, char **state) {
363         char *current, *e;
364         bool escaped = false;
365
366         current = *state ? *state : (char*) c;
367
368         if (!*current || *c == 0)
369                 return NULL;
370
371         current += strspn(current, WHITESPACE);
372
373         if (*current == '\'') {
374                 current ++;
375
376                 for (e = current; *e; e++) {
377                         if (escaped)
378                                 escaped = false;
379                         else if (*e == '\\')
380                                 escaped = true;
381                         else if (*e == '\'')
382                                 break;
383                 }
384
385                 *l = e-current;
386                 *state = *e == 0 ? e : e+1;
387         } else if (*current == '\"') {
388                 current ++;
389
390                 for (e = current; *e; e++) {
391                         if (escaped)
392                                 escaped = false;
393                         else if (*e == '\\')
394                                 escaped = true;
395                         else if (*e == '\"')
396                                 break;
397                 }
398
399                 *l = e-current;
400                 *state = *e == 0 ? e : e+1;
401         } else {
402                 for (e = current; *e; e++) {
403                         if (escaped)
404                                 escaped = false;
405                         else if (*e == '\\')
406                                 escaped = true;
407                         else if (strchr(WHITESPACE, *e))
408                                 break;
409                 }
410                 *l = e-current;
411                 *state = e;
412         }
413
414         return (char*) current;
415 }
416
417 char **split_path_and_make_absolute(const char *p) {
418         char **l;
419         assert(p);
420
421         if (!(l = strv_split(p, ":")))
422                 return NULL;
423
424         if (!strv_path_make_absolute_cwd(l)) {
425                 strv_free(l);
426                 return NULL;
427         }
428
429         return l;
430 }
431
432 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
433         int r;
434         FILE *f;
435         char fn[132], line[256], *p;
436         long unsigned ppid;
437
438         assert(pid >= 0);
439         assert(_ppid);
440
441         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
442         fn[sizeof(fn)-1] = 0;
443
444         if (!(f = fopen(fn, "r")))
445                 return -errno;
446
447         if (!(fgets(line, sizeof(line), f))) {
448                 r = -errno;
449                 fclose(f);
450                 return r;
451         }
452
453         fclose(f);
454
455         /* Let's skip the pid and comm fields. The latter is enclosed
456          * in () but does not escape any () in its value, so let's
457          * skip over it manually */
458
459         if (!(p = strrchr(line, ')')))
460                 return -EIO;
461
462         p++;
463
464         if (sscanf(p, " "
465                    "%*c "  /* state */
466                    "%lu ", /* ppid */
467                    &ppid) != 1)
468                 return -EIO;
469
470         if ((long unsigned) (pid_t) ppid != ppid)
471                 return -ERANGE;
472
473         *_ppid = (pid_t) ppid;
474
475         return 0;
476 }
477
478 int write_one_line_file(const char *fn, const char *line) {
479         FILE *f;
480         int r;
481
482         assert(fn);
483         assert(line);
484
485         if (!(f = fopen(fn, "we")))
486                 return -errno;
487
488         if (fputs(line, f) < 0) {
489                 r = -errno;
490                 goto finish;
491         }
492
493         r = 0;
494 finish:
495         fclose(f);
496         return r;
497 }
498
499 int read_one_line_file(const char *fn, char **line) {
500         FILE *f;
501         int r;
502         char t[2048], *c;
503
504         assert(fn);
505         assert(line);
506
507         if (!(f = fopen(fn, "re")))
508                 return -errno;
509
510         if (!(fgets(t, sizeof(t), f))) {
511                 r = -errno;
512                 goto finish;
513         }
514
515         if (!(c = strdup(t))) {
516                 r = -ENOMEM;
517                 goto finish;
518         }
519
520         *line = c;
521         r = 0;
522
523 finish:
524         fclose(f);
525         return r;
526 }
527
528 char *truncate_nl(char *s) {
529         assert(s);
530
531         s[strcspn(s, NEWLINE)] = 0;
532         return s;
533 }
534
535 int get_process_name(pid_t pid, char **name) {
536         char *p;
537         int r;
538
539         assert(pid >= 1);
540         assert(name);
541
542         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
543                 return -ENOMEM;
544
545         r = read_one_line_file(p, name);
546         free(p);
547
548         if (r < 0)
549                 return r;
550
551         truncate_nl(*name);
552         return 0;
553 }
554
555 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
556         char *p, *r, *k;
557         int c;
558         bool space = false;
559         size_t left;
560         FILE *f;
561
562         assert(pid >= 1);
563         assert(max_length > 0);
564         assert(line);
565
566         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
567                 return -ENOMEM;
568
569         f = fopen(p, "r");
570         free(p);
571
572         if (!f)
573                 return -errno;
574
575         if (!(r = new(char, max_length))) {
576                 fclose(f);
577                 return -ENOMEM;
578         }
579
580         k = r;
581         left = max_length;
582         while ((c = getc(f)) != EOF) {
583
584                 if (isprint(c)) {
585                         if (space) {
586                                 if (left <= 4)
587                                         break;
588
589                                 *(k++) = ' ';
590                                 left--;
591                                 space = false;
592                         }
593
594                         if (left <= 4)
595                                 break;
596
597                         *(k++) = (char) c;
598                         left--;
599                 }  else
600                         space = true;
601         }
602
603         if (left <= 4) {
604                 size_t n = MIN(left-1, 3U);
605                 memcpy(k, "...", n);
606                 k[n] = 0;
607         } else
608                 *k = 0;
609
610         fclose(f);
611
612         if (r[0] == 0)
613                 return get_process_name(pid, line);
614
615         *line = r;
616         return 0;
617 }
618
619 char *strnappend(const char *s, const char *suffix, size_t b) {
620         size_t a;
621         char *r;
622
623         if (!s && !suffix)
624                 return strdup("");
625
626         if (!s)
627                 return strndup(suffix, b);
628
629         if (!suffix)
630                 return strdup(s);
631
632         assert(s);
633         assert(suffix);
634
635         a = strlen(s);
636
637         if (!(r = new(char, a+b+1)))
638                 return NULL;
639
640         memcpy(r, s, a);
641         memcpy(r+a, suffix, b);
642         r[a+b] = 0;
643
644         return r;
645 }
646
647 char *strappend(const char *s, const char *suffix) {
648         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
649 }
650
651 int readlink_malloc(const char *p, char **r) {
652         size_t l = 100;
653
654         assert(p);
655         assert(r);
656
657         for (;;) {
658                 char *c;
659                 ssize_t n;
660
661                 if (!(c = new(char, l)))
662                         return -ENOMEM;
663
664                 if ((n = readlink(p, c, l-1)) < 0) {
665                         int ret = -errno;
666                         free(c);
667                         return ret;
668                 }
669
670                 if ((size_t) n < l-1) {
671                         c[n] = 0;
672                         *r = c;
673                         return 0;
674                 }
675
676                 free(c);
677                 l *= 2;
678         }
679 }
680
681 int readlink_and_make_absolute(const char *p, char **r) {
682         char *target, *k;
683         int j;
684
685         assert(p);
686         assert(r);
687
688         if ((j = readlink_malloc(p, &target)) < 0)
689                 return j;
690
691         k = file_in_same_dir(p, target);
692         free(target);
693
694         if (!k)
695                 return -ENOMEM;
696
697         *r = k;
698         return 0;
699 }
700
701 char *file_name_from_path(const char *p) {
702         char *r;
703
704         assert(p);
705
706         if ((r = strrchr(p, '/')))
707                 return r + 1;
708
709         return (char*) p;
710 }
711
712 bool path_is_absolute(const char *p) {
713         assert(p);
714
715         return p[0] == '/';
716 }
717
718 bool is_path(const char *p) {
719
720         return !!strchr(p, '/');
721 }
722
723 char *path_make_absolute(const char *p, const char *prefix) {
724         char *r;
725
726         assert(p);
727
728         /* Makes every item in the list an absolute path by prepending
729          * the prefix, if specified and necessary */
730
731         if (path_is_absolute(p) || !prefix)
732                 return strdup(p);
733
734         if (asprintf(&r, "%s/%s", prefix, p) < 0)
735                 return NULL;
736
737         return r;
738 }
739
740 char *path_make_absolute_cwd(const char *p) {
741         char *cwd, *r;
742
743         assert(p);
744
745         /* Similar to path_make_absolute(), but prefixes with the
746          * current working directory. */
747
748         if (path_is_absolute(p))
749                 return strdup(p);
750
751         if (!(cwd = get_current_dir_name()))
752                 return NULL;
753
754         r = path_make_absolute(p, cwd);
755         free(cwd);
756
757         return r;
758 }
759
760 char **strv_path_make_absolute_cwd(char **l) {
761         char **s;
762
763         /* Goes through every item in the string list and makes it
764          * absolute. This works in place and won't rollback any
765          * changes on failure. */
766
767         STRV_FOREACH(s, l) {
768                 char *t;
769
770                 if (!(t = path_make_absolute_cwd(*s)))
771                         return NULL;
772
773                 free(*s);
774                 *s = t;
775         }
776
777         return l;
778 }
779
780 char **strv_path_canonicalize(char **l) {
781         char **s;
782         unsigned k = 0;
783         bool enomem = false;
784
785         if (strv_isempty(l))
786                 return l;
787
788         /* Goes through every item in the string list and canonicalize
789          * the path. This works in place and won't rollback any
790          * changes on failure. */
791
792         STRV_FOREACH(s, l) {
793                 char *t, *u;
794
795                 t = path_make_absolute_cwd(*s);
796                 free(*s);
797
798                 if (!t) {
799                         enomem = true;
800                         continue;
801                 }
802
803                 errno = 0;
804                 u = canonicalize_file_name(t);
805                 free(t);
806
807                 if (!u) {
808                         if (errno == ENOMEM || !errno)
809                                 enomem = true;
810
811                         continue;
812                 }
813
814                 l[k++] = u;
815         }
816
817         l[k] = NULL;
818
819         if (enomem)
820                 return NULL;
821
822         return l;
823 }
824
825 int reset_all_signal_handlers(void) {
826         int sig;
827
828         for (sig = 1; sig < _NSIG; sig++) {
829                 struct sigaction sa;
830
831                 if (sig == SIGKILL || sig == SIGSTOP)
832                         continue;
833
834                 zero(sa);
835                 sa.sa_handler = SIG_DFL;
836                 sa.sa_flags = SA_RESTART;
837
838                 /* On Linux the first two RT signals are reserved by
839                  * glibc, and sigaction() will return EINVAL for them. */
840                 if ((sigaction(sig, &sa, NULL) < 0))
841                         if (errno != EINVAL)
842                                 return -errno;
843         }
844
845         return 0;
846 }
847
848 char *strstrip(char *s) {
849         char *e, *l = NULL;
850
851         /* Drops trailing whitespace. Modifies the string in
852          * place. Returns pointer to first non-space character */
853
854         s += strspn(s, WHITESPACE);
855
856         for (e = s; *e; e++)
857                 if (!strchr(WHITESPACE, *e))
858                         l = e;
859
860         if (l)
861                 *(l+1) = 0;
862         else
863                 *s = 0;
864
865         return s;
866 }
867
868 char *delete_chars(char *s, const char *bad) {
869         char *f, *t;
870
871         /* Drops all whitespace, regardless where in the string */
872
873         for (f = s, t = s; *f; f++) {
874                 if (strchr(bad, *f))
875                         continue;
876
877                 *(t++) = *f;
878         }
879
880         *t = 0;
881
882         return s;
883 }
884
885 char *file_in_same_dir(const char *path, const char *filename) {
886         char *e, *r;
887         size_t k;
888
889         assert(path);
890         assert(filename);
891
892         /* This removes the last component of path and appends
893          * filename, unless the latter is absolute anyway or the
894          * former isn't */
895
896         if (path_is_absolute(filename))
897                 return strdup(filename);
898
899         if (!(e = strrchr(path, '/')))
900                 return strdup(filename);
901
902         k = strlen(filename);
903         if (!(r = new(char, e-path+1+k+1)))
904                 return NULL;
905
906         memcpy(r, path, e-path+1);
907         memcpy(r+(e-path)+1, filename, k+1);
908
909         return r;
910 }
911
912 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
913         struct stat st;
914
915         if (mkdir(path, mode) >= 0)
916                 if (chmod_and_chown(path, mode, uid, gid) < 0)
917                         return -errno;
918
919         if (lstat(path, &st) < 0)
920                 return -errno;
921
922         if ((st.st_mode & 0777) != mode ||
923             st.st_uid != uid ||
924             st.st_gid != gid ||
925             !S_ISDIR(st.st_mode)) {
926                 errno = EEXIST;
927                 return -errno;
928         }
929
930         return 0;
931 }
932
933
934 int mkdir_parents(const char *path, mode_t mode) {
935         const char *p, *e;
936
937         assert(path);
938
939         /* Creates every parent directory in the path except the last
940          * component. */
941
942         p = path + strspn(path, "/");
943         for (;;) {
944                 int r;
945                 char *t;
946
947                 e = p + strcspn(p, "/");
948                 p = e + strspn(e, "/");
949
950                 /* Is this the last component? If so, then we're
951                  * done */
952                 if (*p == 0)
953                         return 0;
954
955                 if (!(t = strndup(path, e - path)))
956                         return -ENOMEM;
957
958                 r = mkdir(t, mode);
959                 free(t);
960
961                 if (r < 0 && errno != EEXIST)
962                         return -errno;
963         }
964 }
965
966 int mkdir_p(const char *path, mode_t mode) {
967         int r;
968
969         /* Like mkdir -p */
970
971         if ((r = mkdir_parents(path, mode)) < 0)
972                 return r;
973
974         if (mkdir(path, mode) < 0 && errno != EEXIST)
975                 return -errno;
976
977         return 0;
978 }
979
980 int rmdir_parents(const char *path, const char *stop) {
981         size_t l;
982         int r = 0;
983
984         assert(path);
985         assert(stop);
986
987         l = strlen(path);
988
989         /* Skip trailing slashes */
990         while (l > 0 && path[l-1] == '/')
991                 l--;
992
993         while (l > 0) {
994                 char *t;
995
996                 /* Skip last component */
997                 while (l > 0 && path[l-1] != '/')
998                         l--;
999
1000                 /* Skip trailing slashes */
1001                 while (l > 0 && path[l-1] == '/')
1002                         l--;
1003
1004                 if (l <= 0)
1005                         break;
1006
1007                 if (!(t = strndup(path, l)))
1008                         return -ENOMEM;
1009
1010                 if (path_startswith(stop, t)) {
1011                         free(t);
1012                         return 0;
1013                 }
1014
1015                 r = rmdir(t);
1016                 free(t);
1017
1018                 if (r < 0)
1019                         if (errno != ENOENT)
1020                                 return -errno;
1021         }
1022
1023         return 0;
1024 }
1025
1026
1027 char hexchar(int x) {
1028         static const char table[16] = "0123456789abcdef";
1029
1030         return table[x & 15];
1031 }
1032
1033 int unhexchar(char c) {
1034
1035         if (c >= '0' && c <= '9')
1036                 return c - '0';
1037
1038         if (c >= 'a' && c <= 'f')
1039                 return c - 'a' + 10;
1040
1041         if (c >= 'A' && c <= 'F')
1042                 return c - 'A' + 10;
1043
1044         return -1;
1045 }
1046
1047 char octchar(int x) {
1048         return '0' + (x & 7);
1049 }
1050
1051 int unoctchar(char c) {
1052
1053         if (c >= '0' && c <= '7')
1054                 return c - '0';
1055
1056         return -1;
1057 }
1058
1059 char decchar(int x) {
1060         return '0' + (x % 10);
1061 }
1062
1063 int undecchar(char c) {
1064
1065         if (c >= '0' && c <= '9')
1066                 return c - '0';
1067
1068         return -1;
1069 }
1070
1071 char *cescape(const char *s) {
1072         char *r, *t;
1073         const char *f;
1074
1075         assert(s);
1076
1077         /* Does C style string escaping. */
1078
1079         if (!(r = new(char, strlen(s)*4 + 1)))
1080                 return NULL;
1081
1082         for (f = s, t = r; *f; f++)
1083
1084                 switch (*f) {
1085
1086                 case '\a':
1087                         *(t++) = '\\';
1088                         *(t++) = 'a';
1089                         break;
1090                 case '\b':
1091                         *(t++) = '\\';
1092                         *(t++) = 'b';
1093                         break;
1094                 case '\f':
1095                         *(t++) = '\\';
1096                         *(t++) = 'f';
1097                         break;
1098                 case '\n':
1099                         *(t++) = '\\';
1100                         *(t++) = 'n';
1101                         break;
1102                 case '\r':
1103                         *(t++) = '\\';
1104                         *(t++) = 'r';
1105                         break;
1106                 case '\t':
1107                         *(t++) = '\\';
1108                         *(t++) = 't';
1109                         break;
1110                 case '\v':
1111                         *(t++) = '\\';
1112                         *(t++) = 'v';
1113                         break;
1114                 case '\\':
1115                         *(t++) = '\\';
1116                         *(t++) = '\\';
1117                         break;
1118                 case '"':
1119                         *(t++) = '\\';
1120                         *(t++) = '"';
1121                         break;
1122                 case '\'':
1123                         *(t++) = '\\';
1124                         *(t++) = '\'';
1125                         break;
1126
1127                 default:
1128                         /* For special chars we prefer octal over
1129                          * hexadecimal encoding, simply because glib's
1130                          * g_strescape() does the same */
1131                         if ((*f < ' ') || (*f >= 127)) {
1132                                 *(t++) = '\\';
1133                                 *(t++) = octchar((unsigned char) *f >> 6);
1134                                 *(t++) = octchar((unsigned char) *f >> 3);
1135                                 *(t++) = octchar((unsigned char) *f);
1136                         } else
1137                                 *(t++) = *f;
1138                         break;
1139                 }
1140
1141         *t = 0;
1142
1143         return r;
1144 }
1145
1146 char *cunescape_length(const char *s, size_t length) {
1147         char *r, *t;
1148         const char *f;
1149
1150         assert(s);
1151
1152         /* Undoes C style string escaping */
1153
1154         if (!(r = new(char, length+1)))
1155                 return r;
1156
1157         for (f = s, t = r; f < s + length; f++) {
1158
1159                 if (*f != '\\') {
1160                         *(t++) = *f;
1161                         continue;
1162                 }
1163
1164                 f++;
1165
1166                 switch (*f) {
1167
1168                 case 'a':
1169                         *(t++) = '\a';
1170                         break;
1171                 case 'b':
1172                         *(t++) = '\b';
1173                         break;
1174                 case 'f':
1175                         *(t++) = '\f';
1176                         break;
1177                 case 'n':
1178                         *(t++) = '\n';
1179                         break;
1180                 case 'r':
1181                         *(t++) = '\r';
1182                         break;
1183                 case 't':
1184                         *(t++) = '\t';
1185                         break;
1186                 case 'v':
1187                         *(t++) = '\v';
1188                         break;
1189                 case '\\':
1190                         *(t++) = '\\';
1191                         break;
1192                 case '"':
1193                         *(t++) = '"';
1194                         break;
1195                 case '\'':
1196                         *(t++) = '\'';
1197                         break;
1198
1199                 case 's':
1200                         /* This is an extension of the XDG syntax files */
1201                         *(t++) = ' ';
1202                         break;
1203
1204                 case 'x': {
1205                         /* hexadecimal encoding */
1206                         int a, b;
1207
1208                         if ((a = unhexchar(f[1])) < 0 ||
1209                             (b = unhexchar(f[2])) < 0) {
1210                                 /* Invalid escape code, let's take it literal then */
1211                                 *(t++) = '\\';
1212                                 *(t++) = 'x';
1213                         } else {
1214                                 *(t++) = (char) ((a << 4) | b);
1215                                 f += 2;
1216                         }
1217
1218                         break;
1219                 }
1220
1221                 case '0':
1222                 case '1':
1223                 case '2':
1224                 case '3':
1225                 case '4':
1226                 case '5':
1227                 case '6':
1228                 case '7': {
1229                         /* octal encoding */
1230                         int a, b, c;
1231
1232                         if ((a = unoctchar(f[0])) < 0 ||
1233                             (b = unoctchar(f[1])) < 0 ||
1234                             (c = unoctchar(f[2])) < 0) {
1235                                 /* Invalid escape code, let's take it literal then */
1236                                 *(t++) = '\\';
1237                                 *(t++) = f[0];
1238                         } else {
1239                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1240                                 f += 2;
1241                         }
1242
1243                         break;
1244                 }
1245
1246                 case 0:
1247                         /* premature end of string.*/
1248                         *(t++) = '\\';
1249                         goto finish;
1250
1251                 default:
1252                         /* Invalid escape code, let's take it literal then */
1253                         *(t++) = '\\';
1254                         *(t++) = *f;
1255                         break;
1256                 }
1257         }
1258
1259 finish:
1260         *t = 0;
1261         return r;
1262 }
1263
1264 char *cunescape(const char *s) {
1265         return cunescape_length(s, strlen(s));
1266 }
1267
1268 char *xescape(const char *s, const char *bad) {
1269         char *r, *t;
1270         const char *f;
1271
1272         /* Escapes all chars in bad, in addition to \ and all special
1273          * chars, in \xFF style escaping. May be reversed with
1274          * cunescape. */
1275
1276         if (!(r = new(char, strlen(s)*4+1)))
1277                 return NULL;
1278
1279         for (f = s, t = r; *f; f++) {
1280
1281                 if ((*f < ' ') || (*f >= 127) ||
1282                     (*f == '\\') || strchr(bad, *f)) {
1283                         *(t++) = '\\';
1284                         *(t++) = 'x';
1285                         *(t++) = hexchar(*f >> 4);
1286                         *(t++) = hexchar(*f);
1287                 } else
1288                         *(t++) = *f;
1289         }
1290
1291         *t = 0;
1292
1293         return r;
1294 }
1295
1296 char *bus_path_escape(const char *s) {
1297         char *r, *t;
1298         const char *f;
1299
1300         assert(s);
1301
1302         /* Escapes all chars that D-Bus' object path cannot deal
1303          * with. Can be reverse with bus_path_unescape() */
1304
1305         if (!(r = new(char, strlen(s)*3+1)))
1306                 return NULL;
1307
1308         for (f = s, t = r; *f; f++) {
1309
1310                 if (!(*f >= 'A' && *f <= 'Z') &&
1311                     !(*f >= 'a' && *f <= 'z') &&
1312                     !(*f >= '0' && *f <= '9')) {
1313                         *(t++) = '_';
1314                         *(t++) = hexchar(*f >> 4);
1315                         *(t++) = hexchar(*f);
1316                 } else
1317                         *(t++) = *f;
1318         }
1319
1320         *t = 0;
1321
1322         return r;
1323 }
1324
1325 char *bus_path_unescape(const char *f) {
1326         char *r, *t;
1327
1328         assert(f);
1329
1330         if (!(r = strdup(f)))
1331                 return NULL;
1332
1333         for (t = r; *f; f++) {
1334
1335                 if (*f == '_') {
1336                         int a, b;
1337
1338                         if ((a = unhexchar(f[1])) < 0 ||
1339                             (b = unhexchar(f[2])) < 0) {
1340                                 /* Invalid escape code, let's take it literal then */
1341                                 *(t++) = '_';
1342                         } else {
1343                                 *(t++) = (char) ((a << 4) | b);
1344                                 f += 2;
1345                         }
1346                 } else
1347                         *(t++) = *f;
1348         }
1349
1350         *t = 0;
1351
1352         return r;
1353 }
1354
1355 char *path_kill_slashes(char *path) {
1356         char *f, *t;
1357         bool slash = false;
1358
1359         /* Removes redundant inner and trailing slashes. Modifies the
1360          * passed string in-place.
1361          *
1362          * ///foo///bar/ becomes /foo/bar
1363          */
1364
1365         for (f = path, t = path; *f; f++) {
1366
1367                 if (*f == '/') {
1368                         slash = true;
1369                         continue;
1370                 }
1371
1372                 if (slash) {
1373                         slash = false;
1374                         *(t++) = '/';
1375                 }
1376
1377                 *(t++) = *f;
1378         }
1379
1380         /* Special rule, if we are talking of the root directory, a
1381         trailing slash is good */
1382
1383         if (t == path && slash)
1384                 *(t++) = '/';
1385
1386         *t = 0;
1387         return path;
1388 }
1389
1390 bool path_startswith(const char *path, const char *prefix) {
1391         assert(path);
1392         assert(prefix);
1393
1394         if ((path[0] == '/') != (prefix[0] == '/'))
1395                 return false;
1396
1397         for (;;) {
1398                 size_t a, b;
1399
1400                 path += strspn(path, "/");
1401                 prefix += strspn(prefix, "/");
1402
1403                 if (*prefix == 0)
1404                         return true;
1405
1406                 if (*path == 0)
1407                         return false;
1408
1409                 a = strcspn(path, "/");
1410                 b = strcspn(prefix, "/");
1411
1412                 if (a != b)
1413                         return false;
1414
1415                 if (memcmp(path, prefix, a) != 0)
1416                         return false;
1417
1418                 path += a;
1419                 prefix += b;
1420         }
1421 }
1422
1423 bool path_equal(const char *a, const char *b) {
1424         assert(a);
1425         assert(b);
1426
1427         if ((a[0] == '/') != (b[0] == '/'))
1428                 return false;
1429
1430         for (;;) {
1431                 size_t j, k;
1432
1433                 a += strspn(a, "/");
1434                 b += strspn(b, "/");
1435
1436                 if (*a == 0 && *b == 0)
1437                         return true;
1438
1439                 if (*a == 0 || *b == 0)
1440                         return false;
1441
1442                 j = strcspn(a, "/");
1443                 k = strcspn(b, "/");
1444
1445                 if (j != k)
1446                         return false;
1447
1448                 if (memcmp(a, b, j) != 0)
1449                         return false;
1450
1451                 a += j;
1452                 b += k;
1453         }
1454 }
1455
1456 char *ascii_strlower(char *t) {
1457         char *p;
1458
1459         assert(t);
1460
1461         for (p = t; *p; p++)
1462                 if (*p >= 'A' && *p <= 'Z')
1463                         *p = *p - 'A' + 'a';
1464
1465         return t;
1466 }
1467
1468 bool ignore_file(const char *filename) {
1469         assert(filename);
1470
1471         return
1472                 filename[0] == '.' ||
1473                 streq(filename, "lost+found") ||
1474                 endswith(filename, "~") ||
1475                 endswith(filename, ".rpmnew") ||
1476                 endswith(filename, ".rpmsave") ||
1477                 endswith(filename, ".rpmorig") ||
1478                 endswith(filename, ".dpkg-old") ||
1479                 endswith(filename, ".dpkg-new") ||
1480                 endswith(filename, ".swp");
1481 }
1482
1483 int fd_nonblock(int fd, bool nonblock) {
1484         int flags;
1485
1486         assert(fd >= 0);
1487
1488         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1489                 return -errno;
1490
1491         if (nonblock)
1492                 flags |= O_NONBLOCK;
1493         else
1494                 flags &= ~O_NONBLOCK;
1495
1496         if (fcntl(fd, F_SETFL, flags) < 0)
1497                 return -errno;
1498
1499         return 0;
1500 }
1501
1502 int fd_cloexec(int fd, bool cloexec) {
1503         int flags;
1504
1505         assert(fd >= 0);
1506
1507         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1508                 return -errno;
1509
1510         if (cloexec)
1511                 flags |= FD_CLOEXEC;
1512         else
1513                 flags &= ~FD_CLOEXEC;
1514
1515         if (fcntl(fd, F_SETFD, flags) < 0)
1516                 return -errno;
1517
1518         return 0;
1519 }
1520
1521 int close_all_fds(const int except[], unsigned n_except) {
1522         DIR *d;
1523         struct dirent *de;
1524         int r = 0;
1525
1526         if (!(d = opendir("/proc/self/fd")))
1527                 return -errno;
1528
1529         while ((de = readdir(d))) {
1530                 int fd = -1;
1531
1532                 if (ignore_file(de->d_name))
1533                         continue;
1534
1535                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1536                         goto finish;
1537
1538                 if (fd < 3)
1539                         continue;
1540
1541                 if (fd == dirfd(d))
1542                         continue;
1543
1544                 if (except) {
1545                         bool found;
1546                         unsigned i;
1547
1548                         found = false;
1549                         for (i = 0; i < n_except; i++)
1550                                 if (except[i] == fd) {
1551                                         found = true;
1552                                         break;
1553                                 }
1554
1555                         if (found)
1556                                 continue;
1557                 }
1558
1559                 if ((r = close_nointr(fd)) < 0) {
1560                         /* Valgrind has its own FD and doesn't want to have it closed */
1561                         if (errno != EBADF)
1562                                 goto finish;
1563                 }
1564         }
1565
1566         r = 0;
1567
1568 finish:
1569         closedir(d);
1570         return r;
1571 }
1572
1573 bool chars_intersect(const char *a, const char *b) {
1574         const char *p;
1575
1576         /* Returns true if any of the chars in a are in b. */
1577         for (p = a; *p; p++)
1578                 if (strchr(b, *p))
1579                         return true;
1580
1581         return false;
1582 }
1583
1584 char *format_timestamp(char *buf, size_t l, usec_t t) {
1585         struct tm tm;
1586         time_t sec;
1587
1588         assert(buf);
1589         assert(l > 0);
1590
1591         if (t <= 0)
1592                 return NULL;
1593
1594         sec = (time_t) (t / USEC_PER_SEC);
1595
1596         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1597                 return NULL;
1598
1599         return buf;
1600 }
1601
1602 char *format_timespan(char *buf, size_t l, usec_t t) {
1603         static const struct {
1604                 const char *suffix;
1605                 usec_t usec;
1606         } table[] = {
1607                 { "w", USEC_PER_WEEK },
1608                 { "d", USEC_PER_DAY },
1609                 { "h", USEC_PER_HOUR },
1610                 { "min", USEC_PER_MINUTE },
1611                 { "s", USEC_PER_SEC },
1612                 { "ms", USEC_PER_MSEC },
1613                 { "us", 1 },
1614         };
1615
1616         unsigned i;
1617         char *p = buf;
1618
1619         assert(buf);
1620         assert(l > 0);
1621
1622         if (t == (usec_t) -1)
1623                 return NULL;
1624
1625         /* The result of this function can be parsed with parse_usec */
1626
1627         for (i = 0; i < ELEMENTSOF(table); i++) {
1628                 int k;
1629                 size_t n;
1630
1631                 if (t < table[i].usec)
1632                         continue;
1633
1634                 if (l <= 1)
1635                         break;
1636
1637                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1638                 n = MIN((size_t) k, l);
1639
1640                 l -= n;
1641                 p += n;
1642
1643                 t %= table[i].usec;
1644         }
1645
1646         *p = 0;
1647
1648         return buf;
1649 }
1650
1651 bool fstype_is_network(const char *fstype) {
1652         static const char * const table[] = {
1653                 "cifs",
1654                 "smbfs",
1655                 "ncpfs",
1656                 "nfs",
1657                 "nfs4",
1658                 "gfs",
1659                 "gfs2"
1660         };
1661
1662         unsigned i;
1663
1664         for (i = 0; i < ELEMENTSOF(table); i++)
1665                 if (streq(table[i], fstype))
1666                         return true;
1667
1668         return false;
1669 }
1670
1671 int chvt(int vt) {
1672         int fd, r = 0;
1673
1674         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1675                 return -errno;
1676
1677         if (vt < 0) {
1678                 int tiocl[2] = {
1679                         TIOCL_GETKMSGREDIRECT,
1680                         0
1681                 };
1682
1683                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1684                         return -errno;
1685
1686                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1687         }
1688
1689         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1690                 r = -errno;
1691
1692         close_nointr_nofail(r);
1693         return r;
1694 }
1695
1696 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1697         struct termios old_termios, new_termios;
1698         char c;
1699         char line[1024];
1700
1701         assert(f);
1702         assert(ret);
1703
1704         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1705                 new_termios = old_termios;
1706
1707                 new_termios.c_lflag &= ~ICANON;
1708                 new_termios.c_cc[VMIN] = 1;
1709                 new_termios.c_cc[VTIME] = 0;
1710
1711                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1712                         size_t k;
1713
1714                         k = fread(&c, 1, 1, f);
1715
1716                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1717
1718                         if (k <= 0)
1719                                 return -EIO;
1720
1721                         if (need_nl)
1722                                 *need_nl = c != '\n';
1723
1724                         *ret = c;
1725                         return 0;
1726                 }
1727         }
1728
1729         if (!(fgets(line, sizeof(line), f)))
1730                 return -EIO;
1731
1732         truncate_nl(line);
1733
1734         if (strlen(line) != 1)
1735                 return -EBADMSG;
1736
1737         if (need_nl)
1738                 *need_nl = false;
1739
1740         *ret = line[0];
1741         return 0;
1742 }
1743
1744 int ask(char *ret, const char *replies, const char *text, ...) {
1745         assert(ret);
1746         assert(replies);
1747         assert(text);
1748
1749         for (;;) {
1750                 va_list ap;
1751                 char c;
1752                 int r;
1753                 bool need_nl = true;
1754
1755                 fputs("\x1B[1m", stdout);
1756
1757                 va_start(ap, text);
1758                 vprintf(text, ap);
1759                 va_end(ap);
1760
1761                 fputs("\x1B[0m", stdout);
1762
1763                 fflush(stdout);
1764
1765                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1766
1767                         if (r == -EBADMSG) {
1768                                 puts("Bad input, please try again.");
1769                                 continue;
1770                         }
1771
1772                         putchar('\n');
1773                         return r;
1774                 }
1775
1776                 if (need_nl)
1777                         putchar('\n');
1778
1779                 if (strchr(replies, c)) {
1780                         *ret = c;
1781                         return 0;
1782                 }
1783
1784                 puts("Read unexpected character, please try again.");
1785         }
1786 }
1787
1788 int reset_terminal(int fd) {
1789         struct termios termios;
1790         int r = 0;
1791
1792         assert(fd >= 0);
1793
1794         /* Set terminal to some sane defaults */
1795
1796         if (tcgetattr(fd, &termios) < 0) {
1797                 r = -errno;
1798                 goto finish;
1799         }
1800
1801         /* We only reset the stuff that matters to the software. How
1802          * hardware is set up we don't touch assuming that somebody
1803          * else will do that for us */
1804
1805         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1806         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1807         termios.c_oflag |= ONLCR;
1808         termios.c_cflag |= CREAD;
1809         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1810
1811         termios.c_cc[VINTR]    =   03;  /* ^C */
1812         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1813         termios.c_cc[VERASE]   = 0177;
1814         termios.c_cc[VKILL]    =  025;  /* ^X */
1815         termios.c_cc[VEOF]     =   04;  /* ^D */
1816         termios.c_cc[VSTART]   =  021;  /* ^Q */
1817         termios.c_cc[VSTOP]    =  023;  /* ^S */
1818         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1819         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1820         termios.c_cc[VWERASE]  =  027;  /* ^W */
1821         termios.c_cc[VREPRINT] =  022;  /* ^R */
1822         termios.c_cc[VEOL]     =    0;
1823         termios.c_cc[VEOL2]    =    0;
1824
1825         termios.c_cc[VTIME]  = 0;
1826         termios.c_cc[VMIN]   = 1;
1827
1828         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1829                 r = -errno;
1830
1831 finish:
1832         /* Just in case, flush all crap out */
1833         tcflush(fd, TCIOFLUSH);
1834
1835         return r;
1836 }
1837
1838 int open_terminal(const char *name, int mode) {
1839         int fd, r;
1840
1841         if ((fd = open(name, mode)) < 0)
1842                 return -errno;
1843
1844         if ((r = isatty(fd)) < 0) {
1845                 close_nointr_nofail(fd);
1846                 return -errno;
1847         }
1848
1849         if (!r) {
1850                 close_nointr_nofail(fd);
1851                 return -ENOTTY;
1852         }
1853
1854         return fd;
1855 }
1856
1857 int flush_fd(int fd) {
1858         struct pollfd pollfd;
1859
1860         zero(pollfd);
1861         pollfd.fd = fd;
1862         pollfd.events = POLLIN;
1863
1864         for (;;) {
1865                 char buf[1024];
1866                 ssize_t l;
1867                 int r;
1868
1869                 if ((r = poll(&pollfd, 1, 0)) < 0) {
1870
1871                         if (errno == EINTR)
1872                                 continue;
1873
1874                         return -errno;
1875                 }
1876
1877                 if (r == 0)
1878                         return 0;
1879
1880                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1881
1882                         if (errno == EINTR)
1883                                 continue;
1884
1885                         if (errno == EAGAIN)
1886                                 return 0;
1887
1888                         return -errno;
1889                 }
1890
1891                 if (l <= 0)
1892                         return 0;
1893         }
1894 }
1895
1896 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1897         int fd = -1, notify = -1, r, wd = -1;
1898
1899         assert(name);
1900
1901         /* We use inotify to be notified when the tty is closed. We
1902          * create the watch before checking if we can actually acquire
1903          * it, so that we don't lose any event.
1904          *
1905          * Note: strictly speaking this actually watches for the
1906          * device being closed, it does *not* really watch whether a
1907          * tty loses its controlling process. However, unless some
1908          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1909          * its tty otherwise this will not become a problem. As long
1910          * as the administrator makes sure not configure any service
1911          * on the same tty as an untrusted user this should not be a
1912          * problem. (Which he probably should not do anyway.) */
1913
1914         if (!fail && !force) {
1915                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1916                         r = -errno;
1917                         goto fail;
1918                 }
1919
1920                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1921                         r = -errno;
1922                         goto fail;
1923                 }
1924         }
1925
1926         for (;;) {
1927                 if (notify >= 0)
1928                         if ((r = flush_fd(notify)) < 0)
1929                                 goto fail;
1930
1931                 /* We pass here O_NOCTTY only so that we can check the return
1932                  * value TIOCSCTTY and have a reliable way to figure out if we
1933                  * successfully became the controlling process of the tty */
1934                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1935                         return -errno;
1936
1937                 /* First, try to get the tty */
1938                 r = ioctl(fd, TIOCSCTTY, force);
1939
1940                 /* Sometimes it makes sense to ignore TIOCSCTTY
1941                  * returning EPERM, i.e. when very likely we already
1942                  * are have this controlling terminal. */
1943                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1944                         r = 0;
1945
1946                 if (r < 0 && (force || fail || errno != EPERM)) {
1947                         r = -errno;
1948                         goto fail;
1949                 }
1950
1951                 if (r >= 0)
1952                         break;
1953
1954                 assert(!fail);
1955                 assert(!force);
1956                 assert(notify >= 0);
1957
1958                 for (;;) {
1959                         struct inotify_event e;
1960                         ssize_t l;
1961
1962                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1963
1964                                 if (l < 0) {
1965
1966                                         if (errno == EINTR)
1967                                                 continue;
1968
1969                                         r = -errno;
1970                                 } else
1971                                         r = -EIO;
1972
1973                                 goto fail;
1974                         }
1975
1976                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1977                                 r = -errno;
1978                                 goto fail;
1979                         }
1980
1981                         break;
1982                 }
1983
1984                 /* We close the tty fd here since if the old session
1985                  * ended our handle will be dead. It's important that
1986                  * we do this after sleeping, so that we don't enter
1987                  * an endless loop. */
1988                 close_nointr_nofail(fd);
1989         }
1990
1991         if (notify >= 0)
1992                 close_nointr_nofail(notify);
1993
1994         if ((r = reset_terminal(fd)) < 0)
1995                 log_warning("Failed to reset terminal: %s", strerror(-r));
1996
1997         return fd;
1998
1999 fail:
2000         if (fd >= 0)
2001                 close_nointr_nofail(fd);
2002
2003         if (notify >= 0)
2004                 close_nointr_nofail(notify);
2005
2006         return r;
2007 }
2008
2009 int release_terminal(void) {
2010         int r = 0, fd;
2011         struct sigaction sa_old, sa_new;
2012
2013         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2014                 return -errno;
2015
2016         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2017          * by our own TIOCNOTTY */
2018
2019         zero(sa_new);
2020         sa_new.sa_handler = SIG_IGN;
2021         sa_new.sa_flags = SA_RESTART;
2022         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2023
2024         if (ioctl(fd, TIOCNOTTY) < 0)
2025                 r = -errno;
2026
2027         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2028
2029         close_nointr_nofail(fd);
2030         return r;
2031 }
2032
2033 int sigaction_many(const struct sigaction *sa, ...) {
2034         va_list ap;
2035         int r = 0, sig;
2036
2037         va_start(ap, sa);
2038         while ((sig = va_arg(ap, int)) > 0)
2039                 if (sigaction(sig, sa, NULL) < 0)
2040                         r = -errno;
2041         va_end(ap);
2042
2043         return r;
2044 }
2045
2046 int ignore_signals(int sig, ...) {
2047         struct sigaction sa;
2048         va_list ap;
2049         int r = 0;
2050
2051         zero(sa);
2052         sa.sa_handler = SIG_IGN;
2053         sa.sa_flags = SA_RESTART;
2054
2055         if (sigaction(sig, &sa, NULL) < 0)
2056                 r = -errno;
2057
2058         va_start(ap, sig);
2059         while ((sig = va_arg(ap, int)) > 0)
2060                 if (sigaction(sig, &sa, NULL) < 0)
2061                         r = -errno;
2062         va_end(ap);
2063
2064         return r;
2065 }
2066
2067 int default_signals(int sig, ...) {
2068         struct sigaction sa;
2069         va_list ap;
2070         int r = 0;
2071
2072         zero(sa);
2073         sa.sa_handler = SIG_DFL;
2074         sa.sa_flags = SA_RESTART;
2075
2076         if (sigaction(sig, &sa, NULL) < 0)
2077                 r = -errno;
2078
2079         va_start(ap, sig);
2080         while ((sig = va_arg(ap, int)) > 0)
2081                 if (sigaction(sig, &sa, NULL) < 0)
2082                         r = -errno;
2083         va_end(ap);
2084
2085         return r;
2086 }
2087
2088 int close_pipe(int p[]) {
2089         int a = 0, b = 0;
2090
2091         assert(p);
2092
2093         if (p[0] >= 0) {
2094                 a = close_nointr(p[0]);
2095                 p[0] = -1;
2096         }
2097
2098         if (p[1] >= 0) {
2099                 b = close_nointr(p[1]);
2100                 p[1] = -1;
2101         }
2102
2103         return a < 0 ? a : b;
2104 }
2105
2106 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2107         uint8_t *p;
2108         ssize_t n = 0;
2109
2110         assert(fd >= 0);
2111         assert(buf);
2112
2113         p = buf;
2114
2115         while (nbytes > 0) {
2116                 ssize_t k;
2117
2118                 if ((k = read(fd, p, nbytes)) <= 0) {
2119
2120                         if (k < 0 && errno == EINTR)
2121                                 continue;
2122
2123                         if (k < 0 && errno == EAGAIN && do_poll) {
2124                                 struct pollfd pollfd;
2125
2126                                 zero(pollfd);
2127                                 pollfd.fd = fd;
2128                                 pollfd.events = POLLIN;
2129
2130                                 if (poll(&pollfd, 1, -1) < 0) {
2131                                         if (errno == EINTR)
2132                                                 continue;
2133
2134                                         return n > 0 ? n : -errno;
2135                                 }
2136
2137                                 if (pollfd.revents != POLLIN)
2138                                         return n > 0 ? n : -EIO;
2139
2140                                 continue;
2141                         }
2142
2143                         return n > 0 ? n : (k < 0 ? -errno : 0);
2144                 }
2145
2146                 p += k;
2147                 nbytes -= k;
2148                 n += k;
2149         }
2150
2151         return n;
2152 }
2153
2154 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2155         const uint8_t *p;
2156         ssize_t n = 0;
2157
2158         assert(fd >= 0);
2159         assert(buf);
2160
2161         p = buf;
2162
2163         while (nbytes > 0) {
2164                 ssize_t k;
2165
2166                 if ((k = write(fd, p, nbytes)) <= 0) {
2167
2168                         if (k < 0 && errno == EINTR)
2169                                 continue;
2170
2171                         if (k < 0 && errno == EAGAIN && do_poll) {
2172                                 struct pollfd pollfd;
2173
2174                                 zero(pollfd);
2175                                 pollfd.fd = fd;
2176                                 pollfd.events = POLLOUT;
2177
2178                                 if (poll(&pollfd, 1, -1) < 0) {
2179                                         if (errno == EINTR)
2180                                                 continue;
2181
2182                                         return n > 0 ? n : -errno;
2183                                 }
2184
2185                                 if (pollfd.revents != POLLOUT)
2186                                         return n > 0 ? n : -EIO;
2187
2188                                 continue;
2189                         }
2190
2191                         return n > 0 ? n : (k < 0 ? -errno : 0);
2192                 }
2193
2194                 p += k;
2195                 nbytes -= k;
2196                 n += k;
2197         }
2198
2199         return n;
2200 }
2201
2202 int path_is_mount_point(const char *t) {
2203         struct stat a, b;
2204         char *copy;
2205
2206         if (lstat(t, &a) < 0) {
2207
2208                 if (errno == ENOENT)
2209                         return 0;
2210
2211                 return -errno;
2212         }
2213
2214         if (!(copy = strdup(t)))
2215                 return -ENOMEM;
2216
2217         if (lstat(dirname(copy), &b) < 0) {
2218                 free(copy);
2219                 return -errno;
2220         }
2221
2222         free(copy);
2223
2224         return a.st_dev != b.st_dev;
2225 }
2226
2227 int parse_usec(const char *t, usec_t *usec) {
2228         static const struct {
2229                 const char *suffix;
2230                 usec_t usec;
2231         } table[] = {
2232                 { "sec", USEC_PER_SEC },
2233                 { "s", USEC_PER_SEC },
2234                 { "min", USEC_PER_MINUTE },
2235                 { "hr", USEC_PER_HOUR },
2236                 { "h", USEC_PER_HOUR },
2237                 { "d", USEC_PER_DAY },
2238                 { "w", USEC_PER_WEEK },
2239                 { "msec", USEC_PER_MSEC },
2240                 { "ms", USEC_PER_MSEC },
2241                 { "m", USEC_PER_MINUTE },
2242                 { "usec", 1ULL },
2243                 { "us", 1ULL },
2244                 { "", USEC_PER_SEC },
2245         };
2246
2247         const char *p;
2248         usec_t r = 0;
2249
2250         assert(t);
2251         assert(usec);
2252
2253         p = t;
2254         do {
2255                 long long l;
2256                 char *e;
2257                 unsigned i;
2258
2259                 errno = 0;
2260                 l = strtoll(p, &e, 10);
2261
2262                 if (errno != 0)
2263                         return -errno;
2264
2265                 if (l < 0)
2266                         return -ERANGE;
2267
2268                 if (e == p)
2269                         return -EINVAL;
2270
2271                 e += strspn(e, WHITESPACE);
2272
2273                 for (i = 0; i < ELEMENTSOF(table); i++)
2274                         if (startswith(e, table[i].suffix)) {
2275                                 r += (usec_t) l * table[i].usec;
2276                                 p = e + strlen(table[i].suffix);
2277                                 break;
2278                         }
2279
2280                 if (i >= ELEMENTSOF(table))
2281                         return -EINVAL;
2282
2283         } while (*p != 0);
2284
2285         *usec = r;
2286
2287         return 0;
2288 }
2289
2290 int make_stdio(int fd) {
2291         int r, s, t;
2292
2293         assert(fd >= 0);
2294
2295         r = dup2(fd, STDIN_FILENO);
2296         s = dup2(fd, STDOUT_FILENO);
2297         t = dup2(fd, STDERR_FILENO);
2298
2299         if (fd >= 3)
2300                 close_nointr_nofail(fd);
2301
2302         if (r < 0 || s < 0 || t < 0)
2303                 return -errno;
2304
2305         return 0;
2306 }
2307
2308 bool is_clean_exit(int code, int status) {
2309
2310         if (code == CLD_EXITED)
2311                 return status == 0;
2312
2313         /* If a daemon does not implement handlers for some of the
2314          * signals that's not considered an unclean shutdown */
2315         if (code == CLD_KILLED)
2316                 return
2317                         status == SIGHUP ||
2318                         status == SIGINT ||
2319                         status == SIGTERM ||
2320                         status == SIGPIPE;
2321
2322         return false;
2323 }
2324
2325 bool is_device_path(const char *path) {
2326
2327         /* Returns true on paths that refer to a device, either in
2328          * sysfs or in /dev */
2329
2330         return
2331                 path_startswith(path, "/dev/") ||
2332                 path_startswith(path, "/sys/");
2333 }
2334
2335 int dir_is_empty(const char *path) {
2336         DIR *d;
2337         int r;
2338         struct dirent buf, *de;
2339
2340         if (!(d = opendir(path)))
2341                 return -errno;
2342
2343         for (;;) {
2344                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2345                         r = -r;
2346                         break;
2347                 }
2348
2349                 if (!de) {
2350                         r = 1;
2351                         break;
2352                 }
2353
2354                 if (!ignore_file(de->d_name)) {
2355                         r = 0;
2356                         break;
2357                 }
2358         }
2359
2360         closedir(d);
2361         return r;
2362 }
2363
2364 unsigned long long random_ull(void) {
2365         int fd;
2366         uint64_t ull;
2367         ssize_t r;
2368
2369         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2370                 goto fallback;
2371
2372         r = loop_read(fd, &ull, sizeof(ull), true);
2373         close_nointr_nofail(fd);
2374
2375         if (r != sizeof(ull))
2376                 goto fallback;
2377
2378         return ull;
2379
2380 fallback:
2381         return random() * RAND_MAX + random();
2382 }
2383
2384 void rename_process(const char name[8]) {
2385         assert(name);
2386
2387         prctl(PR_SET_NAME, name);
2388
2389         /* This is a like a poor man's setproctitle(). The string
2390          * passed should fit in 7 chars (i.e. the length of
2391          * "systemd") */
2392
2393         if (program_invocation_name)
2394                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2395 }
2396
2397 void sigset_add_many(sigset_t *ss, ...) {
2398         va_list ap;
2399         int sig;
2400
2401         assert(ss);
2402
2403         va_start(ap, ss);
2404         while ((sig = va_arg(ap, int)) > 0)
2405                 assert_se(sigaddset(ss, sig) == 0);
2406         va_end(ap);
2407 }
2408
2409 char* gethostname_malloc(void) {
2410         struct utsname u;
2411
2412         assert_se(uname(&u) >= 0);
2413
2414         if (u.nodename[0])
2415                 return strdup(u.nodename);
2416
2417         return strdup(u.sysname);
2418 }
2419
2420 int getmachineid_malloc(char **b) {
2421         int r;
2422
2423         assert(b);
2424
2425         if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2426                 return r;
2427
2428         strstrip(*b);
2429         return 0;
2430 }
2431
2432 char* getlogname_malloc(void) {
2433         uid_t uid;
2434         long bufsize;
2435         char *buf, *name;
2436         struct passwd pwbuf, *pw = NULL;
2437         struct stat st;
2438
2439         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2440                 uid = st.st_uid;
2441         else
2442                 uid = getuid();
2443
2444         /* Shortcut things to avoid NSS lookups */
2445         if (uid == 0)
2446                 return strdup("root");
2447
2448         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2449                 bufsize = 4096;
2450
2451         if (!(buf = malloc(bufsize)))
2452                 return NULL;
2453
2454         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2455                 name = strdup(pw->pw_name);
2456                 free(buf);
2457                 return name;
2458         }
2459
2460         free(buf);
2461
2462         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2463                 return NULL;
2464
2465         return name;
2466 }
2467
2468 int getttyname_malloc(char **r) {
2469         char path[PATH_MAX], *p, *c;
2470
2471         assert(r);
2472
2473         if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2474                 return -errno;
2475
2476         char_array_0(path);
2477
2478         p = path;
2479         if (startswith(path, "/dev/"))
2480                 p += 5;
2481
2482         if (!(c = strdup(p)))
2483                 return -ENOMEM;
2484
2485         *r = c;
2486         return 0;
2487 }
2488
2489 static int rm_rf_children(int fd, bool only_dirs) {
2490         DIR *d;
2491         int ret = 0;
2492
2493         assert(fd >= 0);
2494
2495         /* This returns the first error we run into, but nevertheless
2496          * tries to go on */
2497
2498         if (!(d = fdopendir(fd))) {
2499                 close_nointr_nofail(fd);
2500                 return -errno;
2501         }
2502
2503         for (;;) {
2504                 struct dirent buf, *de;
2505                 bool is_dir;
2506                 int r;
2507
2508                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2509                         if (ret == 0)
2510                                 ret = -r;
2511                         break;
2512                 }
2513
2514                 if (!de)
2515                         break;
2516
2517                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2518                         continue;
2519
2520                 if (de->d_type == DT_UNKNOWN) {
2521                         struct stat st;
2522
2523                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2524                                 if (ret == 0)
2525                                         ret = -errno;
2526                                 continue;
2527                         }
2528
2529                         is_dir = S_ISDIR(st.st_mode);
2530                 } else
2531                         is_dir = de->d_type == DT_DIR;
2532
2533                 if (is_dir) {
2534                         int subdir_fd;
2535
2536                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2537                                 if (ret == 0)
2538                                         ret = -errno;
2539                                 continue;
2540                         }
2541
2542                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2543                                 if (ret == 0)
2544                                         ret = r;
2545                         }
2546
2547                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2548                                 if (ret == 0)
2549                                         ret = -errno;
2550                         }
2551                 } else  if (!only_dirs) {
2552
2553                         if (unlinkat(fd, de->d_name, 0) < 0) {
2554                                 if (ret == 0)
2555                                         ret = -errno;
2556                         }
2557                 }
2558         }
2559
2560         closedir(d);
2561
2562         return ret;
2563 }
2564
2565 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2566         int fd;
2567         int r;
2568
2569         assert(path);
2570
2571         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2572
2573                 if (errno != ENOTDIR)
2574                         return -errno;
2575
2576                 if (delete_root && !only_dirs)
2577                         if (unlink(path) < 0)
2578                                 return -errno;
2579
2580                 return 0;
2581         }
2582
2583         r = rm_rf_children(fd, only_dirs);
2584
2585         if (delete_root)
2586                 if (rmdir(path) < 0) {
2587                         if (r == 0)
2588                                 r = -errno;
2589                 }
2590
2591         return r;
2592 }
2593
2594 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2595         assert(path);
2596
2597         /* Under the assumption that we are running privileged we
2598          * first change the access mode and only then hand out
2599          * ownership to avoid a window where access is too open. */
2600
2601         if (chmod(path, mode) < 0)
2602                 return -errno;
2603
2604         if (chown(path, uid, gid) < 0)
2605                 return -errno;
2606
2607         return 0;
2608 }
2609
2610 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2611         cpu_set_t *r;
2612         unsigned n = 1024;
2613
2614         /* Allocates the cpuset in the right size */
2615
2616         for (;;) {
2617                 if (!(r = CPU_ALLOC(n)))
2618                         return NULL;
2619
2620                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2621                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2622
2623                         if (ncpus)
2624                                 *ncpus = n;
2625
2626                         return r;
2627                 }
2628
2629                 CPU_FREE(r);
2630
2631                 if (errno != EINVAL)
2632                         return NULL;
2633
2634                 n *= 2;
2635         }
2636 }
2637
2638 void status_vprintf(const char *format, va_list ap) {
2639         char *s = NULL;
2640         int fd = -1;
2641
2642         assert(format);
2643
2644         /* This independent of logging, as status messages are
2645          * optional and go exclusively to the console. */
2646
2647         if (vasprintf(&s, format, ap) < 0)
2648                 goto finish;
2649
2650         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2651                 goto finish;
2652
2653         write(fd, s, strlen(s));
2654
2655 finish:
2656         free(s);
2657
2658         if (fd >= 0)
2659                 close_nointr_nofail(fd);
2660 }
2661
2662 void status_printf(const char *format, ...) {
2663         va_list ap;
2664
2665         assert(format);
2666
2667         va_start(ap, format);
2668         status_vprintf(format, ap);
2669         va_end(ap);
2670 }
2671
2672 void status_welcome(void) {
2673
2674 #if defined(TARGET_FEDORA)
2675         char *r;
2676
2677         if (read_one_line_file("/etc/system-release", &r) < 0)
2678                 return;
2679
2680         truncate_nl(r);
2681
2682         /* This tries to mimic the color magic the old Red Hat sysinit
2683          * script did. */
2684
2685         if (startswith(r, "Red Hat"))
2686                 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2687         else if (startswith(r, "Fedora"))
2688                 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2689         else
2690                 status_printf("Welcome to %s!\n", r);
2691
2692         free(r);
2693
2694 #elif defined(TARGET_SUSE)
2695         char *r;
2696
2697         if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2698                 return;
2699
2700         truncate_nl(r);
2701
2702         status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2703         free(r);
2704 #else
2705 #warning "You probably should add a welcome text logic here."
2706 #endif
2707 }
2708
2709 char *replace_env(const char *format, char **env) {
2710         enum {
2711                 WORD,
2712                 DOLLAR,
2713                 VARIABLE
2714         } state = WORD;
2715
2716         const char *e, *word = format;
2717         char *r = NULL, *k;
2718
2719         assert(format);
2720
2721         for (e = format; *e; e ++) {
2722
2723                 switch (state) {
2724
2725                 case WORD:
2726                         if (*e == '$')
2727                                 state = DOLLAR;
2728                         break;
2729
2730                 case DOLLAR:
2731                         if (*e == '(') {
2732                                 if (!(k = strnappend(r, word, e-word-1)))
2733                                         goto fail;
2734
2735                                 free(r);
2736                                 r = k;
2737
2738                                 word = e-1;
2739                                 state = VARIABLE;
2740
2741                         } else if (*e == '$') {
2742                                 if (!(k = strnappend(r, word, e-word)))
2743                                         goto fail;
2744
2745                                 free(r);
2746                                 r = k;
2747
2748                                 word = e+1;
2749                                 state = WORD;
2750                         } else
2751                                 state = WORD;
2752                         break;
2753
2754                 case VARIABLE:
2755                         if (*e == ')') {
2756                                 char *t;
2757
2758                                 if ((t = strv_env_get_with_length(env, word+2, e-word-2))) {
2759                                         if (!(k = strappend(r, t)))
2760                                                 goto fail;
2761
2762                                         free(r);
2763                                         r = k;
2764
2765                                         word = e+1;
2766                                 }
2767
2768                                 state = WORD;
2769                         }
2770                         break;
2771                 }
2772         }
2773
2774         if (!(k = strnappend(r, word, e-word)))
2775                 goto fail;
2776
2777         free(r);
2778         return k;
2779
2780 fail:
2781         free(r);
2782         return NULL;
2783 }
2784
2785 char **replace_env_argv(char **argv, char **env) {
2786         char **r, **i;
2787         unsigned k = 0;
2788
2789         if (!(r = new(char*, strv_length(argv)+1)))
2790                 return NULL;
2791
2792         STRV_FOREACH(i, argv) {
2793                 if (!(r[k++] = replace_env(*i, env))) {
2794                         strv_free(r);
2795                         return NULL;
2796                 }
2797         }
2798
2799         r[k] = NULL;
2800         return r;
2801 }
2802
2803 int columns(void) {
2804         static __thread int parsed_columns = 0;
2805         const char *e;
2806
2807         if (parsed_columns > 0)
2808                 return parsed_columns;
2809
2810         if ((e = getenv("COLUMNS")))
2811                 parsed_columns = atoi(e);
2812
2813         if (parsed_columns <= 0) {
2814                 struct winsize ws;
2815                 zero(ws);
2816
2817                 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2818                         parsed_columns = ws.ws_col;
2819         }
2820
2821         if (parsed_columns <= 0)
2822                 parsed_columns = 80;
2823
2824         return parsed_columns;
2825 }
2826
2827 int running_in_chroot(void) {
2828         struct stat a, b;
2829
2830         zero(a);
2831         zero(b);
2832
2833         /* Only works as root */
2834
2835         if (stat("/proc/1/root", &a) < 0)
2836                 return -errno;
2837
2838         if (stat("/", &b) < 0)
2839                 return -errno;
2840
2841         return
2842                 a.st_dev != b.st_dev ||
2843                 a.st_ino != b.st_ino;
2844 }
2845
2846 static const char *const ioprio_class_table[] = {
2847         [IOPRIO_CLASS_NONE] = "none",
2848         [IOPRIO_CLASS_RT] = "realtime",
2849         [IOPRIO_CLASS_BE] = "best-effort",
2850         [IOPRIO_CLASS_IDLE] = "idle"
2851 };
2852
2853 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2854
2855 static const char *const sigchld_code_table[] = {
2856         [CLD_EXITED] = "exited",
2857         [CLD_KILLED] = "killed",
2858         [CLD_DUMPED] = "dumped",
2859         [CLD_TRAPPED] = "trapped",
2860         [CLD_STOPPED] = "stopped",
2861         [CLD_CONTINUED] = "continued",
2862 };
2863
2864 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2865
2866 static const char *const log_facility_table[LOG_NFACILITIES] = {
2867         [LOG_FAC(LOG_KERN)] = "kern",
2868         [LOG_FAC(LOG_USER)] = "user",
2869         [LOG_FAC(LOG_MAIL)] = "mail",
2870         [LOG_FAC(LOG_DAEMON)] = "daemon",
2871         [LOG_FAC(LOG_AUTH)] = "auth",
2872         [LOG_FAC(LOG_SYSLOG)] = "syslog",
2873         [LOG_FAC(LOG_LPR)] = "lpr",
2874         [LOG_FAC(LOG_NEWS)] = "news",
2875         [LOG_FAC(LOG_UUCP)] = "uucp",
2876         [LOG_FAC(LOG_CRON)] = "cron",
2877         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2878         [LOG_FAC(LOG_FTP)] = "ftp",
2879         [LOG_FAC(LOG_LOCAL0)] = "local0",
2880         [LOG_FAC(LOG_LOCAL1)] = "local1",
2881         [LOG_FAC(LOG_LOCAL2)] = "local2",
2882         [LOG_FAC(LOG_LOCAL3)] = "local3",
2883         [LOG_FAC(LOG_LOCAL4)] = "local4",
2884         [LOG_FAC(LOG_LOCAL5)] = "local5",
2885         [LOG_FAC(LOG_LOCAL6)] = "local6",
2886         [LOG_FAC(LOG_LOCAL7)] = "local7"
2887 };
2888
2889 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2890
2891 static const char *const log_level_table[] = {
2892         [LOG_EMERG] = "emerg",
2893         [LOG_ALERT] = "alert",
2894         [LOG_CRIT] = "crit",
2895         [LOG_ERR] = "err",
2896         [LOG_WARNING] = "warning",
2897         [LOG_NOTICE] = "notice",
2898         [LOG_INFO] = "info",
2899         [LOG_DEBUG] = "debug"
2900 };
2901
2902 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2903
2904 static const char* const sched_policy_table[] = {
2905         [SCHED_OTHER] = "other",
2906         [SCHED_BATCH] = "batch",
2907         [SCHED_IDLE] = "idle",
2908         [SCHED_FIFO] = "fifo",
2909         [SCHED_RR] = "rr"
2910 };
2911
2912 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2913
2914 static const char* const rlimit_table[] = {
2915         [RLIMIT_CPU] = "LimitCPU",
2916         [RLIMIT_FSIZE] = "LimitFSIZE",
2917         [RLIMIT_DATA] = "LimitDATA",
2918         [RLIMIT_STACK] = "LimitSTACK",
2919         [RLIMIT_CORE] = "LimitCORE",
2920         [RLIMIT_RSS] = "LimitRSS",
2921         [RLIMIT_NOFILE] = "LimitNOFILE",
2922         [RLIMIT_AS] = "LimitAS",
2923         [RLIMIT_NPROC] = "LimitNPROC",
2924         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2925         [RLIMIT_LOCKS] = "LimitLOCKS",
2926         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2927         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2928         [RLIMIT_NICE] = "LimitNICE",
2929         [RLIMIT_RTPRIO] = "LimitRTPRIO",
2930         [RLIMIT_RTTIME] = "LimitRTTIME"
2931 };
2932
2933 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2934
2935 static const char* const ip_tos_table[] = {
2936         [IPTOS_LOWDELAY] = "low-delay",
2937         [IPTOS_THROUGHPUT] = "throughput",
2938         [IPTOS_RELIABILITY] = "reliability",
2939         [IPTOS_LOWCOST] = "low-cost",
2940 };
2941
2942 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
2943
2944 static const char *const signal_table[] = {
2945         [SIGHUP] = "HUP",
2946         [SIGINT] = "INT",
2947         [SIGQUIT] = "QUIT",
2948         [SIGILL] = "ILL",
2949         [SIGTRAP] = "TRAP",
2950         [SIGABRT] = "ABRT",
2951         [SIGBUS] = "BUS",
2952         [SIGFPE] = "FPE",
2953         [SIGKILL] = "KILL",
2954         [SIGUSR1] = "USR1",
2955         [SIGSEGV] = "SEGV",
2956         [SIGUSR2] = "USR2",
2957         [SIGPIPE] = "PIPE",
2958         [SIGALRM] = "ALRM",
2959         [SIGTERM] = "TERM",
2960         [SIGSTKFLT] = "STKFLT",
2961         [SIGCHLD] = "CHLD",
2962         [SIGCONT] = "CONT",
2963         [SIGSTOP] = "STOP",
2964         [SIGTSTP] = "TSTP",
2965         [SIGTTIN] = "TTIN",
2966         [SIGTTOU] = "TTOU",
2967         [SIGURG] = "URG",
2968         [SIGXCPU] = "XCPU",
2969         [SIGXFSZ] = "XFSZ",
2970         [SIGVTALRM] = "VTALRM",
2971         [SIGPROF] = "PROF",
2972         [SIGWINCH] = "WINCH",
2973         [SIGIO] = "IO",
2974         [SIGPWR] = "PWR",
2975         [SIGSYS] = "SYS"
2976 };
2977
2978 DEFINE_STRING_TABLE_LOOKUP(signal, int);