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