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