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