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