chiark / gitweb /
mount: don't relabel /dev twice in a row
[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 *separator, ...) {
604
605         int r = 0;
606         char *contents, *p;
607
608         assert(fname);
609         assert(separator);
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, separator);
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, separator);
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, separator);
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                                 if (v[0] == '\0') {
657                                         /* return empty value strings as NULL */
658                                         free(v);
659                                         v = NULL;
660                                 }
661
662                                 free(*value);
663                                 *value = v;
664
665                                 p += n;
666
667                                 r ++;
668                                 break;
669                         }
670                         va_end(ap);
671                 }
672
673                 if (!key)
674                         p += strcspn(p, separator);
675         }
676
677 fail:
678         free(contents);
679         return r;
680 }
681
682 char *truncate_nl(char *s) {
683         assert(s);
684
685         s[strcspn(s, NEWLINE)] = 0;
686         return s;
687 }
688
689 int get_process_name(pid_t pid, char **name) {
690         char *p;
691         int r;
692
693         assert(pid >= 1);
694         assert(name);
695
696         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
697                 return -ENOMEM;
698
699         r = read_one_line_file(p, name);
700         free(p);
701
702         if (r < 0)
703                 return r;
704
705         truncate_nl(*name);
706         return 0;
707 }
708
709 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
710         char *p, *r, *k;
711         int c;
712         bool space = false;
713         size_t left;
714         FILE *f;
715
716         assert(pid >= 1);
717         assert(max_length > 0);
718         assert(line);
719
720         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
721                 return -ENOMEM;
722
723         f = fopen(p, "r");
724         free(p);
725
726         if (!f)
727                 return -errno;
728
729         if (!(r = new(char, max_length))) {
730                 fclose(f);
731                 return -ENOMEM;
732         }
733
734         k = r;
735         left = max_length;
736         while ((c = getc(f)) != EOF) {
737
738                 if (isprint(c)) {
739                         if (space) {
740                                 if (left <= 4)
741                                         break;
742
743                                 *(k++) = ' ';
744                                 left--;
745                                 space = false;
746                         }
747
748                         if (left <= 4)
749                                 break;
750
751                         *(k++) = (char) c;
752                         left--;
753                 }  else
754                         space = true;
755         }
756
757         if (left <= 4) {
758                 size_t n = MIN(left-1, 3U);
759                 memcpy(k, "...", n);
760                 k[n] = 0;
761         } else
762                 *k = 0;
763
764         fclose(f);
765
766         /* Kernel threads have no argv[] */
767         if (r[0] == 0) {
768                 char *t;
769                 int h;
770
771                 free(r);
772
773                 if ((h = get_process_name(pid, &t)) < 0)
774                         return h;
775
776                 h = asprintf(&r, "[%s]", t);
777                 free(t);
778
779                 if (h < 0)
780                         return -ENOMEM;
781         }
782
783         *line = r;
784         return 0;
785 }
786
787 char *strnappend(const char *s, const char *suffix, size_t b) {
788         size_t a;
789         char *r;
790
791         if (!s && !suffix)
792                 return strdup("");
793
794         if (!s)
795                 return strndup(suffix, b);
796
797         if (!suffix)
798                 return strdup(s);
799
800         assert(s);
801         assert(suffix);
802
803         a = strlen(s);
804
805         if (!(r = new(char, a+b+1)))
806                 return NULL;
807
808         memcpy(r, s, a);
809         memcpy(r+a, suffix, b);
810         r[a+b] = 0;
811
812         return r;
813 }
814
815 char *strappend(const char *s, const char *suffix) {
816         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
817 }
818
819 int readlink_malloc(const char *p, char **r) {
820         size_t l = 100;
821
822         assert(p);
823         assert(r);
824
825         for (;;) {
826                 char *c;
827                 ssize_t n;
828
829                 if (!(c = new(char, l)))
830                         return -ENOMEM;
831
832                 if ((n = readlink(p, c, l-1)) < 0) {
833                         int ret = -errno;
834                         free(c);
835                         return ret;
836                 }
837
838                 if ((size_t) n < l-1) {
839                         c[n] = 0;
840                         *r = c;
841                         return 0;
842                 }
843
844                 free(c);
845                 l *= 2;
846         }
847 }
848
849 int readlink_and_make_absolute(const char *p, char **r) {
850         char *target, *k;
851         int j;
852
853         assert(p);
854         assert(r);
855
856         if ((j = readlink_malloc(p, &target)) < 0)
857                 return j;
858
859         k = file_in_same_dir(p, target);
860         free(target);
861
862         if (!k)
863                 return -ENOMEM;
864
865         *r = k;
866         return 0;
867 }
868
869 int parent_of_path(const char *path, char **_r) {
870         const char *e, *a = NULL, *b = NULL, *p;
871         char *r;
872         bool slash = false;
873
874         assert(path);
875         assert(_r);
876
877         if (!*path)
878                 return -EINVAL;
879
880         for (e = path; *e; e++) {
881
882                 if (!slash && *e == '/') {
883                         a = b;
884                         b = e;
885                         slash = true;
886                 } else if (slash && *e != '/')
887                         slash = false;
888         }
889
890         if (*(e-1) == '/')
891                 p = a;
892         else
893                 p = b;
894
895         if (!p)
896                 return -EINVAL;
897
898         if (p == path)
899                 r = strdup("/");
900         else
901                 r = strndup(path, p-path);
902
903         if (!r)
904                 return -ENOMEM;
905
906         *_r = r;
907         return 0;
908 }
909
910
911 char *file_name_from_path(const char *p) {
912         char *r;
913
914         assert(p);
915
916         if ((r = strrchr(p, '/')))
917                 return r + 1;
918
919         return (char*) p;
920 }
921
922 bool path_is_absolute(const char *p) {
923         assert(p);
924
925         return p[0] == '/';
926 }
927
928 bool is_path(const char *p) {
929
930         return !!strchr(p, '/');
931 }
932
933 char *path_make_absolute(const char *p, const char *prefix) {
934         char *r;
935
936         assert(p);
937
938         /* Makes every item in the list an absolute path by prepending
939          * the prefix, if specified and necessary */
940
941         if (path_is_absolute(p) || !prefix)
942                 return strdup(p);
943
944         if (asprintf(&r, "%s/%s", prefix, p) < 0)
945                 return NULL;
946
947         return r;
948 }
949
950 char *path_make_absolute_cwd(const char *p) {
951         char *cwd, *r;
952
953         assert(p);
954
955         /* Similar to path_make_absolute(), but prefixes with the
956          * current working directory. */
957
958         if (path_is_absolute(p))
959                 return strdup(p);
960
961         if (!(cwd = get_current_dir_name()))
962                 return NULL;
963
964         r = path_make_absolute(p, cwd);
965         free(cwd);
966
967         return r;
968 }
969
970 char **strv_path_make_absolute_cwd(char **l) {
971         char **s;
972
973         /* Goes through every item in the string list and makes it
974          * absolute. This works in place and won't rollback any
975          * changes on failure. */
976
977         STRV_FOREACH(s, l) {
978                 char *t;
979
980                 if (!(t = path_make_absolute_cwd(*s)))
981                         return NULL;
982
983                 free(*s);
984                 *s = t;
985         }
986
987         return l;
988 }
989
990 char **strv_path_canonicalize(char **l) {
991         char **s;
992         unsigned k = 0;
993         bool enomem = false;
994
995         if (strv_isempty(l))
996                 return l;
997
998         /* Goes through every item in the string list and canonicalize
999          * the path. This works in place and won't rollback any
1000          * changes on failure. */
1001
1002         STRV_FOREACH(s, l) {
1003                 char *t, *u;
1004
1005                 t = path_make_absolute_cwd(*s);
1006                 free(*s);
1007
1008                 if (!t) {
1009                         enomem = true;
1010                         continue;
1011                 }
1012
1013                 errno = 0;
1014                 u = canonicalize_file_name(t);
1015                 free(t);
1016
1017                 if (!u) {
1018                         if (errno == ENOMEM || !errno)
1019                                 enomem = true;
1020
1021                         continue;
1022                 }
1023
1024                 l[k++] = u;
1025         }
1026
1027         l[k] = NULL;
1028
1029         if (enomem)
1030                 return NULL;
1031
1032         return l;
1033 }
1034
1035 int reset_all_signal_handlers(void) {
1036         int sig;
1037
1038         for (sig = 1; sig < _NSIG; sig++) {
1039                 struct sigaction sa;
1040
1041                 if (sig == SIGKILL || sig == SIGSTOP)
1042                         continue;
1043
1044                 zero(sa);
1045                 sa.sa_handler = SIG_DFL;
1046                 sa.sa_flags = SA_RESTART;
1047
1048                 /* On Linux the first two RT signals are reserved by
1049                  * glibc, and sigaction() will return EINVAL for them. */
1050                 if ((sigaction(sig, &sa, NULL) < 0))
1051                         if (errno != EINVAL)
1052                                 return -errno;
1053         }
1054
1055         return 0;
1056 }
1057
1058 char *strstrip(char *s) {
1059         char *e, *l = NULL;
1060
1061         /* Drops trailing whitespace. Modifies the string in
1062          * place. Returns pointer to first non-space character */
1063
1064         s += strspn(s, WHITESPACE);
1065
1066         for (e = s; *e; e++)
1067                 if (!strchr(WHITESPACE, *e))
1068                         l = e;
1069
1070         if (l)
1071                 *(l+1) = 0;
1072         else
1073                 *s = 0;
1074
1075         return s;
1076 }
1077
1078 char *delete_chars(char *s, const char *bad) {
1079         char *f, *t;
1080
1081         /* Drops all whitespace, regardless where in the string */
1082
1083         for (f = s, t = s; *f; f++) {
1084                 if (strchr(bad, *f))
1085                         continue;
1086
1087                 *(t++) = *f;
1088         }
1089
1090         *t = 0;
1091
1092         return s;
1093 }
1094
1095 char *file_in_same_dir(const char *path, const char *filename) {
1096         char *e, *r;
1097         size_t k;
1098
1099         assert(path);
1100         assert(filename);
1101
1102         /* This removes the last component of path and appends
1103          * filename, unless the latter is absolute anyway or the
1104          * former isn't */
1105
1106         if (path_is_absolute(filename))
1107                 return strdup(filename);
1108
1109         if (!(e = strrchr(path, '/')))
1110                 return strdup(filename);
1111
1112         k = strlen(filename);
1113         if (!(r = new(char, e-path+1+k+1)))
1114                 return NULL;
1115
1116         memcpy(r, path, e-path+1);
1117         memcpy(r+(e-path)+1, filename, k+1);
1118
1119         return r;
1120 }
1121
1122 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1123         struct stat st;
1124
1125         if (label_mkdir(path, mode) >= 0)
1126                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1127                         return -errno;
1128
1129         if (lstat(path, &st) < 0)
1130                 return -errno;
1131
1132         if ((st.st_mode & 0777) != mode ||
1133             st.st_uid != uid ||
1134             st.st_gid != gid ||
1135             !S_ISDIR(st.st_mode)) {
1136                 errno = EEXIST;
1137                 return -errno;
1138         }
1139
1140         return 0;
1141 }
1142
1143
1144 int mkdir_parents(const char *path, mode_t mode) {
1145         const char *p, *e;
1146
1147         assert(path);
1148
1149         /* Creates every parent directory in the path except the last
1150          * component. */
1151
1152         p = path + strspn(path, "/");
1153         for (;;) {
1154                 int r;
1155                 char *t;
1156
1157                 e = p + strcspn(p, "/");
1158                 p = e + strspn(e, "/");
1159
1160                 /* Is this the last component? If so, then we're
1161                  * done */
1162                 if (*p == 0)
1163                         return 0;
1164
1165                 if (!(t = strndup(path, e - path)))
1166                         return -ENOMEM;
1167
1168                 r = label_mkdir(t, mode);
1169                 free(t);
1170
1171                 if (r < 0 && errno != EEXIST)
1172                         return -errno;
1173         }
1174 }
1175
1176 int mkdir_p(const char *path, mode_t mode) {
1177         int r;
1178
1179         /* Like mkdir -p */
1180
1181         if ((r = mkdir_parents(path, mode)) < 0)
1182                 return r;
1183
1184         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1185                 return -errno;
1186
1187         return 0;
1188 }
1189
1190 int rmdir_parents(const char *path, const char *stop) {
1191         size_t l;
1192         int r = 0;
1193
1194         assert(path);
1195         assert(stop);
1196
1197         l = strlen(path);
1198
1199         /* Skip trailing slashes */
1200         while (l > 0 && path[l-1] == '/')
1201                 l--;
1202
1203         while (l > 0) {
1204                 char *t;
1205
1206                 /* Skip last component */
1207                 while (l > 0 && path[l-1] != '/')
1208                         l--;
1209
1210                 /* Skip trailing slashes */
1211                 while (l > 0 && path[l-1] == '/')
1212                         l--;
1213
1214                 if (l <= 0)
1215                         break;
1216
1217                 if (!(t = strndup(path, l)))
1218                         return -ENOMEM;
1219
1220                 if (path_startswith(stop, t)) {
1221                         free(t);
1222                         return 0;
1223                 }
1224
1225                 r = rmdir(t);
1226                 free(t);
1227
1228                 if (r < 0)
1229                         if (errno != ENOENT)
1230                                 return -errno;
1231         }
1232
1233         return 0;
1234 }
1235
1236
1237 char hexchar(int x) {
1238         static const char table[16] = "0123456789abcdef";
1239
1240         return table[x & 15];
1241 }
1242
1243 int unhexchar(char c) {
1244
1245         if (c >= '0' && c <= '9')
1246                 return c - '0';
1247
1248         if (c >= 'a' && c <= 'f')
1249                 return c - 'a' + 10;
1250
1251         if (c >= 'A' && c <= 'F')
1252                 return c - 'A' + 10;
1253
1254         return -1;
1255 }
1256
1257 char octchar(int x) {
1258         return '0' + (x & 7);
1259 }
1260
1261 int unoctchar(char c) {
1262
1263         if (c >= '0' && c <= '7')
1264                 return c - '0';
1265
1266         return -1;
1267 }
1268
1269 char decchar(int x) {
1270         return '0' + (x % 10);
1271 }
1272
1273 int undecchar(char c) {
1274
1275         if (c >= '0' && c <= '9')
1276                 return c - '0';
1277
1278         return -1;
1279 }
1280
1281 char *cescape(const char *s) {
1282         char *r, *t;
1283         const char *f;
1284
1285         assert(s);
1286
1287         /* Does C style string escaping. */
1288
1289         if (!(r = new(char, strlen(s)*4 + 1)))
1290                 return NULL;
1291
1292         for (f = s, t = r; *f; f++)
1293
1294                 switch (*f) {
1295
1296                 case '\a':
1297                         *(t++) = '\\';
1298                         *(t++) = 'a';
1299                         break;
1300                 case '\b':
1301                         *(t++) = '\\';
1302                         *(t++) = 'b';
1303                         break;
1304                 case '\f':
1305                         *(t++) = '\\';
1306                         *(t++) = 'f';
1307                         break;
1308                 case '\n':
1309                         *(t++) = '\\';
1310                         *(t++) = 'n';
1311                         break;
1312                 case '\r':
1313                         *(t++) = '\\';
1314                         *(t++) = 'r';
1315                         break;
1316                 case '\t':
1317                         *(t++) = '\\';
1318                         *(t++) = 't';
1319                         break;
1320                 case '\v':
1321                         *(t++) = '\\';
1322                         *(t++) = 'v';
1323                         break;
1324                 case '\\':
1325                         *(t++) = '\\';
1326                         *(t++) = '\\';
1327                         break;
1328                 case '"':
1329                         *(t++) = '\\';
1330                         *(t++) = '"';
1331                         break;
1332                 case '\'':
1333                         *(t++) = '\\';
1334                         *(t++) = '\'';
1335                         break;
1336
1337                 default:
1338                         /* For special chars we prefer octal over
1339                          * hexadecimal encoding, simply because glib's
1340                          * g_strescape() does the same */
1341                         if ((*f < ' ') || (*f >= 127)) {
1342                                 *(t++) = '\\';
1343                                 *(t++) = octchar((unsigned char) *f >> 6);
1344                                 *(t++) = octchar((unsigned char) *f >> 3);
1345                                 *(t++) = octchar((unsigned char) *f);
1346                         } else
1347                                 *(t++) = *f;
1348                         break;
1349                 }
1350
1351         *t = 0;
1352
1353         return r;
1354 }
1355
1356 char *cunescape_length(const char *s, size_t length) {
1357         char *r, *t;
1358         const char *f;
1359
1360         assert(s);
1361
1362         /* Undoes C style string escaping */
1363
1364         if (!(r = new(char, length+1)))
1365                 return r;
1366
1367         for (f = s, t = r; f < s + length; f++) {
1368
1369                 if (*f != '\\') {
1370                         *(t++) = *f;
1371                         continue;
1372                 }
1373
1374                 f++;
1375
1376                 switch (*f) {
1377
1378                 case 'a':
1379                         *(t++) = '\a';
1380                         break;
1381                 case 'b':
1382                         *(t++) = '\b';
1383                         break;
1384                 case 'f':
1385                         *(t++) = '\f';
1386                         break;
1387                 case 'n':
1388                         *(t++) = '\n';
1389                         break;
1390                 case 'r':
1391                         *(t++) = '\r';
1392                         break;
1393                 case 't':
1394                         *(t++) = '\t';
1395                         break;
1396                 case 'v':
1397                         *(t++) = '\v';
1398                         break;
1399                 case '\\':
1400                         *(t++) = '\\';
1401                         break;
1402                 case '"':
1403                         *(t++) = '"';
1404                         break;
1405                 case '\'':
1406                         *(t++) = '\'';
1407                         break;
1408
1409                 case 's':
1410                         /* This is an extension of the XDG syntax files */
1411                         *(t++) = ' ';
1412                         break;
1413
1414                 case 'x': {
1415                         /* hexadecimal encoding */
1416                         int a, b;
1417
1418                         if ((a = unhexchar(f[1])) < 0 ||
1419                             (b = unhexchar(f[2])) < 0) {
1420                                 /* Invalid escape code, let's take it literal then */
1421                                 *(t++) = '\\';
1422                                 *(t++) = 'x';
1423                         } else {
1424                                 *(t++) = (char) ((a << 4) | b);
1425                                 f += 2;
1426                         }
1427
1428                         break;
1429                 }
1430
1431                 case '0':
1432                 case '1':
1433                 case '2':
1434                 case '3':
1435                 case '4':
1436                 case '5':
1437                 case '6':
1438                 case '7': {
1439                         /* octal encoding */
1440                         int a, b, c;
1441
1442                         if ((a = unoctchar(f[0])) < 0 ||
1443                             (b = unoctchar(f[1])) < 0 ||
1444                             (c = unoctchar(f[2])) < 0) {
1445                                 /* Invalid escape code, let's take it literal then */
1446                                 *(t++) = '\\';
1447                                 *(t++) = f[0];
1448                         } else {
1449                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1450                                 f += 2;
1451                         }
1452
1453                         break;
1454                 }
1455
1456                 case 0:
1457                         /* premature end of string.*/
1458                         *(t++) = '\\';
1459                         goto finish;
1460
1461                 default:
1462                         /* Invalid escape code, let's take it literal then */
1463                         *(t++) = '\\';
1464                         *(t++) = *f;
1465                         break;
1466                 }
1467         }
1468
1469 finish:
1470         *t = 0;
1471         return r;
1472 }
1473
1474 char *cunescape(const char *s) {
1475         return cunescape_length(s, strlen(s));
1476 }
1477
1478 char *xescape(const char *s, const char *bad) {
1479         char *r, *t;
1480         const char *f;
1481
1482         /* Escapes all chars in bad, in addition to \ and all special
1483          * chars, in \xFF style escaping. May be reversed with
1484          * cunescape. */
1485
1486         if (!(r = new(char, strlen(s)*4+1)))
1487                 return NULL;
1488
1489         for (f = s, t = r; *f; f++) {
1490
1491                 if ((*f < ' ') || (*f >= 127) ||
1492                     (*f == '\\') || strchr(bad, *f)) {
1493                         *(t++) = '\\';
1494                         *(t++) = 'x';
1495                         *(t++) = hexchar(*f >> 4);
1496                         *(t++) = hexchar(*f);
1497                 } else
1498                         *(t++) = *f;
1499         }
1500
1501         *t = 0;
1502
1503         return r;
1504 }
1505
1506 char *bus_path_escape(const char *s) {
1507         char *r, *t;
1508         const char *f;
1509
1510         assert(s);
1511
1512         /* Escapes all chars that D-Bus' object path cannot deal
1513          * with. Can be reverse with bus_path_unescape() */
1514
1515         if (!(r = new(char, strlen(s)*3+1)))
1516                 return NULL;
1517
1518         for (f = s, t = r; *f; f++) {
1519
1520                 if (!(*f >= 'A' && *f <= 'Z') &&
1521                     !(*f >= 'a' && *f <= 'z') &&
1522                     !(*f >= '0' && *f <= '9')) {
1523                         *(t++) = '_';
1524                         *(t++) = hexchar(*f >> 4);
1525                         *(t++) = hexchar(*f);
1526                 } else
1527                         *(t++) = *f;
1528         }
1529
1530         *t = 0;
1531
1532         return r;
1533 }
1534
1535 char *bus_path_unescape(const char *f) {
1536         char *r, *t;
1537
1538         assert(f);
1539
1540         if (!(r = strdup(f)))
1541                 return NULL;
1542
1543         for (t = r; *f; f++) {
1544
1545                 if (*f == '_') {
1546                         int a, b;
1547
1548                         if ((a = unhexchar(f[1])) < 0 ||
1549                             (b = unhexchar(f[2])) < 0) {
1550                                 /* Invalid escape code, let's take it literal then */
1551                                 *(t++) = '_';
1552                         } else {
1553                                 *(t++) = (char) ((a << 4) | b);
1554                                 f += 2;
1555                         }
1556                 } else
1557                         *(t++) = *f;
1558         }
1559
1560         *t = 0;
1561
1562         return r;
1563 }
1564
1565 char *path_kill_slashes(char *path) {
1566         char *f, *t;
1567         bool slash = false;
1568
1569         /* Removes redundant inner and trailing slashes. Modifies the
1570          * passed string in-place.
1571          *
1572          * ///foo///bar/ becomes /foo/bar
1573          */
1574
1575         for (f = path, t = path; *f; f++) {
1576
1577                 if (*f == '/') {
1578                         slash = true;
1579                         continue;
1580                 }
1581
1582                 if (slash) {
1583                         slash = false;
1584                         *(t++) = '/';
1585                 }
1586
1587                 *(t++) = *f;
1588         }
1589
1590         /* Special rule, if we are talking of the root directory, a
1591         trailing slash is good */
1592
1593         if (t == path && slash)
1594                 *(t++) = '/';
1595
1596         *t = 0;
1597         return path;
1598 }
1599
1600 bool path_startswith(const char *path, const char *prefix) {
1601         assert(path);
1602         assert(prefix);
1603
1604         if ((path[0] == '/') != (prefix[0] == '/'))
1605                 return false;
1606
1607         for (;;) {
1608                 size_t a, b;
1609
1610                 path += strspn(path, "/");
1611                 prefix += strspn(prefix, "/");
1612
1613                 if (*prefix == 0)
1614                         return true;
1615
1616                 if (*path == 0)
1617                         return false;
1618
1619                 a = strcspn(path, "/");
1620                 b = strcspn(prefix, "/");
1621
1622                 if (a != b)
1623                         return false;
1624
1625                 if (memcmp(path, prefix, a) != 0)
1626                         return false;
1627
1628                 path += a;
1629                 prefix += b;
1630         }
1631 }
1632
1633 bool path_equal(const char *a, const char *b) {
1634         assert(a);
1635         assert(b);
1636
1637         if ((a[0] == '/') != (b[0] == '/'))
1638                 return false;
1639
1640         for (;;) {
1641                 size_t j, k;
1642
1643                 a += strspn(a, "/");
1644                 b += strspn(b, "/");
1645
1646                 if (*a == 0 && *b == 0)
1647                         return true;
1648
1649                 if (*a == 0 || *b == 0)
1650                         return false;
1651
1652                 j = strcspn(a, "/");
1653                 k = strcspn(b, "/");
1654
1655                 if (j != k)
1656                         return false;
1657
1658                 if (memcmp(a, b, j) != 0)
1659                         return false;
1660
1661                 a += j;
1662                 b += k;
1663         }
1664 }
1665
1666 char *ascii_strlower(char *t) {
1667         char *p;
1668
1669         assert(t);
1670
1671         for (p = t; *p; p++)
1672                 if (*p >= 'A' && *p <= 'Z')
1673                         *p = *p - 'A' + 'a';
1674
1675         return t;
1676 }
1677
1678 bool ignore_file(const char *filename) {
1679         assert(filename);
1680
1681         return
1682                 filename[0] == '.' ||
1683                 streq(filename, "lost+found") ||
1684                 streq(filename, "aquota.user") ||
1685                 streq(filename, "aquota.group") ||
1686                 endswith(filename, "~") ||
1687                 endswith(filename, ".rpmnew") ||
1688                 endswith(filename, ".rpmsave") ||
1689                 endswith(filename, ".rpmorig") ||
1690                 endswith(filename, ".dpkg-old") ||
1691                 endswith(filename, ".dpkg-new") ||
1692                 endswith(filename, ".swp");
1693 }
1694
1695 int fd_nonblock(int fd, bool nonblock) {
1696         int flags;
1697
1698         assert(fd >= 0);
1699
1700         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1701                 return -errno;
1702
1703         if (nonblock)
1704                 flags |= O_NONBLOCK;
1705         else
1706                 flags &= ~O_NONBLOCK;
1707
1708         if (fcntl(fd, F_SETFL, flags) < 0)
1709                 return -errno;
1710
1711         return 0;
1712 }
1713
1714 int fd_cloexec(int fd, bool cloexec) {
1715         int flags;
1716
1717         assert(fd >= 0);
1718
1719         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1720                 return -errno;
1721
1722         if (cloexec)
1723                 flags |= FD_CLOEXEC;
1724         else
1725                 flags &= ~FD_CLOEXEC;
1726
1727         if (fcntl(fd, F_SETFD, flags) < 0)
1728                 return -errno;
1729
1730         return 0;
1731 }
1732
1733 int close_all_fds(const int except[], unsigned n_except) {
1734         DIR *d;
1735         struct dirent *de;
1736         int r = 0;
1737
1738         if (!(d = opendir("/proc/self/fd")))
1739                 return -errno;
1740
1741         while ((de = readdir(d))) {
1742                 int fd = -1;
1743
1744                 if (ignore_file(de->d_name))
1745                         continue;
1746
1747                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1748                         goto finish;
1749
1750                 if (fd < 3)
1751                         continue;
1752
1753                 if (fd == dirfd(d))
1754                         continue;
1755
1756                 if (except) {
1757                         bool found;
1758                         unsigned i;
1759
1760                         found = false;
1761                         for (i = 0; i < n_except; i++)
1762                                 if (except[i] == fd) {
1763                                         found = true;
1764                                         break;
1765                                 }
1766
1767                         if (found)
1768                                 continue;
1769                 }
1770
1771                 if ((r = close_nointr(fd)) < 0) {
1772                         /* Valgrind has its own FD and doesn't want to have it closed */
1773                         if (errno != EBADF)
1774                                 goto finish;
1775                 }
1776         }
1777
1778         r = 0;
1779
1780 finish:
1781         closedir(d);
1782         return r;
1783 }
1784
1785 bool chars_intersect(const char *a, const char *b) {
1786         const char *p;
1787
1788         /* Returns true if any of the chars in a are in b. */
1789         for (p = a; *p; p++)
1790                 if (strchr(b, *p))
1791                         return true;
1792
1793         return false;
1794 }
1795
1796 char *format_timestamp(char *buf, size_t l, usec_t t) {
1797         struct tm tm;
1798         time_t sec;
1799
1800         assert(buf);
1801         assert(l > 0);
1802
1803         if (t <= 0)
1804                 return NULL;
1805
1806         sec = (time_t) (t / USEC_PER_SEC);
1807
1808         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1809                 return NULL;
1810
1811         return buf;
1812 }
1813
1814 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1815         usec_t n, d;
1816
1817         n = now(CLOCK_REALTIME);
1818
1819         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1820                 return NULL;
1821
1822         d = n - t;
1823
1824         if (d >= USEC_PER_YEAR)
1825                 snprintf(buf, l, "%llu years and %llu months ago",
1826                          (unsigned long long) (d / USEC_PER_YEAR),
1827                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1828         else if (d >= USEC_PER_MONTH)
1829                 snprintf(buf, l, "%llu months and %llu days ago",
1830                          (unsigned long long) (d / USEC_PER_MONTH),
1831                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1832         else if (d >= USEC_PER_WEEK)
1833                 snprintf(buf, l, "%llu weeks and %llu days ago",
1834                          (unsigned long long) (d / USEC_PER_WEEK),
1835                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1836         else if (d >= 2*USEC_PER_DAY)
1837                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1838         else if (d >= 25*USEC_PER_HOUR)
1839                 snprintf(buf, l, "1 day and %lluh ago",
1840                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1841         else if (d >= 6*USEC_PER_HOUR)
1842                 snprintf(buf, l, "%lluh ago",
1843                          (unsigned long long) (d / USEC_PER_HOUR));
1844         else if (d >= USEC_PER_HOUR)
1845                 snprintf(buf, l, "%lluh %llumin ago",
1846                          (unsigned long long) (d / USEC_PER_HOUR),
1847                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1848         else if (d >= 5*USEC_PER_MINUTE)
1849                 snprintf(buf, l, "%llumin ago",
1850                          (unsigned long long) (d / USEC_PER_MINUTE));
1851         else if (d >= USEC_PER_MINUTE)
1852                 snprintf(buf, l, "%llumin %llus ago",
1853                          (unsigned long long) (d / USEC_PER_MINUTE),
1854                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1855         else if (d >= USEC_PER_SEC)
1856                 snprintf(buf, l, "%llus ago",
1857                          (unsigned long long) (d / USEC_PER_SEC));
1858         else if (d >= USEC_PER_MSEC)
1859                 snprintf(buf, l, "%llums ago",
1860                          (unsigned long long) (d / USEC_PER_MSEC));
1861         else if (d > 0)
1862                 snprintf(buf, l, "%lluus ago",
1863                          (unsigned long long) d);
1864         else
1865                 snprintf(buf, l, "now");
1866
1867         buf[l-1] = 0;
1868         return buf;
1869 }
1870
1871 char *format_timespan(char *buf, size_t l, usec_t t) {
1872         static const struct {
1873                 const char *suffix;
1874                 usec_t usec;
1875         } table[] = {
1876                 { "w", USEC_PER_WEEK },
1877                 { "d", USEC_PER_DAY },
1878                 { "h", USEC_PER_HOUR },
1879                 { "min", USEC_PER_MINUTE },
1880                 { "s", USEC_PER_SEC },
1881                 { "ms", USEC_PER_MSEC },
1882                 { "us", 1 },
1883         };
1884
1885         unsigned i;
1886         char *p = buf;
1887
1888         assert(buf);
1889         assert(l > 0);
1890
1891         if (t == (usec_t) -1)
1892                 return NULL;
1893
1894         if (t == 0) {
1895                 snprintf(p, l, "0");
1896                 p[l-1] = 0;
1897                 return p;
1898         }
1899
1900         /* The result of this function can be parsed with parse_usec */
1901
1902         for (i = 0; i < ELEMENTSOF(table); i++) {
1903                 int k;
1904                 size_t n;
1905
1906                 if (t < table[i].usec)
1907                         continue;
1908
1909                 if (l <= 1)
1910                         break;
1911
1912                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1913                 n = MIN((size_t) k, l);
1914
1915                 l -= n;
1916                 p += n;
1917
1918                 t %= table[i].usec;
1919         }
1920
1921         *p = 0;
1922
1923         return buf;
1924 }
1925
1926 bool fstype_is_network(const char *fstype) {
1927         static const char * const table[] = {
1928                 "cifs",
1929                 "smbfs",
1930                 "ncpfs",
1931                 "nfs",
1932                 "nfs4",
1933                 "gfs",
1934                 "gfs2"
1935         };
1936
1937         unsigned i;
1938
1939         for (i = 0; i < ELEMENTSOF(table); i++)
1940                 if (streq(table[i], fstype))
1941                         return true;
1942
1943         return false;
1944 }
1945
1946 int chvt(int vt) {
1947         int fd, r = 0;
1948
1949         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1950                 return -errno;
1951
1952         if (vt < 0) {
1953                 int tiocl[2] = {
1954                         TIOCL_GETKMSGREDIRECT,
1955                         0
1956                 };
1957
1958                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1959                         return -errno;
1960
1961                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1962         }
1963
1964         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1965                 r = -errno;
1966
1967         close_nointr_nofail(r);
1968         return r;
1969 }
1970
1971 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1972         struct termios old_termios, new_termios;
1973         char c;
1974         char line[1024];
1975
1976         assert(f);
1977         assert(ret);
1978
1979         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1980                 new_termios = old_termios;
1981
1982                 new_termios.c_lflag &= ~ICANON;
1983                 new_termios.c_cc[VMIN] = 1;
1984                 new_termios.c_cc[VTIME] = 0;
1985
1986                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1987                         size_t k;
1988
1989                         k = fread(&c, 1, 1, f);
1990
1991                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1992
1993                         if (k <= 0)
1994                                 return -EIO;
1995
1996                         if (need_nl)
1997                                 *need_nl = c != '\n';
1998
1999                         *ret = c;
2000                         return 0;
2001                 }
2002         }
2003
2004         if (!(fgets(line, sizeof(line), f)))
2005                 return -EIO;
2006
2007         truncate_nl(line);
2008
2009         if (strlen(line) != 1)
2010                 return -EBADMSG;
2011
2012         if (need_nl)
2013                 *need_nl = false;
2014
2015         *ret = line[0];
2016         return 0;
2017 }
2018
2019 int ask(char *ret, const char *replies, const char *text, ...) {
2020         bool on_tty;
2021
2022         assert(ret);
2023         assert(replies);
2024         assert(text);
2025
2026         on_tty = isatty(STDOUT_FILENO);
2027
2028         for (;;) {
2029                 va_list ap;
2030                 char c;
2031                 int r;
2032                 bool need_nl = true;
2033
2034                 if (on_tty)
2035                         fputs("\x1B[1m", stdout);
2036
2037                 va_start(ap, text);
2038                 vprintf(text, ap);
2039                 va_end(ap);
2040
2041                 if (on_tty)
2042                         fputs("\x1B[0m", stdout);
2043
2044                 fflush(stdout);
2045
2046                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2047
2048                         if (r == -EBADMSG) {
2049                                 puts("Bad input, please try again.");
2050                                 continue;
2051                         }
2052
2053                         putchar('\n');
2054                         return r;
2055                 }
2056
2057                 if (need_nl)
2058                         putchar('\n');
2059
2060                 if (strchr(replies, c)) {
2061                         *ret = c;
2062                         return 0;
2063                 }
2064
2065                 puts("Read unexpected character, please try again.");
2066         }
2067 }
2068
2069 int reset_terminal(int fd) {
2070         struct termios termios;
2071         int r = 0;
2072         long arg;
2073
2074         /* Set terminal to some sane defaults */
2075
2076         assert(fd >= 0);
2077
2078         /* We leave locked terminal attributes untouched, so that
2079          * Plymouth may set whatever it wants to set, and we don't
2080          * interfere with that. */
2081
2082         /* Disable exclusive mode, just in case */
2083         ioctl(fd, TIOCNXCL);
2084
2085         /* Enable console unicode mode */
2086         arg = K_UNICODE;
2087         ioctl(fd, KDSKBMODE, &arg);
2088
2089         if (tcgetattr(fd, &termios) < 0) {
2090                 r = -errno;
2091                 goto finish;
2092         }
2093
2094         /* We only reset the stuff that matters to the software. How
2095          * hardware is set up we don't touch assuming that somebody
2096          * else will do that for us */
2097
2098         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2099         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2100         termios.c_oflag |= ONLCR;
2101         termios.c_cflag |= CREAD;
2102         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2103
2104         termios.c_cc[VINTR]    =   03;  /* ^C */
2105         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2106         termios.c_cc[VERASE]   = 0177;
2107         termios.c_cc[VKILL]    =  025;  /* ^X */
2108         termios.c_cc[VEOF]     =   04;  /* ^D */
2109         termios.c_cc[VSTART]   =  021;  /* ^Q */
2110         termios.c_cc[VSTOP]    =  023;  /* ^S */
2111         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2112         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2113         termios.c_cc[VWERASE]  =  027;  /* ^W */
2114         termios.c_cc[VREPRINT] =  022;  /* ^R */
2115         termios.c_cc[VEOL]     =    0;
2116         termios.c_cc[VEOL2]    =    0;
2117
2118         termios.c_cc[VTIME]  = 0;
2119         termios.c_cc[VMIN]   = 1;
2120
2121         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2122                 r = -errno;
2123
2124 finish:
2125         /* Just in case, flush all crap out */
2126         tcflush(fd, TCIOFLUSH);
2127
2128         return r;
2129 }
2130
2131 int open_terminal(const char *name, int mode) {
2132         int fd, r;
2133
2134         if ((fd = open(name, mode)) < 0)
2135                 return -errno;
2136
2137         if ((r = isatty(fd)) < 0) {
2138                 close_nointr_nofail(fd);
2139                 return -errno;
2140         }
2141
2142         if (!r) {
2143                 close_nointr_nofail(fd);
2144                 return -ENOTTY;
2145         }
2146
2147         return fd;
2148 }
2149
2150 int flush_fd(int fd) {
2151         struct pollfd pollfd;
2152
2153         zero(pollfd);
2154         pollfd.fd = fd;
2155         pollfd.events = POLLIN;
2156
2157         for (;;) {
2158                 char buf[1024];
2159                 ssize_t l;
2160                 int r;
2161
2162                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2163
2164                         if (errno == EINTR)
2165                                 continue;
2166
2167                         return -errno;
2168                 }
2169
2170                 if (r == 0)
2171                         return 0;
2172
2173                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2174
2175                         if (errno == EINTR)
2176                                 continue;
2177
2178                         if (errno == EAGAIN)
2179                                 return 0;
2180
2181                         return -errno;
2182                 }
2183
2184                 if (l <= 0)
2185                         return 0;
2186         }
2187 }
2188
2189 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2190         int fd = -1, notify = -1, r, wd = -1;
2191
2192         assert(name);
2193
2194         /* We use inotify to be notified when the tty is closed. We
2195          * create the watch before checking if we can actually acquire
2196          * it, so that we don't lose any event.
2197          *
2198          * Note: strictly speaking this actually watches for the
2199          * device being closed, it does *not* really watch whether a
2200          * tty loses its controlling process. However, unless some
2201          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2202          * its tty otherwise this will not become a problem. As long
2203          * as the administrator makes sure not configure any service
2204          * on the same tty as an untrusted user this should not be a
2205          * problem. (Which he probably should not do anyway.) */
2206
2207         if (!fail && !force) {
2208                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2209                         r = -errno;
2210                         goto fail;
2211                 }
2212
2213                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2214                         r = -errno;
2215                         goto fail;
2216                 }
2217         }
2218
2219         for (;;) {
2220                 if (notify >= 0)
2221                         if ((r = flush_fd(notify)) < 0)
2222                                 goto fail;
2223
2224                 /* We pass here O_NOCTTY only so that we can check the return
2225                  * value TIOCSCTTY and have a reliable way to figure out if we
2226                  * successfully became the controlling process of the tty */
2227                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2228                         return -errno;
2229
2230                 /* First, try to get the tty */
2231                 r = ioctl(fd, TIOCSCTTY, force);
2232
2233                 /* Sometimes it makes sense to ignore TIOCSCTTY
2234                  * returning EPERM, i.e. when very likely we already
2235                  * are have this controlling terminal. */
2236                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2237                         r = 0;
2238
2239                 if (r < 0 && (force || fail || errno != EPERM)) {
2240                         r = -errno;
2241                         goto fail;
2242                 }
2243
2244                 if (r >= 0)
2245                         break;
2246
2247                 assert(!fail);
2248                 assert(!force);
2249                 assert(notify >= 0);
2250
2251                 for (;;) {
2252                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2253                         ssize_t l;
2254                         struct inotify_event *e;
2255
2256                         if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2257
2258                                 if (errno == EINTR)
2259                                         continue;
2260
2261                                 r = -errno;
2262                                 goto fail;
2263                         }
2264
2265                         e = (struct inotify_event*) inotify_buffer;
2266
2267                         while (l > 0) {
2268                                 size_t step;
2269
2270                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2271                                         r = -EIO;
2272                                         goto fail;
2273                                 }
2274
2275                                 step = sizeof(struct inotify_event) + e->len;
2276                                 assert(step <= (size_t) l);
2277
2278                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2279                                 l -= step;
2280                         }
2281
2282                         break;
2283                 }
2284
2285                 /* We close the tty fd here since if the old session
2286                  * ended our handle will be dead. It's important that
2287                  * we do this after sleeping, so that we don't enter
2288                  * an endless loop. */
2289                 close_nointr_nofail(fd);
2290         }
2291
2292         if (notify >= 0)
2293                 close_nointr_nofail(notify);
2294
2295         if ((r = reset_terminal(fd)) < 0)
2296                 log_warning("Failed to reset terminal: %s", strerror(-r));
2297
2298         return fd;
2299
2300 fail:
2301         if (fd >= 0)
2302                 close_nointr_nofail(fd);
2303
2304         if (notify >= 0)
2305                 close_nointr_nofail(notify);
2306
2307         return r;
2308 }
2309
2310 int release_terminal(void) {
2311         int r = 0, fd;
2312         struct sigaction sa_old, sa_new;
2313
2314         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2315                 return -errno;
2316
2317         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2318          * by our own TIOCNOTTY */
2319
2320         zero(sa_new);
2321         sa_new.sa_handler = SIG_IGN;
2322         sa_new.sa_flags = SA_RESTART;
2323         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2324
2325         if (ioctl(fd, TIOCNOTTY) < 0)
2326                 r = -errno;
2327
2328         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2329
2330         close_nointr_nofail(fd);
2331         return r;
2332 }
2333
2334 int sigaction_many(const struct sigaction *sa, ...) {
2335         va_list ap;
2336         int r = 0, sig;
2337
2338         va_start(ap, sa);
2339         while ((sig = va_arg(ap, int)) > 0)
2340                 if (sigaction(sig, sa, NULL) < 0)
2341                         r = -errno;
2342         va_end(ap);
2343
2344         return r;
2345 }
2346
2347 int ignore_signals(int sig, ...) {
2348         struct sigaction sa;
2349         va_list ap;
2350         int r = 0;
2351
2352         zero(sa);
2353         sa.sa_handler = SIG_IGN;
2354         sa.sa_flags = SA_RESTART;
2355
2356         if (sigaction(sig, &sa, NULL) < 0)
2357                 r = -errno;
2358
2359         va_start(ap, sig);
2360         while ((sig = va_arg(ap, int)) > 0)
2361                 if (sigaction(sig, &sa, NULL) < 0)
2362                         r = -errno;
2363         va_end(ap);
2364
2365         return r;
2366 }
2367
2368 int default_signals(int sig, ...) {
2369         struct sigaction sa;
2370         va_list ap;
2371         int r = 0;
2372
2373         zero(sa);
2374         sa.sa_handler = SIG_DFL;
2375         sa.sa_flags = SA_RESTART;
2376
2377         if (sigaction(sig, &sa, NULL) < 0)
2378                 r = -errno;
2379
2380         va_start(ap, sig);
2381         while ((sig = va_arg(ap, int)) > 0)
2382                 if (sigaction(sig, &sa, NULL) < 0)
2383                         r = -errno;
2384         va_end(ap);
2385
2386         return r;
2387 }
2388
2389 int close_pipe(int p[]) {
2390         int a = 0, b = 0;
2391
2392         assert(p);
2393
2394         if (p[0] >= 0) {
2395                 a = close_nointr(p[0]);
2396                 p[0] = -1;
2397         }
2398
2399         if (p[1] >= 0) {
2400                 b = close_nointr(p[1]);
2401                 p[1] = -1;
2402         }
2403
2404         return a < 0 ? a : b;
2405 }
2406
2407 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2408         uint8_t *p;
2409         ssize_t n = 0;
2410
2411         assert(fd >= 0);
2412         assert(buf);
2413
2414         p = buf;
2415
2416         while (nbytes > 0) {
2417                 ssize_t k;
2418
2419                 if ((k = read(fd, p, nbytes)) <= 0) {
2420
2421                         if (k < 0 && errno == EINTR)
2422                                 continue;
2423
2424                         if (k < 0 && errno == EAGAIN && do_poll) {
2425                                 struct pollfd pollfd;
2426
2427                                 zero(pollfd);
2428                                 pollfd.fd = fd;
2429                                 pollfd.events = POLLIN;
2430
2431                                 if (poll(&pollfd, 1, -1) < 0) {
2432                                         if (errno == EINTR)
2433                                                 continue;
2434
2435                                         return n > 0 ? n : -errno;
2436                                 }
2437
2438                                 if (pollfd.revents != POLLIN)
2439                                         return n > 0 ? n : -EIO;
2440
2441                                 continue;
2442                         }
2443
2444                         return n > 0 ? n : (k < 0 ? -errno : 0);
2445                 }
2446
2447                 p += k;
2448                 nbytes -= k;
2449                 n += k;
2450         }
2451
2452         return n;
2453 }
2454
2455 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2456         const uint8_t *p;
2457         ssize_t n = 0;
2458
2459         assert(fd >= 0);
2460         assert(buf);
2461
2462         p = buf;
2463
2464         while (nbytes > 0) {
2465                 ssize_t k;
2466
2467                 if ((k = write(fd, p, nbytes)) <= 0) {
2468
2469                         if (k < 0 && errno == EINTR)
2470                                 continue;
2471
2472                         if (k < 0 && errno == EAGAIN && do_poll) {
2473                                 struct pollfd pollfd;
2474
2475                                 zero(pollfd);
2476                                 pollfd.fd = fd;
2477                                 pollfd.events = POLLOUT;
2478
2479                                 if (poll(&pollfd, 1, -1) < 0) {
2480                                         if (errno == EINTR)
2481                                                 continue;
2482
2483                                         return n > 0 ? n : -errno;
2484                                 }
2485
2486                                 if (pollfd.revents != POLLOUT)
2487                                         return n > 0 ? n : -EIO;
2488
2489                                 continue;
2490                         }
2491
2492                         return n > 0 ? n : (k < 0 ? -errno : 0);
2493                 }
2494
2495                 p += k;
2496                 nbytes -= k;
2497                 n += k;
2498         }
2499
2500         return n;
2501 }
2502
2503 int path_is_mount_point(const char *t) {
2504         struct stat a, b;
2505         char *parent;
2506         int r;
2507
2508         if (lstat(t, &a) < 0) {
2509                 if (errno == ENOENT)
2510                         return 0;
2511
2512                 return -errno;
2513         }
2514
2515         if ((r = parent_of_path(t, &parent)) < 0)
2516                 return r;
2517
2518         r = lstat(parent, &b);
2519         free(parent);
2520
2521         if (r < 0)
2522                 return -errno;
2523
2524         return a.st_dev != b.st_dev;
2525 }
2526
2527 int parse_usec(const char *t, usec_t *usec) {
2528         static const struct {
2529                 const char *suffix;
2530                 usec_t usec;
2531         } table[] = {
2532                 { "sec", USEC_PER_SEC },
2533                 { "s", USEC_PER_SEC },
2534                 { "min", USEC_PER_MINUTE },
2535                 { "hr", USEC_PER_HOUR },
2536                 { "h", USEC_PER_HOUR },
2537                 { "d", USEC_PER_DAY },
2538                 { "w", USEC_PER_WEEK },
2539                 { "msec", USEC_PER_MSEC },
2540                 { "ms", USEC_PER_MSEC },
2541                 { "m", USEC_PER_MINUTE },
2542                 { "usec", 1ULL },
2543                 { "us", 1ULL },
2544                 { "", USEC_PER_SEC },
2545         };
2546
2547         const char *p;
2548         usec_t r = 0;
2549
2550         assert(t);
2551         assert(usec);
2552
2553         p = t;
2554         do {
2555                 long long l;
2556                 char *e;
2557                 unsigned i;
2558
2559                 errno = 0;
2560                 l = strtoll(p, &e, 10);
2561
2562                 if (errno != 0)
2563                         return -errno;
2564
2565                 if (l < 0)
2566                         return -ERANGE;
2567
2568                 if (e == p)
2569                         return -EINVAL;
2570
2571                 e += strspn(e, WHITESPACE);
2572
2573                 for (i = 0; i < ELEMENTSOF(table); i++)
2574                         if (startswith(e, table[i].suffix)) {
2575                                 r += (usec_t) l * table[i].usec;
2576                                 p = e + strlen(table[i].suffix);
2577                                 break;
2578                         }
2579
2580                 if (i >= ELEMENTSOF(table))
2581                         return -EINVAL;
2582
2583         } while (*p != 0);
2584
2585         *usec = r;
2586
2587         return 0;
2588 }
2589
2590 int make_stdio(int fd) {
2591         int r, s, t;
2592
2593         assert(fd >= 0);
2594
2595         r = dup2(fd, STDIN_FILENO);
2596         s = dup2(fd, STDOUT_FILENO);
2597         t = dup2(fd, STDERR_FILENO);
2598
2599         if (fd >= 3)
2600                 close_nointr_nofail(fd);
2601
2602         if (r < 0 || s < 0 || t < 0)
2603                 return -errno;
2604
2605         return 0;
2606 }
2607
2608 int make_null_stdio(void) {
2609         int null_fd;
2610
2611         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2612                 return -errno;
2613
2614         return make_stdio(null_fd);
2615 }
2616
2617 bool is_clean_exit(int code, int status) {
2618
2619         if (code == CLD_EXITED)
2620                 return status == 0;
2621
2622         /* If a daemon does not implement handlers for some of the
2623          * signals that's not considered an unclean shutdown */
2624         if (code == CLD_KILLED)
2625                 return
2626                         status == SIGHUP ||
2627                         status == SIGINT ||
2628                         status == SIGTERM ||
2629                         status == SIGPIPE;
2630
2631         return false;
2632 }
2633
2634 bool is_clean_exit_lsb(int code, int status) {
2635
2636         if (is_clean_exit(code, status))
2637                 return true;
2638
2639         return
2640                 code == CLD_EXITED &&
2641                 (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
2642 }
2643
2644 bool is_device_path(const char *path) {
2645
2646         /* Returns true on paths that refer to a device, either in
2647          * sysfs or in /dev */
2648
2649         return
2650                 path_startswith(path, "/dev/") ||
2651                 path_startswith(path, "/sys/");
2652 }
2653
2654 int dir_is_empty(const char *path) {
2655         DIR *d;
2656         int r;
2657         struct dirent buf, *de;
2658
2659         if (!(d = opendir(path)))
2660                 return -errno;
2661
2662         for (;;) {
2663                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2664                         r = -r;
2665                         break;
2666                 }
2667
2668                 if (!de) {
2669                         r = 1;
2670                         break;
2671                 }
2672
2673                 if (!ignore_file(de->d_name)) {
2674                         r = 0;
2675                         break;
2676                 }
2677         }
2678
2679         closedir(d);
2680         return r;
2681 }
2682
2683 unsigned long long random_ull(void) {
2684         int fd;
2685         uint64_t ull;
2686         ssize_t r;
2687
2688         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2689                 goto fallback;
2690
2691         r = loop_read(fd, &ull, sizeof(ull), true);
2692         close_nointr_nofail(fd);
2693
2694         if (r != sizeof(ull))
2695                 goto fallback;
2696
2697         return ull;
2698
2699 fallback:
2700         return random() * RAND_MAX + random();
2701 }
2702
2703 void rename_process(const char name[8]) {
2704         assert(name);
2705
2706         prctl(PR_SET_NAME, name);
2707
2708         /* This is a like a poor man's setproctitle(). The string
2709          * passed should fit in 7 chars (i.e. the length of
2710          * "systemd") */
2711
2712         if (program_invocation_name)
2713                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2714 }
2715
2716 void sigset_add_many(sigset_t *ss, ...) {
2717         va_list ap;
2718         int sig;
2719
2720         assert(ss);
2721
2722         va_start(ap, ss);
2723         while ((sig = va_arg(ap, int)) > 0)
2724                 assert_se(sigaddset(ss, sig) == 0);
2725         va_end(ap);
2726 }
2727
2728 char* gethostname_malloc(void) {
2729         struct utsname u;
2730
2731         assert_se(uname(&u) >= 0);
2732
2733         if (u.nodename[0])
2734                 return strdup(u.nodename);
2735
2736         return strdup(u.sysname);
2737 }
2738
2739 char* getlogname_malloc(void) {
2740         uid_t uid;
2741         long bufsize;
2742         char *buf, *name;
2743         struct passwd pwbuf, *pw = NULL;
2744         struct stat st;
2745
2746         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2747                 uid = st.st_uid;
2748         else
2749                 uid = getuid();
2750
2751         /* Shortcut things to avoid NSS lookups */
2752         if (uid == 0)
2753                 return strdup("root");
2754
2755         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2756                 bufsize = 4096;
2757
2758         if (!(buf = malloc(bufsize)))
2759                 return NULL;
2760
2761         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2762                 name = strdup(pw->pw_name);
2763                 free(buf);
2764                 return name;
2765         }
2766
2767         free(buf);
2768
2769         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2770                 return NULL;
2771
2772         return name;
2773 }
2774
2775 int getttyname_malloc(char **r) {
2776         char path[PATH_MAX], *p, *c;
2777         int k;
2778
2779         assert(r);
2780
2781         if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2782                 return -k;
2783
2784         char_array_0(path);
2785
2786         p = path;
2787         if (startswith(path, "/dev/"))
2788                 p += 5;
2789
2790         if (!(c = strdup(p)))
2791                 return -ENOMEM;
2792
2793         *r = c;
2794         return 0;
2795 }
2796
2797 static int rm_rf_children(int fd, bool only_dirs) {
2798         DIR *d;
2799         int ret = 0;
2800
2801         assert(fd >= 0);
2802
2803         /* This returns the first error we run into, but nevertheless
2804          * tries to go on */
2805
2806         if (!(d = fdopendir(fd))) {
2807                 close_nointr_nofail(fd);
2808
2809                 return errno == ENOENT ? 0 : -errno;
2810         }
2811
2812         for (;;) {
2813                 struct dirent buf, *de;
2814                 bool is_dir;
2815                 int r;
2816
2817                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2818                         if (ret == 0)
2819                                 ret = -r;
2820                         break;
2821                 }
2822
2823                 if (!de)
2824                         break;
2825
2826                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2827                         continue;
2828
2829                 if (de->d_type == DT_UNKNOWN) {
2830                         struct stat st;
2831
2832                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2833                                 if (ret == 0 && errno != ENOENT)
2834                                         ret = -errno;
2835                                 continue;
2836                         }
2837
2838                         is_dir = S_ISDIR(st.st_mode);
2839                 } else
2840                         is_dir = de->d_type == DT_DIR;
2841
2842                 if (is_dir) {
2843                         int subdir_fd;
2844
2845                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2846                                 if (ret == 0 && errno != ENOENT)
2847                                         ret = -errno;
2848                                 continue;
2849                         }
2850
2851                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2852                                 if (ret == 0)
2853                                         ret = r;
2854                         }
2855
2856                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2857                                 if (ret == 0 && errno != ENOENT)
2858                                         ret = -errno;
2859                         }
2860                 } else  if (!only_dirs) {
2861
2862                         if (unlinkat(fd, de->d_name, 0) < 0) {
2863                                 if (ret == 0 && errno != ENOENT)
2864                                         ret = -errno;
2865                         }
2866                 }
2867         }
2868
2869         closedir(d);
2870
2871         return ret;
2872 }
2873
2874 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2875         int fd;
2876         int r;
2877
2878         assert(path);
2879
2880         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2881
2882                 if (errno != ENOTDIR)
2883                         return -errno;
2884
2885                 if (delete_root && !only_dirs)
2886                         if (unlink(path) < 0)
2887                                 return -errno;
2888
2889                 return 0;
2890         }
2891
2892         r = rm_rf_children(fd, only_dirs);
2893
2894         if (delete_root)
2895                 if (rmdir(path) < 0) {
2896                         if (r == 0)
2897                                 r = -errno;
2898                 }
2899
2900         return r;
2901 }
2902
2903 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2904         assert(path);
2905
2906         /* Under the assumption that we are running privileged we
2907          * first change the access mode and only then hand out
2908          * ownership to avoid a window where access is too open. */
2909
2910         if (chmod(path, mode) < 0)
2911                 return -errno;
2912
2913         if (chown(path, uid, gid) < 0)
2914                 return -errno;
2915
2916         return 0;
2917 }
2918
2919 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2920         cpu_set_t *r;
2921         unsigned n = 1024;
2922
2923         /* Allocates the cpuset in the right size */
2924
2925         for (;;) {
2926                 if (!(r = CPU_ALLOC(n)))
2927                         return NULL;
2928
2929                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2930                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2931
2932                         if (ncpus)
2933                                 *ncpus = n;
2934
2935                         return r;
2936                 }
2937
2938                 CPU_FREE(r);
2939
2940                 if (errno != EINVAL)
2941                         return NULL;
2942
2943                 n *= 2;
2944         }
2945 }
2946
2947 void status_vprintf(const char *format, va_list ap) {
2948         char *s = NULL;
2949         int fd = -1;
2950
2951         assert(format);
2952
2953         /* This independent of logging, as status messages are
2954          * optional and go exclusively to the console. */
2955
2956         if (vasprintf(&s, format, ap) < 0)
2957                 goto finish;
2958
2959         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2960                 goto finish;
2961
2962         write(fd, s, strlen(s));
2963
2964 finish:
2965         free(s);
2966
2967         if (fd >= 0)
2968                 close_nointr_nofail(fd);
2969 }
2970
2971 void status_printf(const char *format, ...) {
2972         va_list ap;
2973
2974         assert(format);
2975
2976         va_start(ap, format);
2977         status_vprintf(format, ap);
2978         va_end(ap);
2979 }
2980
2981 void status_welcome(void) {
2982
2983 #if defined(TARGET_FEDORA)
2984         char *r;
2985
2986         if (read_one_line_file("/etc/system-release", &r) < 0)
2987                 return;
2988
2989         truncate_nl(r);
2990
2991         /* This tries to mimic the color magic the old Red Hat sysinit
2992          * script did. */
2993
2994         if (startswith(r, "Red Hat"))
2995                 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2996         else if (startswith(r, "Fedora"))
2997                 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2998         else
2999                 status_printf("Welcome to %s!\n", r);
3000
3001         free(r);
3002
3003 #elif defined(TARGET_SUSE)
3004         char *r;
3005
3006         if (read_one_line_file("/etc/SuSE-release", &r) < 0)
3007                 return;
3008
3009         truncate_nl(r);
3010
3011         status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
3012         free(r);
3013
3014 #elif defined(TARGET_GENTOO)
3015         char *r;
3016
3017         if (read_one_line_file("/etc/gentoo-release", &r) < 0)
3018                 return;
3019
3020         truncate_nl(r);
3021
3022         status_printf("Welcome to \x1B[1;34m%s\x1B[0m!\n", r); /* Light Blue for Gentoo */
3023
3024         free(r);
3025
3026 #elif defined(TARGET_DEBIAN)
3027         char *r;
3028
3029         if (read_one_line_file("/etc/debian_version", &r) < 0)
3030                 return;
3031
3032         truncate_nl(r);
3033
3034         status_printf("Welcome to Debian \x1B[1;31m%s\x1B[0m!\n", r); /* Light Red for Debian */
3035
3036         free(r);
3037 #elif defined(TARGET_UBUNTU)
3038         char *desc = NULL;
3039         char *codename = NULL;
3040
3041         if (parse_env_file("/etc/lsb-release", NEWLINE,
3042                 "DISTRIB_DESCRIPTION", &desc,
3043                 "DISTRIB_CODENAME", &codename, NULL) < 0)
3044                 return;
3045         if (desc && codename)
3046                 /* Light Red for Ubuntu */
3047                 status_printf("Welcome to \x1B[1;31m%s\x1B[0m (%s)\n",
3048                         desc, codename);
3049         free(desc);
3050         free(codename);
3051 #elif defined(TARGET_ARCH)
3052         status_printf("Welcome to \x1B[1;36mArch Linux\x1B[0m!\n"); /* Cyan for Arch */
3053 #else
3054 #warning "You probably should add a welcome text logic here."
3055 #endif
3056 }
3057
3058 char *replace_env(const char *format, char **env) {
3059         enum {
3060                 WORD,
3061                 CURLY,
3062                 VARIABLE
3063         } state = WORD;
3064
3065         const char *e, *word = format;
3066         char *r = NULL, *k;
3067
3068         assert(format);
3069
3070         for (e = format; *e; e ++) {
3071
3072                 switch (state) {
3073
3074                 case WORD:
3075                         if (*e == '$')
3076                                 state = CURLY;
3077                         break;
3078
3079                 case CURLY:
3080                         if (*e == '{') {
3081                                 if (!(k = strnappend(r, word, e-word-1)))
3082                                         goto fail;
3083
3084                                 free(r);
3085                                 r = k;
3086
3087                                 word = e-1;
3088                                 state = VARIABLE;
3089
3090                         } else if (*e == '$') {
3091                                 if (!(k = strnappend(r, word, e-word)))
3092                                         goto fail;
3093
3094                                 free(r);
3095                                 r = k;
3096
3097                                 word = e+1;
3098                                 state = WORD;
3099                         } else
3100                                 state = WORD;
3101                         break;
3102
3103                 case VARIABLE:
3104                         if (*e == '}') {
3105                                 const char *t;
3106
3107                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3108                                         t = "";
3109
3110                                 if (!(k = strappend(r, t)))
3111                                         goto fail;
3112
3113                                 free(r);
3114                                 r = k;
3115
3116                                 word = e+1;
3117                                 state = WORD;
3118                         }
3119                         break;
3120                 }
3121         }
3122
3123         if (!(k = strnappend(r, word, e-word)))
3124                 goto fail;
3125
3126         free(r);
3127         return k;
3128
3129 fail:
3130         free(r);
3131         return NULL;
3132 }
3133
3134 char **replace_env_argv(char **argv, char **env) {
3135         char **r, **i;
3136         unsigned k = 0, l = 0;
3137
3138         l = strv_length(argv);
3139
3140         if (!(r = new(char*, l+1)))
3141                 return NULL;
3142
3143         STRV_FOREACH(i, argv) {
3144
3145                 /* If $FOO appears as single word, replace it by the split up variable */
3146                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3147                         char *e;
3148                         char **w, **m;
3149                         unsigned q;
3150
3151                         if ((e = strv_env_get(env, *i+1))) {
3152
3153                                 if (!(m = strv_split_quoted(e))) {
3154                                         r[k] = NULL;
3155                                         strv_free(r);
3156                                         return NULL;
3157                                 }
3158                         } else
3159                                 m = NULL;
3160
3161                         q = strv_length(m);
3162                         l = l + q - 1;
3163
3164                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3165                                 r[k] = NULL;
3166                                 strv_free(r);
3167                                 strv_free(m);
3168                                 return NULL;
3169                         }
3170
3171                         r = w;
3172                         if (m) {
3173                                 memcpy(r + k, m, q * sizeof(char*));
3174                                 free(m);
3175                         }
3176
3177                         k += q;
3178                         continue;
3179                 }
3180
3181                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3182                 if (!(r[k++] = replace_env(*i, env))) {
3183                         strv_free(r);
3184                         return NULL;
3185                 }
3186         }
3187
3188         r[k] = NULL;
3189         return r;
3190 }
3191
3192 int columns(void) {
3193         static __thread int parsed_columns = 0;
3194         const char *e;
3195
3196         if (parsed_columns > 0)
3197                 return parsed_columns;
3198
3199         if ((e = getenv("COLUMNS")))
3200                 parsed_columns = atoi(e);
3201
3202         if (parsed_columns <= 0) {
3203                 struct winsize ws;
3204                 zero(ws);
3205
3206                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3207                         parsed_columns = ws.ws_col;
3208         }
3209
3210         if (parsed_columns <= 0)
3211                 parsed_columns = 80;
3212
3213         return parsed_columns;
3214 }
3215
3216 int running_in_chroot(void) {
3217         struct stat a, b;
3218
3219         zero(a);
3220         zero(b);
3221
3222         /* Only works as root */
3223
3224         if (stat("/proc/1/root", &a) < 0)
3225                 return -errno;
3226
3227         if (stat("/", &b) < 0)
3228                 return -errno;
3229
3230         return
3231                 a.st_dev != b.st_dev ||
3232                 a.st_ino != b.st_ino;
3233 }
3234
3235 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3236         size_t l, x;
3237         char *r;
3238
3239         assert(s);
3240         assert(percent <= 100);
3241         assert(length >= 3);
3242
3243         l = strlen(s);
3244
3245         if (l <= 3 || l <= length)
3246                 return strdup(s);
3247
3248         if (!(r = new0(char, length+1)))
3249                 return r;
3250
3251         x = (length * percent) / 100;
3252
3253         if (x > length - 3)
3254                 x = length - 3;
3255
3256         memcpy(r, s, x);
3257         r[x] = '.';
3258         r[x+1] = '.';
3259         r[x+2] = '.';
3260         memcpy(r + x + 3,
3261                s + l - (length - x - 3),
3262                length - x - 3);
3263
3264         return r;
3265 }
3266
3267 int touch(const char *path) {
3268         int fd;
3269
3270         assert(path);
3271
3272         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3273                 return -errno;
3274
3275         close_nointr_nofail(fd);
3276         return 0;
3277 }
3278
3279 char *unquote(const char *s, const char* quotes) {
3280         size_t l;
3281         assert(s);
3282
3283         if ((l = strlen(s)) < 2)
3284                 return strdup(s);
3285
3286         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3287                 return strndup(s+1, l-2);
3288
3289         return strdup(s);
3290 }
3291
3292 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3293         assert(pid >= 1);
3294         assert(status);
3295
3296         for (;;) {
3297                 zero(*status);
3298
3299                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3300
3301                         if (errno == EINTR)
3302                                 continue;
3303
3304                         return -errno;
3305                 }
3306
3307                 return 0;
3308         }
3309 }
3310
3311 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3312         int r;
3313         siginfo_t status;
3314
3315         assert(name);
3316         assert(pid > 1);
3317
3318         if ((r = wait_for_terminate(pid, &status)) < 0) {
3319                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3320                 return r;
3321         }
3322
3323         if (status.si_code == CLD_EXITED) {
3324                 if (status.si_status != 0) {
3325                         log_warning("%s failed with error code %i.", name, status.si_status);
3326                         return -EPROTO;
3327                 }
3328
3329                 log_debug("%s succeeded.", name);
3330                 return 0;
3331
3332         } else if (status.si_code == CLD_KILLED ||
3333                    status.si_code == CLD_DUMPED) {
3334
3335                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3336                 return -EPROTO;
3337         }
3338
3339         log_warning("%s failed due to unknown reason.", name);
3340         return -EPROTO;
3341
3342 }
3343
3344 void freeze(void) {
3345         for (;;)
3346                 pause();
3347 }
3348
3349 bool null_or_empty(struct stat *st) {
3350         assert(st);
3351
3352         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3353                 return true;
3354
3355         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3356                 return true;
3357
3358         return false;
3359 }
3360
3361 DIR *xopendirat(int fd, const char *name) {
3362         return fdopendir(openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
3363 }
3364
3365 int signal_from_string_try_harder(const char *s) {
3366         int signo;
3367         assert(s);
3368
3369         if ((signo = signal_from_string(s)) <= 0)
3370                 if (startswith(s, "SIG"))
3371                         return signal_from_string(s+3);
3372
3373         return signo;
3374 }
3375
3376 int ask_password_tty(const char *message, usec_t until, const char *flag_file, char **_passphrase) {
3377         struct termios old_termios, new_termios;
3378         char passphrase[LINE_MAX];
3379         size_t p = 0;
3380         int r, ttyfd = -1, notify = -1;
3381         struct pollfd pollfd[2];
3382         bool reset_tty = false;
3383         enum {
3384                 POLL_TTY,
3385                 POLL_INOTIFY
3386         };
3387
3388         assert(message);
3389         assert(_passphrase);
3390
3391         if (flag_file) {
3392                 if ((notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) {
3393                         r = -errno;
3394                         goto finish;
3395                 }
3396
3397                 if (inotify_add_watch(notify, flag_file, IN_ATTRIB /* for the link count */) < 0) {
3398                         r = -errno;
3399                         goto finish;
3400                 }
3401         }
3402
3403         if ((ttyfd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) >= 0) {
3404
3405                 if (tcgetattr(ttyfd, &old_termios) < 0) {
3406                         r = -errno;
3407                         goto finish;
3408                 }
3409
3410                 loop_write(ttyfd, "\x1B[1m", 4, false);
3411                 loop_write(ttyfd, message, strlen(message), false);
3412                 loop_write(ttyfd, ": ", 2, false);
3413                 loop_write(ttyfd, "\x1B[0m", 4, false);
3414
3415                 new_termios = old_termios;
3416                 new_termios.c_lflag &= ~(ICANON|ECHO);
3417                 new_termios.c_cc[VMIN] = 1;
3418                 new_termios.c_cc[VTIME] = 0;
3419
3420                 if (tcsetattr(ttyfd, TCSADRAIN, &new_termios) < 0) {
3421                         r = -errno;
3422                         goto finish;
3423                 }
3424
3425                 reset_tty = true;
3426         }
3427
3428         zero(pollfd);
3429
3430         pollfd[POLL_TTY].fd = ttyfd >= 0 ? ttyfd : STDIN_FILENO;
3431         pollfd[POLL_TTY].events = POLLIN;
3432         pollfd[POLL_INOTIFY].fd = notify;
3433         pollfd[POLL_INOTIFY].events = POLLIN;
3434
3435         for (;;) {
3436                 char c;
3437                 int sleep_for = -1, k;
3438                 ssize_t n;
3439
3440                 if (until > 0) {
3441                         usec_t y;
3442
3443                         y = now(CLOCK_MONOTONIC);
3444
3445                         if (y > until) {
3446                                 r = -ETIMEDOUT;
3447                                 goto finish;
3448                         }
3449
3450                         sleep_for = (int) ((until - y) / USEC_PER_MSEC);
3451                 }
3452
3453                 if (flag_file)
3454                         if (access(flag_file, F_OK) < 0) {
3455                                 r = -errno;
3456                                 goto finish;
3457                         }
3458
3459                 if ((k = poll(pollfd, notify > 0 ? 2 : 1, sleep_for)) < 0) {
3460
3461                         if (errno == EINTR)
3462                                 continue;
3463
3464                         r = -errno;
3465                         goto finish;
3466                 } else if (k == 0) {
3467                         r = -ETIMEDOUT;
3468                         goto finish;
3469                 }
3470
3471                 if (notify > 0 && pollfd[POLL_INOTIFY].revents != 0)
3472                         flush_fd(notify);
3473
3474                 if (pollfd[POLL_TTY].revents == 0)
3475                         continue;
3476
3477                 if ((n = read(ttyfd >= 0 ? ttyfd : STDIN_FILENO, &c, 1)) < 0) {
3478
3479                         if (errno == EINTR || errno == EAGAIN)
3480                                 continue;
3481
3482                         r = -errno;
3483                         goto finish;
3484
3485                 } else if (n == 0)
3486                         break;
3487
3488                 if (c == '\n')
3489                         break;
3490                 else if (c == 21) {
3491
3492                         while (p > 0) {
3493                                 p--;
3494
3495                                 if (ttyfd >= 0)
3496                                         loop_write(ttyfd, "\b \b", 3, false);
3497                         }
3498
3499                 } else if (c == '\b' || c == 127) {
3500                         if (p > 0) {
3501                                 p--;
3502
3503                                 if (ttyfd >= 0)
3504                                         loop_write(ttyfd, "\b \b", 3, false);
3505                         }
3506                 } else {
3507                         passphrase[p++] = c;
3508
3509                         if (ttyfd >= 0)
3510                                 loop_write(ttyfd, "*", 1, false);
3511                 }
3512         }
3513
3514         if (ttyfd >= 0)
3515                 loop_write(ttyfd, "\n", 1, false);
3516
3517         passphrase[p] = 0;
3518
3519         if (!(*_passphrase = strdup(passphrase))) {
3520                 r = -ENOMEM;
3521                 goto finish;
3522         }
3523
3524         r = 0;
3525
3526 finish:
3527         if (notify >= 0)
3528                 close_nointr_nofail(notify);
3529
3530         if (ttyfd >= 0) {
3531                 if (reset_tty)
3532                         tcsetattr(ttyfd, TCSADRAIN, &old_termios);
3533
3534                 close_nointr_nofail(ttyfd);
3535         }
3536
3537         return r;
3538 }
3539
3540 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3541
3542         assert(f);
3543         assert(name);
3544         assert(t);
3545
3546         if (!dual_timestamp_is_set(t))
3547                 return;
3548
3549         fprintf(f, "%s=%llu %llu\n",
3550                 name,
3551                 (unsigned long long) t->realtime,
3552                 (unsigned long long) t->monotonic);
3553 }
3554
3555 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3556         unsigned long long a, b;
3557
3558         assert(value);
3559         assert(t);
3560
3561         if (sscanf(value, "%lli %llu", &a, &b) != 2)
3562                 log_debug("Failed to parse finish timestamp value %s", value);
3563         else {
3564                 t->realtime = a;
3565                 t->monotonic = b;
3566         }
3567 }
3568
3569 char *fstab_node_to_udev_node(const char *p) {
3570         char *dn, *t, *u;
3571         int r;
3572
3573         /* FIXME: to follow udev's logic 100% we need to leave valid
3574          * UTF8 chars unescaped */
3575
3576         if (startswith(p, "LABEL=")) {
3577
3578                 if (!(u = unquote(p+6, "\"\'")))
3579                         return NULL;
3580
3581                 t = xescape(u, "/ ");
3582                 free(u);
3583
3584                 if (!t)
3585                         return NULL;
3586
3587                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3588                 free(t);
3589
3590                 if (r < 0)
3591                         return NULL;
3592
3593                 return dn;
3594         }
3595
3596         if (startswith(p, "UUID=")) {
3597
3598                 if (!(u = unquote(p+5, "\"\'")))
3599                         return NULL;
3600
3601                 t = xescape(u, "/ ");
3602                 free(u);
3603
3604                 if (!t)
3605                         return NULL;
3606
3607                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", ascii_strlower(t));
3608                 free(t);
3609
3610                 if (r < 0)
3611                         return NULL;
3612
3613                 return dn;
3614         }
3615
3616         return strdup(p);
3617 }
3618
3619 void filter_environ(const char *prefix) {
3620         int i, j;
3621         assert(prefix);
3622
3623         if (!environ)
3624                 return;
3625
3626         for (i = 0, j = 0; environ[i]; i++) {
3627
3628                 if (startswith(environ[i], prefix))
3629                         continue;
3630
3631                 environ[j++] = environ[i];
3632         }
3633
3634         environ[j] = NULL;
3635 }
3636
3637 static const char *const ioprio_class_table[] = {
3638         [IOPRIO_CLASS_NONE] = "none",
3639         [IOPRIO_CLASS_RT] = "realtime",
3640         [IOPRIO_CLASS_BE] = "best-effort",
3641         [IOPRIO_CLASS_IDLE] = "idle"
3642 };
3643
3644 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3645
3646 static const char *const sigchld_code_table[] = {
3647         [CLD_EXITED] = "exited",
3648         [CLD_KILLED] = "killed",
3649         [CLD_DUMPED] = "dumped",
3650         [CLD_TRAPPED] = "trapped",
3651         [CLD_STOPPED] = "stopped",
3652         [CLD_CONTINUED] = "continued",
3653 };
3654
3655 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3656
3657 static const char *const log_facility_table[LOG_NFACILITIES] = {
3658         [LOG_FAC(LOG_KERN)] = "kern",
3659         [LOG_FAC(LOG_USER)] = "user",
3660         [LOG_FAC(LOG_MAIL)] = "mail",
3661         [LOG_FAC(LOG_DAEMON)] = "daemon",
3662         [LOG_FAC(LOG_AUTH)] = "auth",
3663         [LOG_FAC(LOG_SYSLOG)] = "syslog",
3664         [LOG_FAC(LOG_LPR)] = "lpr",
3665         [LOG_FAC(LOG_NEWS)] = "news",
3666         [LOG_FAC(LOG_UUCP)] = "uucp",
3667         [LOG_FAC(LOG_CRON)] = "cron",
3668         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3669         [LOG_FAC(LOG_FTP)] = "ftp",
3670         [LOG_FAC(LOG_LOCAL0)] = "local0",
3671         [LOG_FAC(LOG_LOCAL1)] = "local1",
3672         [LOG_FAC(LOG_LOCAL2)] = "local2",
3673         [LOG_FAC(LOG_LOCAL3)] = "local3",
3674         [LOG_FAC(LOG_LOCAL4)] = "local4",
3675         [LOG_FAC(LOG_LOCAL5)] = "local5",
3676         [LOG_FAC(LOG_LOCAL6)] = "local6",
3677         [LOG_FAC(LOG_LOCAL7)] = "local7"
3678 };
3679
3680 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3681
3682 static const char *const log_level_table[] = {
3683         [LOG_EMERG] = "emerg",
3684         [LOG_ALERT] = "alert",
3685         [LOG_CRIT] = "crit",
3686         [LOG_ERR] = "err",
3687         [LOG_WARNING] = "warning",
3688         [LOG_NOTICE] = "notice",
3689         [LOG_INFO] = "info",
3690         [LOG_DEBUG] = "debug"
3691 };
3692
3693 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3694
3695 static const char* const sched_policy_table[] = {
3696         [SCHED_OTHER] = "other",
3697         [SCHED_BATCH] = "batch",
3698         [SCHED_IDLE] = "idle",
3699         [SCHED_FIFO] = "fifo",
3700         [SCHED_RR] = "rr"
3701 };
3702
3703 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3704
3705 static const char* const rlimit_table[] = {
3706         [RLIMIT_CPU] = "LimitCPU",
3707         [RLIMIT_FSIZE] = "LimitFSIZE",
3708         [RLIMIT_DATA] = "LimitDATA",
3709         [RLIMIT_STACK] = "LimitSTACK",
3710         [RLIMIT_CORE] = "LimitCORE",
3711         [RLIMIT_RSS] = "LimitRSS",
3712         [RLIMIT_NOFILE] = "LimitNOFILE",
3713         [RLIMIT_AS] = "LimitAS",
3714         [RLIMIT_NPROC] = "LimitNPROC",
3715         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3716         [RLIMIT_LOCKS] = "LimitLOCKS",
3717         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3718         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3719         [RLIMIT_NICE] = "LimitNICE",
3720         [RLIMIT_RTPRIO] = "LimitRTPRIO",
3721         [RLIMIT_RTTIME] = "LimitRTTIME"
3722 };
3723
3724 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3725
3726 static const char* const ip_tos_table[] = {
3727         [IPTOS_LOWDELAY] = "low-delay",
3728         [IPTOS_THROUGHPUT] = "throughput",
3729         [IPTOS_RELIABILITY] = "reliability",
3730         [IPTOS_LOWCOST] = "low-cost",
3731 };
3732
3733 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3734
3735 static const char *const signal_table[] = {
3736         [SIGHUP] = "HUP",
3737         [SIGINT] = "INT",
3738         [SIGQUIT] = "QUIT",
3739         [SIGILL] = "ILL",
3740         [SIGTRAP] = "TRAP",
3741         [SIGABRT] = "ABRT",
3742         [SIGBUS] = "BUS",
3743         [SIGFPE] = "FPE",
3744         [SIGKILL] = "KILL",
3745         [SIGUSR1] = "USR1",
3746         [SIGSEGV] = "SEGV",
3747         [SIGUSR2] = "USR2",
3748         [SIGPIPE] = "PIPE",
3749         [SIGALRM] = "ALRM",
3750         [SIGTERM] = "TERM",
3751 #ifdef SIGSTKFLT
3752         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
3753 #endif
3754         [SIGCHLD] = "CHLD",
3755         [SIGCONT] = "CONT",
3756         [SIGSTOP] = "STOP",
3757         [SIGTSTP] = "TSTP",
3758         [SIGTTIN] = "TTIN",
3759         [SIGTTOU] = "TTOU",
3760         [SIGURG] = "URG",
3761         [SIGXCPU] = "XCPU",
3762         [SIGXFSZ] = "XFSZ",
3763         [SIGVTALRM] = "VTALRM",
3764         [SIGPROF] = "PROF",
3765         [SIGWINCH] = "WINCH",
3766         [SIGIO] = "IO",
3767         [SIGPWR] = "PWR",
3768         [SIGSYS] = "SYS"
3769 };
3770
3771 DEFINE_STRING_TABLE_LOOKUP(signal, int);