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