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