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