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