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