chiark / gitweb /
loginctl: implement missing kill verb
[elogind.git] / src / util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <syslog.h>
30 #include <sched.h>
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <dirent.h>
37 #include <sys/ioctl.h>
38 #include <linux/vt.h>
39 #include <linux/tiocl.h>
40 #include <termios.h>
41 #include <stdarg.h>
42 #include <sys/inotify.h>
43 #include <sys/poll.h>
44 #include <libgen.h>
45 #include <ctype.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
48 #include <pwd.h>
49 #include <netinet/ip.h>
50 #include <linux/kd.h>
51 #include <dlfcn.h>
52 #include <sys/wait.h>
53 #include <sys/capability.h>
54 #include <sys/time.h>
55 #include <linux/rtc.h>
56 #include <glob.h>
57
58 #include "macro.h"
59 #include "util.h"
60 #include "ioprio.h"
61 #include "missing.h"
62 #include "log.h"
63 #include "strv.h"
64 #include "label.h"
65 #include "exit-status.h"
66 #include "hashmap.h"
67
68 int saved_argc = 0;
69 char **saved_argv = NULL;
70
71 size_t page_size(void) {
72         static __thread size_t pgsz = 0;
73         long r;
74
75         if (pgsz)
76                 return pgsz;
77
78         assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
79
80         pgsz = (size_t) r;
81
82         return pgsz;
83 }
84
85 bool streq_ptr(const char *a, const char *b) {
86
87         /* Like streq(), but tries to make sense of NULL pointers */
88
89         if (a && b)
90                 return streq(a, b);
91
92         if (!a && !b)
93                 return true;
94
95         return false;
96 }
97
98 usec_t now(clockid_t clock_id) {
99         struct timespec ts;
100
101         assert_se(clock_gettime(clock_id, &ts) == 0);
102
103         return timespec_load(&ts);
104 }
105
106 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
107         assert(ts);
108
109         ts->realtime = now(CLOCK_REALTIME);
110         ts->monotonic = now(CLOCK_MONOTONIC);
111
112         return ts;
113 }
114
115 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
116         int64_t delta;
117         assert(ts);
118
119         ts->realtime = u;
120
121         if (u == 0)
122                 ts->monotonic = 0;
123         else {
124                 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
125
126                 ts->monotonic = now(CLOCK_MONOTONIC);
127
128                 if ((int64_t) ts->monotonic > delta)
129                         ts->monotonic -= delta;
130                 else
131                         ts->monotonic = 0;
132         }
133
134         return ts;
135 }
136
137 usec_t timespec_load(const struct timespec *ts) {
138         assert(ts);
139
140         return
141                 (usec_t) ts->tv_sec * USEC_PER_SEC +
142                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
143 }
144
145 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
146         assert(ts);
147
148         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
149         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
150
151         return ts;
152 }
153
154 usec_t timeval_load(const struct timeval *tv) {
155         assert(tv);
156
157         return
158                 (usec_t) tv->tv_sec * USEC_PER_SEC +
159                 (usec_t) tv->tv_usec;
160 }
161
162 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
163         assert(tv);
164
165         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
166         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
167
168         return tv;
169 }
170
171 bool endswith(const char *s, const char *postfix) {
172         size_t sl, pl;
173
174         assert(s);
175         assert(postfix);
176
177         sl = strlen(s);
178         pl = strlen(postfix);
179
180         if (pl == 0)
181                 return true;
182
183         if (sl < pl)
184                 return false;
185
186         return memcmp(s + sl - pl, postfix, pl) == 0;
187 }
188
189 bool startswith(const char *s, const char *prefix) {
190         size_t sl, pl;
191
192         assert(s);
193         assert(prefix);
194
195         sl = strlen(s);
196         pl = strlen(prefix);
197
198         if (pl == 0)
199                 return true;
200
201         if (sl < pl)
202                 return false;
203
204         return memcmp(s, prefix, pl) == 0;
205 }
206
207 bool startswith_no_case(const char *s, const char *prefix) {
208         size_t sl, pl;
209         unsigned i;
210
211         assert(s);
212         assert(prefix);
213
214         sl = strlen(s);
215         pl = strlen(prefix);
216
217         if (pl == 0)
218                 return true;
219
220         if (sl < pl)
221                 return false;
222
223         for(i = 0; i < pl; ++i) {
224                 if (tolower(s[i]) != tolower(prefix[i]))
225                         return false;
226         }
227
228         return true;
229 }
230
231 bool first_word(const char *s, const char *word) {
232         size_t sl, wl;
233
234         assert(s);
235         assert(word);
236
237         sl = strlen(s);
238         wl = strlen(word);
239
240         if (sl < wl)
241                 return false;
242
243         if (wl == 0)
244                 return true;
245
246         if (memcmp(s, word, wl) != 0)
247                 return false;
248
249         return s[wl] == 0 ||
250                 strchr(WHITESPACE, s[wl]);
251 }
252
253 int close_nointr(int fd) {
254         assert(fd >= 0);
255
256         for (;;) {
257                 int r;
258
259                 r = close(fd);
260                 if (r >= 0)
261                         return r;
262
263                 if (errno != EINTR)
264                         return -errno;
265         }
266 }
267
268 void close_nointr_nofail(int fd) {
269         int saved_errno = errno;
270
271         /* like close_nointr() but cannot fail, and guarantees errno
272          * is unchanged */
273
274         assert_se(close_nointr(fd) == 0);
275
276         errno = saved_errno;
277 }
278
279 void close_many(const int fds[], unsigned n_fd) {
280         unsigned i;
281
282         for (i = 0; i < n_fd; i++)
283                 close_nointr_nofail(fds[i]);
284 }
285
286 int parse_boolean(const char *v) {
287         assert(v);
288
289         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
290                 return 1;
291         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
292                 return 0;
293
294         return -EINVAL;
295 }
296
297 int parse_pid(const char *s, pid_t* ret_pid) {
298         unsigned long ul = 0;
299         pid_t pid;
300         int r;
301
302         assert(s);
303         assert(ret_pid);
304
305         if ((r = safe_atolu(s, &ul)) < 0)
306                 return r;
307
308         pid = (pid_t) ul;
309
310         if ((unsigned long) pid != ul)
311                 return -ERANGE;
312
313         if (pid <= 0)
314                 return -ERANGE;
315
316         *ret_pid = pid;
317         return 0;
318 }
319
320 int safe_atou(const char *s, unsigned *ret_u) {
321         char *x = NULL;
322         unsigned long l;
323
324         assert(s);
325         assert(ret_u);
326
327         errno = 0;
328         l = strtoul(s, &x, 0);
329
330         if (!x || *x || errno)
331                 return errno ? -errno : -EINVAL;
332
333         if ((unsigned long) (unsigned) l != l)
334                 return -ERANGE;
335
336         *ret_u = (unsigned) l;
337         return 0;
338 }
339
340 int safe_atoi(const char *s, int *ret_i) {
341         char *x = NULL;
342         long l;
343
344         assert(s);
345         assert(ret_i);
346
347         errno = 0;
348         l = strtol(s, &x, 0);
349
350         if (!x || *x || errno)
351                 return errno ? -errno : -EINVAL;
352
353         if ((long) (int) l != l)
354                 return -ERANGE;
355
356         *ret_i = (int) l;
357         return 0;
358 }
359
360 int safe_atollu(const char *s, long long unsigned *ret_llu) {
361         char *x = NULL;
362         unsigned long long l;
363
364         assert(s);
365         assert(ret_llu);
366
367         errno = 0;
368         l = strtoull(s, &x, 0);
369
370         if (!x || *x || errno)
371                 return errno ? -errno : -EINVAL;
372
373         *ret_llu = l;
374         return 0;
375 }
376
377 int safe_atolli(const char *s, long long int *ret_lli) {
378         char *x = NULL;
379         long long l;
380
381         assert(s);
382         assert(ret_lli);
383
384         errno = 0;
385         l = strtoll(s, &x, 0);
386
387         if (!x || *x || errno)
388                 return errno ? -errno : -EINVAL;
389
390         *ret_lli = l;
391         return 0;
392 }
393
394 /* Split a string into words. */
395 char *split(const char *c, size_t *l, const char *separator, char **state) {
396         char *current;
397
398         current = *state ? *state : (char*) c;
399
400         if (!*current || *c == 0)
401                 return NULL;
402
403         current += strspn(current, separator);
404         *l = strcspn(current, separator);
405         *state = current+*l;
406
407         return (char*) current;
408 }
409
410 /* Split a string into words, but consider strings enclosed in '' and
411  * "" as words even if they include spaces. */
412 char *split_quoted(const char *c, size_t *l, char **state) {
413         char *current, *e;
414         bool escaped = false;
415
416         current = *state ? *state : (char*) c;
417
418         if (!*current || *c == 0)
419                 return NULL;
420
421         current += strspn(current, WHITESPACE);
422
423         if (*current == '\'') {
424                 current ++;
425
426                 for (e = current; *e; e++) {
427                         if (escaped)
428                                 escaped = false;
429                         else if (*e == '\\')
430                                 escaped = true;
431                         else if (*e == '\'')
432                                 break;
433                 }
434
435                 *l = e-current;
436                 *state = *e == 0 ? e : e+1;
437         } else if (*current == '\"') {
438                 current ++;
439
440                 for (e = current; *e; e++) {
441                         if (escaped)
442                                 escaped = false;
443                         else if (*e == '\\')
444                                 escaped = true;
445                         else if (*e == '\"')
446                                 break;
447                 }
448
449                 *l = e-current;
450                 *state = *e == 0 ? e : e+1;
451         } else {
452                 for (e = current; *e; e++) {
453                         if (escaped)
454                                 escaped = false;
455                         else if (*e == '\\')
456                                 escaped = true;
457                         else if (strchr(WHITESPACE, *e))
458                                 break;
459                 }
460                 *l = e-current;
461                 *state = e;
462         }
463
464         return (char*) current;
465 }
466
467 char **split_path_and_make_absolute(const char *p) {
468         char **l;
469         assert(p);
470
471         if (!(l = strv_split(p, ":")))
472                 return NULL;
473
474         if (!strv_path_make_absolute_cwd(l)) {
475                 strv_free(l);
476                 return NULL;
477         }
478
479         return l;
480 }
481
482 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
483         int r;
484         FILE *f;
485         char fn[PATH_MAX], line[LINE_MAX], *p;
486         long unsigned ppid;
487
488         assert(pid > 0);
489         assert(_ppid);
490
491         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
492         char_array_0(fn);
493
494         if (!(f = fopen(fn, "re")))
495                 return -errno;
496
497         if (!(fgets(line, sizeof(line), f))) {
498                 r = -errno;
499                 fclose(f);
500                 return r;
501         }
502
503         fclose(f);
504
505         /* Let's skip the pid and comm fields. The latter is enclosed
506          * in () but does not escape any () in its value, so let's
507          * skip over it manually */
508
509         if (!(p = strrchr(line, ')')))
510                 return -EIO;
511
512         p++;
513
514         if (sscanf(p, " "
515                    "%*c "  /* state */
516                    "%lu ", /* ppid */
517                    &ppid) != 1)
518                 return -EIO;
519
520         if ((long unsigned) (pid_t) ppid != ppid)
521                 return -ERANGE;
522
523         *_ppid = (pid_t) ppid;
524
525         return 0;
526 }
527
528 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
529         int r;
530         FILE *f;
531         char fn[PATH_MAX], line[LINE_MAX], *p;
532
533         assert(pid > 0);
534         assert(st);
535
536         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
537         char_array_0(fn);
538
539         if (!(f = fopen(fn, "re")))
540                 return -errno;
541
542         if (!(fgets(line, sizeof(line), f))) {
543                 r = -errno;
544                 fclose(f);
545                 return r;
546         }
547
548         fclose(f);
549
550         /* Let's skip the pid and comm fields. The latter is enclosed
551          * in () but does not escape any () in its value, so let's
552          * skip over it manually */
553
554         if (!(p = strrchr(line, ')')))
555                 return -EIO;
556
557         p++;
558
559         if (sscanf(p, " "
560                    "%*c "  /* state */
561                    "%*d "  /* ppid */
562                    "%*d "  /* pgrp */
563                    "%*d "  /* session */
564                    "%*d "  /* tty_nr */
565                    "%*d "  /* tpgid */
566                    "%*u "  /* flags */
567                    "%*u "  /* minflt */
568                    "%*u "  /* cminflt */
569                    "%*u "  /* majflt */
570                    "%*u "  /* cmajflt */
571                    "%*u "  /* utime */
572                    "%*u "  /* stime */
573                    "%*d "  /* cutime */
574                    "%*d "  /* cstime */
575                    "%*d "  /* priority */
576                    "%*d "  /* nice */
577                    "%*d "  /* num_threads */
578                    "%*d "  /* itrealvalue */
579                    "%llu "  /* starttime */,
580                    st) != 1)
581                 return -EIO;
582
583         return 0;
584 }
585
586 int write_one_line_file(const char *fn, const char *line) {
587         FILE *f;
588         int r;
589
590         assert(fn);
591         assert(line);
592
593         if (!(f = fopen(fn, "we")))
594                 return -errno;
595
596         errno = 0;
597         if (fputs(line, f) < 0) {
598                 r = -errno;
599                 goto finish;
600         }
601
602         if (!endswith(line, "\n"))
603                 fputc('\n', f);
604
605         fflush(f);
606
607         if (ferror(f)) {
608                 if (errno != 0)
609                         r = -errno;
610                 else
611                         r = -EIO;
612         } else
613                 r = 0;
614
615 finish:
616         fclose(f);
617         return r;
618 }
619
620 int fchmod_umask(int fd, mode_t m) {
621         mode_t u;
622         int r;
623
624         u = umask(0777);
625         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
626         umask(u);
627
628         return r;
629 }
630
631 int write_one_line_file_atomic(const char *fn, const char *line) {
632         FILE *f;
633         int r;
634         char *p;
635
636         assert(fn);
637         assert(line);
638
639         r = fopen_temporary(fn, &f, &p);
640         if (r < 0)
641                 return r;
642
643         fchmod_umask(fileno(f), 0644);
644
645         errno = 0;
646         if (fputs(line, f) < 0) {
647                 r = -errno;
648                 goto finish;
649         }
650
651         if (!endswith(line, "\n"))
652                 fputc('\n', f);
653
654         fflush(f);
655
656         if (ferror(f)) {
657                 if (errno != 0)
658                         r = -errno;
659                 else
660                         r = -EIO;
661         } else {
662                 if (rename(p, fn) < 0)
663                         r = -errno;
664                 else
665                         r = 0;
666         }
667
668 finish:
669         if (r < 0)
670                 unlink(p);
671
672         fclose(f);
673         free(p);
674
675         return r;
676 }
677
678 int read_one_line_file(const char *fn, char **line) {
679         FILE *f;
680         int r;
681         char t[LINE_MAX], *c;
682
683         assert(fn);
684         assert(line);
685
686         if (!(f = fopen(fn, "re")))
687                 return -errno;
688
689         if (!(fgets(t, sizeof(t), f))) {
690                 r = -errno;
691                 goto finish;
692         }
693
694         if (!(c = strdup(t))) {
695                 r = -ENOMEM;
696                 goto finish;
697         }
698
699         truncate_nl(c);
700
701         *line = c;
702         r = 0;
703
704 finish:
705         fclose(f);
706         return r;
707 }
708
709 int read_full_file(const char *fn, char **contents, size_t *size) {
710         FILE *f;
711         int r;
712         size_t n, l;
713         char *buf = NULL;
714         struct stat st;
715
716         if (!(f = fopen(fn, "re")))
717                 return -errno;
718
719         if (fstat(fileno(f), &st) < 0) {
720                 r = -errno;
721                 goto finish;
722         }
723
724         /* Safety check */
725         if (st.st_size > 4*1024*1024) {
726                 r = -E2BIG;
727                 goto finish;
728         }
729
730         n = st.st_size > 0 ? st.st_size : LINE_MAX;
731         l = 0;
732
733         for (;;) {
734                 char *t;
735                 size_t k;
736
737                 if (!(t = realloc(buf, n+1))) {
738                         r = -ENOMEM;
739                         goto finish;
740                 }
741
742                 buf = t;
743                 k = fread(buf + l, 1, n - l, f);
744
745                 if (k <= 0) {
746                         if (ferror(f)) {
747                                 r = -errno;
748                                 goto finish;
749                         }
750
751                         break;
752                 }
753
754                 l += k;
755                 n *= 2;
756
757                 /* Safety check */
758                 if (n > 4*1024*1024) {
759                         r = -E2BIG;
760                         goto finish;
761                 }
762         }
763
764         if (buf)
765                 buf[l] = 0;
766         else if (!(buf = calloc(1, 1))) {
767                 r = -errno;
768                 goto finish;
769         }
770
771         *contents = buf;
772         buf = NULL;
773
774         if (size)
775                 *size = l;
776
777         r = 0;
778
779 finish:
780         fclose(f);
781         free(buf);
782
783         return r;
784 }
785
786 int parse_env_file(
787                 const char *fname,
788                 const char *separator, ...) {
789
790         int r = 0;
791         char *contents, *p;
792
793         assert(fname);
794         assert(separator);
795
796         if ((r = read_full_file(fname, &contents, NULL)) < 0)
797                 return r;
798
799         p = contents;
800         for (;;) {
801                 const char *key = NULL;
802
803                 p += strspn(p, separator);
804                 p += strspn(p, WHITESPACE);
805
806                 if (!*p)
807                         break;
808
809                 if (!strchr(COMMENTS, *p)) {
810                         va_list ap;
811                         char **value;
812
813                         va_start(ap, separator);
814                         while ((key = va_arg(ap, char *))) {
815                                 size_t n;
816                                 char *v;
817
818                                 value = va_arg(ap, char **);
819
820                                 n = strlen(key);
821                                 if (strncmp(p, key, n) != 0 ||
822                                     p[n] != '=')
823                                         continue;
824
825                                 p += n + 1;
826                                 n = strcspn(p, separator);
827
828                                 if (n >= 2 &&
829                                     strchr(QUOTES, p[0]) &&
830                                     p[n-1] == p[0])
831                                         v = strndup(p+1, n-2);
832                                 else
833                                         v = strndup(p, n);
834
835                                 if (!v) {
836                                         r = -ENOMEM;
837                                         va_end(ap);
838                                         goto fail;
839                                 }
840
841                                 if (v[0] == '\0') {
842                                         /* return empty value strings as NULL */
843                                         free(v);
844                                         v = NULL;
845                                 }
846
847                                 free(*value);
848                                 *value = v;
849
850                                 p += n;
851
852                                 r ++;
853                                 break;
854                         }
855                         va_end(ap);
856                 }
857
858                 if (!key)
859                         p += strcspn(p, separator);
860         }
861
862 fail:
863         free(contents);
864         return r;
865 }
866
867 int load_env_file(
868                 const char *fname,
869                 char ***rl) {
870
871         FILE *f;
872         char **m = 0;
873         int r;
874
875         assert(fname);
876         assert(rl);
877
878         if (!(f = fopen(fname, "re")))
879                 return -errno;
880
881         while (!feof(f)) {
882                 char l[LINE_MAX], *p, *u;
883                 char **t;
884
885                 if (!fgets(l, sizeof(l), f)) {
886                         if (feof(f))
887                                 break;
888
889                         r = -errno;
890                         goto finish;
891                 }
892
893                 p = strstrip(l);
894
895                 if (!*p)
896                         continue;
897
898                 if (strchr(COMMENTS, *p))
899                         continue;
900
901                 if (!(u = normalize_env_assignment(p))) {
902                         log_error("Out of memory");
903                         r = -ENOMEM;
904                         goto finish;
905                 }
906
907                 t = strv_append(m, u);
908                 free(u);
909
910                 if (!t) {
911                         log_error("Out of memory");
912                         r = -ENOMEM;
913                         goto finish;
914                 }
915
916                 strv_free(m);
917                 m = t;
918         }
919
920         r = 0;
921
922         *rl = m;
923         m = NULL;
924
925 finish:
926         if (f)
927                 fclose(f);
928
929         strv_free(m);
930
931         return r;
932 }
933
934 int write_env_file(const char *fname, char **l) {
935         char **i, *p;
936         FILE *f;
937         int r;
938
939         r = fopen_temporary(fname, &f, &p);
940         if (r < 0)
941                 return r;
942
943         fchmod_umask(fileno(f), 0644);
944
945         errno = 0;
946         STRV_FOREACH(i, l) {
947                 fputs(*i, f);
948                 fputc('\n', f);
949         }
950
951         fflush(f);
952
953         if (ferror(f)) {
954                 if (errno != 0)
955                         r = -errno;
956                 else
957                         r = -EIO;
958         } else {
959                 if (rename(p, fname) < 0)
960                         r = -errno;
961                 else
962                         r = 0;
963         }
964
965         if (r < 0)
966                 unlink(p);
967
968         fclose(f);
969         free(p);
970
971         return r;
972 }
973
974 char *truncate_nl(char *s) {
975         assert(s);
976
977         s[strcspn(s, NEWLINE)] = 0;
978         return s;
979 }
980
981 int get_process_name(pid_t pid, char **name) {
982         char *p;
983         int r;
984
985         assert(pid >= 1);
986         assert(name);
987
988         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
989                 return -ENOMEM;
990
991         r = read_one_line_file(p, name);
992         free(p);
993
994         if (r < 0)
995                 return r;
996
997         return 0;
998 }
999
1000 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1001         char *p, *r, *k;
1002         int c;
1003         bool space = false;
1004         size_t left;
1005         FILE *f;
1006
1007         assert(pid >= 1);
1008         assert(max_length > 0);
1009         assert(line);
1010
1011         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1012                 return -ENOMEM;
1013
1014         f = fopen(p, "re");
1015         free(p);
1016
1017         if (!f)
1018                 return -errno;
1019
1020         if (!(r = new(char, max_length))) {
1021                 fclose(f);
1022                 return -ENOMEM;
1023         }
1024
1025         k = r;
1026         left = max_length;
1027         while ((c = getc(f)) != EOF) {
1028
1029                 if (isprint(c)) {
1030                         if (space) {
1031                                 if (left <= 4)
1032                                         break;
1033
1034                                 *(k++) = ' ';
1035                                 left--;
1036                                 space = false;
1037                         }
1038
1039                         if (left <= 4)
1040                                 break;
1041
1042                         *(k++) = (char) c;
1043                         left--;
1044                 }  else
1045                         space = true;
1046         }
1047
1048         if (left <= 4) {
1049                 size_t n = MIN(left-1, 3U);
1050                 memcpy(k, "...", n);
1051                 k[n] = 0;
1052         } else
1053                 *k = 0;
1054
1055         fclose(f);
1056
1057         /* Kernel threads have no argv[] */
1058         if (r[0] == 0) {
1059                 char *t;
1060                 int h;
1061
1062                 free(r);
1063
1064                 if ((h = get_process_name(pid, &t)) < 0)
1065                         return h;
1066
1067                 h = asprintf(&r, "[%s]", t);
1068                 free(t);
1069
1070                 if (h < 0)
1071                         return -ENOMEM;
1072         }
1073
1074         *line = r;
1075         return 0;
1076 }
1077
1078 char *strnappend(const char *s, const char *suffix, size_t b) {
1079         size_t a;
1080         char *r;
1081
1082         if (!s && !suffix)
1083                 return strdup("");
1084
1085         if (!s)
1086                 return strndup(suffix, b);
1087
1088         if (!suffix)
1089                 return strdup(s);
1090
1091         assert(s);
1092         assert(suffix);
1093
1094         a = strlen(s);
1095
1096         if (!(r = new(char, a+b+1)))
1097                 return NULL;
1098
1099         memcpy(r, s, a);
1100         memcpy(r+a, suffix, b);
1101         r[a+b] = 0;
1102
1103         return r;
1104 }
1105
1106 char *strappend(const char *s, const char *suffix) {
1107         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1108 }
1109
1110 int readlink_malloc(const char *p, char **r) {
1111         size_t l = 100;
1112
1113         assert(p);
1114         assert(r);
1115
1116         for (;;) {
1117                 char *c;
1118                 ssize_t n;
1119
1120                 if (!(c = new(char, l)))
1121                         return -ENOMEM;
1122
1123                 if ((n = readlink(p, c, l-1)) < 0) {
1124                         int ret = -errno;
1125                         free(c);
1126                         return ret;
1127                 }
1128
1129                 if ((size_t) n < l-1) {
1130                         c[n] = 0;
1131                         *r = c;
1132                         return 0;
1133                 }
1134
1135                 free(c);
1136                 l *= 2;
1137         }
1138 }
1139
1140 int readlink_and_make_absolute(const char *p, char **r) {
1141         char *target, *k;
1142         int j;
1143
1144         assert(p);
1145         assert(r);
1146
1147         if ((j = readlink_malloc(p, &target)) < 0)
1148                 return j;
1149
1150         k = file_in_same_dir(p, target);
1151         free(target);
1152
1153         if (!k)
1154                 return -ENOMEM;
1155
1156         *r = k;
1157         return 0;
1158 }
1159
1160 int parent_of_path(const char *path, char **_r) {
1161         const char *e, *a = NULL, *b = NULL, *p;
1162         char *r;
1163         bool slash = false;
1164
1165         assert(path);
1166         assert(_r);
1167
1168         if (!*path)
1169                 return -EINVAL;
1170
1171         for (e = path; *e; e++) {
1172
1173                 if (!slash && *e == '/') {
1174                         a = b;
1175                         b = e;
1176                         slash = true;
1177                 } else if (slash && *e != '/')
1178                         slash = false;
1179         }
1180
1181         if (*(e-1) == '/')
1182                 p = a;
1183         else
1184                 p = b;
1185
1186         if (!p)
1187                 return -EINVAL;
1188
1189         if (p == path)
1190                 r = strdup("/");
1191         else
1192                 r = strndup(path, p-path);
1193
1194         if (!r)
1195                 return -ENOMEM;
1196
1197         *_r = r;
1198         return 0;
1199 }
1200
1201
1202 char *file_name_from_path(const char *p) {
1203         char *r;
1204
1205         assert(p);
1206
1207         if ((r = strrchr(p, '/')))
1208                 return r + 1;
1209
1210         return (char*) p;
1211 }
1212
1213 bool path_is_absolute(const char *p) {
1214         assert(p);
1215
1216         return p[0] == '/';
1217 }
1218
1219 bool is_path(const char *p) {
1220
1221         return !!strchr(p, '/');
1222 }
1223
1224 char *path_make_absolute(const char *p, const char *prefix) {
1225         char *r;
1226
1227         assert(p);
1228
1229         /* Makes every item in the list an absolute path by prepending
1230          * the prefix, if specified and necessary */
1231
1232         if (path_is_absolute(p) || !prefix)
1233                 return strdup(p);
1234
1235         if (asprintf(&r, "%s/%s", prefix, p) < 0)
1236                 return NULL;
1237
1238         return r;
1239 }
1240
1241 char *path_make_absolute_cwd(const char *p) {
1242         char *cwd, *r;
1243
1244         assert(p);
1245
1246         /* Similar to path_make_absolute(), but prefixes with the
1247          * current working directory. */
1248
1249         if (path_is_absolute(p))
1250                 return strdup(p);
1251
1252         if (!(cwd = get_current_dir_name()))
1253                 return NULL;
1254
1255         r = path_make_absolute(p, cwd);
1256         free(cwd);
1257
1258         return r;
1259 }
1260
1261 char **strv_path_make_absolute_cwd(char **l) {
1262         char **s;
1263
1264         /* Goes through every item in the string list and makes it
1265          * absolute. This works in place and won't rollback any
1266          * changes on failure. */
1267
1268         STRV_FOREACH(s, l) {
1269                 char *t;
1270
1271                 if (!(t = path_make_absolute_cwd(*s)))
1272                         return NULL;
1273
1274                 free(*s);
1275                 *s = t;
1276         }
1277
1278         return l;
1279 }
1280
1281 char **strv_path_canonicalize(char **l) {
1282         char **s;
1283         unsigned k = 0;
1284         bool enomem = false;
1285
1286         if (strv_isempty(l))
1287                 return l;
1288
1289         /* Goes through every item in the string list and canonicalize
1290          * the path. This works in place and won't rollback any
1291          * changes on failure. */
1292
1293         STRV_FOREACH(s, l) {
1294                 char *t, *u;
1295
1296                 t = path_make_absolute_cwd(*s);
1297                 free(*s);
1298
1299                 if (!t) {
1300                         enomem = true;
1301                         continue;
1302                 }
1303
1304                 errno = 0;
1305                 u = canonicalize_file_name(t);
1306                 free(t);
1307
1308                 if (!u) {
1309                         if (errno == ENOMEM || !errno)
1310                                 enomem = true;
1311
1312                         continue;
1313                 }
1314
1315                 l[k++] = u;
1316         }
1317
1318         l[k] = NULL;
1319
1320         if (enomem)
1321                 return NULL;
1322
1323         return l;
1324 }
1325
1326 char **strv_path_remove_empty(char **l) {
1327         char **f, **t;
1328
1329         if (!l)
1330                 return NULL;
1331
1332         for (f = t = l; *f; f++) {
1333
1334                 if (dir_is_empty(*f) > 0) {
1335                         free(*f);
1336                         continue;
1337                 }
1338
1339                 *(t++) = *f;
1340         }
1341
1342         *t = NULL;
1343         return l;
1344 }
1345
1346 int reset_all_signal_handlers(void) {
1347         int sig;
1348
1349         for (sig = 1; sig < _NSIG; sig++) {
1350                 struct sigaction sa;
1351
1352                 if (sig == SIGKILL || sig == SIGSTOP)
1353                         continue;
1354
1355                 zero(sa);
1356                 sa.sa_handler = SIG_DFL;
1357                 sa.sa_flags = SA_RESTART;
1358
1359                 /* On Linux the first two RT signals are reserved by
1360                  * glibc, and sigaction() will return EINVAL for them. */
1361                 if ((sigaction(sig, &sa, NULL) < 0))
1362                         if (errno != EINVAL)
1363                                 return -errno;
1364         }
1365
1366         return 0;
1367 }
1368
1369 char *strstrip(char *s) {
1370         char *e, *l = NULL;
1371
1372         /* Drops trailing whitespace. Modifies the string in
1373          * place. Returns pointer to first non-space character */
1374
1375         s += strspn(s, WHITESPACE);
1376
1377         for (e = s; *e; e++)
1378                 if (!strchr(WHITESPACE, *e))
1379                         l = e;
1380
1381         if (l)
1382                 *(l+1) = 0;
1383         else
1384                 *s = 0;
1385
1386         return s;
1387 }
1388
1389 char *delete_chars(char *s, const char *bad) {
1390         char *f, *t;
1391
1392         /* Drops all whitespace, regardless where in the string */
1393
1394         for (f = s, t = s; *f; f++) {
1395                 if (strchr(bad, *f))
1396                         continue;
1397
1398                 *(t++) = *f;
1399         }
1400
1401         *t = 0;
1402
1403         return s;
1404 }
1405
1406 char *file_in_same_dir(const char *path, const char *filename) {
1407         char *e, *r;
1408         size_t k;
1409
1410         assert(path);
1411         assert(filename);
1412
1413         /* This removes the last component of path and appends
1414          * filename, unless the latter is absolute anyway or the
1415          * former isn't */
1416
1417         if (path_is_absolute(filename))
1418                 return strdup(filename);
1419
1420         if (!(e = strrchr(path, '/')))
1421                 return strdup(filename);
1422
1423         k = strlen(filename);
1424         if (!(r = new(char, e-path+1+k+1)))
1425                 return NULL;
1426
1427         memcpy(r, path, e-path+1);
1428         memcpy(r+(e-path)+1, filename, k+1);
1429
1430         return r;
1431 }
1432
1433 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1434         struct stat st;
1435
1436         if (label_mkdir(path, mode) >= 0)
1437                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1438                         return -errno;
1439
1440         if (lstat(path, &st) < 0)
1441                 return -errno;
1442
1443         if ((st.st_mode & 0777) != mode ||
1444             st.st_uid != uid ||
1445             st.st_gid != gid ||
1446             !S_ISDIR(st.st_mode)) {
1447                 errno = EEXIST;
1448                 return -errno;
1449         }
1450
1451         return 0;
1452 }
1453
1454
1455 int mkdir_parents(const char *path, mode_t mode) {
1456         const char *p, *e;
1457
1458         assert(path);
1459
1460         /* Creates every parent directory in the path except the last
1461          * component. */
1462
1463         p = path + strspn(path, "/");
1464         for (;;) {
1465                 int r;
1466                 char *t;
1467
1468                 e = p + strcspn(p, "/");
1469                 p = e + strspn(e, "/");
1470
1471                 /* Is this the last component? If so, then we're
1472                  * done */
1473                 if (*p == 0)
1474                         return 0;
1475
1476                 if (!(t = strndup(path, e - path)))
1477                         return -ENOMEM;
1478
1479                 r = label_mkdir(t, mode);
1480                 free(t);
1481
1482                 if (r < 0 && errno != EEXIST)
1483                         return -errno;
1484         }
1485 }
1486
1487 int mkdir_p(const char *path, mode_t mode) {
1488         int r;
1489
1490         /* Like mkdir -p */
1491
1492         if ((r = mkdir_parents(path, mode)) < 0)
1493                 return r;
1494
1495         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1496                 return -errno;
1497
1498         return 0;
1499 }
1500
1501 int rmdir_parents(const char *path, const char *stop) {
1502         size_t l;
1503         int r = 0;
1504
1505         assert(path);
1506         assert(stop);
1507
1508         l = strlen(path);
1509
1510         /* Skip trailing slashes */
1511         while (l > 0 && path[l-1] == '/')
1512                 l--;
1513
1514         while (l > 0) {
1515                 char *t;
1516
1517                 /* Skip last component */
1518                 while (l > 0 && path[l-1] != '/')
1519                         l--;
1520
1521                 /* Skip trailing slashes */
1522                 while (l > 0 && path[l-1] == '/')
1523                         l--;
1524
1525                 if (l <= 0)
1526                         break;
1527
1528                 if (!(t = strndup(path, l)))
1529                         return -ENOMEM;
1530
1531                 if (path_startswith(stop, t)) {
1532                         free(t);
1533                         return 0;
1534                 }
1535
1536                 r = rmdir(t);
1537                 free(t);
1538
1539                 if (r < 0)
1540                         if (errno != ENOENT)
1541                                 return -errno;
1542         }
1543
1544         return 0;
1545 }
1546
1547
1548 char hexchar(int x) {
1549         static const char table[16] = "0123456789abcdef";
1550
1551         return table[x & 15];
1552 }
1553
1554 int unhexchar(char c) {
1555
1556         if (c >= '0' && c <= '9')
1557                 return c - '0';
1558
1559         if (c >= 'a' && c <= 'f')
1560                 return c - 'a' + 10;
1561
1562         if (c >= 'A' && c <= 'F')
1563                 return c - 'A' + 10;
1564
1565         return -1;
1566 }
1567
1568 char octchar(int x) {
1569         return '0' + (x & 7);
1570 }
1571
1572 int unoctchar(char c) {
1573
1574         if (c >= '0' && c <= '7')
1575                 return c - '0';
1576
1577         return -1;
1578 }
1579
1580 char decchar(int x) {
1581         return '0' + (x % 10);
1582 }
1583
1584 int undecchar(char c) {
1585
1586         if (c >= '0' && c <= '9')
1587                 return c - '0';
1588
1589         return -1;
1590 }
1591
1592 char *cescape(const char *s) {
1593         char *r, *t;
1594         const char *f;
1595
1596         assert(s);
1597
1598         /* Does C style string escaping. */
1599
1600         if (!(r = new(char, strlen(s)*4 + 1)))
1601                 return NULL;
1602
1603         for (f = s, t = r; *f; f++)
1604
1605                 switch (*f) {
1606
1607                 case '\a':
1608                         *(t++) = '\\';
1609                         *(t++) = 'a';
1610                         break;
1611                 case '\b':
1612                         *(t++) = '\\';
1613                         *(t++) = 'b';
1614                         break;
1615                 case '\f':
1616                         *(t++) = '\\';
1617                         *(t++) = 'f';
1618                         break;
1619                 case '\n':
1620                         *(t++) = '\\';
1621                         *(t++) = 'n';
1622                         break;
1623                 case '\r':
1624                         *(t++) = '\\';
1625                         *(t++) = 'r';
1626                         break;
1627                 case '\t':
1628                         *(t++) = '\\';
1629                         *(t++) = 't';
1630                         break;
1631                 case '\v':
1632                         *(t++) = '\\';
1633                         *(t++) = 'v';
1634                         break;
1635                 case '\\':
1636                         *(t++) = '\\';
1637                         *(t++) = '\\';
1638                         break;
1639                 case '"':
1640                         *(t++) = '\\';
1641                         *(t++) = '"';
1642                         break;
1643                 case '\'':
1644                         *(t++) = '\\';
1645                         *(t++) = '\'';
1646                         break;
1647
1648                 default:
1649                         /* For special chars we prefer octal over
1650                          * hexadecimal encoding, simply because glib's
1651                          * g_strescape() does the same */
1652                         if ((*f < ' ') || (*f >= 127)) {
1653                                 *(t++) = '\\';
1654                                 *(t++) = octchar((unsigned char) *f >> 6);
1655                                 *(t++) = octchar((unsigned char) *f >> 3);
1656                                 *(t++) = octchar((unsigned char) *f);
1657                         } else
1658                                 *(t++) = *f;
1659                         break;
1660                 }
1661
1662         *t = 0;
1663
1664         return r;
1665 }
1666
1667 char *cunescape_length(const char *s, size_t length) {
1668         char *r, *t;
1669         const char *f;
1670
1671         assert(s);
1672
1673         /* Undoes C style string escaping */
1674
1675         if (!(r = new(char, length+1)))
1676                 return r;
1677
1678         for (f = s, t = r; f < s + length; f++) {
1679
1680                 if (*f != '\\') {
1681                         *(t++) = *f;
1682                         continue;
1683                 }
1684
1685                 f++;
1686
1687                 switch (*f) {
1688
1689                 case 'a':
1690                         *(t++) = '\a';
1691                         break;
1692                 case 'b':
1693                         *(t++) = '\b';
1694                         break;
1695                 case 'f':
1696                         *(t++) = '\f';
1697                         break;
1698                 case 'n':
1699                         *(t++) = '\n';
1700                         break;
1701                 case 'r':
1702                         *(t++) = '\r';
1703                         break;
1704                 case 't':
1705                         *(t++) = '\t';
1706                         break;
1707                 case 'v':
1708                         *(t++) = '\v';
1709                         break;
1710                 case '\\':
1711                         *(t++) = '\\';
1712                         break;
1713                 case '"':
1714                         *(t++) = '"';
1715                         break;
1716                 case '\'':
1717                         *(t++) = '\'';
1718                         break;
1719
1720                 case 's':
1721                         /* This is an extension of the XDG syntax files */
1722                         *(t++) = ' ';
1723                         break;
1724
1725                 case 'x': {
1726                         /* hexadecimal encoding */
1727                         int a, b;
1728
1729                         if ((a = unhexchar(f[1])) < 0 ||
1730                             (b = unhexchar(f[2])) < 0) {
1731                                 /* Invalid escape code, let's take it literal then */
1732                                 *(t++) = '\\';
1733                                 *(t++) = 'x';
1734                         } else {
1735                                 *(t++) = (char) ((a << 4) | b);
1736                                 f += 2;
1737                         }
1738
1739                         break;
1740                 }
1741
1742                 case '0':
1743                 case '1':
1744                 case '2':
1745                 case '3':
1746                 case '4':
1747                 case '5':
1748                 case '6':
1749                 case '7': {
1750                         /* octal encoding */
1751                         int a, b, c;
1752
1753                         if ((a = unoctchar(f[0])) < 0 ||
1754                             (b = unoctchar(f[1])) < 0 ||
1755                             (c = unoctchar(f[2])) < 0) {
1756                                 /* Invalid escape code, let's take it literal then */
1757                                 *(t++) = '\\';
1758                                 *(t++) = f[0];
1759                         } else {
1760                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1761                                 f += 2;
1762                         }
1763
1764                         break;
1765                 }
1766
1767                 case 0:
1768                         /* premature end of string.*/
1769                         *(t++) = '\\';
1770                         goto finish;
1771
1772                 default:
1773                         /* Invalid escape code, let's take it literal then */
1774                         *(t++) = '\\';
1775                         *(t++) = *f;
1776                         break;
1777                 }
1778         }
1779
1780 finish:
1781         *t = 0;
1782         return r;
1783 }
1784
1785 char *cunescape(const char *s) {
1786         return cunescape_length(s, strlen(s));
1787 }
1788
1789 char *xescape(const char *s, const char *bad) {
1790         char *r, *t;
1791         const char *f;
1792
1793         /* Escapes all chars in bad, in addition to \ and all special
1794          * chars, in \xFF style escaping. May be reversed with
1795          * cunescape. */
1796
1797         if (!(r = new(char, strlen(s)*4+1)))
1798                 return NULL;
1799
1800         for (f = s, t = r; *f; f++) {
1801
1802                 if ((*f < ' ') || (*f >= 127) ||
1803                     (*f == '\\') || strchr(bad, *f)) {
1804                         *(t++) = '\\';
1805                         *(t++) = 'x';
1806                         *(t++) = hexchar(*f >> 4);
1807                         *(t++) = hexchar(*f);
1808                 } else
1809                         *(t++) = *f;
1810         }
1811
1812         *t = 0;
1813
1814         return r;
1815 }
1816
1817 char *bus_path_escape(const char *s) {
1818         char *r, *t;
1819         const char *f;
1820
1821         assert(s);
1822
1823         /* Escapes all chars that D-Bus' object path cannot deal
1824          * with. Can be reverse with bus_path_unescape() */
1825
1826         if (!(r = new(char, strlen(s)*3+1)))
1827                 return NULL;
1828
1829         for (f = s, t = r; *f; f++) {
1830
1831                 if (!(*f >= 'A' && *f <= 'Z') &&
1832                     !(*f >= 'a' && *f <= 'z') &&
1833                     !(*f >= '0' && *f <= '9')) {
1834                         *(t++) = '_';
1835                         *(t++) = hexchar(*f >> 4);
1836                         *(t++) = hexchar(*f);
1837                 } else
1838                         *(t++) = *f;
1839         }
1840
1841         *t = 0;
1842
1843         return r;
1844 }
1845
1846 char *bus_path_unescape(const char *f) {
1847         char *r, *t;
1848
1849         assert(f);
1850
1851         if (!(r = strdup(f)))
1852                 return NULL;
1853
1854         for (t = r; *f; f++) {
1855
1856                 if (*f == '_') {
1857                         int a, b;
1858
1859                         if ((a = unhexchar(f[1])) < 0 ||
1860                             (b = unhexchar(f[2])) < 0) {
1861                                 /* Invalid escape code, let's take it literal then */
1862                                 *(t++) = '_';
1863                         } else {
1864                                 *(t++) = (char) ((a << 4) | b);
1865                                 f += 2;
1866                         }
1867                 } else
1868                         *(t++) = *f;
1869         }
1870
1871         *t = 0;
1872
1873         return r;
1874 }
1875
1876 char *path_kill_slashes(char *path) {
1877         char *f, *t;
1878         bool slash = false;
1879
1880         /* Removes redundant inner and trailing slashes. Modifies the
1881          * passed string in-place.
1882          *
1883          * ///foo///bar/ becomes /foo/bar
1884          */
1885
1886         for (f = path, t = path; *f; f++) {
1887
1888                 if (*f == '/') {
1889                         slash = true;
1890                         continue;
1891                 }
1892
1893                 if (slash) {
1894                         slash = false;
1895                         *(t++) = '/';
1896                 }
1897
1898                 *(t++) = *f;
1899         }
1900
1901         /* Special rule, if we are talking of the root directory, a
1902         trailing slash is good */
1903
1904         if (t == path && slash)
1905                 *(t++) = '/';
1906
1907         *t = 0;
1908         return path;
1909 }
1910
1911 bool path_startswith(const char *path, const char *prefix) {
1912         assert(path);
1913         assert(prefix);
1914
1915         if ((path[0] == '/') != (prefix[0] == '/'))
1916                 return false;
1917
1918         for (;;) {
1919                 size_t a, b;
1920
1921                 path += strspn(path, "/");
1922                 prefix += strspn(prefix, "/");
1923
1924                 if (*prefix == 0)
1925                         return true;
1926
1927                 if (*path == 0)
1928                         return false;
1929
1930                 a = strcspn(path, "/");
1931                 b = strcspn(prefix, "/");
1932
1933                 if (a != b)
1934                         return false;
1935
1936                 if (memcmp(path, prefix, a) != 0)
1937                         return false;
1938
1939                 path += a;
1940                 prefix += b;
1941         }
1942 }
1943
1944 bool path_equal(const char *a, const char *b) {
1945         assert(a);
1946         assert(b);
1947
1948         if ((a[0] == '/') != (b[0] == '/'))
1949                 return false;
1950
1951         for (;;) {
1952                 size_t j, k;
1953
1954                 a += strspn(a, "/");
1955                 b += strspn(b, "/");
1956
1957                 if (*a == 0 && *b == 0)
1958                         return true;
1959
1960                 if (*a == 0 || *b == 0)
1961                         return false;
1962
1963                 j = strcspn(a, "/");
1964                 k = strcspn(b, "/");
1965
1966                 if (j != k)
1967                         return false;
1968
1969                 if (memcmp(a, b, j) != 0)
1970                         return false;
1971
1972                 a += j;
1973                 b += k;
1974         }
1975 }
1976
1977 char *ascii_strlower(char *t) {
1978         char *p;
1979
1980         assert(t);
1981
1982         for (p = t; *p; p++)
1983                 if (*p >= 'A' && *p <= 'Z')
1984                         *p = *p - 'A' + 'a';
1985
1986         return t;
1987 }
1988
1989 bool ignore_file(const char *filename) {
1990         assert(filename);
1991
1992         return
1993                 filename[0] == '.' ||
1994                 streq(filename, "lost+found") ||
1995                 streq(filename, "aquota.user") ||
1996                 streq(filename, "aquota.group") ||
1997                 endswith(filename, "~") ||
1998                 endswith(filename, ".rpmnew") ||
1999                 endswith(filename, ".rpmsave") ||
2000                 endswith(filename, ".rpmorig") ||
2001                 endswith(filename, ".dpkg-old") ||
2002                 endswith(filename, ".dpkg-new") ||
2003                 endswith(filename, ".swp");
2004 }
2005
2006 int fd_nonblock(int fd, bool nonblock) {
2007         int flags;
2008
2009         assert(fd >= 0);
2010
2011         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2012                 return -errno;
2013
2014         if (nonblock)
2015                 flags |= O_NONBLOCK;
2016         else
2017                 flags &= ~O_NONBLOCK;
2018
2019         if (fcntl(fd, F_SETFL, flags) < 0)
2020                 return -errno;
2021
2022         return 0;
2023 }
2024
2025 int fd_cloexec(int fd, bool cloexec) {
2026         int flags;
2027
2028         assert(fd >= 0);
2029
2030         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2031                 return -errno;
2032
2033         if (cloexec)
2034                 flags |= FD_CLOEXEC;
2035         else
2036                 flags &= ~FD_CLOEXEC;
2037
2038         if (fcntl(fd, F_SETFD, flags) < 0)
2039                 return -errno;
2040
2041         return 0;
2042 }
2043
2044 int close_all_fds(const int except[], unsigned n_except) {
2045         DIR *d;
2046         struct dirent *de;
2047         int r = 0;
2048
2049         if (!(d = opendir("/proc/self/fd")))
2050                 return -errno;
2051
2052         while ((de = readdir(d))) {
2053                 int fd = -1;
2054
2055                 if (ignore_file(de->d_name))
2056                         continue;
2057
2058                 if (safe_atoi(de->d_name, &fd) < 0)
2059                         /* Let's better ignore this, just in case */
2060                         continue;
2061
2062                 if (fd < 3)
2063                         continue;
2064
2065                 if (fd == dirfd(d))
2066                         continue;
2067
2068                 if (except) {
2069                         bool found;
2070                         unsigned i;
2071
2072                         found = false;
2073                         for (i = 0; i < n_except; i++)
2074                                 if (except[i] == fd) {
2075                                         found = true;
2076                                         break;
2077                                 }
2078
2079                         if (found)
2080                                 continue;
2081                 }
2082
2083                 if (close_nointr(fd) < 0) {
2084                         /* Valgrind has its own FD and doesn't want to have it closed */
2085                         if (errno != EBADF && r == 0)
2086                                 r = -errno;
2087                 }
2088         }
2089
2090         closedir(d);
2091         return r;
2092 }
2093
2094 bool chars_intersect(const char *a, const char *b) {
2095         const char *p;
2096
2097         /* Returns true if any of the chars in a are in b. */
2098         for (p = a; *p; p++)
2099                 if (strchr(b, *p))
2100                         return true;
2101
2102         return false;
2103 }
2104
2105 char *format_timestamp(char *buf, size_t l, usec_t t) {
2106         struct tm tm;
2107         time_t sec;
2108
2109         assert(buf);
2110         assert(l > 0);
2111
2112         if (t <= 0)
2113                 return NULL;
2114
2115         sec = (time_t) (t / USEC_PER_SEC);
2116
2117         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2118                 return NULL;
2119
2120         return buf;
2121 }
2122
2123 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2124         usec_t n, d;
2125
2126         n = now(CLOCK_REALTIME);
2127
2128         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2129                 return NULL;
2130
2131         d = n - t;
2132
2133         if (d >= USEC_PER_YEAR)
2134                 snprintf(buf, l, "%llu years and %llu months ago",
2135                          (unsigned long long) (d / USEC_PER_YEAR),
2136                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2137         else if (d >= USEC_PER_MONTH)
2138                 snprintf(buf, l, "%llu months and %llu days ago",
2139                          (unsigned long long) (d / USEC_PER_MONTH),
2140                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2141         else if (d >= USEC_PER_WEEK)
2142                 snprintf(buf, l, "%llu weeks and %llu days ago",
2143                          (unsigned long long) (d / USEC_PER_WEEK),
2144                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2145         else if (d >= 2*USEC_PER_DAY)
2146                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2147         else if (d >= 25*USEC_PER_HOUR)
2148                 snprintf(buf, l, "1 day and %lluh ago",
2149                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2150         else if (d >= 6*USEC_PER_HOUR)
2151                 snprintf(buf, l, "%lluh ago",
2152                          (unsigned long long) (d / USEC_PER_HOUR));
2153         else if (d >= USEC_PER_HOUR)
2154                 snprintf(buf, l, "%lluh %llumin ago",
2155                          (unsigned long long) (d / USEC_PER_HOUR),
2156                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2157         else if (d >= 5*USEC_PER_MINUTE)
2158                 snprintf(buf, l, "%llumin ago",
2159                          (unsigned long long) (d / USEC_PER_MINUTE));
2160         else if (d >= USEC_PER_MINUTE)
2161                 snprintf(buf, l, "%llumin %llus ago",
2162                          (unsigned long long) (d / USEC_PER_MINUTE),
2163                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2164         else if (d >= USEC_PER_SEC)
2165                 snprintf(buf, l, "%llus ago",
2166                          (unsigned long long) (d / USEC_PER_SEC));
2167         else if (d >= USEC_PER_MSEC)
2168                 snprintf(buf, l, "%llums ago",
2169                          (unsigned long long) (d / USEC_PER_MSEC));
2170         else if (d > 0)
2171                 snprintf(buf, l, "%lluus ago",
2172                          (unsigned long long) d);
2173         else
2174                 snprintf(buf, l, "now");
2175
2176         buf[l-1] = 0;
2177         return buf;
2178 }
2179
2180 char *format_timespan(char *buf, size_t l, usec_t t) {
2181         static const struct {
2182                 const char *suffix;
2183                 usec_t usec;
2184         } table[] = {
2185                 { "w", USEC_PER_WEEK },
2186                 { "d", USEC_PER_DAY },
2187                 { "h", USEC_PER_HOUR },
2188                 { "min", USEC_PER_MINUTE },
2189                 { "s", USEC_PER_SEC },
2190                 { "ms", USEC_PER_MSEC },
2191                 { "us", 1 },
2192         };
2193
2194         unsigned i;
2195         char *p = buf;
2196
2197         assert(buf);
2198         assert(l > 0);
2199
2200         if (t == (usec_t) -1)
2201                 return NULL;
2202
2203         if (t == 0) {
2204                 snprintf(p, l, "0");
2205                 p[l-1] = 0;
2206                 return p;
2207         }
2208
2209         /* The result of this function can be parsed with parse_usec */
2210
2211         for (i = 0; i < ELEMENTSOF(table); i++) {
2212                 int k;
2213                 size_t n;
2214
2215                 if (t < table[i].usec)
2216                         continue;
2217
2218                 if (l <= 1)
2219                         break;
2220
2221                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2222                 n = MIN((size_t) k, l);
2223
2224                 l -= n;
2225                 p += n;
2226
2227                 t %= table[i].usec;
2228         }
2229
2230         *p = 0;
2231
2232         return buf;
2233 }
2234
2235 bool fstype_is_network(const char *fstype) {
2236         static const char * const table[] = {
2237                 "cifs",
2238                 "smbfs",
2239                 "ncpfs",
2240                 "nfs",
2241                 "nfs4",
2242                 "gfs",
2243                 "gfs2"
2244         };
2245
2246         unsigned i;
2247
2248         for (i = 0; i < ELEMENTSOF(table); i++)
2249                 if (streq(table[i], fstype))
2250                         return true;
2251
2252         return false;
2253 }
2254
2255 int chvt(int vt) {
2256         int fd, r = 0;
2257
2258         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2259                 return -errno;
2260
2261         if (vt < 0) {
2262                 int tiocl[2] = {
2263                         TIOCL_GETKMSGREDIRECT,
2264                         0
2265                 };
2266
2267                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2268                         return -errno;
2269
2270                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2271         }
2272
2273         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2274                 r = -errno;
2275
2276         close_nointr_nofail(r);
2277         return r;
2278 }
2279
2280 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2281         struct termios old_termios, new_termios;
2282         char c;
2283         char line[LINE_MAX];
2284
2285         assert(f);
2286         assert(ret);
2287
2288         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2289                 new_termios = old_termios;
2290
2291                 new_termios.c_lflag &= ~ICANON;
2292                 new_termios.c_cc[VMIN] = 1;
2293                 new_termios.c_cc[VTIME] = 0;
2294
2295                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2296                         size_t k;
2297
2298                         k = fread(&c, 1, 1, f);
2299
2300                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2301
2302                         if (k <= 0)
2303                                 return -EIO;
2304
2305                         if (need_nl)
2306                                 *need_nl = c != '\n';
2307
2308                         *ret = c;
2309                         return 0;
2310                 }
2311         }
2312
2313         if (!(fgets(line, sizeof(line), f)))
2314                 return -EIO;
2315
2316         truncate_nl(line);
2317
2318         if (strlen(line) != 1)
2319                 return -EBADMSG;
2320
2321         if (need_nl)
2322                 *need_nl = false;
2323
2324         *ret = line[0];
2325         return 0;
2326 }
2327
2328 int ask(char *ret, const char *replies, const char *text, ...) {
2329         bool on_tty;
2330
2331         assert(ret);
2332         assert(replies);
2333         assert(text);
2334
2335         on_tty = isatty(STDOUT_FILENO);
2336
2337         for (;;) {
2338                 va_list ap;
2339                 char c;
2340                 int r;
2341                 bool need_nl = true;
2342
2343                 if (on_tty)
2344                         fputs("\x1B[1m", stdout);
2345
2346                 va_start(ap, text);
2347                 vprintf(text, ap);
2348                 va_end(ap);
2349
2350                 if (on_tty)
2351                         fputs("\x1B[0m", stdout);
2352
2353                 fflush(stdout);
2354
2355                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2356
2357                         if (r == -EBADMSG) {
2358                                 puts("Bad input, please try again.");
2359                                 continue;
2360                         }
2361
2362                         putchar('\n');
2363                         return r;
2364                 }
2365
2366                 if (need_nl)
2367                         putchar('\n');
2368
2369                 if (strchr(replies, c)) {
2370                         *ret = c;
2371                         return 0;
2372                 }
2373
2374                 puts("Read unexpected character, please try again.");
2375         }
2376 }
2377
2378 int reset_terminal_fd(int fd) {
2379         struct termios termios;
2380         int r = 0;
2381         long arg;
2382
2383         /* Set terminal to some sane defaults */
2384
2385         assert(fd >= 0);
2386
2387         /* We leave locked terminal attributes untouched, so that
2388          * Plymouth may set whatever it wants to set, and we don't
2389          * interfere with that. */
2390
2391         /* Disable exclusive mode, just in case */
2392         ioctl(fd, TIOCNXCL);
2393
2394         /* Enable console unicode mode */
2395         arg = K_UNICODE;
2396         ioctl(fd, KDSKBMODE, &arg);
2397
2398         if (tcgetattr(fd, &termios) < 0) {
2399                 r = -errno;
2400                 goto finish;
2401         }
2402
2403         /* We only reset the stuff that matters to the software. How
2404          * hardware is set up we don't touch assuming that somebody
2405          * else will do that for us */
2406
2407         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2408         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2409         termios.c_oflag |= ONLCR;
2410         termios.c_cflag |= CREAD;
2411         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2412
2413         termios.c_cc[VINTR]    =   03;  /* ^C */
2414         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2415         termios.c_cc[VERASE]   = 0177;
2416         termios.c_cc[VKILL]    =  025;  /* ^X */
2417         termios.c_cc[VEOF]     =   04;  /* ^D */
2418         termios.c_cc[VSTART]   =  021;  /* ^Q */
2419         termios.c_cc[VSTOP]    =  023;  /* ^S */
2420         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2421         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2422         termios.c_cc[VWERASE]  =  027;  /* ^W */
2423         termios.c_cc[VREPRINT] =  022;  /* ^R */
2424         termios.c_cc[VEOL]     =    0;
2425         termios.c_cc[VEOL2]    =    0;
2426
2427         termios.c_cc[VTIME]  = 0;
2428         termios.c_cc[VMIN]   = 1;
2429
2430         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2431                 r = -errno;
2432
2433 finish:
2434         /* Just in case, flush all crap out */
2435         tcflush(fd, TCIOFLUSH);
2436
2437         return r;
2438 }
2439
2440 int reset_terminal(const char *name) {
2441         int fd, r;
2442
2443         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2444         if (fd < 0)
2445                 return fd;
2446
2447         r = reset_terminal_fd(fd);
2448         close_nointr_nofail(fd);
2449
2450         return r;
2451 }
2452
2453 int open_terminal(const char *name, int mode) {
2454         int fd, r;
2455         unsigned c = 0;
2456
2457         /*
2458          * If a TTY is in the process of being closed opening it might
2459          * cause EIO. This is horribly awful, but unlikely to be
2460          * changed in the kernel. Hence we work around this problem by
2461          * retrying a couple of times.
2462          *
2463          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2464          */
2465
2466         for (;;) {
2467                 if ((fd = open(name, mode)) >= 0)
2468                         break;
2469
2470                 if (errno != EIO)
2471                         return -errno;
2472
2473                 if (c >= 20)
2474                         return -errno;
2475
2476                 usleep(50 * USEC_PER_MSEC);
2477                 c++;
2478         }
2479
2480         if (fd < 0)
2481                 return -errno;
2482
2483         if ((r = isatty(fd)) < 0) {
2484                 close_nointr_nofail(fd);
2485                 return -errno;
2486         }
2487
2488         if (!r) {
2489                 close_nointr_nofail(fd);
2490                 return -ENOTTY;
2491         }
2492
2493         return fd;
2494 }
2495
2496 int flush_fd(int fd) {
2497         struct pollfd pollfd;
2498
2499         zero(pollfd);
2500         pollfd.fd = fd;
2501         pollfd.events = POLLIN;
2502
2503         for (;;) {
2504                 char buf[LINE_MAX];
2505                 ssize_t l;
2506                 int r;
2507
2508                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2509
2510                         if (errno == EINTR)
2511                                 continue;
2512
2513                         return -errno;
2514                 }
2515
2516                 if (r == 0)
2517                         return 0;
2518
2519                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2520
2521                         if (errno == EINTR)
2522                                 continue;
2523
2524                         if (errno == EAGAIN)
2525                                 return 0;
2526
2527                         return -errno;
2528                 }
2529
2530                 if (l <= 0)
2531                         return 0;
2532         }
2533 }
2534
2535 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2536         int fd = -1, notify = -1, r, wd = -1;
2537
2538         assert(name);
2539
2540         /* We use inotify to be notified when the tty is closed. We
2541          * create the watch before checking if we can actually acquire
2542          * it, so that we don't lose any event.
2543          *
2544          * Note: strictly speaking this actually watches for the
2545          * device being closed, it does *not* really watch whether a
2546          * tty loses its controlling process. However, unless some
2547          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2548          * its tty otherwise this will not become a problem. As long
2549          * as the administrator makes sure not configure any service
2550          * on the same tty as an untrusted user this should not be a
2551          * problem. (Which he probably should not do anyway.) */
2552
2553         if (!fail && !force) {
2554                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2555                         r = -errno;
2556                         goto fail;
2557                 }
2558
2559                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2560                         r = -errno;
2561                         goto fail;
2562                 }
2563         }
2564
2565         for (;;) {
2566                 if (notify >= 0)
2567                         if ((r = flush_fd(notify)) < 0)
2568                                 goto fail;
2569
2570                 /* We pass here O_NOCTTY only so that we can check the return
2571                  * value TIOCSCTTY and have a reliable way to figure out if we
2572                  * successfully became the controlling process of the tty */
2573                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2574                         return fd;
2575
2576                 /* First, try to get the tty */
2577                 r = ioctl(fd, TIOCSCTTY, force);
2578
2579                 /* Sometimes it makes sense to ignore TIOCSCTTY
2580                  * returning EPERM, i.e. when very likely we already
2581                  * are have this controlling terminal. */
2582                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2583                         r = 0;
2584
2585                 if (r < 0 && (force || fail || errno != EPERM)) {
2586                         r = -errno;
2587                         goto fail;
2588                 }
2589
2590                 if (r >= 0)
2591                         break;
2592
2593                 assert(!fail);
2594                 assert(!force);
2595                 assert(notify >= 0);
2596
2597                 for (;;) {
2598                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2599                         ssize_t l;
2600                         struct inotify_event *e;
2601
2602                         if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2603
2604                                 if (errno == EINTR)
2605                                         continue;
2606
2607                                 r = -errno;
2608                                 goto fail;
2609                         }
2610
2611                         e = (struct inotify_event*) inotify_buffer;
2612
2613                         while (l > 0) {
2614                                 size_t step;
2615
2616                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2617                                         r = -EIO;
2618                                         goto fail;
2619                                 }
2620
2621                                 step = sizeof(struct inotify_event) + e->len;
2622                                 assert(step <= (size_t) l);
2623
2624                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2625                                 l -= step;
2626                         }
2627
2628                         break;
2629                 }
2630
2631                 /* We close the tty fd here since if the old session
2632                  * ended our handle will be dead. It's important that
2633                  * we do this after sleeping, so that we don't enter
2634                  * an endless loop. */
2635                 close_nointr_nofail(fd);
2636         }
2637
2638         if (notify >= 0)
2639                 close_nointr_nofail(notify);
2640
2641         if ((r = reset_terminal_fd(fd)) < 0)
2642                 log_warning("Failed to reset terminal: %s", strerror(-r));
2643
2644         return fd;
2645
2646 fail:
2647         if (fd >= 0)
2648                 close_nointr_nofail(fd);
2649
2650         if (notify >= 0)
2651                 close_nointr_nofail(notify);
2652
2653         return r;
2654 }
2655
2656 int release_terminal(void) {
2657         int r = 0, fd;
2658         struct sigaction sa_old, sa_new;
2659
2660         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2661                 return -errno;
2662
2663         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2664          * by our own TIOCNOTTY */
2665
2666         zero(sa_new);
2667         sa_new.sa_handler = SIG_IGN;
2668         sa_new.sa_flags = SA_RESTART;
2669         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2670
2671         if (ioctl(fd, TIOCNOTTY) < 0)
2672                 r = -errno;
2673
2674         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2675
2676         close_nointr_nofail(fd);
2677         return r;
2678 }
2679
2680 int sigaction_many(const struct sigaction *sa, ...) {
2681         va_list ap;
2682         int r = 0, sig;
2683
2684         va_start(ap, sa);
2685         while ((sig = va_arg(ap, int)) > 0)
2686                 if (sigaction(sig, sa, NULL) < 0)
2687                         r = -errno;
2688         va_end(ap);
2689
2690         return r;
2691 }
2692
2693 int ignore_signals(int sig, ...) {
2694         struct sigaction sa;
2695         va_list ap;
2696         int r = 0;
2697
2698         zero(sa);
2699         sa.sa_handler = SIG_IGN;
2700         sa.sa_flags = SA_RESTART;
2701
2702         if (sigaction(sig, &sa, NULL) < 0)
2703                 r = -errno;
2704
2705         va_start(ap, sig);
2706         while ((sig = va_arg(ap, int)) > 0)
2707                 if (sigaction(sig, &sa, NULL) < 0)
2708                         r = -errno;
2709         va_end(ap);
2710
2711         return r;
2712 }
2713
2714 int default_signals(int sig, ...) {
2715         struct sigaction sa;
2716         va_list ap;
2717         int r = 0;
2718
2719         zero(sa);
2720         sa.sa_handler = SIG_DFL;
2721         sa.sa_flags = SA_RESTART;
2722
2723         if (sigaction(sig, &sa, NULL) < 0)
2724                 r = -errno;
2725
2726         va_start(ap, sig);
2727         while ((sig = va_arg(ap, int)) > 0)
2728                 if (sigaction(sig, &sa, NULL) < 0)
2729                         r = -errno;
2730         va_end(ap);
2731
2732         return r;
2733 }
2734
2735 int close_pipe(int p[]) {
2736         int a = 0, b = 0;
2737
2738         assert(p);
2739
2740         if (p[0] >= 0) {
2741                 a = close_nointr(p[0]);
2742                 p[0] = -1;
2743         }
2744
2745         if (p[1] >= 0) {
2746                 b = close_nointr(p[1]);
2747                 p[1] = -1;
2748         }
2749
2750         return a < 0 ? a : b;
2751 }
2752
2753 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2754         uint8_t *p;
2755         ssize_t n = 0;
2756
2757         assert(fd >= 0);
2758         assert(buf);
2759
2760         p = buf;
2761
2762         while (nbytes > 0) {
2763                 ssize_t k;
2764
2765                 if ((k = read(fd, p, nbytes)) <= 0) {
2766
2767                         if (k < 0 && errno == EINTR)
2768                                 continue;
2769
2770                         if (k < 0 && errno == EAGAIN && do_poll) {
2771                                 struct pollfd pollfd;
2772
2773                                 zero(pollfd);
2774                                 pollfd.fd = fd;
2775                                 pollfd.events = POLLIN;
2776
2777                                 if (poll(&pollfd, 1, -1) < 0) {
2778                                         if (errno == EINTR)
2779                                                 continue;
2780
2781                                         return n > 0 ? n : -errno;
2782                                 }
2783
2784                                 if (pollfd.revents != POLLIN)
2785                                         return n > 0 ? n : -EIO;
2786
2787                                 continue;
2788                         }
2789
2790                         return n > 0 ? n : (k < 0 ? -errno : 0);
2791                 }
2792
2793                 p += k;
2794                 nbytes -= k;
2795                 n += k;
2796         }
2797
2798         return n;
2799 }
2800
2801 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2802         const uint8_t *p;
2803         ssize_t n = 0;
2804
2805         assert(fd >= 0);
2806         assert(buf);
2807
2808         p = buf;
2809
2810         while (nbytes > 0) {
2811                 ssize_t k;
2812
2813                 if ((k = write(fd, p, nbytes)) <= 0) {
2814
2815                         if (k < 0 && errno == EINTR)
2816                                 continue;
2817
2818                         if (k < 0 && errno == EAGAIN && do_poll) {
2819                                 struct pollfd pollfd;
2820
2821                                 zero(pollfd);
2822                                 pollfd.fd = fd;
2823                                 pollfd.events = POLLOUT;
2824
2825                                 if (poll(&pollfd, 1, -1) < 0) {
2826                                         if (errno == EINTR)
2827                                                 continue;
2828
2829                                         return n > 0 ? n : -errno;
2830                                 }
2831
2832                                 if (pollfd.revents != POLLOUT)
2833                                         return n > 0 ? n : -EIO;
2834
2835                                 continue;
2836                         }
2837
2838                         return n > 0 ? n : (k < 0 ? -errno : 0);
2839                 }
2840
2841                 p += k;
2842                 nbytes -= k;
2843                 n += k;
2844         }
2845
2846         return n;
2847 }
2848
2849 int path_is_mount_point(const char *t) {
2850         struct stat a, b;
2851         char *parent;
2852         int r;
2853
2854         if (lstat(t, &a) < 0) {
2855                 if (errno == ENOENT)
2856                         return 0;
2857
2858                 return -errno;
2859         }
2860
2861         if ((r = parent_of_path(t, &parent)) < 0)
2862                 return r;
2863
2864         r = lstat(parent, &b);
2865         free(parent);
2866
2867         if (r < 0)
2868                 return -errno;
2869
2870         return a.st_dev != b.st_dev;
2871 }
2872
2873 int parse_usec(const char *t, usec_t *usec) {
2874         static const struct {
2875                 const char *suffix;
2876                 usec_t usec;
2877         } table[] = {
2878                 { "sec", USEC_PER_SEC },
2879                 { "s", USEC_PER_SEC },
2880                 { "min", USEC_PER_MINUTE },
2881                 { "hr", USEC_PER_HOUR },
2882                 { "h", USEC_PER_HOUR },
2883                 { "d", USEC_PER_DAY },
2884                 { "w", USEC_PER_WEEK },
2885                 { "msec", USEC_PER_MSEC },
2886                 { "ms", USEC_PER_MSEC },
2887                 { "m", USEC_PER_MINUTE },
2888                 { "usec", 1ULL },
2889                 { "us", 1ULL },
2890                 { "", USEC_PER_SEC },
2891         };
2892
2893         const char *p;
2894         usec_t r = 0;
2895
2896         assert(t);
2897         assert(usec);
2898
2899         p = t;
2900         do {
2901                 long long l;
2902                 char *e;
2903                 unsigned i;
2904
2905                 errno = 0;
2906                 l = strtoll(p, &e, 10);
2907
2908                 if (errno != 0)
2909                         return -errno;
2910
2911                 if (l < 0)
2912                         return -ERANGE;
2913
2914                 if (e == p)
2915                         return -EINVAL;
2916
2917                 e += strspn(e, WHITESPACE);
2918
2919                 for (i = 0; i < ELEMENTSOF(table); i++)
2920                         if (startswith(e, table[i].suffix)) {
2921                                 r += (usec_t) l * table[i].usec;
2922                                 p = e + strlen(table[i].suffix);
2923                                 break;
2924                         }
2925
2926                 if (i >= ELEMENTSOF(table))
2927                         return -EINVAL;
2928
2929         } while (*p != 0);
2930
2931         *usec = r;
2932
2933         return 0;
2934 }
2935
2936 int make_stdio(int fd) {
2937         int r, s, t;
2938
2939         assert(fd >= 0);
2940
2941         r = dup2(fd, STDIN_FILENO);
2942         s = dup2(fd, STDOUT_FILENO);
2943         t = dup2(fd, STDERR_FILENO);
2944
2945         if (fd >= 3)
2946                 close_nointr_nofail(fd);
2947
2948         if (r < 0 || s < 0 || t < 0)
2949                 return -errno;
2950
2951         fd_cloexec(STDIN_FILENO, false);
2952         fd_cloexec(STDOUT_FILENO, false);
2953         fd_cloexec(STDERR_FILENO, false);
2954
2955         return 0;
2956 }
2957
2958 int make_null_stdio(void) {
2959         int null_fd;
2960
2961         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2962                 return -errno;
2963
2964         return make_stdio(null_fd);
2965 }
2966
2967 bool is_device_path(const char *path) {
2968
2969         /* Returns true on paths that refer to a device, either in
2970          * sysfs or in /dev */
2971
2972         return
2973                 path_startswith(path, "/dev/") ||
2974                 path_startswith(path, "/sys/");
2975 }
2976
2977 int dir_is_empty(const char *path) {
2978         DIR *d;
2979         int r;
2980         struct dirent buf, *de;
2981
2982         if (!(d = opendir(path)))
2983                 return -errno;
2984
2985         for (;;) {
2986                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2987                         r = -r;
2988                         break;
2989                 }
2990
2991                 if (!de) {
2992                         r = 1;
2993                         break;
2994                 }
2995
2996                 if (!ignore_file(de->d_name)) {
2997                         r = 0;
2998                         break;
2999                 }
3000         }
3001
3002         closedir(d);
3003         return r;
3004 }
3005
3006 unsigned long long random_ull(void) {
3007         int fd;
3008         uint64_t ull;
3009         ssize_t r;
3010
3011         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3012                 goto fallback;
3013
3014         r = loop_read(fd, &ull, sizeof(ull), true);
3015         close_nointr_nofail(fd);
3016
3017         if (r != sizeof(ull))
3018                 goto fallback;
3019
3020         return ull;
3021
3022 fallback:
3023         return random() * RAND_MAX + random();
3024 }
3025
3026 void rename_process(const char name[8]) {
3027         assert(name);
3028
3029         prctl(PR_SET_NAME, name);
3030
3031         /* This is a like a poor man's setproctitle(). The string
3032          * passed should fit in 7 chars (i.e. the length of
3033          * "systemd") */
3034
3035         if (program_invocation_name)
3036                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3037
3038         if (saved_argc > 0) {
3039                 int i;
3040
3041                 if (saved_argv[0])
3042                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3043
3044                 for (i = 1; i < saved_argc; i++) {
3045                         if (!saved_argv[i])
3046                                 break;
3047
3048                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3049                 }
3050         }
3051 }
3052
3053 void sigset_add_many(sigset_t *ss, ...) {
3054         va_list ap;
3055         int sig;
3056
3057         assert(ss);
3058
3059         va_start(ap, ss);
3060         while ((sig = va_arg(ap, int)) > 0)
3061                 assert_se(sigaddset(ss, sig) == 0);
3062         va_end(ap);
3063 }
3064
3065 char* gethostname_malloc(void) {
3066         struct utsname u;
3067
3068         assert_se(uname(&u) >= 0);
3069
3070         if (u.nodename[0])
3071                 return strdup(u.nodename);
3072
3073         return strdup(u.sysname);
3074 }
3075
3076 char* getlogname_malloc(void) {
3077         uid_t uid;
3078         long bufsize;
3079         char *buf, *name;
3080         struct passwd pwbuf, *pw = NULL;
3081         struct stat st;
3082
3083         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3084                 uid = st.st_uid;
3085         else
3086                 uid = getuid();
3087
3088         /* Shortcut things to avoid NSS lookups */
3089         if (uid == 0)
3090                 return strdup("root");
3091
3092         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3093                 bufsize = 4096;
3094
3095         if (!(buf = malloc(bufsize)))
3096                 return NULL;
3097
3098         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3099                 name = strdup(pw->pw_name);
3100                 free(buf);
3101                 return name;
3102         }
3103
3104         free(buf);
3105
3106         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3107                 return NULL;
3108
3109         return name;
3110 }
3111
3112 int getttyname_malloc(int fd, char **r) {
3113         char path[PATH_MAX], *c;
3114         int k;
3115
3116         assert(r);
3117
3118         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3119                 return -k;
3120
3121         char_array_0(path);
3122
3123         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3124                 return -ENOMEM;
3125
3126         *r = c;
3127         return 0;
3128 }
3129
3130 int getttyname_harder(int fd, char **r) {
3131         int k;
3132         char *s;
3133
3134         if ((k = getttyname_malloc(fd, &s)) < 0)
3135                 return k;
3136
3137         if (streq(s, "tty")) {
3138                 free(s);
3139                 return get_ctty(0, NULL, r);
3140         }
3141
3142         *r = s;
3143         return 0;
3144 }
3145
3146 int get_ctty_devnr(pid_t pid, dev_t *d) {
3147         int k;
3148         char line[LINE_MAX], *p, *fn;
3149         unsigned long ttynr;
3150         FILE *f;
3151
3152         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3153                 return -ENOMEM;
3154
3155         f = fopen(fn, "re");
3156         free(fn);
3157         if (!f)
3158                 return -errno;
3159
3160         if (!fgets(line, sizeof(line), f)) {
3161                 k = -errno;
3162                 fclose(f);
3163                 return k;
3164         }
3165
3166         fclose(f);
3167
3168         p = strrchr(line, ')');
3169         if (!p)
3170                 return -EIO;
3171
3172         p++;
3173
3174         if (sscanf(p, " "
3175                    "%*c "  /* state */
3176                    "%*d "  /* ppid */
3177                    "%*d "  /* pgrp */
3178                    "%*d "  /* session */
3179                    "%lu ", /* ttynr */
3180                    &ttynr) != 1)
3181                 return -EIO;
3182
3183         *d = (dev_t) ttynr;
3184         return 0;
3185 }
3186
3187 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3188         int k;
3189         char fn[PATH_MAX], *s, *b, *p;
3190         dev_t devnr;
3191
3192         assert(r);
3193
3194         k = get_ctty_devnr(pid, &devnr);
3195         if (k < 0)
3196                 return k;
3197
3198         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3199         char_array_0(fn);
3200
3201         if ((k = readlink_malloc(fn, &s)) < 0) {
3202
3203                 if (k != -ENOENT)
3204                         return k;
3205
3206                 /* This is an ugly hack */
3207                 if (major(devnr) == 136) {
3208                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3209                                 return -ENOMEM;
3210
3211                         *r = b;
3212                         if (_devnr)
3213                                 *_devnr = devnr;
3214
3215                         return 0;
3216                 }
3217
3218                 /* Probably something like the ptys which have no
3219                  * symlink in /dev/char. Let's return something
3220                  * vaguely useful. */
3221
3222                 if (!(b = strdup(fn + 5)))
3223                         return -ENOMEM;
3224
3225                 *r = b;
3226                 if (_devnr)
3227                         *_devnr = devnr;
3228
3229                 return 0;
3230         }
3231
3232         if (startswith(s, "/dev/"))
3233                 p = s + 5;
3234         else if (startswith(s, "../"))
3235                 p = s + 3;
3236         else
3237                 p = s;
3238
3239         b = strdup(p);
3240         free(s);
3241
3242         if (!b)
3243                 return -ENOMEM;
3244
3245         *r = b;
3246         if (_devnr)
3247                 *_devnr = devnr;
3248
3249         return 0;
3250 }
3251
3252 static int rm_rf_children(int fd, bool only_dirs) {
3253         DIR *d;
3254         int ret = 0;
3255
3256         assert(fd >= 0);
3257
3258         /* This returns the first error we run into, but nevertheless
3259          * tries to go on */
3260
3261         if (!(d = fdopendir(fd))) {
3262                 close_nointr_nofail(fd);
3263
3264                 return errno == ENOENT ? 0 : -errno;
3265         }
3266
3267         for (;;) {
3268                 struct dirent buf, *de;
3269                 bool is_dir;
3270                 int r;
3271
3272                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3273                         if (ret == 0)
3274                                 ret = -r;
3275                         break;
3276                 }
3277
3278                 if (!de)
3279                         break;
3280
3281                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3282                         continue;
3283
3284                 if (de->d_type == DT_UNKNOWN) {
3285                         struct stat st;
3286
3287                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3288                                 if (ret == 0 && errno != ENOENT)
3289                                         ret = -errno;
3290                                 continue;
3291                         }
3292
3293                         is_dir = S_ISDIR(st.st_mode);
3294                 } else
3295                         is_dir = de->d_type == DT_DIR;
3296
3297                 if (is_dir) {
3298                         int subdir_fd;
3299
3300                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3301                                 if (ret == 0 && errno != ENOENT)
3302                                         ret = -errno;
3303                                 continue;
3304                         }
3305
3306                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3307                                 if (ret == 0)
3308                                         ret = r;
3309                         }
3310
3311                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3312                                 if (ret == 0 && errno != ENOENT)
3313                                         ret = -errno;
3314                         }
3315                 } else  if (!only_dirs) {
3316
3317                         if (unlinkat(fd, de->d_name, 0) < 0) {
3318                                 if (ret == 0 && errno != ENOENT)
3319                                         ret = -errno;
3320                         }
3321                 }
3322         }
3323
3324         closedir(d);
3325
3326         return ret;
3327 }
3328
3329 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3330         int fd;
3331         int r;
3332
3333         assert(path);
3334
3335         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3336
3337                 if (errno != ENOTDIR)
3338                         return -errno;
3339
3340                 if (delete_root && !only_dirs)
3341                         if (unlink(path) < 0)
3342                                 return -errno;
3343
3344                 return 0;
3345         }
3346
3347         r = rm_rf_children(fd, only_dirs);
3348
3349         if (delete_root)
3350                 if (rmdir(path) < 0) {
3351                         if (r == 0)
3352                                 r = -errno;
3353                 }
3354
3355         return r;
3356 }
3357
3358 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3359         assert(path);
3360
3361         /* Under the assumption that we are running privileged we
3362          * first change the access mode and only then hand out
3363          * ownership to avoid a window where access is too open. */
3364
3365         if (chmod(path, mode) < 0)
3366                 return -errno;
3367
3368         if (chown(path, uid, gid) < 0)
3369                 return -errno;
3370
3371         return 0;
3372 }
3373
3374 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3375         cpu_set_t *r;
3376         unsigned n = 1024;
3377
3378         /* Allocates the cpuset in the right size */
3379
3380         for (;;) {
3381                 if (!(r = CPU_ALLOC(n)))
3382                         return NULL;
3383
3384                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3385                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3386
3387                         if (ncpus)
3388                                 *ncpus = n;
3389
3390                         return r;
3391                 }
3392
3393                 CPU_FREE(r);
3394
3395                 if (errno != EINVAL)
3396                         return NULL;
3397
3398                 n *= 2;
3399         }
3400 }
3401
3402 void status_vprintf(const char *format, va_list ap) {
3403         char *s = NULL;
3404         int fd = -1;
3405
3406         assert(format);
3407
3408         /* This independent of logging, as status messages are
3409          * optional and go exclusively to the console. */
3410
3411         if (vasprintf(&s, format, ap) < 0)
3412                 goto finish;
3413
3414         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3415                 goto finish;
3416
3417         write(fd, s, strlen(s));
3418
3419 finish:
3420         free(s);
3421
3422         if (fd >= 0)
3423                 close_nointr_nofail(fd);
3424 }
3425
3426 void status_printf(const char *format, ...) {
3427         va_list ap;
3428
3429         assert(format);
3430
3431         va_start(ap, format);
3432         status_vprintf(format, ap);
3433         va_end(ap);
3434 }
3435
3436 void status_welcome(void) {
3437         char *pretty_name = NULL, *ansi_color = NULL;
3438         const char *const_pretty = NULL, *const_color = NULL;
3439         int r;
3440
3441         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3442                                 "PRETTY_NAME", &pretty_name,
3443                                 "ANSI_COLOR", &ansi_color,
3444                                 NULL)) < 0) {
3445
3446                 if (r != -ENOENT)
3447                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3448         }
3449
3450 #if defined(TARGET_FEDORA)
3451         if (!pretty_name) {
3452                 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3453
3454                         if (r != -ENOENT)
3455                                 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3456                 }
3457         }
3458
3459         if (!ansi_color && pretty_name) {
3460
3461                 /* This tries to mimic the color magic the old Red Hat sysinit
3462                  * script did. */
3463
3464                 if (startswith(pretty_name, "Red Hat"))
3465                         const_color = "0;31"; /* Red for RHEL */
3466                 else if (startswith(pretty_name, "Fedora"))
3467                         const_color = "0;34"; /* Blue for Fedora */
3468         }
3469
3470 #elif defined(TARGET_SUSE)
3471
3472         if (!pretty_name) {
3473                 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3474
3475                         if (r != -ENOENT)
3476                                 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3477                 }
3478         }
3479
3480         if (!ansi_color)
3481                 const_color = "0;32"; /* Green for openSUSE */
3482
3483 #elif defined(TARGET_GENTOO)
3484
3485         if (!pretty_name) {
3486                 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3487
3488                         if (r != -ENOENT)
3489                                 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3490                 }
3491         }
3492
3493         if (!ansi_color)
3494                 const_color = "1;34"; /* Light Blue for Gentoo */
3495
3496 #elif defined(TARGET_ALTLINUX)
3497
3498         if (!pretty_name) {
3499                 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3500
3501                         if (r != -ENOENT)
3502                                 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3503                 }
3504         }
3505
3506         if (!ansi_color)
3507                 const_color = "0;36"; /* Cyan for ALTLinux */
3508
3509
3510 #elif defined(TARGET_DEBIAN)
3511
3512         if (!pretty_name) {
3513                 char *version;
3514
3515                 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3516
3517                         if (r != -ENOENT)
3518                                 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3519                 } else {
3520                         pretty_name = strappend("Debian ", version);
3521                         free(version);
3522
3523                         if (!pretty_name)
3524                                 log_warning("Failed to allocate Debian version string.");
3525                 }
3526         }
3527
3528         if (!ansi_color)
3529                 const_color = "1;31"; /* Light Red for Debian */
3530
3531 #elif defined(TARGET_UBUNTU)
3532
3533         if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3534                                 "DISTRIB_DESCRIPTION", &pretty_name,
3535                                 NULL)) < 0) {
3536
3537                 if (r != -ENOENT)
3538                         log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3539         }
3540
3541         if (!ansi_color)
3542                 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3543
3544 #elif defined(TARGET_MANDRIVA)
3545
3546         if (!pretty_name) {
3547                 char *s, *p;
3548
3549                 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3550                         if (r != -ENOENT)
3551                                 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3552                 } else {
3553                         p = strstr(s, " release ");
3554                         if (p) {
3555                                 *p = '\0';
3556                                 p += 9;
3557                                 p[strcspn(p, " ")] = '\0';
3558
3559                                 /* This corresponds to standard rc.sysinit */
3560                                 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3561                                         const_color = "1;36";
3562                                 else
3563                                         log_warning("Failed to allocate Mandriva version string.");
3564                         } else
3565                                 log_warning("Failed to parse /etc/mandriva-release");
3566                         free(s);
3567                 }
3568         }
3569 #elif defined(TARGET_MEEGO)
3570
3571         if (!pretty_name) {
3572                 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3573
3574                         if (r != -ENOENT)
3575                                 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3576                 }
3577         }
3578
3579        if (!ansi_color)
3580                const_color = "1;35"; /* Bright Magenta for MeeGo */
3581 #endif
3582
3583         if (!pretty_name && !const_pretty)
3584                 const_pretty = "Linux";
3585
3586         if (!ansi_color && !const_color)
3587                 const_color = "1";
3588
3589         status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3590                       const_color ? const_color : ansi_color,
3591                       const_pretty ? const_pretty : pretty_name);
3592
3593         free(ansi_color);
3594         free(pretty_name);
3595 }
3596
3597 char *replace_env(const char *format, char **env) {
3598         enum {
3599                 WORD,
3600                 CURLY,
3601                 VARIABLE
3602         } state = WORD;
3603
3604         const char *e, *word = format;
3605         char *r = NULL, *k;
3606
3607         assert(format);
3608
3609         for (e = format; *e; e ++) {
3610
3611                 switch (state) {
3612
3613                 case WORD:
3614                         if (*e == '$')
3615                                 state = CURLY;
3616                         break;
3617
3618                 case CURLY:
3619                         if (*e == '{') {
3620                                 if (!(k = strnappend(r, word, e-word-1)))
3621                                         goto fail;
3622
3623                                 free(r);
3624                                 r = k;
3625
3626                                 word = e-1;
3627                                 state = VARIABLE;
3628
3629                         } else if (*e == '$') {
3630                                 if (!(k = strnappend(r, word, e-word)))
3631                                         goto fail;
3632
3633                                 free(r);
3634                                 r = k;
3635
3636                                 word = e+1;
3637                                 state = WORD;
3638                         } else
3639                                 state = WORD;
3640                         break;
3641
3642                 case VARIABLE:
3643                         if (*e == '}') {
3644                                 const char *t;
3645
3646                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3647                                         t = "";
3648
3649                                 if (!(k = strappend(r, t)))
3650                                         goto fail;
3651
3652                                 free(r);
3653                                 r = k;
3654
3655                                 word = e+1;
3656                                 state = WORD;
3657                         }
3658                         break;
3659                 }
3660         }
3661
3662         if (!(k = strnappend(r, word, e-word)))
3663                 goto fail;
3664
3665         free(r);
3666         return k;
3667
3668 fail:
3669         free(r);
3670         return NULL;
3671 }
3672
3673 char **replace_env_argv(char **argv, char **env) {
3674         char **r, **i;
3675         unsigned k = 0, l = 0;
3676
3677         l = strv_length(argv);
3678
3679         if (!(r = new(char*, l+1)))
3680                 return NULL;
3681
3682         STRV_FOREACH(i, argv) {
3683
3684                 /* If $FOO appears as single word, replace it by the split up variable */
3685                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3686                         char *e;
3687                         char **w, **m;
3688                         unsigned q;
3689
3690                         if ((e = strv_env_get(env, *i+1))) {
3691
3692                                 if (!(m = strv_split_quoted(e))) {
3693                                         r[k] = NULL;
3694                                         strv_free(r);
3695                                         return NULL;
3696                                 }
3697                         } else
3698                                 m = NULL;
3699
3700                         q = strv_length(m);
3701                         l = l + q - 1;
3702
3703                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3704                                 r[k] = NULL;
3705                                 strv_free(r);
3706                                 strv_free(m);
3707                                 return NULL;
3708                         }
3709
3710                         r = w;
3711                         if (m) {
3712                                 memcpy(r + k, m, q * sizeof(char*));
3713                                 free(m);
3714                         }
3715
3716                         k += q;
3717                         continue;
3718                 }
3719
3720                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3721                 if (!(r[k++] = replace_env(*i, env))) {
3722                         strv_free(r);
3723                         return NULL;
3724                 }
3725         }
3726
3727         r[k] = NULL;
3728         return r;
3729 }
3730
3731 int columns(void) {
3732         static __thread int parsed_columns = 0;
3733         const char *e;
3734
3735         if (parsed_columns > 0)
3736                 return parsed_columns;
3737
3738         if ((e = getenv("COLUMNS")))
3739                 parsed_columns = atoi(e);
3740
3741         if (parsed_columns <= 0) {
3742                 struct winsize ws;
3743                 zero(ws);
3744
3745                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3746                         parsed_columns = ws.ws_col;
3747         }
3748
3749         if (parsed_columns <= 0)
3750                 parsed_columns = 80;
3751
3752         return parsed_columns;
3753 }
3754
3755 int running_in_chroot(void) {
3756         struct stat a, b;
3757
3758         zero(a);
3759         zero(b);
3760
3761         /* Only works as root */
3762
3763         if (stat("/proc/1/root", &a) < 0)
3764                 return -errno;
3765
3766         if (stat("/", &b) < 0)
3767                 return -errno;
3768
3769         return
3770                 a.st_dev != b.st_dev ||
3771                 a.st_ino != b.st_ino;
3772 }
3773
3774 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3775         size_t l, x;
3776         char *r;
3777
3778         assert(s);
3779         assert(percent <= 100);
3780         assert(length >= 3);
3781
3782         l = strlen(s);
3783
3784         if (l <= 3 || l <= length)
3785                 return strdup(s);
3786
3787         if (!(r = new0(char, length+1)))
3788                 return r;
3789
3790         x = (length * percent) / 100;
3791
3792         if (x > length - 3)
3793                 x = length - 3;
3794
3795         memcpy(r, s, x);
3796         r[x] = '.';
3797         r[x+1] = '.';
3798         r[x+2] = '.';
3799         memcpy(r + x + 3,
3800                s + l - (length - x - 3),
3801                length - x - 3);
3802
3803         return r;
3804 }
3805
3806 int touch(const char *path) {
3807         int fd;
3808
3809         assert(path);
3810
3811         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3812                 return -errno;
3813
3814         close_nointr_nofail(fd);
3815         return 0;
3816 }
3817
3818 char *unquote(const char *s, const char* quotes) {
3819         size_t l;
3820         assert(s);
3821
3822         if ((l = strlen(s)) < 2)
3823                 return strdup(s);
3824
3825         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3826                 return strndup(s+1, l-2);
3827
3828         return strdup(s);
3829 }
3830
3831 char *normalize_env_assignment(const char *s) {
3832         char *name, *value, *p, *r;
3833
3834         p = strchr(s, '=');
3835
3836         if (!p) {
3837                 if (!(r = strdup(s)))
3838                         return NULL;
3839
3840                 return strstrip(r);
3841         }
3842
3843         if (!(name = strndup(s, p - s)))
3844                 return NULL;
3845
3846         if (!(p = strdup(p+1))) {
3847                 free(name);
3848                 return NULL;
3849         }
3850
3851         value = unquote(strstrip(p), QUOTES);
3852         free(p);
3853
3854         if (!value) {
3855                 free(name);
3856                 return NULL;
3857         }
3858
3859         if (asprintf(&r, "%s=%s", name, value) < 0)
3860                 r = NULL;
3861
3862         free(value);
3863         free(name);
3864
3865         return r;
3866 }
3867
3868 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3869         siginfo_t dummy;
3870
3871         assert(pid >= 1);
3872
3873         if (!status)
3874                 status = &dummy;
3875
3876         for (;;) {
3877                 zero(*status);
3878
3879                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3880
3881                         if (errno == EINTR)
3882                                 continue;
3883
3884                         return -errno;
3885                 }
3886
3887                 return 0;
3888         }
3889 }
3890
3891 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3892         int r;
3893         siginfo_t status;
3894
3895         assert(name);
3896         assert(pid > 1);
3897
3898         if ((r = wait_for_terminate(pid, &status)) < 0) {
3899                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3900                 return r;
3901         }
3902
3903         if (status.si_code == CLD_EXITED) {
3904                 if (status.si_status != 0) {
3905                         log_warning("%s failed with error code %i.", name, status.si_status);
3906                         return status.si_status;
3907                 }
3908
3909                 log_debug("%s succeeded.", name);
3910                 return 0;
3911
3912         } else if (status.si_code == CLD_KILLED ||
3913                    status.si_code == CLD_DUMPED) {
3914
3915                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3916                 return -EPROTO;
3917         }
3918
3919         log_warning("%s failed due to unknown reason.", name);
3920         return -EPROTO;
3921
3922 }
3923
3924 void freeze(void) {
3925
3926         /* Make sure nobody waits for us on a socket anymore */
3927         close_all_fds(NULL, 0);
3928
3929         sync();
3930
3931         for (;;)
3932                 pause();
3933 }
3934
3935 bool null_or_empty(struct stat *st) {
3936         assert(st);
3937
3938         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3939                 return true;
3940
3941         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3942                 return true;
3943
3944         return false;
3945 }
3946
3947 DIR *xopendirat(int fd, const char *name, int flags) {
3948         int nfd;
3949         DIR *d;
3950
3951         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3952                 return NULL;
3953
3954         if (!(d = fdopendir(nfd))) {
3955                 close_nointr_nofail(nfd);
3956                 return NULL;
3957         }
3958
3959         return d;
3960 }
3961
3962 int signal_from_string_try_harder(const char *s) {
3963         int signo;
3964         assert(s);
3965
3966         if ((signo = signal_from_string(s)) <= 0)
3967                 if (startswith(s, "SIG"))
3968                         return signal_from_string(s+3);
3969
3970         return signo;
3971 }
3972
3973 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3974
3975         assert(f);
3976         assert(name);
3977         assert(t);
3978
3979         if (!dual_timestamp_is_set(t))
3980                 return;
3981
3982         fprintf(f, "%s=%llu %llu\n",
3983                 name,
3984                 (unsigned long long) t->realtime,
3985                 (unsigned long long) t->monotonic);
3986 }
3987
3988 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3989         unsigned long long a, b;
3990
3991         assert(value);
3992         assert(t);
3993
3994         if (sscanf(value, "%lli %llu", &a, &b) != 2)
3995                 log_debug("Failed to parse finish timestamp value %s", value);
3996         else {
3997                 t->realtime = a;
3998                 t->monotonic = b;
3999         }
4000 }
4001
4002 char *fstab_node_to_udev_node(const char *p) {
4003         char *dn, *t, *u;
4004         int r;
4005
4006         /* FIXME: to follow udev's logic 100% we need to leave valid
4007          * UTF8 chars unescaped */
4008
4009         if (startswith(p, "LABEL=")) {
4010
4011                 if (!(u = unquote(p+6, "\"\'")))
4012                         return NULL;
4013
4014                 t = xescape(u, "/ ");
4015                 free(u);
4016
4017                 if (!t)
4018                         return NULL;
4019
4020                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4021                 free(t);
4022
4023                 if (r < 0)
4024                         return NULL;
4025
4026                 return dn;
4027         }
4028
4029         if (startswith(p, "UUID=")) {
4030
4031                 if (!(u = unquote(p+5, "\"\'")))
4032                         return NULL;
4033
4034                 t = xescape(u, "/ ");
4035                 free(u);
4036
4037                 if (!t)
4038                         return NULL;
4039
4040                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4041                 free(t);
4042
4043                 if (r < 0)
4044                         return NULL;
4045
4046                 return dn;
4047         }
4048
4049         return strdup(p);
4050 }
4051
4052 void filter_environ(const char *prefix) {
4053         int i, j;
4054         assert(prefix);
4055
4056         if (!environ)
4057                 return;
4058
4059         for (i = 0, j = 0; environ[i]; i++) {
4060
4061                 if (startswith(environ[i], prefix))
4062                         continue;
4063
4064                 environ[j++] = environ[i];
4065         }
4066
4067         environ[j] = NULL;
4068 }
4069
4070 bool tty_is_vc(const char *tty) {
4071         assert(tty);
4072
4073         if (startswith(tty, "/dev/"))
4074                 tty += 5;
4075
4076         return vtnr_from_tty(tty) >= 0;
4077 }
4078
4079 int vtnr_from_tty(const char *tty) {
4080         int i, r;
4081
4082         assert(tty);
4083
4084         if (startswith(tty, "/dev/"))
4085                 tty += 5;
4086
4087         if (!startswith(tty, "tty") )
4088                 return -EINVAL;
4089
4090         if (tty[3] < '0' || tty[3] > '9')
4091                 return -EINVAL;
4092
4093         r = safe_atoi(tty+3, &i);
4094         if (r < 0)
4095                 return r;
4096
4097         if (i < 0 || i > 63)
4098                 return -EINVAL;
4099
4100         return i;
4101 }
4102
4103 const char *default_term_for_tty(const char *tty) {
4104         char *active = NULL;
4105         const char *term;
4106
4107         assert(tty);
4108
4109         if (startswith(tty, "/dev/"))
4110                 tty += 5;
4111
4112         /* Resolve where /dev/console is pointing when determining
4113          * TERM */
4114         if (streq(tty, "console"))
4115                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4116                         /* If multiple log outputs are configured the
4117                          * last one is what /dev/console points to */
4118                         if ((tty = strrchr(active, ' ')))
4119                                 tty++;
4120                         else
4121                                 tty = active;
4122                 }
4123
4124         term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4125         free(active);
4126
4127         return term;
4128 }
4129
4130 /* Returns a short identifier for the various VM implementations */
4131 int detect_vm(const char **id) {
4132
4133 #if defined(__i386__) || defined(__x86_64__)
4134
4135         /* Both CPUID and DMI are x86 specific interfaces... */
4136
4137         static const char *const dmi_vendors[] = {
4138                 "/sys/class/dmi/id/sys_vendor",
4139                 "/sys/class/dmi/id/board_vendor",
4140                 "/sys/class/dmi/id/bios_vendor"
4141         };
4142
4143         static const char dmi_vendor_table[] =
4144                 "QEMU\0"                  "qemu\0"
4145                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4146                 "VMware\0"                "vmware\0"
4147                 "VMW\0"                   "vmware\0"
4148                 "Microsoft Corporation\0" "microsoft\0"
4149                 "innotek GmbH\0"          "oracle\0"
4150                 "Xen\0"                   "xen\0"
4151                 "Bochs\0"                 "bochs\0";
4152
4153         static const char cpuid_vendor_table[] =
4154                 "XenVMMXenVMM\0"          "xen\0"
4155                 "KVMKVMKVM\0"             "kvm\0"
4156                 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4157                 "VMwareVMware\0"          "vmware\0"
4158                 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4159                 "Microsoft Hv\0"          "microsoft\0";
4160
4161         uint32_t eax, ecx;
4162         union {
4163                 uint32_t sig32[3];
4164                 char text[13];
4165         } sig;
4166         unsigned i;
4167         const char *j, *k;
4168         bool hypervisor;
4169
4170         /* http://lwn.net/Articles/301888/ */
4171         zero(sig);
4172
4173 #if defined (__i386__)
4174 #define REG_a "eax"
4175 #define REG_b "ebx"
4176 #elif defined (__amd64__)
4177 #define REG_a "rax"
4178 #define REG_b "rbx"
4179 #endif
4180
4181         /* First detect whether there is a hypervisor */
4182         eax = 1;
4183         __asm__ __volatile__ (
4184                 /* ebx/rbx is being used for PIC! */
4185                 "  push %%"REG_b"         \n\t"
4186                 "  cpuid                  \n\t"
4187                 "  pop %%"REG_b"          \n\t"
4188
4189                 : "=a" (eax), "=c" (ecx)
4190                 : "0" (eax)
4191         );
4192
4193         hypervisor = !!(ecx & 0x80000000U);
4194
4195         if (hypervisor) {
4196
4197                 /* There is a hypervisor, see what it is */
4198                 eax = 0x40000000U;
4199                 __asm__ __volatile__ (
4200                         /* ebx/rbx is being used for PIC! */
4201                         "  push %%"REG_b"         \n\t"
4202                         "  cpuid                  \n\t"
4203                         "  mov %%ebx, %1          \n\t"
4204                         "  pop %%"REG_b"          \n\t"
4205
4206                         : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4207                         : "0" (eax)
4208                 );
4209
4210                 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4211                         if (streq(sig.text, j)) {
4212
4213                                 if (id)
4214                                         *id = k;
4215
4216                                 return 1;
4217                         }
4218         }
4219
4220         for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4221                 char *s;
4222                 int r;
4223                 const char *found = NULL;
4224
4225                 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4226                         if (r != -ENOENT)
4227                                 return r;
4228
4229                         continue;
4230                 }
4231
4232                 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4233                         if (startswith(s, j))
4234                                 found = k;
4235                 free(s);
4236
4237                 if (found) {
4238                         if (id)
4239                                 *id = found;
4240
4241                         return 1;
4242                 }
4243         }
4244
4245         if (hypervisor) {
4246                 if (id)
4247                         *id = "other";
4248
4249                 return 1;
4250         }
4251
4252 #endif
4253         return 0;
4254 }
4255
4256 int detect_container(const char **id) {
4257         FILE *f;
4258
4259         /* Unfortunately many of these operations require root access
4260          * in one way or another */
4261
4262         if (geteuid() != 0)
4263                 return -EPERM;
4264
4265         if (running_in_chroot() > 0) {
4266
4267                 if (id)
4268                         *id = "chroot";
4269
4270                 return 1;
4271         }
4272
4273         /* /proc/vz exists in container and outside of the container,
4274          * /proc/bc only outside of the container. */
4275         if (access("/proc/vz", F_OK) >= 0 &&
4276             access("/proc/bc", F_OK) < 0) {
4277
4278                 if (id)
4279                         *id = "openvz";
4280
4281                 return 1;
4282         }
4283
4284         if ((f = fopen("/proc/self/cgroup", "re"))) {
4285
4286                 for (;;) {
4287                         char line[LINE_MAX], *p;
4288
4289                         if (!fgets(line, sizeof(line), f))
4290                                 break;
4291
4292                         if (!(p = strchr(strstrip(line), ':')))
4293                                 continue;
4294
4295                         if (strncmp(p, ":ns:", 4))
4296                                 continue;
4297
4298                         if (!streq(p, ":ns:/")) {
4299                                 fclose(f);
4300
4301                                 if (id)
4302                                         *id = "pidns";
4303
4304                                 return 1;
4305                         }
4306                 }
4307
4308                 fclose(f);
4309         }
4310
4311         return 0;
4312 }
4313
4314 /* Returns a short identifier for the various VM/container implementations */
4315 int detect_virtualization(const char **id) {
4316         static __thread const char *cached_id = NULL;
4317         const char *_id;
4318         int r;
4319
4320         if (cached_id) {
4321
4322                 if (cached_id == (const char*) -1)
4323                         return 0;
4324
4325                 if (id)
4326                         *id = cached_id;
4327
4328                 return 1;
4329         }
4330
4331         if ((r = detect_container(&_id)) != 0)
4332                 goto finish;
4333
4334         r = detect_vm(&_id);
4335
4336 finish:
4337         if (r > 0) {
4338                 cached_id = _id;
4339
4340                 if (id)
4341                         *id = _id;
4342         } else if (r == 0)
4343                 cached_id = (const char*) -1;
4344
4345         return r;
4346 }
4347
4348 bool dirent_is_file(struct dirent *de) {
4349         assert(de);
4350
4351         if (ignore_file(de->d_name))
4352                 return false;
4353
4354         if (de->d_type != DT_REG &&
4355             de->d_type != DT_LNK &&
4356             de->d_type != DT_UNKNOWN)
4357                 return false;
4358
4359         return true;
4360 }
4361
4362 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4363         DIR *_d = NULL;
4364         struct dirent *de;
4365         Hashmap *pids = NULL;
4366
4367         assert(directory);
4368
4369         /* Executes all binaries in a directory in parallel and waits
4370          * until all they all finished. */
4371
4372         if (!d) {
4373                 if (!(_d = opendir(directory))) {
4374
4375                         if (errno == ENOENT)
4376                                 return;
4377
4378                         log_error("Failed to enumerate directory %s: %m", directory);
4379                         return;
4380                 }
4381
4382                 d = _d;
4383         }
4384
4385         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4386                 log_error("Failed to allocate set.");
4387                 goto finish;
4388         }
4389
4390         while ((de = readdir(d))) {
4391                 char *path;
4392                 pid_t pid;
4393                 int k;
4394
4395                 if (!dirent_is_file(de))
4396                         continue;
4397
4398                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4399                         log_error("Out of memory");
4400                         continue;
4401                 }
4402
4403                 if ((pid = fork()) < 0) {
4404                         log_error("Failed to fork: %m");
4405                         free(path);
4406                         continue;
4407                 }
4408
4409                 if (pid == 0) {
4410                         char *_argv[2];
4411                         /* Child */
4412
4413                         if (!argv) {
4414                                 _argv[0] = path;
4415                                 _argv[1] = NULL;
4416                                 argv = _argv;
4417                         } else
4418                                 if (!argv[0])
4419                                         argv[0] = path;
4420
4421                         execv(path, argv);
4422
4423                         log_error("Failed to execute %s: %m", path);
4424                         _exit(EXIT_FAILURE);
4425                 }
4426
4427                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4428
4429                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4430                         log_error("Failed to add PID to set: %s", strerror(-k));
4431                         free(path);
4432                 }
4433         }
4434
4435         while (!hashmap_isempty(pids)) {
4436                 siginfo_t si;
4437                 char *path;
4438
4439                 zero(si);
4440                 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4441
4442                         if (errno == EINTR)
4443                                 continue;
4444
4445                         log_error("waitid() failed: %m");
4446                         goto finish;
4447                 }
4448
4449                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4450                         if (!is_clean_exit(si.si_code, si.si_status)) {
4451                                 if (si.si_code == CLD_EXITED)
4452                                         log_error("%s exited with exit status %i.", path, si.si_status);
4453                                 else
4454                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4455                         } else
4456                                 log_debug("%s exited successfully.", path);
4457
4458                         free(path);
4459                 }
4460         }
4461
4462 finish:
4463         if (_d)
4464                 closedir(_d);
4465
4466         if (pids)
4467                 hashmap_free_free(pids);
4468 }
4469
4470 int kill_and_sigcont(pid_t pid, int sig) {
4471         int r;
4472
4473         r = kill(pid, sig) < 0 ? -errno : 0;
4474
4475         if (r >= 0)
4476                 kill(pid, SIGCONT);
4477
4478         return r;
4479 }
4480
4481 bool nulstr_contains(const char*nulstr, const char *needle) {
4482         const char *i;
4483
4484         if (!nulstr)
4485                 return false;
4486
4487         NULSTR_FOREACH(i, nulstr)
4488                 if (streq(i, needle))
4489                         return true;
4490
4491         return false;
4492 }
4493
4494 bool plymouth_running(void) {
4495         return access("/run/plymouth/pid", F_OK) >= 0;
4496 }
4497
4498 void parse_syslog_priority(char **p, int *priority) {
4499         int a = 0, b = 0, c = 0;
4500         int k;
4501
4502         assert(p);
4503         assert(*p);
4504         assert(priority);
4505
4506         if ((*p)[0] != '<')
4507                 return;
4508
4509         if (!strchr(*p, '>'))
4510                 return;
4511
4512         if ((*p)[2] == '>') {
4513                 c = undecchar((*p)[1]);
4514                 k = 3;
4515         } else if ((*p)[3] == '>') {
4516                 b = undecchar((*p)[1]);
4517                 c = undecchar((*p)[2]);
4518                 k = 4;
4519         } else if ((*p)[4] == '>') {
4520                 a = undecchar((*p)[1]);
4521                 b = undecchar((*p)[2]);
4522                 c = undecchar((*p)[3]);
4523                 k = 5;
4524         } else
4525                 return;
4526
4527         if (a < 0 || b < 0 || c < 0)
4528                 return;
4529
4530         *priority = a*100+b*10+c;
4531         *p += k;
4532 }
4533
4534 int have_effective_cap(int value) {
4535         cap_t cap;
4536         cap_flag_value_t fv;
4537         int r;
4538
4539         if (!(cap = cap_get_proc()))
4540                 return -errno;
4541
4542         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4543                 r = -errno;
4544         else
4545                 r = fv == CAP_SET;
4546
4547         cap_free(cap);
4548         return r;
4549 }
4550
4551 char* strshorten(char *s, size_t l) {
4552         assert(s);
4553
4554         if (l < strlen(s))
4555                 s[l] = 0;
4556
4557         return s;
4558 }
4559
4560 static bool hostname_valid_char(char c) {
4561         return
4562                 (c >= 'a' && c <= 'z') ||
4563                 (c >= 'A' && c <= 'Z') ||
4564                 (c >= '0' && c <= '9') ||
4565                 c == '-' ||
4566                 c == '_' ||
4567                 c == '.';
4568 }
4569
4570 bool hostname_is_valid(const char *s) {
4571         const char *p;
4572
4573         if (isempty(s))
4574                 return false;
4575
4576         for (p = s; *p; p++)
4577                 if (!hostname_valid_char(*p))
4578                         return false;
4579
4580         if (p-s > HOST_NAME_MAX)
4581                 return false;
4582
4583         return true;
4584 }
4585
4586 char* hostname_cleanup(char *s) {
4587         char *p, *d;
4588
4589         for (p = s, d = s; *p; p++)
4590                 if ((*p >= 'a' && *p <= 'z') ||
4591                     (*p >= 'A' && *p <= 'Z') ||
4592                     (*p >= '0' && *p <= '9') ||
4593                     *p == '-' ||
4594                     *p == '_' ||
4595                     *p == '.')
4596                         *(d++) = *p;
4597
4598         *d = 0;
4599
4600         strshorten(s, HOST_NAME_MAX);
4601         return s;
4602 }
4603
4604 int pipe_eof(int fd) {
4605         struct pollfd pollfd;
4606         int r;
4607
4608         zero(pollfd);
4609         pollfd.fd = fd;
4610         pollfd.events = POLLIN|POLLHUP;
4611
4612         r = poll(&pollfd, 1, 0);
4613         if (r < 0)
4614                 return -errno;
4615
4616         if (r == 0)
4617                 return 0;
4618
4619         return pollfd.revents & POLLHUP;
4620 }
4621
4622 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4623         FILE *f;
4624         char *t;
4625         const char *fn;
4626         size_t k;
4627         int fd;
4628
4629         assert(path);
4630         assert(_f);
4631         assert(_temp_path);
4632
4633         t = new(char, strlen(path) + 1 + 6 + 1);
4634         if (!t)
4635                 return -ENOMEM;
4636
4637         fn = file_name_from_path(path);
4638         k = fn-path;
4639         memcpy(t, path, k);
4640         t[k] = '.';
4641         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4642
4643         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4644         if (fd < 0) {
4645                 free(t);
4646                 return -errno;
4647         }
4648
4649         f = fdopen(fd, "we");
4650         if (!f) {
4651                 unlink(t);
4652                 free(t);
4653                 return -errno;
4654         }
4655
4656         *_f = f;
4657         *_temp_path = t;
4658
4659         return 0;
4660 }
4661
4662 int terminal_vhangup_fd(int fd) {
4663         assert(fd >= 0);
4664
4665         if (ioctl(fd, TIOCVHANGUP) < 0)
4666                 return -errno;
4667
4668         return 0;
4669 }
4670
4671 int terminal_vhangup(const char *name) {
4672         int fd, r;
4673
4674         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4675         if (fd < 0)
4676                 return fd;
4677
4678         r = terminal_vhangup_fd(fd);
4679         close_nointr_nofail(fd);
4680
4681         return r;
4682 }
4683
4684 int vt_disallocate(const char *name) {
4685         int fd, r;
4686         unsigned u;
4687
4688         /* Deallocate the VT if possible. If not possible
4689          * (i.e. because it is the active one), at least clear it
4690          * entirely (including the scrollback buffer) */
4691
4692         if (!startswith(name, "/dev/"))
4693                 return -EINVAL;
4694
4695         if (!tty_is_vc(name)) {
4696                 /* So this is not a VT. I guess we cannot deallocate
4697                  * it then. But let's at least clear the screen */
4698
4699                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4700                 if (fd < 0)
4701                         return fd;
4702
4703                 loop_write(fd,
4704                            "\033[r"    /* clear scrolling region */
4705                            "\033[H"    /* move home */
4706                            "\033[2J",  /* clear screen */
4707                            10, false);
4708                 close_nointr_nofail(fd);
4709
4710                 return 0;
4711         }
4712
4713         if (!startswith(name, "/dev/tty"))
4714                 return -EINVAL;
4715
4716         r = safe_atou(name+8, &u);
4717         if (r < 0)
4718                 return r;
4719
4720         if (u <= 0)
4721                 return -EINVAL;
4722
4723         /* Try to deallocate */
4724         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4725         if (fd < 0)
4726                 return fd;
4727
4728         r = ioctl(fd, VT_DISALLOCATE, u);
4729         close_nointr_nofail(fd);
4730
4731         if (r >= 0)
4732                 return 0;
4733
4734         if (errno != EBUSY)
4735                 return -errno;
4736
4737         /* Couldn't deallocate, so let's clear it fully with
4738          * scrollback */
4739         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4740         if (fd < 0)
4741                 return fd;
4742
4743         loop_write(fd,
4744                    "\033[r"   /* clear scrolling region */
4745                    "\033[H"   /* move home */
4746                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4747                    10, false);
4748         close_nointr_nofail(fd);
4749
4750         return 0;
4751 }
4752
4753
4754 static int file_is_conf(const struct dirent *d, const char *suffix) {
4755         assert(d);
4756
4757         if (ignore_file(d->d_name))
4758                 return 0;
4759
4760         if (d->d_type != DT_REG &&
4761             d->d_type != DT_LNK &&
4762             d->d_type != DT_UNKNOWN)
4763                 return 0;
4764
4765         return endswith(d->d_name, suffix);
4766 }
4767
4768 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4769         DIR *dir;
4770         struct dirent *de;
4771         int r = 0;
4772
4773         dir = opendir(path);
4774         if (!dir) {
4775                 if (errno == ENOENT)
4776                         return 0;
4777                 return -errno;
4778         }
4779
4780         for (de = readdir(dir); de; de = readdir(dir)) {
4781                 char *p, *f;
4782                 const char *base;
4783
4784                 if (!file_is_conf(de, suffix))
4785                         continue;
4786
4787                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4788                         r = -ENOMEM;
4789                         goto finish;
4790                 }
4791
4792                 f = canonicalize_file_name(p);
4793                 if (!f) {
4794                         log_error("Failed to canonicalize file name '%s': %m", p);
4795                         free(p);
4796                         continue;
4797                 }
4798                 free(p);
4799
4800                 log_debug("found: %s\n", f);
4801                 base = f + strlen(path) + 1;
4802                 if (hashmap_put(h, base, f) <= 0)
4803                         free(f);
4804         }
4805
4806 finish:
4807         closedir(dir);
4808         return r;
4809 }
4810
4811 static int base_cmp(const void *a, const void *b) {
4812         const char *s1, *s2;
4813
4814         s1 = *(char * const *)a;
4815         s2 = *(char * const *)b;
4816         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4817 }
4818
4819 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4820         Hashmap *fh = NULL;
4821         char **dirs = NULL;
4822         char **files = NULL;
4823         char **p;
4824         va_list ap;
4825         int r = 0;
4826
4827         va_start(ap, dir);
4828         dirs = strv_new_ap(dir, ap);
4829         va_end(ap);
4830         if (!dirs) {
4831                 r = -ENOMEM;
4832                 goto finish;
4833         }
4834         if (!strv_path_canonicalize(dirs)) {
4835                 r = -ENOMEM;
4836                 goto finish;
4837         }
4838         if (!strv_uniq(dirs)) {
4839                 r = -ENOMEM;
4840                 goto finish;
4841         }
4842
4843         fh = hashmap_new(string_hash_func, string_compare_func);
4844         if (!fh) {
4845                 r = -ENOMEM;
4846                 goto finish;
4847         }
4848
4849         STRV_FOREACH(p, dirs) {
4850                 if (files_add(fh, *p, suffix) < 0) {
4851                         log_error("Failed to search for files.");
4852                         r = -EINVAL;
4853                         goto finish;
4854                 }
4855         }
4856
4857         files = hashmap_get_strv(fh);
4858         if (files == NULL) {
4859                 log_error("Failed to compose list of files.");
4860                 r = -ENOMEM;
4861                 goto finish;
4862         }
4863
4864         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4865
4866 finish:
4867         strv_free(dirs);
4868         hashmap_free(fh);
4869         *strv = files;
4870         return r;
4871 }
4872
4873 int hwclock_is_localtime(void) {
4874         FILE *f;
4875         bool local = false;
4876
4877         /*
4878          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4879          *   # /etc/adjtime
4880          *   0.0 0 0
4881          *   0
4882          *   UTC
4883          */
4884         f = fopen("/etc/adjtime", "re");
4885         if (f) {
4886                 char line[LINE_MAX];
4887                 bool b;
4888
4889                 b = fgets(line, sizeof(line), f) &&
4890                         fgets(line, sizeof(line), f) &&
4891                         fgets(line, sizeof(line), f);
4892
4893                 fclose(f);
4894
4895                 if (!b)
4896                         return -EIO;
4897
4898
4899                 truncate_nl(line);
4900                 local = streq(line, "LOCAL");
4901
4902         } else if (errno != -ENOENT)
4903                 return -errno;
4904
4905         return local;
4906 }
4907
4908 int hwclock_apply_localtime_delta(void) {
4909         const struct timeval *tv_null = NULL;
4910         struct timespec ts;
4911         struct tm *tm;
4912         int minuteswest;
4913         struct timezone tz;
4914
4915         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4916         assert_se(tm = localtime(&ts.tv_sec));
4917         minuteswest = tm->tm_gmtoff / 60;
4918
4919         tz.tz_minuteswest = -minuteswest;
4920         tz.tz_dsttime = 0; /* DST_NONE*/
4921
4922         /*
4923          * If the hardware clock does not run in UTC, but in local time:
4924          * The very first time we set the kernel's timezone, it will warp
4925          * the clock so that it runs in UTC instead of local time.
4926          */
4927         if (settimeofday(tv_null, &tz) < 0)
4928                 return -errno;
4929
4930         return minuteswest;
4931 }
4932
4933 int hwclock_reset_localtime_delta(void) {
4934         const struct timeval *tv_null = NULL;
4935         struct timezone tz;
4936
4937         tz.tz_minuteswest = 0;
4938         tz.tz_dsttime = 0; /* DST_NONE*/
4939
4940         if (settimeofday(tv_null, &tz) < 0)
4941                 return -errno;
4942
4943         return 0;
4944 }
4945
4946 int hwclock_get_time(struct tm *tm) {
4947         int fd;
4948         int err = 0;
4949
4950         assert(tm);
4951
4952         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4953         if (fd < 0)
4954                 return -errno;
4955
4956         /* This leaves the timezone fields of struct tm
4957          * uninitialized! */
4958         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4959                 err = -errno;
4960
4961         /* We don't now daylight saving, so we reset this in order not
4962          * to confused mktime(). */
4963         tm->tm_isdst = -1;
4964
4965         close_nointr_nofail(fd);
4966
4967         return err;
4968 }
4969
4970 int hwclock_set_time(const struct tm *tm) {
4971         int fd;
4972         int err = 0;
4973
4974         assert(tm);
4975
4976         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4977         if (fd < 0)
4978                 return -errno;
4979
4980         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4981                 err = -errno;
4982
4983         close_nointr_nofail(fd);
4984
4985         return err;
4986 }
4987
4988 int copy_file(const char *from, const char *to) {
4989         int r, fdf, fdt;
4990
4991         assert(from);
4992         assert(to);
4993
4994         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4995         if (fdf < 0)
4996                 return -errno;
4997
4998         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4999         if (fdt < 0) {
5000                 close_nointr_nofail(fdf);
5001                 return -errno;
5002         }
5003
5004         for (;;) {
5005                 char buf[PIPE_BUF];
5006                 ssize_t n, k;
5007
5008                 n = read(fdf, buf, sizeof(buf));
5009                 if (n < 0) {
5010                         r = -errno;
5011
5012                         close_nointr_nofail(fdf);
5013                         close_nointr(fdt);
5014                         unlink(to);
5015
5016                         return r;
5017                 }
5018
5019                 if (n == 0)
5020                         break;
5021
5022                 errno = 0;
5023                 k = loop_write(fdt, buf, n, false);
5024                 if (n != k) {
5025                         r = k < 0 ? k : (errno ? -errno : -EIO);
5026
5027                         close_nointr_nofail(fdf);
5028                         close_nointr(fdt);
5029
5030                         unlink(to);
5031                         return r;
5032                 }
5033         }
5034
5035         close_nointr_nofail(fdf);
5036         r = close_nointr(fdt);
5037
5038         if (r < 0) {
5039                 unlink(to);
5040                 return r;
5041         }
5042
5043         return 0;
5044 }
5045
5046 int symlink_or_copy(const char *from, const char *to) {
5047         char *pf = NULL, *pt = NULL;
5048         struct stat a, b;
5049         int r;
5050
5051         assert(from);
5052         assert(to);
5053
5054         if (parent_of_path(from, &pf) < 0 ||
5055             parent_of_path(to, &pt) < 0) {
5056                 r = -ENOMEM;
5057                 goto finish;
5058         }
5059
5060         if (stat(pf, &a) < 0 ||
5061             stat(pt, &b) < 0) {
5062                 r = -errno;
5063                 goto finish;
5064         }
5065
5066         if (a.st_dev != b.st_dev) {
5067                 free(pf);
5068                 free(pt);
5069
5070                 return copy_file(from, to);
5071         }
5072
5073         if (symlink(from, to) < 0) {
5074                 r = -errno;
5075                 goto finish;
5076         }
5077
5078         r = 0;
5079
5080 finish:
5081         free(pf);
5082         free(pt);
5083
5084         return r;
5085 }
5086
5087 int symlink_or_copy_atomic(const char *from, const char *to) {
5088         char *t, *x;
5089         const char *fn;
5090         size_t k;
5091         unsigned long long ull;
5092         unsigned i;
5093         int r;
5094
5095         assert(from);
5096         assert(to);
5097
5098         t = new(char, strlen(to) + 1 + 16 + 1);
5099         if (!t)
5100                 return -ENOMEM;
5101
5102         fn = file_name_from_path(to);
5103         k = fn-to;
5104         memcpy(t, to, k);
5105         t[k] = '.';
5106         x = stpcpy(t+k+1, fn);
5107
5108         ull = random_ull();
5109         for (i = 0; i < 16; i++) {
5110                 *(x++) = hexchar(ull & 0xF);
5111                 ull >>= 4;
5112         }
5113
5114         *x = 0;
5115
5116         r = symlink_or_copy(from, t);
5117         if (r < 0) {
5118                 unlink(t);
5119                 free(t);
5120                 return r;
5121         }
5122
5123         if (rename(t, to) < 0) {
5124                 r = -errno;
5125                 unlink(t);
5126                 free(t);
5127                 return r;
5128         }
5129
5130         free(t);
5131         return r;
5132 }
5133
5134 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5135         char *p, *s;
5136         uint32_t u;
5137         int r;
5138
5139         assert(pid >= 1);
5140         assert(id);
5141
5142         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5143                 return -ENOENT;
5144
5145         if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5146                 return -ENOMEM;
5147
5148         r = read_one_line_file(p, &s);
5149         free(p);
5150         if (r < 0)
5151                 return r;
5152
5153         r = safe_atou32(s, &u);
5154         free(s);
5155
5156         if (r < 0)
5157                 return r;
5158
5159         if (u == (uint32_t) -1 || u <= 0)
5160                 return -ENOENT;
5161
5162         *id = u;
5163         return 0;
5164 }
5165
5166 bool display_is_local(const char *display) {
5167         assert(display);
5168
5169         return
5170                 display[0] == ':' &&
5171                 display[1] >= '0' &&
5172                 display[1] <= '9';
5173 }
5174
5175 int socket_from_display(const char *display, char **path) {
5176         size_t k;
5177         char *f, *c;
5178
5179         assert(display);
5180         assert(path);
5181
5182         if (!display_is_local(display))
5183                 return -EINVAL;
5184
5185         k = strspn(display+1, "0123456789");
5186
5187         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5188         if (!f)
5189                 return -ENOMEM;
5190
5191         c = stpcpy(f, "/tmp/.X11-unix/X");
5192         memcpy(c, display+1, k);
5193         c[k] = 0;
5194
5195         *path = f;
5196
5197         return 0;
5198 }
5199
5200 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5201         struct passwd *p;
5202         unsigned long lu;
5203
5204         assert(username);
5205         assert(*username);
5206         assert(uid);
5207         assert(gid);
5208         assert(home);
5209
5210         /* We enforce some special rules for uid=0: in order to avoid
5211          * NSS lookups for root we hardcode its data. */
5212
5213         if (streq(*username, "root") || streq(*username, "0")) {
5214                 *username = "root";
5215                 *uid = 0;
5216                 *gid = 0;
5217                 *home = "/root";
5218                 return 0;
5219         }
5220
5221         if (safe_atolu(*username, &lu) >= 0) {
5222                 errno = 0;
5223                 p = getpwuid((uid_t) lu);
5224
5225                 /* If there are multiple users with the same id, make
5226                  * sure to leave $USER to the configured value instead
5227                  * of the first occurrence in the database. However if
5228                  * the uid was configured by a numeric uid, then let's
5229                  * pick the real username from /etc/passwd. */
5230                 if (p)
5231                         *username = p->pw_name;
5232         } else {
5233                 errno = 0;
5234                 p = getpwnam(*username);
5235         }
5236
5237         if (!p)
5238                 return errno != 0 ? -errno : -ESRCH;
5239
5240         *uid = p->pw_uid;
5241         *gid = p->pw_gid;
5242         *home = p->pw_dir;
5243         return 0;
5244 }
5245
5246 int glob_exists(const char *path) {
5247         glob_t g;
5248         int r, k;
5249
5250         assert(path);
5251
5252         zero(g);
5253         errno = 0;
5254         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5255
5256         if (k == GLOB_NOMATCH)
5257                 r = 0;
5258         else if (k == GLOB_NOSPACE)
5259                 r = -ENOMEM;
5260         else if (k == 0)
5261                 r = !strv_isempty(g.gl_pathv);
5262         else
5263                 r = errno ? -errno : -EIO;
5264
5265         globfree(&g);
5266
5267         return r;
5268 }
5269
5270 static const char *const ioprio_class_table[] = {
5271         [IOPRIO_CLASS_NONE] = "none",
5272         [IOPRIO_CLASS_RT] = "realtime",
5273         [IOPRIO_CLASS_BE] = "best-effort",
5274         [IOPRIO_CLASS_IDLE] = "idle"
5275 };
5276
5277 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5278
5279 static const char *const sigchld_code_table[] = {
5280         [CLD_EXITED] = "exited",
5281         [CLD_KILLED] = "killed",
5282         [CLD_DUMPED] = "dumped",
5283         [CLD_TRAPPED] = "trapped",
5284         [CLD_STOPPED] = "stopped",
5285         [CLD_CONTINUED] = "continued",
5286 };
5287
5288 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5289
5290 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5291         [LOG_FAC(LOG_KERN)] = "kern",
5292         [LOG_FAC(LOG_USER)] = "user",
5293         [LOG_FAC(LOG_MAIL)] = "mail",
5294         [LOG_FAC(LOG_DAEMON)] = "daemon",
5295         [LOG_FAC(LOG_AUTH)] = "auth",
5296         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5297         [LOG_FAC(LOG_LPR)] = "lpr",
5298         [LOG_FAC(LOG_NEWS)] = "news",
5299         [LOG_FAC(LOG_UUCP)] = "uucp",
5300         [LOG_FAC(LOG_CRON)] = "cron",
5301         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5302         [LOG_FAC(LOG_FTP)] = "ftp",
5303         [LOG_FAC(LOG_LOCAL0)] = "local0",
5304         [LOG_FAC(LOG_LOCAL1)] = "local1",
5305         [LOG_FAC(LOG_LOCAL2)] = "local2",
5306         [LOG_FAC(LOG_LOCAL3)] = "local3",
5307         [LOG_FAC(LOG_LOCAL4)] = "local4",
5308         [LOG_FAC(LOG_LOCAL5)] = "local5",
5309         [LOG_FAC(LOG_LOCAL6)] = "local6",
5310         [LOG_FAC(LOG_LOCAL7)] = "local7"
5311 };
5312
5313 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5314
5315 static const char *const log_level_table[] = {
5316         [LOG_EMERG] = "emerg",
5317         [LOG_ALERT] = "alert",
5318         [LOG_CRIT] = "crit",
5319         [LOG_ERR] = "err",
5320         [LOG_WARNING] = "warning",
5321         [LOG_NOTICE] = "notice",
5322         [LOG_INFO] = "info",
5323         [LOG_DEBUG] = "debug"
5324 };
5325
5326 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5327
5328 static const char* const sched_policy_table[] = {
5329         [SCHED_OTHER] = "other",
5330         [SCHED_BATCH] = "batch",
5331         [SCHED_IDLE] = "idle",
5332         [SCHED_FIFO] = "fifo",
5333         [SCHED_RR] = "rr"
5334 };
5335
5336 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5337
5338 static const char* const rlimit_table[] = {
5339         [RLIMIT_CPU] = "LimitCPU",
5340         [RLIMIT_FSIZE] = "LimitFSIZE",
5341         [RLIMIT_DATA] = "LimitDATA",
5342         [RLIMIT_STACK] = "LimitSTACK",
5343         [RLIMIT_CORE] = "LimitCORE",
5344         [RLIMIT_RSS] = "LimitRSS",
5345         [RLIMIT_NOFILE] = "LimitNOFILE",
5346         [RLIMIT_AS] = "LimitAS",
5347         [RLIMIT_NPROC] = "LimitNPROC",
5348         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5349         [RLIMIT_LOCKS] = "LimitLOCKS",
5350         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5351         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5352         [RLIMIT_NICE] = "LimitNICE",
5353         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5354         [RLIMIT_RTTIME] = "LimitRTTIME"
5355 };
5356
5357 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5358
5359 static const char* const ip_tos_table[] = {
5360         [IPTOS_LOWDELAY] = "low-delay",
5361         [IPTOS_THROUGHPUT] = "throughput",
5362         [IPTOS_RELIABILITY] = "reliability",
5363         [IPTOS_LOWCOST] = "low-cost",
5364 };
5365
5366 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5367
5368 static const char *const signal_table[] = {
5369         [SIGHUP] = "HUP",
5370         [SIGINT] = "INT",
5371         [SIGQUIT] = "QUIT",
5372         [SIGILL] = "ILL",
5373         [SIGTRAP] = "TRAP",
5374         [SIGABRT] = "ABRT",
5375         [SIGBUS] = "BUS",
5376         [SIGFPE] = "FPE",
5377         [SIGKILL] = "KILL",
5378         [SIGUSR1] = "USR1",
5379         [SIGSEGV] = "SEGV",
5380         [SIGUSR2] = "USR2",
5381         [SIGPIPE] = "PIPE",
5382         [SIGALRM] = "ALRM",
5383         [SIGTERM] = "TERM",
5384 #ifdef SIGSTKFLT
5385         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5386 #endif
5387         [SIGCHLD] = "CHLD",
5388         [SIGCONT] = "CONT",
5389         [SIGSTOP] = "STOP",
5390         [SIGTSTP] = "TSTP",
5391         [SIGTTIN] = "TTIN",
5392         [SIGTTOU] = "TTOU",
5393         [SIGURG] = "URG",
5394         [SIGXCPU] = "XCPU",
5395         [SIGXFSZ] = "XFSZ",
5396         [SIGVTALRM] = "VTALRM",
5397         [SIGPROF] = "PROF",
5398         [SIGWINCH] = "WINCH",
5399         [SIGIO] = "IO",
5400         [SIGPWR] = "PWR",
5401         [SIGSYS] = "SYS"
5402 };
5403
5404 DEFINE_STRING_TABLE_LOOKUP(signal, int);