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