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