chiark / gitweb /
man: update daemon man page a little
[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
960                 free(t);
961
962                 if (r < 0 && errno != EEXIST)
963                         return -errno;
964         }
965 }
966
967 int mkdir_p(const char *path, mode_t mode) {
968         int r;
969
970         /* Like mkdir -p */
971
972         if ((r = mkdir_parents(path, mode)) < 0)
973                 return r;
974
975         if (mkdir(path, mode) < 0)
976                 return -errno;
977
978         return 0;
979 }
980
981 int rmdir_parents(const char *path, const char *stop) {
982         size_t l;
983         int r = 0;
984
985         assert(path);
986         assert(stop);
987
988         l = strlen(path);
989
990         /* Skip trailing slashes */
991         while (l > 0 && path[l-1] == '/')
992                 l--;
993
994         while (l > 0) {
995                 char *t;
996
997                 /* Skip last component */
998                 while (l > 0 && path[l-1] != '/')
999                         l--;
1000
1001                 /* Skip trailing slashes */
1002                 while (l > 0 && path[l-1] == '/')
1003                         l--;
1004
1005                 if (l <= 0)
1006                         break;
1007
1008                 if (!(t = strndup(path, l)))
1009                         return -ENOMEM;
1010
1011                 if (path_startswith(stop, t)) {
1012                         free(t);
1013                         return 0;
1014                 }
1015
1016                 r = rmdir(t);
1017                 free(t);
1018
1019                 if (r < 0)
1020                         if (errno != ENOENT)
1021                                 return -errno;
1022         }
1023
1024         return 0;
1025 }
1026
1027
1028 char hexchar(int x) {
1029         static const char table[16] = "0123456789abcdef";
1030
1031         return table[x & 15];
1032 }
1033
1034 int unhexchar(char c) {
1035
1036         if (c >= '0' && c <= '9')
1037                 return c - '0';
1038
1039         if (c >= 'a' && c <= 'f')
1040                 return c - 'a' + 10;
1041
1042         if (c >= 'A' && c <= 'F')
1043                 return c - 'A' + 10;
1044
1045         return -1;
1046 }
1047
1048 char octchar(int x) {
1049         return '0' + (x & 7);
1050 }
1051
1052 int unoctchar(char c) {
1053
1054         if (c >= '0' && c <= '7')
1055                 return c - '0';
1056
1057         return -1;
1058 }
1059
1060 char decchar(int x) {
1061         return '0' + (x % 10);
1062 }
1063
1064 int undecchar(char c) {
1065
1066         if (c >= '0' && c <= '9')
1067                 return c - '0';
1068
1069         return -1;
1070 }
1071
1072 char *cescape(const char *s) {
1073         char *r, *t;
1074         const char *f;
1075
1076         assert(s);
1077
1078         /* Does C style string escaping. */
1079
1080         if (!(r = new(char, strlen(s)*4 + 1)))
1081                 return NULL;
1082
1083         for (f = s, t = r; *f; f++)
1084
1085                 switch (*f) {
1086
1087                 case '\a':
1088                         *(t++) = '\\';
1089                         *(t++) = 'a';
1090                         break;
1091                 case '\b':
1092                         *(t++) = '\\';
1093                         *(t++) = 'b';
1094                         break;
1095                 case '\f':
1096                         *(t++) = '\\';
1097                         *(t++) = 'f';
1098                         break;
1099                 case '\n':
1100                         *(t++) = '\\';
1101                         *(t++) = 'n';
1102                         break;
1103                 case '\r':
1104                         *(t++) = '\\';
1105                         *(t++) = 'r';
1106                         break;
1107                 case '\t':
1108                         *(t++) = '\\';
1109                         *(t++) = 't';
1110                         break;
1111                 case '\v':
1112                         *(t++) = '\\';
1113                         *(t++) = 'v';
1114                         break;
1115                 case '\\':
1116                         *(t++) = '\\';
1117                         *(t++) = '\\';
1118                         break;
1119                 case '"':
1120                         *(t++) = '\\';
1121                         *(t++) = '"';
1122                         break;
1123                 case '\'':
1124                         *(t++) = '\\';
1125                         *(t++) = '\'';
1126                         break;
1127
1128                 default:
1129                         /* For special chars we prefer octal over
1130                          * hexadecimal encoding, simply because glib's
1131                          * g_strescape() does the same */
1132                         if ((*f < ' ') || (*f >= 127)) {
1133                                 *(t++) = '\\';
1134                                 *(t++) = octchar((unsigned char) *f >> 6);
1135                                 *(t++) = octchar((unsigned char) *f >> 3);
1136                                 *(t++) = octchar((unsigned char) *f);
1137                         } else
1138                                 *(t++) = *f;
1139                         break;
1140                 }
1141
1142         *t = 0;
1143
1144         return r;
1145 }
1146
1147 char *cunescape_length(const char *s, size_t length) {
1148         char *r, *t;
1149         const char *f;
1150
1151         assert(s);
1152
1153         /* Undoes C style string escaping */
1154
1155         if (!(r = new(char, length+1)))
1156                 return r;
1157
1158         for (f = s, t = r; f < s + length; f++) {
1159
1160                 if (*f != '\\') {
1161                         *(t++) = *f;
1162                         continue;
1163                 }
1164
1165                 f++;
1166
1167                 switch (*f) {
1168
1169                 case 'a':
1170                         *(t++) = '\a';
1171                         break;
1172                 case 'b':
1173                         *(t++) = '\b';
1174                         break;
1175                 case 'f':
1176                         *(t++) = '\f';
1177                         break;
1178                 case 'n':
1179                         *(t++) = '\n';
1180                         break;
1181                 case 'r':
1182                         *(t++) = '\r';
1183                         break;
1184                 case 't':
1185                         *(t++) = '\t';
1186                         break;
1187                 case 'v':
1188                         *(t++) = '\v';
1189                         break;
1190                 case '\\':
1191                         *(t++) = '\\';
1192                         break;
1193                 case '"':
1194                         *(t++) = '"';
1195                         break;
1196                 case '\'':
1197                         *(t++) = '\'';
1198                         break;
1199
1200                 case 's':
1201                         /* This is an extension of the XDG syntax files */
1202                         *(t++) = ' ';
1203                         break;
1204
1205                 case 'x': {
1206                         /* hexadecimal encoding */
1207                         int a, b;
1208
1209                         if ((a = unhexchar(f[1])) < 0 ||
1210                             (b = unhexchar(f[2])) < 0) {
1211                                 /* Invalid escape code, let's take it literal then */
1212                                 *(t++) = '\\';
1213                                 *(t++) = 'x';
1214                         } else {
1215                                 *(t++) = (char) ((a << 4) | b);
1216                                 f += 2;
1217                         }
1218
1219                         break;
1220                 }
1221
1222                 case '0':
1223                 case '1':
1224                 case '2':
1225                 case '3':
1226                 case '4':
1227                 case '5':
1228                 case '6':
1229                 case '7': {
1230                         /* octal encoding */
1231                         int a, b, c;
1232
1233                         if ((a = unoctchar(f[0])) < 0 ||
1234                             (b = unoctchar(f[1])) < 0 ||
1235                             (c = unoctchar(f[2])) < 0) {
1236                                 /* Invalid escape code, let's take it literal then */
1237                                 *(t++) = '\\';
1238                                 *(t++) = f[0];
1239                         } else {
1240                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1241                                 f += 2;
1242                         }
1243
1244                         break;
1245                 }
1246
1247                 case 0:
1248                         /* premature end of string.*/
1249                         *(t++) = '\\';
1250                         goto finish;
1251
1252                 default:
1253                         /* Invalid escape code, let's take it literal then */
1254                         *(t++) = '\\';
1255                         *(t++) = *f;
1256                         break;
1257                 }
1258         }
1259
1260 finish:
1261         *t = 0;
1262         return r;
1263 }
1264
1265 char *cunescape(const char *s) {
1266         return cunescape_length(s, strlen(s));
1267 }
1268
1269 char *xescape(const char *s, const char *bad) {
1270         char *r, *t;
1271         const char *f;
1272
1273         /* Escapes all chars in bad, in addition to \ and all special
1274          * chars, in \xFF style escaping. May be reversed with
1275          * cunescape. */
1276
1277         if (!(r = new(char, strlen(s)*4+1)))
1278                 return NULL;
1279
1280         for (f = s, t = r; *f; f++) {
1281
1282                 if ((*f < ' ') || (*f >= 127) ||
1283                     (*f == '\\') || strchr(bad, *f)) {
1284                         *(t++) = '\\';
1285                         *(t++) = 'x';
1286                         *(t++) = hexchar(*f >> 4);
1287                         *(t++) = hexchar(*f);
1288                 } else
1289                         *(t++) = *f;
1290         }
1291
1292         *t = 0;
1293
1294         return r;
1295 }
1296
1297 char *bus_path_escape(const char *s) {
1298         char *r, *t;
1299         const char *f;
1300
1301         assert(s);
1302
1303         /* Escapes all chars that D-Bus' object path cannot deal
1304          * with. Can be reverse with bus_path_unescape() */
1305
1306         if (!(r = new(char, strlen(s)*3+1)))
1307                 return NULL;
1308
1309         for (f = s, t = r; *f; f++) {
1310
1311                 if (!(*f >= 'A' && *f <= 'Z') &&
1312                     !(*f >= 'a' && *f <= 'z') &&
1313                     !(*f >= '0' && *f <= '9')) {
1314                         *(t++) = '_';
1315                         *(t++) = hexchar(*f >> 4);
1316                         *(t++) = hexchar(*f);
1317                 } else
1318                         *(t++) = *f;
1319         }
1320
1321         *t = 0;
1322
1323         return r;
1324 }
1325
1326 char *bus_path_unescape(const char *f) {
1327         char *r, *t;
1328
1329         assert(f);
1330
1331         if (!(r = strdup(f)))
1332                 return NULL;
1333
1334         for (t = r; *f; f++) {
1335
1336                 if (*f == '_') {
1337                         int a, b;
1338
1339                         if ((a = unhexchar(f[1])) < 0 ||
1340                             (b = unhexchar(f[2])) < 0) {
1341                                 /* Invalid escape code, let's take it literal then */
1342                                 *(t++) = '_';
1343                         } else {
1344                                 *(t++) = (char) ((a << 4) | b);
1345                                 f += 2;
1346                         }
1347                 } else
1348                         *(t++) = *f;
1349         }
1350
1351         *t = 0;
1352
1353         return r;
1354 }
1355
1356 char *path_kill_slashes(char *path) {
1357         char *f, *t;
1358         bool slash = false;
1359
1360         /* Removes redundant inner and trailing slashes. Modifies the
1361          * passed string in-place.
1362          *
1363          * ///foo///bar/ becomes /foo/bar
1364          */
1365
1366         for (f = path, t = path; *f; f++) {
1367
1368                 if (*f == '/') {
1369                         slash = true;
1370                         continue;
1371                 }
1372
1373                 if (slash) {
1374                         slash = false;
1375                         *(t++) = '/';
1376                 }
1377
1378                 *(t++) = *f;
1379         }
1380
1381         /* Special rule, if we are talking of the root directory, a
1382         trailing slash is good */
1383
1384         if (t == path && slash)
1385                 *(t++) = '/';
1386
1387         *t = 0;
1388         return path;
1389 }
1390
1391 bool path_startswith(const char *path, const char *prefix) {
1392         assert(path);
1393         assert(prefix);
1394
1395         if ((path[0] == '/') != (prefix[0] == '/'))
1396                 return false;
1397
1398         for (;;) {
1399                 size_t a, b;
1400
1401                 path += strspn(path, "/");
1402                 prefix += strspn(prefix, "/");
1403
1404                 if (*prefix == 0)
1405                         return true;
1406
1407                 if (*path == 0)
1408                         return false;
1409
1410                 a = strcspn(path, "/");
1411                 b = strcspn(prefix, "/");
1412
1413                 if (a != b)
1414                         return false;
1415
1416                 if (memcmp(path, prefix, a) != 0)
1417                         return false;
1418
1419                 path += a;
1420                 prefix += b;
1421         }
1422 }
1423
1424 bool path_equal(const char *a, const char *b) {
1425         assert(a);
1426         assert(b);
1427
1428         if ((a[0] == '/') != (b[0] == '/'))
1429                 return false;
1430
1431         for (;;) {
1432                 size_t j, k;
1433
1434                 a += strspn(a, "/");
1435                 b += strspn(b, "/");
1436
1437                 if (*a == 0 && *b == 0)
1438                         return true;
1439
1440                 if (*a == 0 || *b == 0)
1441                         return false;
1442
1443                 j = strcspn(a, "/");
1444                 k = strcspn(b, "/");
1445
1446                 if (j != k)
1447                         return false;
1448
1449                 if (memcmp(a, b, j) != 0)
1450                         return false;
1451
1452                 a += j;
1453                 b += k;
1454         }
1455 }
1456
1457 char *ascii_strlower(char *t) {
1458         char *p;
1459
1460         assert(t);
1461
1462         for (p = t; *p; p++)
1463                 if (*p >= 'A' && *p <= 'Z')
1464                         *p = *p - 'A' + 'a';
1465
1466         return t;
1467 }
1468
1469 bool ignore_file(const char *filename) {
1470         assert(filename);
1471
1472         return
1473                 filename[0] == '.' ||
1474                 streq(filename, "lost+found") ||
1475                 endswith(filename, "~") ||
1476                 endswith(filename, ".rpmnew") ||
1477                 endswith(filename, ".rpmsave") ||
1478                 endswith(filename, ".rpmorig") ||
1479                 endswith(filename, ".dpkg-old") ||
1480                 endswith(filename, ".dpkg-new") ||
1481                 endswith(filename, ".swp");
1482 }
1483
1484 int fd_nonblock(int fd, bool nonblock) {
1485         int flags;
1486
1487         assert(fd >= 0);
1488
1489         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1490                 return -errno;
1491
1492         if (nonblock)
1493                 flags |= O_NONBLOCK;
1494         else
1495                 flags &= ~O_NONBLOCK;
1496
1497         if (fcntl(fd, F_SETFL, flags) < 0)
1498                 return -errno;
1499
1500         return 0;
1501 }
1502
1503 int fd_cloexec(int fd, bool cloexec) {
1504         int flags;
1505
1506         assert(fd >= 0);
1507
1508         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1509                 return -errno;
1510
1511         if (cloexec)
1512                 flags |= FD_CLOEXEC;
1513         else
1514                 flags &= ~FD_CLOEXEC;
1515
1516         if (fcntl(fd, F_SETFD, flags) < 0)
1517                 return -errno;
1518
1519         return 0;
1520 }
1521
1522 int close_all_fds(const int except[], unsigned n_except) {
1523         DIR *d;
1524         struct dirent *de;
1525         int r = 0;
1526
1527         if (!(d = opendir("/proc/self/fd")))
1528                 return -errno;
1529
1530         while ((de = readdir(d))) {
1531                 int fd = -1;
1532
1533                 if (ignore_file(de->d_name))
1534                         continue;
1535
1536                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1537                         goto finish;
1538
1539                 if (fd < 3)
1540                         continue;
1541
1542                 if (fd == dirfd(d))
1543                         continue;
1544
1545                 if (except) {
1546                         bool found;
1547                         unsigned i;
1548
1549                         found = false;
1550                         for (i = 0; i < n_except; i++)
1551                                 if (except[i] == fd) {
1552                                         found = true;
1553                                         break;
1554                                 }
1555
1556                         if (found)
1557                                 continue;
1558                 }
1559
1560                 if ((r = close_nointr(fd)) < 0) {
1561                         /* Valgrind has its own FD and doesn't want to have it closed */
1562                         if (errno != EBADF)
1563                                 goto finish;
1564                 }
1565         }
1566
1567         r = 0;
1568
1569 finish:
1570         closedir(d);
1571         return r;
1572 }
1573
1574 bool chars_intersect(const char *a, const char *b) {
1575         const char *p;
1576
1577         /* Returns true if any of the chars in a are in b. */
1578         for (p = a; *p; p++)
1579                 if (strchr(b, *p))
1580                         return true;
1581
1582         return false;
1583 }
1584
1585 char *format_timestamp(char *buf, size_t l, usec_t t) {
1586         struct tm tm;
1587         time_t sec;
1588
1589         assert(buf);
1590         assert(l > 0);
1591
1592         if (t <= 0)
1593                 return NULL;
1594
1595         sec = (time_t) (t / USEC_PER_SEC);
1596
1597         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1598                 return NULL;
1599
1600         return buf;
1601 }
1602
1603 char *format_timespan(char *buf, size_t l, usec_t t) {
1604         static const struct {
1605                 const char *suffix;
1606                 usec_t usec;
1607         } table[] = {
1608                 { "w", USEC_PER_WEEK },
1609                 { "d", USEC_PER_DAY },
1610                 { "h", USEC_PER_HOUR },
1611                 { "min", USEC_PER_MINUTE },
1612                 { "s", USEC_PER_SEC },
1613                 { "ms", USEC_PER_MSEC },
1614                 { "us", 1 },
1615         };
1616
1617         unsigned i;
1618         char *p = buf;
1619
1620         assert(buf);
1621         assert(l > 0);
1622
1623         if (t == (usec_t) -1)
1624                 return NULL;
1625
1626         /* The result of this function can be parsed with parse_usec */
1627
1628         for (i = 0; i < ELEMENTSOF(table); i++) {
1629                 int k;
1630                 size_t n;
1631
1632                 if (t < table[i].usec)
1633                         continue;
1634
1635                 if (l <= 1)
1636                         break;
1637
1638                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1639                 n = MIN((size_t) k, l);
1640
1641                 l -= n;
1642                 p += n;
1643
1644                 t %= table[i].usec;
1645         }
1646
1647         *p = 0;
1648
1649         return buf;
1650 }
1651
1652 bool fstype_is_network(const char *fstype) {
1653         static const char * const table[] = {
1654                 "cifs",
1655                 "smbfs",
1656                 "ncpfs",
1657                 "nfs",
1658                 "nfs4",
1659                 "gfs",
1660                 "gfs2"
1661         };
1662
1663         unsigned i;
1664
1665         for (i = 0; i < ELEMENTSOF(table); i++)
1666                 if (streq(table[i], fstype))
1667                         return true;
1668
1669         return false;
1670 }
1671
1672 int chvt(int vt) {
1673         int fd, r = 0;
1674
1675         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1676                 return -errno;
1677
1678         if (vt < 0) {
1679                 int tiocl[2] = {
1680                         TIOCL_GETKMSGREDIRECT,
1681                         0
1682                 };
1683
1684                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1685                         return -errno;
1686
1687                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1688         }
1689
1690         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1691                 r = -errno;
1692
1693         close_nointr_nofail(r);
1694         return r;
1695 }
1696
1697 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1698         struct termios old_termios, new_termios;
1699         char c;
1700         char line[1024];
1701
1702         assert(f);
1703         assert(ret);
1704
1705         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1706                 new_termios = old_termios;
1707
1708                 new_termios.c_lflag &= ~ICANON;
1709                 new_termios.c_cc[VMIN] = 1;
1710                 new_termios.c_cc[VTIME] = 0;
1711
1712                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1713                         size_t k;
1714
1715                         k = fread(&c, 1, 1, f);
1716
1717                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1718
1719                         if (k <= 0)
1720                                 return -EIO;
1721
1722                         if (need_nl)
1723                                 *need_nl = c != '\n';
1724
1725                         *ret = c;
1726                         return 0;
1727                 }
1728         }
1729
1730         if (!(fgets(line, sizeof(line), f)))
1731                 return -EIO;
1732
1733         truncate_nl(line);
1734
1735         if (strlen(line) != 1)
1736                 return -EBADMSG;
1737
1738         if (need_nl)
1739                 *need_nl = false;
1740
1741         *ret = line[0];
1742         return 0;
1743 }
1744
1745 int ask(char *ret, const char *replies, const char *text, ...) {
1746         assert(ret);
1747         assert(replies);
1748         assert(text);
1749
1750         for (;;) {
1751                 va_list ap;
1752                 char c;
1753                 int r;
1754                 bool need_nl = true;
1755
1756                 fputs("\x1B[1m", stdout);
1757
1758                 va_start(ap, text);
1759                 vprintf(text, ap);
1760                 va_end(ap);
1761
1762                 fputs("\x1B[0m", stdout);
1763
1764                 fflush(stdout);
1765
1766                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1767
1768                         if (r == -EBADMSG) {
1769                                 puts("Bad input, please try again.");
1770                                 continue;
1771                         }
1772
1773                         putchar('\n');
1774                         return r;
1775                 }
1776
1777                 if (need_nl)
1778                         putchar('\n');
1779
1780                 if (strchr(replies, c)) {
1781                         *ret = c;
1782                         return 0;
1783                 }
1784
1785                 puts("Read unexpected character, please try again.");
1786         }
1787 }
1788
1789 int reset_terminal(int fd) {
1790         struct termios termios;
1791         int r = 0;
1792
1793         assert(fd >= 0);
1794
1795         /* Set terminal to some sane defaults */
1796
1797         if (tcgetattr(fd, &termios) < 0) {
1798                 r = -errno;
1799                 goto finish;
1800         }
1801
1802         /* We only reset the stuff that matters to the software. How
1803          * hardware is set up we don't touch assuming that somebody
1804          * else will do that for us */
1805
1806         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1807         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1808         termios.c_oflag |= ONLCR;
1809         termios.c_cflag |= CREAD;
1810         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1811
1812         termios.c_cc[VINTR]    =   03;  /* ^C */
1813         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1814         termios.c_cc[VERASE]   = 0177;
1815         termios.c_cc[VKILL]    =  025;  /* ^X */
1816         termios.c_cc[VEOF]     =   04;  /* ^D */
1817         termios.c_cc[VSTART]   =  021;  /* ^Q */
1818         termios.c_cc[VSTOP]    =  023;  /* ^S */
1819         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1820         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1821         termios.c_cc[VWERASE]  =  027;  /* ^W */
1822         termios.c_cc[VREPRINT] =  022;  /* ^R */
1823         termios.c_cc[VEOL]     =    0;
1824         termios.c_cc[VEOL2]    =    0;
1825
1826         termios.c_cc[VTIME]  = 0;
1827         termios.c_cc[VMIN]   = 1;
1828
1829         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1830                 r = -errno;
1831
1832 finish:
1833         /* Just in case, flush all crap out */
1834         tcflush(fd, TCIOFLUSH);
1835
1836         return r;
1837 }
1838
1839 int open_terminal(const char *name, int mode) {
1840         int fd, r;
1841
1842         if ((fd = open(name, mode)) < 0)
1843                 return -errno;
1844
1845         if ((r = isatty(fd)) < 0) {
1846                 close_nointr_nofail(fd);
1847                 return -errno;
1848         }
1849
1850         if (!r) {
1851                 close_nointr_nofail(fd);
1852                 return -ENOTTY;
1853         }
1854
1855         return fd;
1856 }
1857
1858 int flush_fd(int fd) {
1859         struct pollfd pollfd;
1860
1861         zero(pollfd);
1862         pollfd.fd = fd;
1863         pollfd.events = POLLIN;
1864
1865         for (;;) {
1866                 char buf[1024];
1867                 ssize_t l;
1868                 int r;
1869
1870                 if ((r = poll(&pollfd, 1, 0)) < 0) {
1871
1872                         if (errno == EINTR)
1873                                 continue;
1874
1875                         return -errno;
1876                 }
1877
1878                 if (r == 0)
1879                         return 0;
1880
1881                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1882
1883                         if (errno == EINTR)
1884                                 continue;
1885
1886                         if (errno == EAGAIN)
1887                                 return 0;
1888
1889                         return -errno;
1890                 }
1891
1892                 if (l <= 0)
1893                         return 0;
1894         }
1895 }
1896
1897 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1898         int fd = -1, notify = -1, r, wd = -1;
1899
1900         assert(name);
1901
1902         /* We use inotify to be notified when the tty is closed. We
1903          * create the watch before checking if we can actually acquire
1904          * it, so that we don't lose any event.
1905          *
1906          * Note: strictly speaking this actually watches for the
1907          * device being closed, it does *not* really watch whether a
1908          * tty loses its controlling process. However, unless some
1909          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1910          * its tty otherwise this will not become a problem. As long
1911          * as the administrator makes sure not configure any service
1912          * on the same tty as an untrusted user this should not be a
1913          * problem. (Which he probably should not do anyway.) */
1914
1915         if (!fail && !force) {
1916                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1917                         r = -errno;
1918                         goto fail;
1919                 }
1920
1921                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1922                         r = -errno;
1923                         goto fail;
1924                 }
1925         }
1926
1927         for (;;) {
1928                 if (notify >= 0)
1929                         if ((r = flush_fd(notify)) < 0)
1930                                 goto fail;
1931
1932                 /* We pass here O_NOCTTY only so that we can check the return
1933                  * value TIOCSCTTY and have a reliable way to figure out if we
1934                  * successfully became the controlling process of the tty */
1935                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1936                         return -errno;
1937
1938                 /* First, try to get the tty */
1939                 r = ioctl(fd, TIOCSCTTY, force);
1940
1941                 /* Sometimes it makes sense to ignore TIOCSCTTY
1942                  * returning EPERM, i.e. when very likely we already
1943                  * are have this controlling terminal. */
1944                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1945                         r = 0;
1946
1947                 if (r < 0 && (force || fail || errno != EPERM)) {
1948                         r = -errno;
1949                         goto fail;
1950                 }
1951
1952                 if (r >= 0)
1953                         break;
1954
1955                 assert(!fail);
1956                 assert(!force);
1957                 assert(notify >= 0);
1958
1959                 for (;;) {
1960                         struct inotify_event e;
1961                         ssize_t l;
1962
1963                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1964
1965                                 if (l < 0) {
1966
1967                                         if (errno == EINTR)
1968                                                 continue;
1969
1970                                         r = -errno;
1971                                 } else
1972                                         r = -EIO;
1973
1974                                 goto fail;
1975                         }
1976
1977                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1978                                 r = -errno;
1979                                 goto fail;
1980                         }
1981
1982                         break;
1983                 }
1984
1985                 /* We close the tty fd here since if the old session
1986                  * ended our handle will be dead. It's important that
1987                  * we do this after sleeping, so that we don't enter
1988                  * an endless loop. */
1989                 close_nointr_nofail(fd);
1990         }
1991
1992         if (notify >= 0)
1993                 close_nointr_nofail(notify);
1994
1995         if ((r = reset_terminal(fd)) < 0)
1996                 log_warning("Failed to reset terminal: %s", strerror(-r));
1997
1998         return fd;
1999
2000 fail:
2001         if (fd >= 0)
2002                 close_nointr_nofail(fd);
2003
2004         if (notify >= 0)
2005                 close_nointr_nofail(notify);
2006
2007         return r;
2008 }
2009
2010 int release_terminal(void) {
2011         int r = 0, fd;
2012         struct sigaction sa_old, sa_new;
2013
2014         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2015                 return -errno;
2016
2017         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2018          * by our own TIOCNOTTY */
2019
2020         zero(sa_new);
2021         sa_new.sa_handler = SIG_IGN;
2022         sa_new.sa_flags = SA_RESTART;
2023         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2024
2025         if (ioctl(fd, TIOCNOTTY) < 0)
2026                 r = -errno;
2027
2028         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2029
2030         close_nointr_nofail(fd);
2031         return r;
2032 }
2033
2034 int sigaction_many(const struct sigaction *sa, ...) {
2035         va_list ap;
2036         int r = 0, sig;
2037
2038         va_start(ap, sa);
2039         while ((sig = va_arg(ap, int)) > 0)
2040                 if (sigaction(sig, sa, NULL) < 0)
2041                         r = -errno;
2042         va_end(ap);
2043
2044         return r;
2045 }
2046
2047 int ignore_signals(int sig, ...) {
2048         struct sigaction sa;
2049         va_list ap;
2050         int r = 0;
2051
2052         zero(sa);
2053         sa.sa_handler = SIG_IGN;
2054         sa.sa_flags = SA_RESTART;
2055
2056         if (sigaction(sig, &sa, NULL) < 0)
2057                 r = -errno;
2058
2059         va_start(ap, sig);
2060         while ((sig = va_arg(ap, int)) > 0)
2061                 if (sigaction(sig, &sa, NULL) < 0)
2062                         r = -errno;
2063         va_end(ap);
2064
2065         return r;
2066 }
2067
2068 int default_signals(int sig, ...) {
2069         struct sigaction sa;
2070         va_list ap;
2071         int r = 0;
2072
2073         zero(sa);
2074         sa.sa_handler = SIG_DFL;
2075         sa.sa_flags = SA_RESTART;
2076
2077         if (sigaction(sig, &sa, NULL) < 0)
2078                 r = -errno;
2079
2080         va_start(ap, sig);
2081         while ((sig = va_arg(ap, int)) > 0)
2082                 if (sigaction(sig, &sa, NULL) < 0)
2083                         r = -errno;
2084         va_end(ap);
2085
2086         return r;
2087 }
2088
2089 int close_pipe(int p[]) {
2090         int a = 0, b = 0;
2091
2092         assert(p);
2093
2094         if (p[0] >= 0) {
2095                 a = close_nointr(p[0]);
2096                 p[0] = -1;
2097         }
2098
2099         if (p[1] >= 0) {
2100                 b = close_nointr(p[1]);
2101                 p[1] = -1;
2102         }
2103
2104         return a < 0 ? a : b;
2105 }
2106
2107 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2108         uint8_t *p;
2109         ssize_t n = 0;
2110
2111         assert(fd >= 0);
2112         assert(buf);
2113
2114         p = buf;
2115
2116         while (nbytes > 0) {
2117                 ssize_t k;
2118
2119                 if ((k = read(fd, p, nbytes)) <= 0) {
2120
2121                         if (k < 0 && errno == EINTR)
2122                                 continue;
2123
2124                         if (k < 0 && errno == EAGAIN && do_poll) {
2125                                 struct pollfd pollfd;
2126
2127                                 zero(pollfd);
2128                                 pollfd.fd = fd;
2129                                 pollfd.events = POLLIN;
2130
2131                                 if (poll(&pollfd, 1, -1) < 0) {
2132                                         if (errno == EINTR)
2133                                                 continue;
2134
2135                                         return n > 0 ? n : -errno;
2136                                 }
2137
2138                                 if (pollfd.revents != POLLIN)
2139                                         return n > 0 ? n : -EIO;
2140
2141                                 continue;
2142                         }
2143
2144                         return n > 0 ? n : (k < 0 ? -errno : 0);
2145                 }
2146
2147                 p += k;
2148                 nbytes -= k;
2149                 n += k;
2150         }
2151
2152         return n;
2153 }
2154
2155 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2156         const uint8_t *p;
2157         ssize_t n = 0;
2158
2159         assert(fd >= 0);
2160         assert(buf);
2161
2162         p = buf;
2163
2164         while (nbytes > 0) {
2165                 ssize_t k;
2166
2167                 if ((k = write(fd, p, nbytes)) <= 0) {
2168
2169                         if (k < 0 && errno == EINTR)
2170                                 continue;
2171
2172                         if (k < 0 && errno == EAGAIN && do_poll) {
2173                                 struct pollfd pollfd;
2174
2175                                 zero(pollfd);
2176                                 pollfd.fd = fd;
2177                                 pollfd.events = POLLOUT;
2178
2179                                 if (poll(&pollfd, 1, -1) < 0) {
2180                                         if (errno == EINTR)
2181                                                 continue;
2182
2183                                         return n > 0 ? n : -errno;
2184                                 }
2185
2186                                 if (pollfd.revents != POLLOUT)
2187                                         return n > 0 ? n : -EIO;
2188
2189                                 continue;
2190                         }
2191
2192                         return n > 0 ? n : (k < 0 ? -errno : 0);
2193                 }
2194
2195                 p += k;
2196                 nbytes -= k;
2197                 n += k;
2198         }
2199
2200         return n;
2201 }
2202
2203 int path_is_mount_point(const char *t) {
2204         struct stat a, b;
2205         char *copy;
2206
2207         if (lstat(t, &a) < 0) {
2208
2209                 if (errno == ENOENT)
2210                         return 0;
2211
2212                 return -errno;
2213         }
2214
2215         if (!(copy = strdup(t)))
2216                 return -ENOMEM;
2217
2218         if (lstat(dirname(copy), &b) < 0) {
2219                 free(copy);
2220                 return -errno;
2221         }
2222
2223         free(copy);
2224
2225         return a.st_dev != b.st_dev;
2226 }
2227
2228 int parse_usec(const char *t, usec_t *usec) {
2229         static const struct {
2230                 const char *suffix;
2231                 usec_t usec;
2232         } table[] = {
2233                 { "sec", USEC_PER_SEC },
2234                 { "s", USEC_PER_SEC },
2235                 { "min", USEC_PER_MINUTE },
2236                 { "hr", USEC_PER_HOUR },
2237                 { "h", USEC_PER_HOUR },
2238                 { "d", USEC_PER_DAY },
2239                 { "w", USEC_PER_WEEK },
2240                 { "msec", USEC_PER_MSEC },
2241                 { "ms", USEC_PER_MSEC },
2242                 { "m", USEC_PER_MINUTE },
2243                 { "usec", 1ULL },
2244                 { "us", 1ULL },
2245                 { "", USEC_PER_SEC },
2246         };
2247
2248         const char *p;
2249         usec_t r = 0;
2250
2251         assert(t);
2252         assert(usec);
2253
2254         p = t;
2255         do {
2256                 long long l;
2257                 char *e;
2258                 unsigned i;
2259
2260                 errno = 0;
2261                 l = strtoll(p, &e, 10);
2262
2263                 if (errno != 0)
2264                         return -errno;
2265
2266                 if (l < 0)
2267                         return -ERANGE;
2268
2269                 if (e == p)
2270                         return -EINVAL;
2271
2272                 e += strspn(e, WHITESPACE);
2273
2274                 for (i = 0; i < ELEMENTSOF(table); i++)
2275                         if (startswith(e, table[i].suffix)) {
2276                                 r += (usec_t) l * table[i].usec;
2277                                 p = e + strlen(table[i].suffix);
2278                                 break;
2279                         }
2280
2281                 if (i >= ELEMENTSOF(table))
2282                         return -EINVAL;
2283
2284         } while (*p != 0);
2285
2286         *usec = r;
2287
2288         return 0;
2289 }
2290
2291 int make_stdio(int fd) {
2292         int r, s, t;
2293
2294         assert(fd >= 0);
2295
2296         r = dup2(fd, STDIN_FILENO);
2297         s = dup2(fd, STDOUT_FILENO);
2298         t = dup2(fd, STDERR_FILENO);
2299
2300         if (fd >= 3)
2301                 close_nointr_nofail(fd);
2302
2303         if (r < 0 || s < 0 || t < 0)
2304                 return -errno;
2305
2306         return 0;
2307 }
2308
2309 bool is_clean_exit(int code, int status) {
2310
2311         if (code == CLD_EXITED)
2312                 return status == 0;
2313
2314         /* If a daemon does not implement handlers for some of the
2315          * signals that's not considered an unclean shutdown */
2316         if (code == CLD_KILLED)
2317                 return
2318                         status == SIGHUP ||
2319                         status == SIGINT ||
2320                         status == SIGTERM ||
2321                         status == SIGPIPE;
2322
2323         return false;
2324 }
2325
2326 bool is_device_path(const char *path) {
2327
2328         /* Returns true on paths that refer to a device, either in
2329          * sysfs or in /dev */
2330
2331         return
2332                 path_startswith(path, "/dev/") ||
2333                 path_startswith(path, "/sys/");
2334 }
2335
2336 int dir_is_empty(const char *path) {
2337         DIR *d;
2338         int r;
2339         struct dirent buf, *de;
2340
2341         if (!(d = opendir(path)))
2342                 return -errno;
2343
2344         for (;;) {
2345                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2346                         r = -r;
2347                         break;
2348                 }
2349
2350                 if (!de) {
2351                         r = 1;
2352                         break;
2353                 }
2354
2355                 if (!ignore_file(de->d_name)) {
2356                         r = 0;
2357                         break;
2358                 }
2359         }
2360
2361         closedir(d);
2362         return r;
2363 }
2364
2365 unsigned long long random_ull(void) {
2366         int fd;
2367         uint64_t ull;
2368         ssize_t r;
2369
2370         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2371                 goto fallback;
2372
2373         r = loop_read(fd, &ull, sizeof(ull), true);
2374         close_nointr_nofail(fd);
2375
2376         if (r != sizeof(ull))
2377                 goto fallback;
2378
2379         return ull;
2380
2381 fallback:
2382         return random() * RAND_MAX + random();
2383 }
2384
2385 void rename_process(const char name[8]) {
2386         assert(name);
2387
2388         prctl(PR_SET_NAME, name);
2389
2390         /* This is a like a poor man's setproctitle(). The string
2391          * passed should fit in 7 chars (i.e. the length of
2392          * "systemd") */
2393
2394         if (program_invocation_name)
2395                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2396 }
2397
2398 void sigset_add_many(sigset_t *ss, ...) {
2399         va_list ap;
2400         int sig;
2401
2402         assert(ss);
2403
2404         va_start(ap, ss);
2405         while ((sig = va_arg(ap, int)) > 0)
2406                 assert_se(sigaddset(ss, sig) == 0);
2407         va_end(ap);
2408 }
2409
2410 char* gethostname_malloc(void) {
2411         struct utsname u;
2412
2413         assert_se(uname(&u) >= 0);
2414
2415         if (u.nodename[0])
2416                 return strdup(u.nodename);
2417
2418         return strdup(u.sysname);
2419 }
2420
2421 int getmachineid_malloc(char **b) {
2422         int r;
2423
2424         assert(b);
2425
2426         if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2427                 return r;
2428
2429         strstrip(*b);
2430         return 0;
2431 }
2432
2433 char* getlogname_malloc(void) {
2434         uid_t uid;
2435         long bufsize;
2436         char *buf, *name;
2437         struct passwd pwbuf, *pw = NULL;
2438         struct stat st;
2439
2440         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2441                 uid = st.st_uid;
2442         else
2443                 uid = getuid();
2444
2445         /* Shortcut things to avoid NSS lookups */
2446         if (uid == 0)
2447                 return strdup("root");
2448
2449         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2450                 bufsize = 4096;
2451
2452         if (!(buf = malloc(bufsize)))
2453                 return NULL;
2454
2455         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2456                 name = strdup(pw->pw_name);
2457                 free(buf);
2458                 return name;
2459         }
2460
2461         free(buf);
2462
2463         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2464                 return NULL;
2465
2466         return name;
2467 }
2468
2469 int getttyname_malloc(char **r) {
2470         char path[PATH_MAX], *p, *c;
2471
2472         assert(r);
2473
2474         if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2475                 return -errno;
2476
2477         char_array_0(path);
2478
2479         p = path;
2480         if (startswith(path, "/dev/"))
2481                 p += 5;
2482
2483         if (!(c = strdup(p)))
2484                 return -ENOMEM;
2485
2486         *r = c;
2487         return 0;
2488 }
2489
2490 static int rm_rf_children(int fd, bool only_dirs) {
2491         DIR *d;
2492         int ret = 0;
2493
2494         assert(fd >= 0);
2495
2496         /* This returns the first error we run into, but nevertheless
2497          * tries to go on */
2498
2499         if (!(d = fdopendir(fd))) {
2500                 close_nointr_nofail(fd);
2501                 return -errno;
2502         }
2503
2504         for (;;) {
2505                 struct dirent buf, *de;
2506                 bool is_dir;
2507                 int r;
2508
2509                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2510                         if (ret == 0)
2511                                 ret = -r;
2512                         break;
2513                 }
2514
2515                 if (!de)
2516                         break;
2517
2518                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2519                         continue;
2520
2521                 if (de->d_type == DT_UNKNOWN) {
2522                         struct stat st;
2523
2524                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2525                                 if (ret == 0)
2526                                         ret = -errno;
2527                                 continue;
2528                         }
2529
2530                         is_dir = S_ISDIR(st.st_mode);
2531                 } else
2532                         is_dir = de->d_type == DT_DIR;
2533
2534                 if (is_dir) {
2535                         int subdir_fd;
2536
2537                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2538                                 if (ret == 0)
2539                                         ret = -errno;
2540                                 continue;
2541                         }
2542
2543                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2544                                 if (ret == 0)
2545                                         ret = r;
2546                         }
2547
2548                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2549                                 if (ret == 0)
2550                                         ret = -errno;
2551                         }
2552                 } else  if (!only_dirs) {
2553
2554                         if (unlinkat(fd, de->d_name, 0) < 0) {
2555                                 if (ret == 0)
2556                                         ret = -errno;
2557                         }
2558                 }
2559         }
2560
2561         closedir(d);
2562
2563         return ret;
2564 }
2565
2566 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2567         int fd;
2568         int r;
2569
2570         assert(path);
2571
2572         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2573
2574                 if (errno != ENOTDIR)
2575                         return -errno;
2576
2577                 if (delete_root && !only_dirs)
2578                         if (unlink(path) < 0)
2579                                 return -errno;
2580
2581                 return 0;
2582         }
2583
2584         r = rm_rf_children(fd, only_dirs);
2585
2586         if (delete_root)
2587                 if (rmdir(path) < 0) {
2588                         if (r == 0)
2589                                 r = -errno;
2590                 }
2591
2592         return r;
2593 }
2594
2595 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2596         assert(path);
2597
2598         /* Under the assumption that we are running privileged we
2599          * first change the access mode and only then hand out
2600          * ownership to avoid a window where access is too open. */
2601
2602         if (chmod(path, mode) < 0)
2603                 return -errno;
2604
2605         if (chown(path, uid, gid) < 0)
2606                 return -errno;
2607
2608         return 0;
2609 }
2610
2611 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2612         cpu_set_t *r;
2613         unsigned n = 1024;
2614
2615         /* Allocates the cpuset in the right size */
2616
2617         for (;;) {
2618                 if (!(r = CPU_ALLOC(n)))
2619                         return NULL;
2620
2621                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2622                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2623
2624                         if (ncpus)
2625                                 *ncpus = n;
2626
2627                         return r;
2628                 }
2629
2630                 CPU_FREE(r);
2631
2632                 if (errno != EINVAL)
2633                         return NULL;
2634
2635                 n *= 2;
2636         }
2637 }
2638
2639 void status_vprintf(const char *format, va_list ap) {
2640         char *s = NULL;
2641         int fd = -1;
2642
2643         assert(format);
2644
2645         /* This independent of logging, as status messages are
2646          * optional and go exclusively to the console. */
2647
2648         if (vasprintf(&s, format, ap) < 0)
2649                 goto finish;
2650
2651         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2652                 goto finish;
2653
2654         write(fd, s, strlen(s));
2655
2656 finish:
2657         free(s);
2658
2659         if (fd >= 0)
2660                 close_nointr_nofail(fd);
2661 }
2662
2663 void status_printf(const char *format, ...) {
2664         va_list ap;
2665
2666         assert(format);
2667
2668         va_start(ap, format);
2669         status_vprintf(format, ap);
2670         va_end(ap);
2671 }
2672
2673 void status_welcome(void) {
2674
2675 #if defined(TARGET_FEDORA)
2676         char *r;
2677
2678         if (read_one_line_file("/etc/system-release", &r) < 0)
2679                 return;
2680
2681         truncate_nl(r);
2682
2683         /* This tries to mimic the color magic the old Red Hat sysinit
2684          * script did. */
2685
2686         if (startswith(r, "Red Hat"))
2687                 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2688         else if (startswith(r, "Fedora"))
2689                 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2690         else
2691                 status_printf("Welcome to %s!\n", r);
2692
2693         free(r);
2694
2695 #elif defined(TARGET_SUSE)
2696         char *r;
2697
2698         if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2699                 return;
2700
2701         truncate_nl(r);
2702
2703         status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2704         free(r);
2705 #else
2706 #warning "You probably should add a welcome text logic here."
2707 #endif
2708 }
2709
2710 char *replace_env(const char *format, char **env) {
2711         enum {
2712                 WORD,
2713                 DOLLAR,
2714                 VARIABLE
2715         } state = WORD;
2716
2717         const char *e, *word = format;
2718         char *r = NULL, *k;
2719
2720         assert(format);
2721
2722         for (e = format; *e; e ++) {
2723
2724                 switch (state) {
2725
2726                 case WORD:
2727                         if (*e == '$')
2728                                 state = DOLLAR;
2729                         break;
2730
2731                 case DOLLAR:
2732                         if (*e == '(') {
2733                                 if (!(k = strnappend(r, word, e-word-1)))
2734                                         goto fail;
2735
2736                                 free(r);
2737                                 r = k;
2738
2739                                 word = e-1;
2740                                 state = VARIABLE;
2741
2742                         } else if (*e == '$') {
2743                                 if (!(k = strnappend(r, word, e-word)))
2744                                         goto fail;
2745
2746                                 free(r);
2747                                 r = k;
2748
2749                                 word = e+1;
2750                                 state = WORD;
2751                         } else
2752                                 state = WORD;
2753                         break;
2754
2755                 case VARIABLE:
2756                         if (*e == ')') {
2757                                 char *t;
2758
2759                                 if ((t = strv_env_get_with_length(env, word+2, e-word-2))) {
2760                                         if (!(k = strappend(r, t)))
2761                                                 goto fail;
2762
2763                                         free(r);
2764                                         r = k;
2765
2766                                         word = e+1;
2767                                 }
2768
2769                                 state = WORD;
2770                         }
2771                         break;
2772                 }
2773         }
2774
2775         if (!(k = strnappend(r, word, e-word)))
2776                 goto fail;
2777
2778         free(r);
2779         return k;
2780
2781 fail:
2782         free(r);
2783         return NULL;
2784 }
2785
2786 char **replace_env_argv(char **argv, char **env) {
2787         char **r, **i;
2788         unsigned k = 0;
2789
2790         if (!(r = new(char*, strv_length(argv)+1)))
2791                 return NULL;
2792
2793         STRV_FOREACH(i, argv) {
2794                 if (!(r[k++] = replace_env(*i, env))) {
2795                         strv_free(r);
2796                         return NULL;
2797                 }
2798         }
2799
2800         r[k] = NULL;
2801         return r;
2802 }
2803
2804 int columns(void) {
2805         static __thread int parsed_columns = 0;
2806         const char *e;
2807
2808         if (parsed_columns > 0)
2809                 return parsed_columns;
2810
2811         if ((e = getenv("COLUMNS")))
2812                 parsed_columns = atoi(e);
2813
2814         if (parsed_columns <= 0) {
2815                 struct winsize ws;
2816                 zero(ws);
2817
2818                 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2819                         parsed_columns = ws.ws_col;
2820         }
2821
2822         if (parsed_columns <= 0)
2823                 parsed_columns = 80;
2824
2825         return parsed_columns;
2826 }
2827
2828 int running_in_chroot(void) {
2829         struct stat a, b;
2830
2831         zero(a);
2832         zero(b);
2833
2834         /* Only works as root */
2835
2836         if (stat("/proc/1/root", &a) < 0)
2837                 return -errno;
2838
2839         if (stat("/", &b) < 0)
2840                 return -errno;
2841
2842         return
2843                 a.st_dev != b.st_dev ||
2844                 a.st_ino != b.st_ino;
2845 }
2846
2847 static const char *const ioprio_class_table[] = {
2848         [IOPRIO_CLASS_NONE] = "none",
2849         [IOPRIO_CLASS_RT] = "realtime",
2850         [IOPRIO_CLASS_BE] = "best-effort",
2851         [IOPRIO_CLASS_IDLE] = "idle"
2852 };
2853
2854 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2855
2856 static const char *const sigchld_code_table[] = {
2857         [CLD_EXITED] = "exited",
2858         [CLD_KILLED] = "killed",
2859         [CLD_DUMPED] = "dumped",
2860         [CLD_TRAPPED] = "trapped",
2861         [CLD_STOPPED] = "stopped",
2862         [CLD_CONTINUED] = "continued",
2863 };
2864
2865 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2866
2867 static const char *const log_facility_table[LOG_NFACILITIES] = {
2868         [LOG_FAC(LOG_KERN)] = "kern",
2869         [LOG_FAC(LOG_USER)] = "user",
2870         [LOG_FAC(LOG_MAIL)] = "mail",
2871         [LOG_FAC(LOG_DAEMON)] = "daemon",
2872         [LOG_FAC(LOG_AUTH)] = "auth",
2873         [LOG_FAC(LOG_SYSLOG)] = "syslog",
2874         [LOG_FAC(LOG_LPR)] = "lpr",
2875         [LOG_FAC(LOG_NEWS)] = "news",
2876         [LOG_FAC(LOG_UUCP)] = "uucp",
2877         [LOG_FAC(LOG_CRON)] = "cron",
2878         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2879         [LOG_FAC(LOG_FTP)] = "ftp",
2880         [LOG_FAC(LOG_LOCAL0)] = "local0",
2881         [LOG_FAC(LOG_LOCAL1)] = "local1",
2882         [LOG_FAC(LOG_LOCAL2)] = "local2",
2883         [LOG_FAC(LOG_LOCAL3)] = "local3",
2884         [LOG_FAC(LOG_LOCAL4)] = "local4",
2885         [LOG_FAC(LOG_LOCAL5)] = "local5",
2886         [LOG_FAC(LOG_LOCAL6)] = "local6",
2887         [LOG_FAC(LOG_LOCAL7)] = "local7"
2888 };
2889
2890 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2891
2892 static const char *const log_level_table[] = {
2893         [LOG_EMERG] = "emerg",
2894         [LOG_ALERT] = "alert",
2895         [LOG_CRIT] = "crit",
2896         [LOG_ERR] = "err",
2897         [LOG_WARNING] = "warning",
2898         [LOG_NOTICE] = "notice",
2899         [LOG_INFO] = "info",
2900         [LOG_DEBUG] = "debug"
2901 };
2902
2903 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2904
2905 static const char* const sched_policy_table[] = {
2906         [SCHED_OTHER] = "other",
2907         [SCHED_BATCH] = "batch",
2908         [SCHED_IDLE] = "idle",
2909         [SCHED_FIFO] = "fifo",
2910         [SCHED_RR] = "rr"
2911 };
2912
2913 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2914
2915 static const char* const rlimit_table[] = {
2916         [RLIMIT_CPU] = "LimitCPU",
2917         [RLIMIT_FSIZE] = "LimitFSIZE",
2918         [RLIMIT_DATA] = "LimitDATA",
2919         [RLIMIT_STACK] = "LimitSTACK",
2920         [RLIMIT_CORE] = "LimitCORE",
2921         [RLIMIT_RSS] = "LimitRSS",
2922         [RLIMIT_NOFILE] = "LimitNOFILE",
2923         [RLIMIT_AS] = "LimitAS",
2924         [RLIMIT_NPROC] = "LimitNPROC",
2925         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2926         [RLIMIT_LOCKS] = "LimitLOCKS",
2927         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2928         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2929         [RLIMIT_NICE] = "LimitNICE",
2930         [RLIMIT_RTPRIO] = "LimitRTPRIO",
2931         [RLIMIT_RTTIME] = "LimitRTTIME"
2932 };
2933
2934 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2935
2936 static const char* const ip_tos_table[] = {
2937         [IPTOS_LOWDELAY] = "low-delay",
2938         [IPTOS_THROUGHPUT] = "throughput",
2939         [IPTOS_RELIABILITY] = "reliability",
2940         [IPTOS_LOWCOST] = "low-cost",
2941 };
2942
2943 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);