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