chiark / gitweb /
util: add Debian welcome message
[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
53 #include "macro.h"
54 #include "util.h"
55 #include "ioprio.h"
56 #include "missing.h"
57 #include "log.h"
58 #include "strv.h"
59 #include "label.h"
60 #include "exit-status.h"
61
62 bool streq_ptr(const char *a, const char *b) {
63
64         /* Like streq(), but tries to make sense of NULL pointers */
65
66         if (a && b)
67                 return streq(a, b);
68
69         if (!a && !b)
70                 return true;
71
72         return false;
73 }
74
75 usec_t now(clockid_t clock_id) {
76         struct timespec ts;
77
78         assert_se(clock_gettime(clock_id, &ts) == 0);
79
80         return timespec_load(&ts);
81 }
82
83 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
84         assert(ts);
85
86         ts->realtime = now(CLOCK_REALTIME);
87         ts->monotonic = now(CLOCK_MONOTONIC);
88
89         return ts;
90 }
91
92 usec_t timespec_load(const struct timespec *ts) {
93         assert(ts);
94
95         return
96                 (usec_t) ts->tv_sec * USEC_PER_SEC +
97                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
98 }
99
100 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
101         assert(ts);
102
103         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
104         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
105
106         return ts;
107 }
108
109 usec_t timeval_load(const struct timeval *tv) {
110         assert(tv);
111
112         return
113                 (usec_t) tv->tv_sec * USEC_PER_SEC +
114                 (usec_t) tv->tv_usec;
115 }
116
117 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
118         assert(tv);
119
120         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
121         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
122
123         return tv;
124 }
125
126 bool endswith(const char *s, const char *postfix) {
127         size_t sl, pl;
128
129         assert(s);
130         assert(postfix);
131
132         sl = strlen(s);
133         pl = strlen(postfix);
134
135         if (pl == 0)
136                 return true;
137
138         if (sl < pl)
139                 return false;
140
141         return memcmp(s + sl - pl, postfix, pl) == 0;
142 }
143
144 bool startswith(const char *s, const char *prefix) {
145         size_t sl, pl;
146
147         assert(s);
148         assert(prefix);
149
150         sl = strlen(s);
151         pl = strlen(prefix);
152
153         if (pl == 0)
154                 return true;
155
156         if (sl < pl)
157                 return false;
158
159         return memcmp(s, prefix, pl) == 0;
160 }
161
162 bool startswith_no_case(const char *s, const char *prefix) {
163         size_t sl, pl;
164         unsigned i;
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         for(i = 0; i < pl; ++i) {
179                 if (tolower(s[i]) != tolower(prefix[i]))
180                         return false;
181         }
182
183         return true;
184 }
185
186 bool first_word(const char *s, const char *word) {
187         size_t sl, wl;
188
189         assert(s);
190         assert(word);
191
192         sl = strlen(s);
193         wl = strlen(word);
194
195         if (sl < wl)
196                 return false;
197
198         if (wl == 0)
199                 return true;
200
201         if (memcmp(s, word, wl) != 0)
202                 return false;
203
204         return s[wl] == 0 ||
205                 strchr(WHITESPACE, s[wl]);
206 }
207
208 int close_nointr(int fd) {
209         assert(fd >= 0);
210
211         for (;;) {
212                 int r;
213
214                 if ((r = close(fd)) >= 0)
215                         return r;
216
217                 if (errno != EINTR)
218                         return r;
219         }
220 }
221
222 void close_nointr_nofail(int fd) {
223         int saved_errno = errno;
224
225         /* like close_nointr() but cannot fail, and guarantees errno
226          * is unchanged */
227
228         assert_se(close_nointr(fd) == 0);
229
230         errno = saved_errno;
231 }
232
233 void close_many(const int fds[], unsigned n_fd) {
234         unsigned i;
235
236         for (i = 0; i < n_fd; i++)
237                 close_nointr_nofail(fds[i]);
238 }
239
240 int parse_boolean(const char *v) {
241         assert(v);
242
243         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
244                 return 1;
245         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
246                 return 0;
247
248         return -EINVAL;
249 }
250
251 int parse_pid(const char *s, pid_t* ret_pid) {
252         unsigned long ul;
253         pid_t pid;
254         int r;
255
256         assert(s);
257         assert(ret_pid);
258
259         if ((r = safe_atolu(s, &ul)) < 0)
260                 return r;
261
262         pid = (pid_t) ul;
263
264         if ((unsigned long) pid != ul)
265                 return -ERANGE;
266
267         if (pid <= 0)
268                 return -ERANGE;
269
270         *ret_pid = pid;
271         return 0;
272 }
273
274 int safe_atou(const char *s, unsigned *ret_u) {
275         char *x = NULL;
276         unsigned long l;
277
278         assert(s);
279         assert(ret_u);
280
281         errno = 0;
282         l = strtoul(s, &x, 0);
283
284         if (!x || *x || errno)
285                 return errno ? -errno : -EINVAL;
286
287         if ((unsigned long) (unsigned) l != l)
288                 return -ERANGE;
289
290         *ret_u = (unsigned) l;
291         return 0;
292 }
293
294 int safe_atoi(const char *s, int *ret_i) {
295         char *x = NULL;
296         long l;
297
298         assert(s);
299         assert(ret_i);
300
301         errno = 0;
302         l = strtol(s, &x, 0);
303
304         if (!x || *x || errno)
305                 return errno ? -errno : -EINVAL;
306
307         if ((long) (int) l != l)
308                 return -ERANGE;
309
310         *ret_i = (int) l;
311         return 0;
312 }
313
314 int safe_atollu(const char *s, long long unsigned *ret_llu) {
315         char *x = NULL;
316         unsigned long long l;
317
318         assert(s);
319         assert(ret_llu);
320
321         errno = 0;
322         l = strtoull(s, &x, 0);
323
324         if (!x || *x || errno)
325                 return errno ? -errno : -EINVAL;
326
327         *ret_llu = l;
328         return 0;
329 }
330
331 int safe_atolli(const char *s, long long int *ret_lli) {
332         char *x = NULL;
333         long long l;
334
335         assert(s);
336         assert(ret_lli);
337
338         errno = 0;
339         l = strtoll(s, &x, 0);
340
341         if (!x || *x || errno)
342                 return errno ? -errno : -EINVAL;
343
344         *ret_lli = l;
345         return 0;
346 }
347
348 /* Split a string into words. */
349 char *split(const char *c, size_t *l, const char *separator, char **state) {
350         char *current;
351
352         current = *state ? *state : (char*) c;
353
354         if (!*current || *c == 0)
355                 return NULL;
356
357         current += strspn(current, separator);
358         *l = strcspn(current, separator);
359         *state = current+*l;
360
361         return (char*) current;
362 }
363
364 /* Split a string into words, but consider strings enclosed in '' and
365  * "" as words even if they include spaces. */
366 char *split_quoted(const char *c, size_t *l, char **state) {
367         char *current, *e;
368         bool escaped = false;
369
370         current = *state ? *state : (char*) c;
371
372         if (!*current || *c == 0)
373                 return NULL;
374
375         current += strspn(current, WHITESPACE);
376
377         if (*current == '\'') {
378                 current ++;
379
380                 for (e = current; *e; e++) {
381                         if (escaped)
382                                 escaped = false;
383                         else if (*e == '\\')
384                                 escaped = true;
385                         else if (*e == '\'')
386                                 break;
387                 }
388
389                 *l = e-current;
390                 *state = *e == 0 ? e : e+1;
391         } else if (*current == '\"') {
392                 current ++;
393
394                 for (e = current; *e; e++) {
395                         if (escaped)
396                                 escaped = false;
397                         else if (*e == '\\')
398                                 escaped = true;
399                         else if (*e == '\"')
400                                 break;
401                 }
402
403                 *l = e-current;
404                 *state = *e == 0 ? e : e+1;
405         } else {
406                 for (e = current; *e; e++) {
407                         if (escaped)
408                                 escaped = false;
409                         else if (*e == '\\')
410                                 escaped = true;
411                         else if (strchr(WHITESPACE, *e))
412                                 break;
413                 }
414                 *l = e-current;
415                 *state = e;
416         }
417
418         return (char*) current;
419 }
420
421 char **split_path_and_make_absolute(const char *p) {
422         char **l;
423         assert(p);
424
425         if (!(l = strv_split(p, ":")))
426                 return NULL;
427
428         if (!strv_path_make_absolute_cwd(l)) {
429                 strv_free(l);
430                 return NULL;
431         }
432
433         return l;
434 }
435
436 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
437         int r;
438         FILE *f;
439         char fn[132], line[256], *p;
440         long unsigned ppid;
441
442         assert(pid >= 0);
443         assert(_ppid);
444
445         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
446         fn[sizeof(fn)-1] = 0;
447
448         if (!(f = fopen(fn, "r")))
449                 return -errno;
450
451         if (!(fgets(line, sizeof(line), f))) {
452                 r = -errno;
453                 fclose(f);
454                 return r;
455         }
456
457         fclose(f);
458
459         /* Let's skip the pid and comm fields. The latter is enclosed
460          * in () but does not escape any () in its value, so let's
461          * skip over it manually */
462
463         if (!(p = strrchr(line, ')')))
464                 return -EIO;
465
466         p++;
467
468         if (sscanf(p, " "
469                    "%*c "  /* state */
470                    "%lu ", /* ppid */
471                    &ppid) != 1)
472                 return -EIO;
473
474         if ((long unsigned) (pid_t) ppid != ppid)
475                 return -ERANGE;
476
477         *_ppid = (pid_t) ppid;
478
479         return 0;
480 }
481
482 int write_one_line_file(const char *fn, const char *line) {
483         FILE *f;
484         int r;
485
486         assert(fn);
487         assert(line);
488
489         if (!(f = fopen(fn, "we")))
490                 return -errno;
491
492         if (fputs(line, f) < 0) {
493                 r = -errno;
494                 goto finish;
495         }
496
497         r = 0;
498 finish:
499         fclose(f);
500         return r;
501 }
502
503 int read_one_line_file(const char *fn, char **line) {
504         FILE *f;
505         int r;
506         char t[2048], *c;
507
508         assert(fn);
509         assert(line);
510
511         if (!(f = fopen(fn, "re")))
512                 return -errno;
513
514         if (!(fgets(t, sizeof(t), f))) {
515                 r = -errno;
516                 goto finish;
517         }
518
519         if (!(c = strdup(t))) {
520                 r = -ENOMEM;
521                 goto finish;
522         }
523
524         *line = c;
525         r = 0;
526
527 finish:
528         fclose(f);
529         return r;
530 }
531
532 char *truncate_nl(char *s) {
533         assert(s);
534
535         s[strcspn(s, NEWLINE)] = 0;
536         return s;
537 }
538
539 int get_process_name(pid_t pid, char **name) {
540         char *p;
541         int r;
542
543         assert(pid >= 1);
544         assert(name);
545
546         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
547                 return -ENOMEM;
548
549         r = read_one_line_file(p, name);
550         free(p);
551
552         if (r < 0)
553                 return r;
554
555         truncate_nl(*name);
556         return 0;
557 }
558
559 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
560         char *p, *r, *k;
561         int c;
562         bool space = false;
563         size_t left;
564         FILE *f;
565
566         assert(pid >= 1);
567         assert(max_length > 0);
568         assert(line);
569
570         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
571                 return -ENOMEM;
572
573         f = fopen(p, "r");
574         free(p);
575
576         if (!f)
577                 return -errno;
578
579         if (!(r = new(char, max_length))) {
580                 fclose(f);
581                 return -ENOMEM;
582         }
583
584         k = r;
585         left = max_length;
586         while ((c = getc(f)) != EOF) {
587
588                 if (isprint(c)) {
589                         if (space) {
590                                 if (left <= 4)
591                                         break;
592
593                                 *(k++) = ' ';
594                                 left--;
595                                 space = false;
596                         }
597
598                         if (left <= 4)
599                                 break;
600
601                         *(k++) = (char) c;
602                         left--;
603                 }  else
604                         space = true;
605         }
606
607         if (left <= 4) {
608                 size_t n = MIN(left-1, 3U);
609                 memcpy(k, "...", n);
610                 k[n] = 0;
611         } else
612                 *k = 0;
613
614         fclose(f);
615
616         /* Kernel threads have no argv[] */
617         if (r[0] == 0) {
618                 char *t;
619                 int h;
620
621                 free(r);
622
623                 if ((h = get_process_name(pid, &t)) < 0)
624                         return h;
625
626                 h = asprintf(&r, "[%s]", t);
627                 free(t);
628
629                 if (h < 0)
630                         return -ENOMEM;
631         }
632
633         *line = r;
634         return 0;
635 }
636
637 char *strnappend(const char *s, const char *suffix, size_t b) {
638         size_t a;
639         char *r;
640
641         if (!s && !suffix)
642                 return strdup("");
643
644         if (!s)
645                 return strndup(suffix, b);
646
647         if (!suffix)
648                 return strdup(s);
649
650         assert(s);
651         assert(suffix);
652
653         a = strlen(s);
654
655         if (!(r = new(char, a+b+1)))
656                 return NULL;
657
658         memcpy(r, s, a);
659         memcpy(r+a, suffix, b);
660         r[a+b] = 0;
661
662         return r;
663 }
664
665 char *strappend(const char *s, const char *suffix) {
666         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
667 }
668
669 int readlink_malloc(const char *p, char **r) {
670         size_t l = 100;
671
672         assert(p);
673         assert(r);
674
675         for (;;) {
676                 char *c;
677                 ssize_t n;
678
679                 if (!(c = new(char, l)))
680                         return -ENOMEM;
681
682                 if ((n = readlink(p, c, l-1)) < 0) {
683                         int ret = -errno;
684                         free(c);
685                         return ret;
686                 }
687
688                 if ((size_t) n < l-1) {
689                         c[n] = 0;
690                         *r = c;
691                         return 0;
692                 }
693
694                 free(c);
695                 l *= 2;
696         }
697 }
698
699 int readlink_and_make_absolute(const char *p, char **r) {
700         char *target, *k;
701         int j;
702
703         assert(p);
704         assert(r);
705
706         if ((j = readlink_malloc(p, &target)) < 0)
707                 return j;
708
709         k = file_in_same_dir(p, target);
710         free(target);
711
712         if (!k)
713                 return -ENOMEM;
714
715         *r = k;
716         return 0;
717 }
718
719 int parent_of_path(const char *path, char **_r) {
720         const char *e, *a = NULL, *b = NULL, *p;
721         char *r;
722         bool slash = false;
723
724         assert(path);
725         assert(_r);
726
727         if (!*path)
728                 return -EINVAL;
729
730         for (e = path; *e; e++) {
731
732                 if (!slash && *e == '/') {
733                         a = b;
734                         b = e;
735                         slash = true;
736                 } else if (slash && *e != '/')
737                         slash = false;
738         }
739
740         if (*(e-1) == '/')
741                 p = a;
742         else
743                 p = b;
744
745         if (!p)
746                 return -EINVAL;
747
748         if (p == path)
749                 r = strdup("/");
750         else
751                 r = strndup(path, p-path);
752
753         if (!r)
754                 return -ENOMEM;
755
756         *_r = r;
757         return 0;
758 }
759
760
761 char *file_name_from_path(const char *p) {
762         char *r;
763
764         assert(p);
765
766         if ((r = strrchr(p, '/')))
767                 return r + 1;
768
769         return (char*) p;
770 }
771
772 bool path_is_absolute(const char *p) {
773         assert(p);
774
775         return p[0] == '/';
776 }
777
778 bool is_path(const char *p) {
779
780         return !!strchr(p, '/');
781 }
782
783 char *path_make_absolute(const char *p, const char *prefix) {
784         char *r;
785
786         assert(p);
787
788         /* Makes every item in the list an absolute path by prepending
789          * the prefix, if specified and necessary */
790
791         if (path_is_absolute(p) || !prefix)
792                 return strdup(p);
793
794         if (asprintf(&r, "%s/%s", prefix, p) < 0)
795                 return NULL;
796
797         return r;
798 }
799
800 char *path_make_absolute_cwd(const char *p) {
801         char *cwd, *r;
802
803         assert(p);
804
805         /* Similar to path_make_absolute(), but prefixes with the
806          * current working directory. */
807
808         if (path_is_absolute(p))
809                 return strdup(p);
810
811         if (!(cwd = get_current_dir_name()))
812                 return NULL;
813
814         r = path_make_absolute(p, cwd);
815         free(cwd);
816
817         return r;
818 }
819
820 char **strv_path_make_absolute_cwd(char **l) {
821         char **s;
822
823         /* Goes through every item in the string list and makes it
824          * absolute. This works in place and won't rollback any
825          * changes on failure. */
826
827         STRV_FOREACH(s, l) {
828                 char *t;
829
830                 if (!(t = path_make_absolute_cwd(*s)))
831                         return NULL;
832
833                 free(*s);
834                 *s = t;
835         }
836
837         return l;
838 }
839
840 char **strv_path_canonicalize(char **l) {
841         char **s;
842         unsigned k = 0;
843         bool enomem = false;
844
845         if (strv_isempty(l))
846                 return l;
847
848         /* Goes through every item in the string list and canonicalize
849          * the path. This works in place and won't rollback any
850          * changes on failure. */
851
852         STRV_FOREACH(s, l) {
853                 char *t, *u;
854
855                 t = path_make_absolute_cwd(*s);
856                 free(*s);
857
858                 if (!t) {
859                         enomem = true;
860                         continue;
861                 }
862
863                 errno = 0;
864                 u = canonicalize_file_name(t);
865                 free(t);
866
867                 if (!u) {
868                         if (errno == ENOMEM || !errno)
869                                 enomem = true;
870
871                         continue;
872                 }
873
874                 l[k++] = u;
875         }
876
877         l[k] = NULL;
878
879         if (enomem)
880                 return NULL;
881
882         return l;
883 }
884
885 int reset_all_signal_handlers(void) {
886         int sig;
887
888         for (sig = 1; sig < _NSIG; sig++) {
889                 struct sigaction sa;
890
891                 if (sig == SIGKILL || sig == SIGSTOP)
892                         continue;
893
894                 zero(sa);
895                 sa.sa_handler = SIG_DFL;
896                 sa.sa_flags = SA_RESTART;
897
898                 /* On Linux the first two RT signals are reserved by
899                  * glibc, and sigaction() will return EINVAL for them. */
900                 if ((sigaction(sig, &sa, NULL) < 0))
901                         if (errno != EINVAL)
902                                 return -errno;
903         }
904
905         return 0;
906 }
907
908 char *strstrip(char *s) {
909         char *e, *l = NULL;
910
911         /* Drops trailing whitespace. Modifies the string in
912          * place. Returns pointer to first non-space character */
913
914         s += strspn(s, WHITESPACE);
915
916         for (e = s; *e; e++)
917                 if (!strchr(WHITESPACE, *e))
918                         l = e;
919
920         if (l)
921                 *(l+1) = 0;
922         else
923                 *s = 0;
924
925         return s;
926 }
927
928 char *delete_chars(char *s, const char *bad) {
929         char *f, *t;
930
931         /* Drops all whitespace, regardless where in the string */
932
933         for (f = s, t = s; *f; f++) {
934                 if (strchr(bad, *f))
935                         continue;
936
937                 *(t++) = *f;
938         }
939
940         *t = 0;
941
942         return s;
943 }
944
945 char *file_in_same_dir(const char *path, const char *filename) {
946         char *e, *r;
947         size_t k;
948
949         assert(path);
950         assert(filename);
951
952         /* This removes the last component of path and appends
953          * filename, unless the latter is absolute anyway or the
954          * former isn't */
955
956         if (path_is_absolute(filename))
957                 return strdup(filename);
958
959         if (!(e = strrchr(path, '/')))
960                 return strdup(filename);
961
962         k = strlen(filename);
963         if (!(r = new(char, e-path+1+k+1)))
964                 return NULL;
965
966         memcpy(r, path, e-path+1);
967         memcpy(r+(e-path)+1, filename, k+1);
968
969         return r;
970 }
971
972 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
973         struct stat st;
974
975         if (label_mkdir(path, mode) >= 0)
976                 if (chmod_and_chown(path, mode, uid, gid) < 0)
977                         return -errno;
978
979         if (lstat(path, &st) < 0)
980                 return -errno;
981
982         if ((st.st_mode & 0777) != mode ||
983             st.st_uid != uid ||
984             st.st_gid != gid ||
985             !S_ISDIR(st.st_mode)) {
986                 errno = EEXIST;
987                 return -errno;
988         }
989
990         return 0;
991 }
992
993
994 int mkdir_parents(const char *path, mode_t mode) {
995         const char *p, *e;
996
997         assert(path);
998
999         /* Creates every parent directory in the path except the last
1000          * component. */
1001
1002         p = path + strspn(path, "/");
1003         for (;;) {
1004                 int r;
1005                 char *t;
1006
1007                 e = p + strcspn(p, "/");
1008                 p = e + strspn(e, "/");
1009
1010                 /* Is this the last component? If so, then we're
1011                  * done */
1012                 if (*p == 0)
1013                         return 0;
1014
1015                 if (!(t = strndup(path, e - path)))
1016                         return -ENOMEM;
1017
1018                 r = label_mkdir(t, mode);
1019                 free(t);
1020
1021                 if (r < 0 && errno != EEXIST)
1022                         return -errno;
1023         }
1024 }
1025
1026 int mkdir_p(const char *path, mode_t mode) {
1027         int r;
1028
1029         /* Like mkdir -p */
1030
1031         if ((r = mkdir_parents(path, mode)) < 0)
1032                 return r;
1033
1034         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1035                 return -errno;
1036
1037         return 0;
1038 }
1039
1040 int rmdir_parents(const char *path, const char *stop) {
1041         size_t l;
1042         int r = 0;
1043
1044         assert(path);
1045         assert(stop);
1046
1047         l = strlen(path);
1048
1049         /* Skip trailing slashes */
1050         while (l > 0 && path[l-1] == '/')
1051                 l--;
1052
1053         while (l > 0) {
1054                 char *t;
1055
1056                 /* Skip last component */
1057                 while (l > 0 && path[l-1] != '/')
1058                         l--;
1059
1060                 /* Skip trailing slashes */
1061                 while (l > 0 && path[l-1] == '/')
1062                         l--;
1063
1064                 if (l <= 0)
1065                         break;
1066
1067                 if (!(t = strndup(path, l)))
1068                         return -ENOMEM;
1069
1070                 if (path_startswith(stop, t)) {
1071                         free(t);
1072                         return 0;
1073                 }
1074
1075                 r = rmdir(t);
1076                 free(t);
1077
1078                 if (r < 0)
1079                         if (errno != ENOENT)
1080                                 return -errno;
1081         }
1082
1083         return 0;
1084 }
1085
1086
1087 char hexchar(int x) {
1088         static const char table[16] = "0123456789abcdef";
1089
1090         return table[x & 15];
1091 }
1092
1093 int unhexchar(char c) {
1094
1095         if (c >= '0' && c <= '9')
1096                 return c - '0';
1097
1098         if (c >= 'a' && c <= 'f')
1099                 return c - 'a' + 10;
1100
1101         if (c >= 'A' && c <= 'F')
1102                 return c - 'A' + 10;
1103
1104         return -1;
1105 }
1106
1107 char octchar(int x) {
1108         return '0' + (x & 7);
1109 }
1110
1111 int unoctchar(char c) {
1112
1113         if (c >= '0' && c <= '7')
1114                 return c - '0';
1115
1116         return -1;
1117 }
1118
1119 char decchar(int x) {
1120         return '0' + (x % 10);
1121 }
1122
1123 int undecchar(char c) {
1124
1125         if (c >= '0' && c <= '9')
1126                 return c - '0';
1127
1128         return -1;
1129 }
1130
1131 char *cescape(const char *s) {
1132         char *r, *t;
1133         const char *f;
1134
1135         assert(s);
1136
1137         /* Does C style string escaping. */
1138
1139         if (!(r = new(char, strlen(s)*4 + 1)))
1140                 return NULL;
1141
1142         for (f = s, t = r; *f; f++)
1143
1144                 switch (*f) {
1145
1146                 case '\a':
1147                         *(t++) = '\\';
1148                         *(t++) = 'a';
1149                         break;
1150                 case '\b':
1151                         *(t++) = '\\';
1152                         *(t++) = 'b';
1153                         break;
1154                 case '\f':
1155                         *(t++) = '\\';
1156                         *(t++) = 'f';
1157                         break;
1158                 case '\n':
1159                         *(t++) = '\\';
1160                         *(t++) = 'n';
1161                         break;
1162                 case '\r':
1163                         *(t++) = '\\';
1164                         *(t++) = 'r';
1165                         break;
1166                 case '\t':
1167                         *(t++) = '\\';
1168                         *(t++) = 't';
1169                         break;
1170                 case '\v':
1171                         *(t++) = '\\';
1172                         *(t++) = 'v';
1173                         break;
1174                 case '\\':
1175                         *(t++) = '\\';
1176                         *(t++) = '\\';
1177                         break;
1178                 case '"':
1179                         *(t++) = '\\';
1180                         *(t++) = '"';
1181                         break;
1182                 case '\'':
1183                         *(t++) = '\\';
1184                         *(t++) = '\'';
1185                         break;
1186
1187                 default:
1188                         /* For special chars we prefer octal over
1189                          * hexadecimal encoding, simply because glib's
1190                          * g_strescape() does the same */
1191                         if ((*f < ' ') || (*f >= 127)) {
1192                                 *(t++) = '\\';
1193                                 *(t++) = octchar((unsigned char) *f >> 6);
1194                                 *(t++) = octchar((unsigned char) *f >> 3);
1195                                 *(t++) = octchar((unsigned char) *f);
1196                         } else
1197                                 *(t++) = *f;
1198                         break;
1199                 }
1200
1201         *t = 0;
1202
1203         return r;
1204 }
1205
1206 char *cunescape_length(const char *s, size_t length) {
1207         char *r, *t;
1208         const char *f;
1209
1210         assert(s);
1211
1212         /* Undoes C style string escaping */
1213
1214         if (!(r = new(char, length+1)))
1215                 return r;
1216
1217         for (f = s, t = r; f < s + length; f++) {
1218
1219                 if (*f != '\\') {
1220                         *(t++) = *f;
1221                         continue;
1222                 }
1223
1224                 f++;
1225
1226                 switch (*f) {
1227
1228                 case 'a':
1229                         *(t++) = '\a';
1230                         break;
1231                 case 'b':
1232                         *(t++) = '\b';
1233                         break;
1234                 case 'f':
1235                         *(t++) = '\f';
1236                         break;
1237                 case 'n':
1238                         *(t++) = '\n';
1239                         break;
1240                 case 'r':
1241                         *(t++) = '\r';
1242                         break;
1243                 case 't':
1244                         *(t++) = '\t';
1245                         break;
1246                 case 'v':
1247                         *(t++) = '\v';
1248                         break;
1249                 case '\\':
1250                         *(t++) = '\\';
1251                         break;
1252                 case '"':
1253                         *(t++) = '"';
1254                         break;
1255                 case '\'':
1256                         *(t++) = '\'';
1257                         break;
1258
1259                 case 's':
1260                         /* This is an extension of the XDG syntax files */
1261                         *(t++) = ' ';
1262                         break;
1263
1264                 case 'x': {
1265                         /* hexadecimal encoding */
1266                         int a, b;
1267
1268                         if ((a = unhexchar(f[1])) < 0 ||
1269                             (b = unhexchar(f[2])) < 0) {
1270                                 /* Invalid escape code, let's take it literal then */
1271                                 *(t++) = '\\';
1272                                 *(t++) = 'x';
1273                         } else {
1274                                 *(t++) = (char) ((a << 4) | b);
1275                                 f += 2;
1276                         }
1277
1278                         break;
1279                 }
1280
1281                 case '0':
1282                 case '1':
1283                 case '2':
1284                 case '3':
1285                 case '4':
1286                 case '5':
1287                 case '6':
1288                 case '7': {
1289                         /* octal encoding */
1290                         int a, b, c;
1291
1292                         if ((a = unoctchar(f[0])) < 0 ||
1293                             (b = unoctchar(f[1])) < 0 ||
1294                             (c = unoctchar(f[2])) < 0) {
1295                                 /* Invalid escape code, let's take it literal then */
1296                                 *(t++) = '\\';
1297                                 *(t++) = f[0];
1298                         } else {
1299                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1300                                 f += 2;
1301                         }
1302
1303                         break;
1304                 }
1305
1306                 case 0:
1307                         /* premature end of string.*/
1308                         *(t++) = '\\';
1309                         goto finish;
1310
1311                 default:
1312                         /* Invalid escape code, let's take it literal then */
1313                         *(t++) = '\\';
1314                         *(t++) = *f;
1315                         break;
1316                 }
1317         }
1318
1319 finish:
1320         *t = 0;
1321         return r;
1322 }
1323
1324 char *cunescape(const char *s) {
1325         return cunescape_length(s, strlen(s));
1326 }
1327
1328 char *xescape(const char *s, const char *bad) {
1329         char *r, *t;
1330         const char *f;
1331
1332         /* Escapes all chars in bad, in addition to \ and all special
1333          * chars, in \xFF style escaping. May be reversed with
1334          * cunescape. */
1335
1336         if (!(r = new(char, strlen(s)*4+1)))
1337                 return NULL;
1338
1339         for (f = s, t = r; *f; f++) {
1340
1341                 if ((*f < ' ') || (*f >= 127) ||
1342                     (*f == '\\') || strchr(bad, *f)) {
1343                         *(t++) = '\\';
1344                         *(t++) = 'x';
1345                         *(t++) = hexchar(*f >> 4);
1346                         *(t++) = hexchar(*f);
1347                 } else
1348                         *(t++) = *f;
1349         }
1350
1351         *t = 0;
1352
1353         return r;
1354 }
1355
1356 char *bus_path_escape(const char *s) {
1357         char *r, *t;
1358         const char *f;
1359
1360         assert(s);
1361
1362         /* Escapes all chars that D-Bus' object path cannot deal
1363          * with. Can be reverse with bus_path_unescape() */
1364
1365         if (!(r = new(char, strlen(s)*3+1)))
1366                 return NULL;
1367
1368         for (f = s, t = r; *f; f++) {
1369
1370                 if (!(*f >= 'A' && *f <= 'Z') &&
1371                     !(*f >= 'a' && *f <= 'z') &&
1372                     !(*f >= '0' && *f <= '9')) {
1373                         *(t++) = '_';
1374                         *(t++) = hexchar(*f >> 4);
1375                         *(t++) = hexchar(*f);
1376                 } else
1377                         *(t++) = *f;
1378         }
1379
1380         *t = 0;
1381
1382         return r;
1383 }
1384
1385 char *bus_path_unescape(const char *f) {
1386         char *r, *t;
1387
1388         assert(f);
1389
1390         if (!(r = strdup(f)))
1391                 return NULL;
1392
1393         for (t = r; *f; f++) {
1394
1395                 if (*f == '_') {
1396                         int a, b;
1397
1398                         if ((a = unhexchar(f[1])) < 0 ||
1399                             (b = unhexchar(f[2])) < 0) {
1400                                 /* Invalid escape code, let's take it literal then */
1401                                 *(t++) = '_';
1402                         } else {
1403                                 *(t++) = (char) ((a << 4) | b);
1404                                 f += 2;
1405                         }
1406                 } else
1407                         *(t++) = *f;
1408         }
1409
1410         *t = 0;
1411
1412         return r;
1413 }
1414
1415 char *path_kill_slashes(char *path) {
1416         char *f, *t;
1417         bool slash = false;
1418
1419         /* Removes redundant inner and trailing slashes. Modifies the
1420          * passed string in-place.
1421          *
1422          * ///foo///bar/ becomes /foo/bar
1423          */
1424
1425         for (f = path, t = path; *f; f++) {
1426
1427                 if (*f == '/') {
1428                         slash = true;
1429                         continue;
1430                 }
1431
1432                 if (slash) {
1433                         slash = false;
1434                         *(t++) = '/';
1435                 }
1436
1437                 *(t++) = *f;
1438         }
1439
1440         /* Special rule, if we are talking of the root directory, a
1441         trailing slash is good */
1442
1443         if (t == path && slash)
1444                 *(t++) = '/';
1445
1446         *t = 0;
1447         return path;
1448 }
1449
1450 bool path_startswith(const char *path, const char *prefix) {
1451         assert(path);
1452         assert(prefix);
1453
1454         if ((path[0] == '/') != (prefix[0] == '/'))
1455                 return false;
1456
1457         for (;;) {
1458                 size_t a, b;
1459
1460                 path += strspn(path, "/");
1461                 prefix += strspn(prefix, "/");
1462
1463                 if (*prefix == 0)
1464                         return true;
1465
1466                 if (*path == 0)
1467                         return false;
1468
1469                 a = strcspn(path, "/");
1470                 b = strcspn(prefix, "/");
1471
1472                 if (a != b)
1473                         return false;
1474
1475                 if (memcmp(path, prefix, a) != 0)
1476                         return false;
1477
1478                 path += a;
1479                 prefix += b;
1480         }
1481 }
1482
1483 bool path_equal(const char *a, const char *b) {
1484         assert(a);
1485         assert(b);
1486
1487         if ((a[0] == '/') != (b[0] == '/'))
1488                 return false;
1489
1490         for (;;) {
1491                 size_t j, k;
1492
1493                 a += strspn(a, "/");
1494                 b += strspn(b, "/");
1495
1496                 if (*a == 0 && *b == 0)
1497                         return true;
1498
1499                 if (*a == 0 || *b == 0)
1500                         return false;
1501
1502                 j = strcspn(a, "/");
1503                 k = strcspn(b, "/");
1504
1505                 if (j != k)
1506                         return false;
1507
1508                 if (memcmp(a, b, j) != 0)
1509                         return false;
1510
1511                 a += j;
1512                 b += k;
1513         }
1514 }
1515
1516 char *ascii_strlower(char *t) {
1517         char *p;
1518
1519         assert(t);
1520
1521         for (p = t; *p; p++)
1522                 if (*p >= 'A' && *p <= 'Z')
1523                         *p = *p - 'A' + 'a';
1524
1525         return t;
1526 }
1527
1528 bool ignore_file(const char *filename) {
1529         assert(filename);
1530
1531         return
1532                 filename[0] == '.' ||
1533                 streq(filename, "lost+found") ||
1534                 endswith(filename, "~") ||
1535                 endswith(filename, ".rpmnew") ||
1536                 endswith(filename, ".rpmsave") ||
1537                 endswith(filename, ".rpmorig") ||
1538                 endswith(filename, ".dpkg-old") ||
1539                 endswith(filename, ".dpkg-new") ||
1540                 endswith(filename, ".swp");
1541 }
1542
1543 int fd_nonblock(int fd, bool nonblock) {
1544         int flags;
1545
1546         assert(fd >= 0);
1547
1548         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1549                 return -errno;
1550
1551         if (nonblock)
1552                 flags |= O_NONBLOCK;
1553         else
1554                 flags &= ~O_NONBLOCK;
1555
1556         if (fcntl(fd, F_SETFL, flags) < 0)
1557                 return -errno;
1558
1559         return 0;
1560 }
1561
1562 int fd_cloexec(int fd, bool cloexec) {
1563         int flags;
1564
1565         assert(fd >= 0);
1566
1567         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1568                 return -errno;
1569
1570         if (cloexec)
1571                 flags |= FD_CLOEXEC;
1572         else
1573                 flags &= ~FD_CLOEXEC;
1574
1575         if (fcntl(fd, F_SETFD, flags) < 0)
1576                 return -errno;
1577
1578         return 0;
1579 }
1580
1581 int close_all_fds(const int except[], unsigned n_except) {
1582         DIR *d;
1583         struct dirent *de;
1584         int r = 0;
1585
1586         if (!(d = opendir("/proc/self/fd")))
1587                 return -errno;
1588
1589         while ((de = readdir(d))) {
1590                 int fd = -1;
1591
1592                 if (ignore_file(de->d_name))
1593                         continue;
1594
1595                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1596                         goto finish;
1597
1598                 if (fd < 3)
1599                         continue;
1600
1601                 if (fd == dirfd(d))
1602                         continue;
1603
1604                 if (except) {
1605                         bool found;
1606                         unsigned i;
1607
1608                         found = false;
1609                         for (i = 0; i < n_except; i++)
1610                                 if (except[i] == fd) {
1611                                         found = true;
1612                                         break;
1613                                 }
1614
1615                         if (found)
1616                                 continue;
1617                 }
1618
1619                 if ((r = close_nointr(fd)) < 0) {
1620                         /* Valgrind has its own FD and doesn't want to have it closed */
1621                         if (errno != EBADF)
1622                                 goto finish;
1623                 }
1624         }
1625
1626         r = 0;
1627
1628 finish:
1629         closedir(d);
1630         return r;
1631 }
1632
1633 bool chars_intersect(const char *a, const char *b) {
1634         const char *p;
1635
1636         /* Returns true if any of the chars in a are in b. */
1637         for (p = a; *p; p++)
1638                 if (strchr(b, *p))
1639                         return true;
1640
1641         return false;
1642 }
1643
1644 char *format_timestamp(char *buf, size_t l, usec_t t) {
1645         struct tm tm;
1646         time_t sec;
1647
1648         assert(buf);
1649         assert(l > 0);
1650
1651         if (t <= 0)
1652                 return NULL;
1653
1654         sec = (time_t) (t / USEC_PER_SEC);
1655
1656         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1657                 return NULL;
1658
1659         return buf;
1660 }
1661
1662 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1663         usec_t n, d;
1664
1665         n = now(CLOCK_REALTIME);
1666
1667         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1668                 return NULL;
1669
1670         d = n - t;
1671
1672         if (d >= USEC_PER_YEAR)
1673                 snprintf(buf, l, "%llu years and %llu months ago",
1674                          (unsigned long long) (d / USEC_PER_YEAR),
1675                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1676         else if (d >= USEC_PER_MONTH)
1677                 snprintf(buf, l, "%llu months and %llu days ago",
1678                          (unsigned long long) (d / USEC_PER_MONTH),
1679                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1680         else if (d >= USEC_PER_WEEK)
1681                 snprintf(buf, l, "%llu weeks and %llu days ago",
1682                          (unsigned long long) (d / USEC_PER_WEEK),
1683                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1684         else if (d >= 2*USEC_PER_DAY)
1685                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1686         else if (d >= 25*USEC_PER_HOUR)
1687                 snprintf(buf, l, "1 day and %lluh ago",
1688                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1689         else if (d >= 6*USEC_PER_HOUR)
1690                 snprintf(buf, l, "%lluh ago",
1691                          (unsigned long long) (d / USEC_PER_HOUR));
1692         else if (d >= USEC_PER_HOUR)
1693                 snprintf(buf, l, "%lluh %llumin ago",
1694                          (unsigned long long) (d / USEC_PER_HOUR),
1695                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1696         else if (d >= 5*USEC_PER_MINUTE)
1697                 snprintf(buf, l, "%llumin ago",
1698                          (unsigned long long) (d / USEC_PER_MINUTE));
1699         else if (d >= USEC_PER_MINUTE)
1700                 snprintf(buf, l, "%llumin %llus ago",
1701                          (unsigned long long) (d / USEC_PER_MINUTE),
1702                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1703         else if (d >= USEC_PER_SEC)
1704                 snprintf(buf, l, "%llus ago",
1705                          (unsigned long long) (d / USEC_PER_SEC));
1706         else if (d >= USEC_PER_MSEC)
1707                 snprintf(buf, l, "%llums ago",
1708                          (unsigned long long) (d / USEC_PER_MSEC));
1709         else if (d > 0)
1710                 snprintf(buf, l, "%lluus ago",
1711                          (unsigned long long) d);
1712         else
1713                 snprintf(buf, l, "now");
1714
1715         buf[l-1] = 0;
1716         return buf;
1717 }
1718
1719 char *format_timespan(char *buf, size_t l, usec_t t) {
1720         static const struct {
1721                 const char *suffix;
1722                 usec_t usec;
1723         } table[] = {
1724                 { "w", USEC_PER_WEEK },
1725                 { "d", USEC_PER_DAY },
1726                 { "h", USEC_PER_HOUR },
1727                 { "min", USEC_PER_MINUTE },
1728                 { "s", USEC_PER_SEC },
1729                 { "ms", USEC_PER_MSEC },
1730                 { "us", 1 },
1731         };
1732
1733         unsigned i;
1734         char *p = buf;
1735
1736         assert(buf);
1737         assert(l > 0);
1738
1739         if (t == (usec_t) -1)
1740                 return NULL;
1741
1742         if (t == 0) {
1743                 snprintf(p, l, "0");
1744                 p[l-1] = 0;
1745                 return p;
1746         }
1747
1748         /* The result of this function can be parsed with parse_usec */
1749
1750         for (i = 0; i < ELEMENTSOF(table); i++) {
1751                 int k;
1752                 size_t n;
1753
1754                 if (t < table[i].usec)
1755                         continue;
1756
1757                 if (l <= 1)
1758                         break;
1759
1760                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1761                 n = MIN((size_t) k, l);
1762
1763                 l -= n;
1764                 p += n;
1765
1766                 t %= table[i].usec;
1767         }
1768
1769         *p = 0;
1770
1771         return buf;
1772 }
1773
1774 bool fstype_is_network(const char *fstype) {
1775         static const char * const table[] = {
1776                 "cifs",
1777                 "smbfs",
1778                 "ncpfs",
1779                 "nfs",
1780                 "nfs4",
1781                 "gfs",
1782                 "gfs2"
1783         };
1784
1785         unsigned i;
1786
1787         for (i = 0; i < ELEMENTSOF(table); i++)
1788                 if (streq(table[i], fstype))
1789                         return true;
1790
1791         return false;
1792 }
1793
1794 int chvt(int vt) {
1795         int fd, r = 0;
1796
1797         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1798                 return -errno;
1799
1800         if (vt < 0) {
1801                 int tiocl[2] = {
1802                         TIOCL_GETKMSGREDIRECT,
1803                         0
1804                 };
1805
1806                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1807                         return -errno;
1808
1809                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1810         }
1811
1812         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1813                 r = -errno;
1814
1815         close_nointr_nofail(r);
1816         return r;
1817 }
1818
1819 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1820         struct termios old_termios, new_termios;
1821         char c;
1822         char line[1024];
1823
1824         assert(f);
1825         assert(ret);
1826
1827         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1828                 new_termios = old_termios;
1829
1830                 new_termios.c_lflag &= ~ICANON;
1831                 new_termios.c_cc[VMIN] = 1;
1832                 new_termios.c_cc[VTIME] = 0;
1833
1834                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1835                         size_t k;
1836
1837                         k = fread(&c, 1, 1, f);
1838
1839                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1840
1841                         if (k <= 0)
1842                                 return -EIO;
1843
1844                         if (need_nl)
1845                                 *need_nl = c != '\n';
1846
1847                         *ret = c;
1848                         return 0;
1849                 }
1850         }
1851
1852         if (!(fgets(line, sizeof(line), f)))
1853                 return -EIO;
1854
1855         truncate_nl(line);
1856
1857         if (strlen(line) != 1)
1858                 return -EBADMSG;
1859
1860         if (need_nl)
1861                 *need_nl = false;
1862
1863         *ret = line[0];
1864         return 0;
1865 }
1866
1867 int ask(char *ret, const char *replies, const char *text, ...) {
1868         assert(ret);
1869         assert(replies);
1870         assert(text);
1871
1872         for (;;) {
1873                 va_list ap;
1874                 char c;
1875                 int r;
1876                 bool need_nl = true;
1877
1878                 fputs("\x1B[1m", stdout);
1879
1880                 va_start(ap, text);
1881                 vprintf(text, ap);
1882                 va_end(ap);
1883
1884                 fputs("\x1B[0m", stdout);
1885
1886                 fflush(stdout);
1887
1888                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1889
1890                         if (r == -EBADMSG) {
1891                                 puts("Bad input, please try again.");
1892                                 continue;
1893                         }
1894
1895                         putchar('\n');
1896                         return r;
1897                 }
1898
1899                 if (need_nl)
1900                         putchar('\n');
1901
1902                 if (strchr(replies, c)) {
1903                         *ret = c;
1904                         return 0;
1905                 }
1906
1907                 puts("Read unexpected character, please try again.");
1908         }
1909 }
1910
1911 int reset_terminal(int fd) {
1912         struct termios termios;
1913         int r = 0;
1914         long arg;
1915
1916         /* Set terminal to some sane defaults */
1917
1918         assert(fd >= 0);
1919
1920         /* We leave locked terminal attributes untouched, so that
1921          * Plymouth may set whatever it wants to set, and we don't
1922          * interfere with that. */
1923
1924         /* Disable exclusive mode, just in case */
1925         ioctl(fd, TIOCNXCL);
1926
1927         /* Enable console unicode mode */
1928         arg = K_UNICODE;
1929         ioctl(fd, KDSKBMODE, &arg);
1930
1931         if (tcgetattr(fd, &termios) < 0) {
1932                 r = -errno;
1933                 goto finish;
1934         }
1935
1936         /* We only reset the stuff that matters to the software. How
1937          * hardware is set up we don't touch assuming that somebody
1938          * else will do that for us */
1939
1940         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1941         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1942         termios.c_oflag |= ONLCR;
1943         termios.c_cflag |= CREAD;
1944         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1945
1946         termios.c_cc[VINTR]    =   03;  /* ^C */
1947         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1948         termios.c_cc[VERASE]   = 0177;
1949         termios.c_cc[VKILL]    =  025;  /* ^X */
1950         termios.c_cc[VEOF]     =   04;  /* ^D */
1951         termios.c_cc[VSTART]   =  021;  /* ^Q */
1952         termios.c_cc[VSTOP]    =  023;  /* ^S */
1953         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1954         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1955         termios.c_cc[VWERASE]  =  027;  /* ^W */
1956         termios.c_cc[VREPRINT] =  022;  /* ^R */
1957         termios.c_cc[VEOL]     =    0;
1958         termios.c_cc[VEOL2]    =    0;
1959
1960         termios.c_cc[VTIME]  = 0;
1961         termios.c_cc[VMIN]   = 1;
1962
1963         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1964                 r = -errno;
1965
1966 finish:
1967         /* Just in case, flush all crap out */
1968         tcflush(fd, TCIOFLUSH);
1969
1970         return r;
1971 }
1972
1973 int open_terminal(const char *name, int mode) {
1974         int fd, r;
1975
1976         if ((fd = open(name, mode)) < 0)
1977                 return -errno;
1978
1979         if ((r = isatty(fd)) < 0) {
1980                 close_nointr_nofail(fd);
1981                 return -errno;
1982         }
1983
1984         if (!r) {
1985                 close_nointr_nofail(fd);
1986                 return -ENOTTY;
1987         }
1988
1989         return fd;
1990 }
1991
1992 int flush_fd(int fd) {
1993         struct pollfd pollfd;
1994
1995         zero(pollfd);
1996         pollfd.fd = fd;
1997         pollfd.events = POLLIN;
1998
1999         for (;;) {
2000                 char buf[1024];
2001                 ssize_t l;
2002                 int r;
2003
2004                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2005
2006                         if (errno == EINTR)
2007                                 continue;
2008
2009                         return -errno;
2010                 }
2011
2012                 if (r == 0)
2013                         return 0;
2014
2015                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2016
2017                         if (errno == EINTR)
2018                                 continue;
2019
2020                         if (errno == EAGAIN)
2021                                 return 0;
2022
2023                         return -errno;
2024                 }
2025
2026                 if (l <= 0)
2027                         return 0;
2028         }
2029 }
2030
2031 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2032         int fd = -1, notify = -1, r, wd = -1;
2033
2034         assert(name);
2035
2036         /* We use inotify to be notified when the tty is closed. We
2037          * create the watch before checking if we can actually acquire
2038          * it, so that we don't lose any event.
2039          *
2040          * Note: strictly speaking this actually watches for the
2041          * device being closed, it does *not* really watch whether a
2042          * tty loses its controlling process. However, unless some
2043          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2044          * its tty otherwise this will not become a problem. As long
2045          * as the administrator makes sure not configure any service
2046          * on the same tty as an untrusted user this should not be a
2047          * problem. (Which he probably should not do anyway.) */
2048
2049         if (!fail && !force) {
2050                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2051                         r = -errno;
2052                         goto fail;
2053                 }
2054
2055                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2056                         r = -errno;
2057                         goto fail;
2058                 }
2059         }
2060
2061         for (;;) {
2062                 if (notify >= 0)
2063                         if ((r = flush_fd(notify)) < 0)
2064                                 goto fail;
2065
2066                 /* We pass here O_NOCTTY only so that we can check the return
2067                  * value TIOCSCTTY and have a reliable way to figure out if we
2068                  * successfully became the controlling process of the tty */
2069                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2070                         return -errno;
2071
2072                 /* First, try to get the tty */
2073                 r = ioctl(fd, TIOCSCTTY, force);
2074
2075                 /* Sometimes it makes sense to ignore TIOCSCTTY
2076                  * returning EPERM, i.e. when very likely we already
2077                  * are have this controlling terminal. */
2078                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2079                         r = 0;
2080
2081                 if (r < 0 && (force || fail || errno != EPERM)) {
2082                         r = -errno;
2083                         goto fail;
2084                 }
2085
2086                 if (r >= 0)
2087                         break;
2088
2089                 assert(!fail);
2090                 assert(!force);
2091                 assert(notify >= 0);
2092
2093                 for (;;) {
2094                         struct inotify_event e;
2095                         ssize_t l;
2096
2097                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2098
2099                                 if (l < 0) {
2100
2101                                         if (errno == EINTR)
2102                                                 continue;
2103
2104                                         r = -errno;
2105                                 } else
2106                                         r = -EIO;
2107
2108                                 goto fail;
2109                         }
2110
2111                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
2112                                 r = -EIO;
2113                                 goto fail;
2114                         }
2115
2116                         break;
2117                 }
2118
2119                 /* We close the tty fd here since if the old session
2120                  * ended our handle will be dead. It's important that
2121                  * we do this after sleeping, so that we don't enter
2122                  * an endless loop. */
2123                 close_nointr_nofail(fd);
2124         }
2125
2126         if (notify >= 0)
2127                 close_nointr_nofail(notify);
2128
2129         if ((r = reset_terminal(fd)) < 0)
2130                 log_warning("Failed to reset terminal: %s", strerror(-r));
2131
2132         return fd;
2133
2134 fail:
2135         if (fd >= 0)
2136                 close_nointr_nofail(fd);
2137
2138         if (notify >= 0)
2139                 close_nointr_nofail(notify);
2140
2141         return r;
2142 }
2143
2144 int release_terminal(void) {
2145         int r = 0, fd;
2146         struct sigaction sa_old, sa_new;
2147
2148         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2149                 return -errno;
2150
2151         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2152          * by our own TIOCNOTTY */
2153
2154         zero(sa_new);
2155         sa_new.sa_handler = SIG_IGN;
2156         sa_new.sa_flags = SA_RESTART;
2157         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2158
2159         if (ioctl(fd, TIOCNOTTY) < 0)
2160                 r = -errno;
2161
2162         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2163
2164         close_nointr_nofail(fd);
2165         return r;
2166 }
2167
2168 int sigaction_many(const struct sigaction *sa, ...) {
2169         va_list ap;
2170         int r = 0, sig;
2171
2172         va_start(ap, sa);
2173         while ((sig = va_arg(ap, int)) > 0)
2174                 if (sigaction(sig, sa, NULL) < 0)
2175                         r = -errno;
2176         va_end(ap);
2177
2178         return r;
2179 }
2180
2181 int ignore_signals(int sig, ...) {
2182         struct sigaction sa;
2183         va_list ap;
2184         int r = 0;
2185
2186         zero(sa);
2187         sa.sa_handler = SIG_IGN;
2188         sa.sa_flags = SA_RESTART;
2189
2190         if (sigaction(sig, &sa, NULL) < 0)
2191                 r = -errno;
2192
2193         va_start(ap, sig);
2194         while ((sig = va_arg(ap, int)) > 0)
2195                 if (sigaction(sig, &sa, NULL) < 0)
2196                         r = -errno;
2197         va_end(ap);
2198
2199         return r;
2200 }
2201
2202 int default_signals(int sig, ...) {
2203         struct sigaction sa;
2204         va_list ap;
2205         int r = 0;
2206
2207         zero(sa);
2208         sa.sa_handler = SIG_DFL;
2209         sa.sa_flags = SA_RESTART;
2210
2211         if (sigaction(sig, &sa, NULL) < 0)
2212                 r = -errno;
2213
2214         va_start(ap, sig);
2215         while ((sig = va_arg(ap, int)) > 0)
2216                 if (sigaction(sig, &sa, NULL) < 0)
2217                         r = -errno;
2218         va_end(ap);
2219
2220         return r;
2221 }
2222
2223 int close_pipe(int p[]) {
2224         int a = 0, b = 0;
2225
2226         assert(p);
2227
2228         if (p[0] >= 0) {
2229                 a = close_nointr(p[0]);
2230                 p[0] = -1;
2231         }
2232
2233         if (p[1] >= 0) {
2234                 b = close_nointr(p[1]);
2235                 p[1] = -1;
2236         }
2237
2238         return a < 0 ? a : b;
2239 }
2240
2241 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2242         uint8_t *p;
2243         ssize_t n = 0;
2244
2245         assert(fd >= 0);
2246         assert(buf);
2247
2248         p = buf;
2249
2250         while (nbytes > 0) {
2251                 ssize_t k;
2252
2253                 if ((k = read(fd, p, nbytes)) <= 0) {
2254
2255                         if (k < 0 && errno == EINTR)
2256                                 continue;
2257
2258                         if (k < 0 && errno == EAGAIN && do_poll) {
2259                                 struct pollfd pollfd;
2260
2261                                 zero(pollfd);
2262                                 pollfd.fd = fd;
2263                                 pollfd.events = POLLIN;
2264
2265                                 if (poll(&pollfd, 1, -1) < 0) {
2266                                         if (errno == EINTR)
2267                                                 continue;
2268
2269                                         return n > 0 ? n : -errno;
2270                                 }
2271
2272                                 if (pollfd.revents != POLLIN)
2273                                         return n > 0 ? n : -EIO;
2274
2275                                 continue;
2276                         }
2277
2278                         return n > 0 ? n : (k < 0 ? -errno : 0);
2279                 }
2280
2281                 p += k;
2282                 nbytes -= k;
2283                 n += k;
2284         }
2285
2286         return n;
2287 }
2288
2289 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2290         const uint8_t *p;
2291         ssize_t n = 0;
2292
2293         assert(fd >= 0);
2294         assert(buf);
2295
2296         p = buf;
2297
2298         while (nbytes > 0) {
2299                 ssize_t k;
2300
2301                 if ((k = write(fd, p, nbytes)) <= 0) {
2302
2303                         if (k < 0 && errno == EINTR)
2304                                 continue;
2305
2306                         if (k < 0 && errno == EAGAIN && do_poll) {
2307                                 struct pollfd pollfd;
2308
2309                                 zero(pollfd);
2310                                 pollfd.fd = fd;
2311                                 pollfd.events = POLLOUT;
2312
2313                                 if (poll(&pollfd, 1, -1) < 0) {
2314                                         if (errno == EINTR)
2315                                                 continue;
2316
2317                                         return n > 0 ? n : -errno;
2318                                 }
2319
2320                                 if (pollfd.revents != POLLOUT)
2321                                         return n > 0 ? n : -EIO;
2322
2323                                 continue;
2324                         }
2325
2326                         return n > 0 ? n : (k < 0 ? -errno : 0);
2327                 }
2328
2329                 p += k;
2330                 nbytes -= k;
2331                 n += k;
2332         }
2333
2334         return n;
2335 }
2336
2337 int path_is_mount_point(const char *t) {
2338         struct stat a, b;
2339         char *parent;
2340         int r;
2341
2342         if (lstat(t, &a) < 0) {
2343                 if (errno == ENOENT)
2344                         return 0;
2345
2346                 return -errno;
2347         }
2348
2349         if ((r = parent_of_path(t, &parent)) < 0)
2350                 return r;
2351
2352         r = lstat(parent, &b);
2353         free(parent);
2354
2355         if (r < 0)
2356                 return -errno;
2357
2358         return a.st_dev != b.st_dev;
2359 }
2360
2361 int parse_usec(const char *t, usec_t *usec) {
2362         static const struct {
2363                 const char *suffix;
2364                 usec_t usec;
2365         } table[] = {
2366                 { "sec", USEC_PER_SEC },
2367                 { "s", USEC_PER_SEC },
2368                 { "min", USEC_PER_MINUTE },
2369                 { "hr", USEC_PER_HOUR },
2370                 { "h", USEC_PER_HOUR },
2371                 { "d", USEC_PER_DAY },
2372                 { "w", USEC_PER_WEEK },
2373                 { "msec", USEC_PER_MSEC },
2374                 { "ms", USEC_PER_MSEC },
2375                 { "m", USEC_PER_MINUTE },
2376                 { "usec", 1ULL },
2377                 { "us", 1ULL },
2378                 { "", USEC_PER_SEC },
2379         };
2380
2381         const char *p;
2382         usec_t r = 0;
2383
2384         assert(t);
2385         assert(usec);
2386
2387         p = t;
2388         do {
2389                 long long l;
2390                 char *e;
2391                 unsigned i;
2392
2393                 errno = 0;
2394                 l = strtoll(p, &e, 10);
2395
2396                 if (errno != 0)
2397                         return -errno;
2398
2399                 if (l < 0)
2400                         return -ERANGE;
2401
2402                 if (e == p)
2403                         return -EINVAL;
2404
2405                 e += strspn(e, WHITESPACE);
2406
2407                 for (i = 0; i < ELEMENTSOF(table); i++)
2408                         if (startswith(e, table[i].suffix)) {
2409                                 r += (usec_t) l * table[i].usec;
2410                                 p = e + strlen(table[i].suffix);
2411                                 break;
2412                         }
2413
2414                 if (i >= ELEMENTSOF(table))
2415                         return -EINVAL;
2416
2417         } while (*p != 0);
2418
2419         *usec = r;
2420
2421         return 0;
2422 }
2423
2424 int make_stdio(int fd) {
2425         int r, s, t;
2426
2427         assert(fd >= 0);
2428
2429         r = dup2(fd, STDIN_FILENO);
2430         s = dup2(fd, STDOUT_FILENO);
2431         t = dup2(fd, STDERR_FILENO);
2432
2433         if (fd >= 3)
2434                 close_nointr_nofail(fd);
2435
2436         if (r < 0 || s < 0 || t < 0)
2437                 return -errno;
2438
2439         return 0;
2440 }
2441
2442 bool is_clean_exit(int code, int status) {
2443
2444         if (code == CLD_EXITED)
2445                 return status == 0;
2446
2447         /* If a daemon does not implement handlers for some of the
2448          * signals that's not considered an unclean shutdown */
2449         if (code == CLD_KILLED)
2450                 return
2451                         status == SIGHUP ||
2452                         status == SIGINT ||
2453                         status == SIGTERM ||
2454                         status == SIGPIPE;
2455
2456         return false;
2457 }
2458
2459 bool is_clean_exit_lsb(int code, int status) {
2460
2461         if (is_clean_exit(code, status))
2462                 return true;
2463
2464         return
2465                 code == CLD_EXITED &&
2466                 (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
2467 }
2468
2469 bool is_device_path(const char *path) {
2470
2471         /* Returns true on paths that refer to a device, either in
2472          * sysfs or in /dev */
2473
2474         return
2475                 path_startswith(path, "/dev/") ||
2476                 path_startswith(path, "/sys/");
2477 }
2478
2479 int dir_is_empty(const char *path) {
2480         DIR *d;
2481         int r;
2482         struct dirent buf, *de;
2483
2484         if (!(d = opendir(path)))
2485                 return -errno;
2486
2487         for (;;) {
2488                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2489                         r = -r;
2490                         break;
2491                 }
2492
2493                 if (!de) {
2494                         r = 1;
2495                         break;
2496                 }
2497
2498                 if (!ignore_file(de->d_name)) {
2499                         r = 0;
2500                         break;
2501                 }
2502         }
2503
2504         closedir(d);
2505         return r;
2506 }
2507
2508 unsigned long long random_ull(void) {
2509         int fd;
2510         uint64_t ull;
2511         ssize_t r;
2512
2513         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2514                 goto fallback;
2515
2516         r = loop_read(fd, &ull, sizeof(ull), true);
2517         close_nointr_nofail(fd);
2518
2519         if (r != sizeof(ull))
2520                 goto fallback;
2521
2522         return ull;
2523
2524 fallback:
2525         return random() * RAND_MAX + random();
2526 }
2527
2528 void rename_process(const char name[8]) {
2529         assert(name);
2530
2531         prctl(PR_SET_NAME, name);
2532
2533         /* This is a like a poor man's setproctitle(). The string
2534          * passed should fit in 7 chars (i.e. the length of
2535          * "systemd") */
2536
2537         if (program_invocation_name)
2538                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2539 }
2540
2541 void sigset_add_many(sigset_t *ss, ...) {
2542         va_list ap;
2543         int sig;
2544
2545         assert(ss);
2546
2547         va_start(ap, ss);
2548         while ((sig = va_arg(ap, int)) > 0)
2549                 assert_se(sigaddset(ss, sig) == 0);
2550         va_end(ap);
2551 }
2552
2553 char* gethostname_malloc(void) {
2554         struct utsname u;
2555
2556         assert_se(uname(&u) >= 0);
2557
2558         if (u.nodename[0])
2559                 return strdup(u.nodename);
2560
2561         return strdup(u.sysname);
2562 }
2563
2564 char* getlogname_malloc(void) {
2565         uid_t uid;
2566         long bufsize;
2567         char *buf, *name;
2568         struct passwd pwbuf, *pw = NULL;
2569         struct stat st;
2570
2571         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2572                 uid = st.st_uid;
2573         else
2574                 uid = getuid();
2575
2576         /* Shortcut things to avoid NSS lookups */
2577         if (uid == 0)
2578                 return strdup("root");
2579
2580         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2581                 bufsize = 4096;
2582
2583         if (!(buf = malloc(bufsize)))
2584                 return NULL;
2585
2586         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2587                 name = strdup(pw->pw_name);
2588                 free(buf);
2589                 return name;
2590         }
2591
2592         free(buf);
2593
2594         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2595                 return NULL;
2596
2597         return name;
2598 }
2599
2600 int getttyname_malloc(char **r) {
2601         char path[PATH_MAX], *p, *c;
2602         int k;
2603
2604         assert(r);
2605
2606         if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2607                 return -k;
2608
2609         char_array_0(path);
2610
2611         p = path;
2612         if (startswith(path, "/dev/"))
2613                 p += 5;
2614
2615         if (!(c = strdup(p)))
2616                 return -ENOMEM;
2617
2618         *r = c;
2619         return 0;
2620 }
2621
2622 static int rm_rf_children(int fd, bool only_dirs) {
2623         DIR *d;
2624         int ret = 0;
2625
2626         assert(fd >= 0);
2627
2628         /* This returns the first error we run into, but nevertheless
2629          * tries to go on */
2630
2631         if (!(d = fdopendir(fd))) {
2632                 close_nointr_nofail(fd);
2633
2634                 return errno == ENOENT ? 0 : -errno;
2635         }
2636
2637         for (;;) {
2638                 struct dirent buf, *de;
2639                 bool is_dir;
2640                 int r;
2641
2642                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2643                         if (ret == 0)
2644                                 ret = -r;
2645                         break;
2646                 }
2647
2648                 if (!de)
2649                         break;
2650
2651                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2652                         continue;
2653
2654                 if (de->d_type == DT_UNKNOWN) {
2655                         struct stat st;
2656
2657                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2658                                 if (ret == 0 && errno != ENOENT)
2659                                         ret = -errno;
2660                                 continue;
2661                         }
2662
2663                         is_dir = S_ISDIR(st.st_mode);
2664                 } else
2665                         is_dir = de->d_type == DT_DIR;
2666
2667                 if (is_dir) {
2668                         int subdir_fd;
2669
2670                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2671                                 if (ret == 0 && errno != ENOENT)
2672                                         ret = -errno;
2673                                 continue;
2674                         }
2675
2676                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2677                                 if (ret == 0)
2678                                         ret = r;
2679                         }
2680
2681                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2682                                 if (ret == 0 && errno != ENOENT)
2683                                         ret = -errno;
2684                         }
2685                 } else  if (!only_dirs) {
2686
2687                         if (unlinkat(fd, de->d_name, 0) < 0) {
2688                                 if (ret == 0 && errno != ENOENT)
2689                                         ret = -errno;
2690                         }
2691                 }
2692         }
2693
2694         closedir(d);
2695
2696         return ret;
2697 }
2698
2699 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2700         int fd;
2701         int r;
2702
2703         assert(path);
2704
2705         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2706
2707                 if (errno != ENOTDIR)
2708                         return -errno;
2709
2710                 if (delete_root && !only_dirs)
2711                         if (unlink(path) < 0)
2712                                 return -errno;
2713
2714                 return 0;
2715         }
2716
2717         r = rm_rf_children(fd, only_dirs);
2718
2719         if (delete_root)
2720                 if (rmdir(path) < 0) {
2721                         if (r == 0)
2722                                 r = -errno;
2723                 }
2724
2725         return r;
2726 }
2727
2728 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2729         assert(path);
2730
2731         /* Under the assumption that we are running privileged we
2732          * first change the access mode and only then hand out
2733          * ownership to avoid a window where access is too open. */
2734
2735         if (chmod(path, mode) < 0)
2736                 return -errno;
2737
2738         if (chown(path, uid, gid) < 0)
2739                 return -errno;
2740
2741         return 0;
2742 }
2743
2744 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2745         cpu_set_t *r;
2746         unsigned n = 1024;
2747
2748         /* Allocates the cpuset in the right size */
2749
2750         for (;;) {
2751                 if (!(r = CPU_ALLOC(n)))
2752                         return NULL;
2753
2754                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2755                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2756
2757                         if (ncpus)
2758                                 *ncpus = n;
2759
2760                         return r;
2761                 }
2762
2763                 CPU_FREE(r);
2764
2765                 if (errno != EINVAL)
2766                         return NULL;
2767
2768                 n *= 2;
2769         }
2770 }
2771
2772 void status_vprintf(const char *format, va_list ap) {
2773         char *s = NULL;
2774         int fd = -1;
2775
2776         assert(format);
2777
2778         /* This independent of logging, as status messages are
2779          * optional and go exclusively to the console. */
2780
2781         if (vasprintf(&s, format, ap) < 0)
2782                 goto finish;
2783
2784         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2785                 goto finish;
2786
2787         write(fd, s, strlen(s));
2788
2789 finish:
2790         free(s);
2791
2792         if (fd >= 0)
2793                 close_nointr_nofail(fd);
2794 }
2795
2796 void status_printf(const char *format, ...) {
2797         va_list ap;
2798
2799         assert(format);
2800
2801         va_start(ap, format);
2802         status_vprintf(format, ap);
2803         va_end(ap);
2804 }
2805
2806 void status_welcome(void) {
2807
2808 #if defined(TARGET_FEDORA)
2809         char *r;
2810
2811         if (read_one_line_file("/etc/system-release", &r) < 0)
2812                 return;
2813
2814         truncate_nl(r);
2815
2816         /* This tries to mimic the color magic the old Red Hat sysinit
2817          * script did. */
2818
2819         if (startswith(r, "Red Hat"))
2820                 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2821         else if (startswith(r, "Fedora"))
2822                 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2823         else
2824                 status_printf("Welcome to %s!\n", r);
2825
2826         free(r);
2827
2828 #elif defined(TARGET_SUSE)
2829         char *r;
2830
2831         if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2832                 return;
2833
2834         truncate_nl(r);
2835
2836         status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2837         free(r);
2838
2839 #elif defined(TARGET_GENTOO)
2840         char *r;
2841
2842         if (read_one_line_file("/etc/gentoo-release", &r) < 0)
2843                 return;
2844
2845         truncate_nl(r);
2846
2847         status_printf("Welcome to \x1B[1;34m%s\x1B[0m!\n", r); /* Light Blue for Gentoo */
2848
2849         free(r);
2850
2851 #elif defined(TARGET_DEBIAN)
2852         char *r;
2853
2854         if (read_one_line_file("/etc/debian_version", &r) < 0)
2855                 return;
2856
2857         truncate_nl(r);
2858
2859         status_printf("Welcome to Debian \x1B[1;31m%s\x1B[0m!\n", r); /* Light Red for Debian */
2860
2861         free(r);
2862 #else
2863 #warning "You probably should add a welcome text logic here."
2864 #endif
2865 }
2866
2867 char *replace_env(const char *format, char **env) {
2868         enum {
2869                 WORD,
2870                 CURLY,
2871                 VARIABLE
2872         } state = WORD;
2873
2874         const char *e, *word = format;
2875         char *r = NULL, *k;
2876
2877         assert(format);
2878
2879         for (e = format; *e; e ++) {
2880
2881                 switch (state) {
2882
2883                 case WORD:
2884                         if (*e == '$')
2885                                 state = CURLY;
2886                         break;
2887
2888                 case CURLY:
2889                         if (*e == '{') {
2890                                 if (!(k = strnappend(r, word, e-word-1)))
2891                                         goto fail;
2892
2893                                 free(r);
2894                                 r = k;
2895
2896                                 word = e-1;
2897                                 state = VARIABLE;
2898
2899                         } else if (*e == '$') {
2900                                 if (!(k = strnappend(r, word, e-word)))
2901                                         goto fail;
2902
2903                                 free(r);
2904                                 r = k;
2905
2906                                 word = e+1;
2907                                 state = WORD;
2908                         } else
2909                                 state = WORD;
2910                         break;
2911
2912                 case VARIABLE:
2913                         if (*e == '}') {
2914                                 const char *t;
2915
2916                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
2917                                         t = "";
2918
2919                                 if (!(k = strappend(r, t)))
2920                                         goto fail;
2921
2922                                 free(r);
2923                                 r = k;
2924
2925                                 word = e+1;
2926                                 state = WORD;
2927                         }
2928                         break;
2929                 }
2930         }
2931
2932         if (!(k = strnappend(r, word, e-word)))
2933                 goto fail;
2934
2935         free(r);
2936         return k;
2937
2938 fail:
2939         free(r);
2940         return NULL;
2941 }
2942
2943 char **replace_env_argv(char **argv, char **env) {
2944         char **r, **i;
2945         unsigned k = 0, l = 0;
2946
2947         l = strv_length(argv);
2948
2949         if (!(r = new(char*, l+1)))
2950                 return NULL;
2951
2952         STRV_FOREACH(i, argv) {
2953
2954                 /* If $FOO appears as single word, replace it by the split up variable */
2955                 if ((*i)[0] == '$' && (*i)[1] != '{') {
2956                         char *e;
2957                         char **w, **m;
2958                         unsigned q;
2959
2960                         if ((e = strv_env_get(env, *i+1))) {
2961
2962                                 if (!(m = strv_split_quoted(e))) {
2963                                         r[k] = NULL;
2964                                         strv_free(r);
2965                                         return NULL;
2966                                 }
2967                         } else
2968                                 m = NULL;
2969
2970                         q = strv_length(m);
2971                         l = l + q - 1;
2972
2973                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
2974                                 r[k] = NULL;
2975                                 strv_free(r);
2976                                 strv_free(m);
2977                                 return NULL;
2978                         }
2979
2980                         r = w;
2981                         if (m) {
2982                                 memcpy(r + k, m, q * sizeof(char*));
2983                                 free(m);
2984                         }
2985
2986                         k += q;
2987                         continue;
2988                 }
2989
2990                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
2991                 if (!(r[k++] = replace_env(*i, env))) {
2992                         strv_free(r);
2993                         return NULL;
2994                 }
2995         }
2996
2997         r[k] = NULL;
2998         return r;
2999 }
3000
3001 int columns(void) {
3002         static __thread int parsed_columns = 0;
3003         const char *e;
3004
3005         if (parsed_columns > 0)
3006                 return parsed_columns;
3007
3008         if ((e = getenv("COLUMNS")))
3009                 parsed_columns = atoi(e);
3010
3011         if (parsed_columns <= 0) {
3012                 struct winsize ws;
3013                 zero(ws);
3014
3015                 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3016                         parsed_columns = ws.ws_col;
3017         }
3018
3019         if (parsed_columns <= 0)
3020                 parsed_columns = 80;
3021
3022         return parsed_columns;
3023 }
3024
3025 int running_in_chroot(void) {
3026         struct stat a, b;
3027
3028         zero(a);
3029         zero(b);
3030
3031         /* Only works as root */
3032
3033         if (stat("/proc/1/root", &a) < 0)
3034                 return -errno;
3035
3036         if (stat("/", &b) < 0)
3037                 return -errno;
3038
3039         return
3040                 a.st_dev != b.st_dev ||
3041                 a.st_ino != b.st_ino;
3042 }
3043
3044 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3045         size_t l, x;
3046         char *r;
3047
3048         assert(s);
3049         assert(percent <= 100);
3050         assert(length >= 3);
3051
3052         l = strlen(s);
3053
3054         if (l <= 3 || l <= length)
3055                 return strdup(s);
3056
3057         if (!(r = new0(char, length+1)))
3058                 return r;
3059
3060         x = (length * percent) / 100;
3061
3062         if (x > length - 3)
3063                 x = length - 3;
3064
3065         memcpy(r, s, x);
3066         r[x] = '.';
3067         r[x+1] = '.';
3068         r[x+2] = '.';
3069         memcpy(r + x + 3,
3070                s + l - (length - x - 3),
3071                length - x - 3);
3072
3073         return r;
3074 }
3075
3076 int touch(const char *path) {
3077         int fd;
3078
3079         assert(path);
3080
3081         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3082                 return -errno;
3083
3084         close_nointr_nofail(fd);
3085         return 0;
3086 }
3087
3088 char *unquote(const char *s, const char quote) {
3089         size_t l;
3090         assert(s);
3091
3092         if ((l = strlen(s)) < 2)
3093                 return strdup(s);
3094
3095         if (s[0] == quote && s[l-1] == quote)
3096                 return strndup(s+1, l-2);
3097
3098         return strdup(s);
3099 }
3100
3101 static const char *const ioprio_class_table[] = {
3102         [IOPRIO_CLASS_NONE] = "none",
3103         [IOPRIO_CLASS_RT] = "realtime",
3104         [IOPRIO_CLASS_BE] = "best-effort",
3105         [IOPRIO_CLASS_IDLE] = "idle"
3106 };
3107
3108 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3109
3110 static const char *const sigchld_code_table[] = {
3111         [CLD_EXITED] = "exited",
3112         [CLD_KILLED] = "killed",
3113         [CLD_DUMPED] = "dumped",
3114         [CLD_TRAPPED] = "trapped",
3115         [CLD_STOPPED] = "stopped",
3116         [CLD_CONTINUED] = "continued",
3117 };
3118
3119 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3120
3121 static const char *const log_facility_table[LOG_NFACILITIES] = {
3122         [LOG_FAC(LOG_KERN)] = "kern",
3123         [LOG_FAC(LOG_USER)] = "user",
3124         [LOG_FAC(LOG_MAIL)] = "mail",
3125         [LOG_FAC(LOG_DAEMON)] = "daemon",
3126         [LOG_FAC(LOG_AUTH)] = "auth",
3127         [LOG_FAC(LOG_SYSLOG)] = "syslog",
3128         [LOG_FAC(LOG_LPR)] = "lpr",
3129         [LOG_FAC(LOG_NEWS)] = "news",
3130         [LOG_FAC(LOG_UUCP)] = "uucp",
3131         [LOG_FAC(LOG_CRON)] = "cron",
3132         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3133         [LOG_FAC(LOG_FTP)] = "ftp",
3134         [LOG_FAC(LOG_LOCAL0)] = "local0",
3135         [LOG_FAC(LOG_LOCAL1)] = "local1",
3136         [LOG_FAC(LOG_LOCAL2)] = "local2",
3137         [LOG_FAC(LOG_LOCAL3)] = "local3",
3138         [LOG_FAC(LOG_LOCAL4)] = "local4",
3139         [LOG_FAC(LOG_LOCAL5)] = "local5",
3140         [LOG_FAC(LOG_LOCAL6)] = "local6",
3141         [LOG_FAC(LOG_LOCAL7)] = "local7"
3142 };
3143
3144 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3145
3146 static const char *const log_level_table[] = {
3147         [LOG_EMERG] = "emerg",
3148         [LOG_ALERT] = "alert",
3149         [LOG_CRIT] = "crit",
3150         [LOG_ERR] = "err",
3151         [LOG_WARNING] = "warning",
3152         [LOG_NOTICE] = "notice",
3153         [LOG_INFO] = "info",
3154         [LOG_DEBUG] = "debug"
3155 };
3156
3157 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3158
3159 static const char* const sched_policy_table[] = {
3160         [SCHED_OTHER] = "other",
3161         [SCHED_BATCH] = "batch",
3162         [SCHED_IDLE] = "idle",
3163         [SCHED_FIFO] = "fifo",
3164         [SCHED_RR] = "rr"
3165 };
3166
3167 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3168
3169 static const char* const rlimit_table[] = {
3170         [RLIMIT_CPU] = "LimitCPU",
3171         [RLIMIT_FSIZE] = "LimitFSIZE",
3172         [RLIMIT_DATA] = "LimitDATA",
3173         [RLIMIT_STACK] = "LimitSTACK",
3174         [RLIMIT_CORE] = "LimitCORE",
3175         [RLIMIT_RSS] = "LimitRSS",
3176         [RLIMIT_NOFILE] = "LimitNOFILE",
3177         [RLIMIT_AS] = "LimitAS",
3178         [RLIMIT_NPROC] = "LimitNPROC",
3179         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3180         [RLIMIT_LOCKS] = "LimitLOCKS",
3181         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3182         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3183         [RLIMIT_NICE] = "LimitNICE",
3184         [RLIMIT_RTPRIO] = "LimitRTPRIO",
3185         [RLIMIT_RTTIME] = "LimitRTTIME"
3186 };
3187
3188 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3189
3190 static const char* const ip_tos_table[] = {
3191         [IPTOS_LOWDELAY] = "low-delay",
3192         [IPTOS_THROUGHPUT] = "throughput",
3193         [IPTOS_RELIABILITY] = "reliability",
3194         [IPTOS_LOWCOST] = "low-cost",
3195 };
3196
3197 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3198
3199 static const char *const signal_table[] = {
3200         [SIGHUP] = "HUP",
3201         [SIGINT] = "INT",
3202         [SIGQUIT] = "QUIT",
3203         [SIGILL] = "ILL",
3204         [SIGTRAP] = "TRAP",
3205         [SIGABRT] = "ABRT",
3206         [SIGBUS] = "BUS",
3207         [SIGFPE] = "FPE",
3208         [SIGKILL] = "KILL",
3209         [SIGUSR1] = "USR1",
3210         [SIGSEGV] = "SEGV",
3211         [SIGUSR2] = "USR2",
3212         [SIGPIPE] = "PIPE",
3213         [SIGALRM] = "ALRM",
3214         [SIGTERM] = "TERM",
3215         [SIGSTKFLT] = "STKFLT",
3216         [SIGCHLD] = "CHLD",
3217         [SIGCONT] = "CONT",
3218         [SIGSTOP] = "STOP",
3219         [SIGTSTP] = "TSTP",
3220         [SIGTTIN] = "TTIN",
3221         [SIGTTOU] = "TTOU",
3222         [SIGURG] = "URG",
3223         [SIGXCPU] = "XCPU",
3224         [SIGXFSZ] = "XFSZ",
3225         [SIGVTALRM] = "VTALRM",
3226         [SIGPROF] = "PROF",
3227         [SIGWINCH] = "WINCH",
3228         [SIGIO] = "IO",
3229         [SIGPWR] = "PWR",
3230         [SIGSYS] = "SYS"
3231 };
3232
3233 DEFINE_STRING_TABLE_LOOKUP(signal, int);