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