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