chiark / gitweb /
backlight: Fix copy/paste error printing an unrelated error code
[elogind.git] / src / shared / util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 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   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser 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 <ctype.h>
45 #include <sys/prctl.h>
46 #include <sys/utsname.h>
47 #include <pwd.h>
48 #include <netinet/ip.h>
49 #include <linux/kd.h>
50 #include <dlfcn.h>
51 #include <sys/wait.h>
52 #include <sys/time.h>
53 #include <glob.h>
54 #include <grp.h>
55 #include <sys/mman.h>
56 #include <sys/vfs.h>
57 #include <linux/magic.h>
58 #include <limits.h>
59 #include <langinfo.h>
60 #include <locale.h>
61 #include <sys/personality.h>
62 #include <libgen.h>
63 #undef basename
64
65 #ifdef HAVE_SYS_AUXV_H
66 #include <sys/auxv.h>
67 #endif
68
69 #include "macro.h"
70 #include "util.h"
71 #include "ioprio.h"
72 #include "missing.h"
73 #include "log.h"
74 #include "strv.h"
75 #include "label.h"
76 #include "path-util.h"
77 #include "exit-status.h"
78 #include "hashmap.h"
79 #include "env-util.h"
80 #include "fileio.h"
81 #include "device-nodes.h"
82 #include "utf8.h"
83 #include "gunicode.h"
84 #include "virt.h"
85 #include "def.h"
86 #include "missing.h"
87
88 int saved_argc = 0;
89 char **saved_argv = NULL;
90
91 static volatile unsigned cached_columns = 0;
92 static volatile unsigned cached_lines = 0;
93
94 size_t page_size(void) {
95         static thread_local size_t pgsz = 0;
96         long r;
97
98         if (_likely_(pgsz > 0))
99                 return pgsz;
100
101         r = sysconf(_SC_PAGESIZE);
102         assert(r > 0);
103
104         pgsz = (size_t) r;
105         return pgsz;
106 }
107
108 bool streq_ptr(const char *a, const char *b) {
109
110         /* Like streq(), but tries to make sense of NULL pointers */
111
112         if (a && b)
113                 return streq(a, b);
114
115         if (!a && !b)
116                 return true;
117
118         return false;
119 }
120
121 char* endswith(const char *s, const char *postfix) {
122         size_t sl, pl;
123
124         assert(s);
125         assert(postfix);
126
127         sl = strlen(s);
128         pl = strlen(postfix);
129
130         if (pl == 0)
131                 return (char*) s + sl;
132
133         if (sl < pl)
134                 return NULL;
135
136         if (memcmp(s + sl - pl, postfix, pl) != 0)
137                 return NULL;
138
139         return (char*) s + sl - pl;
140 }
141
142 bool first_word(const char *s, const char *word) {
143         size_t sl, wl;
144
145         assert(s);
146         assert(word);
147
148         sl = strlen(s);
149         wl = strlen(word);
150
151         if (sl < wl)
152                 return false;
153
154         if (wl == 0)
155                 return true;
156
157         if (memcmp(s, word, wl) != 0)
158                 return false;
159
160         return s[wl] == 0 ||
161                 strchr(WHITESPACE, s[wl]);
162 }
163
164 int close_nointr(int fd) {
165         int r;
166
167         assert(fd >= 0);
168         r = close(fd);
169
170         /* Just ignore EINTR; a retry loop is the wrong
171          * thing to do on Linux.
172          *
173          * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
174          * https://bugzilla.gnome.org/show_bug.cgi?id=682819
175          * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
176          * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
177          */
178         if (_unlikely_(r < 0 && errno == EINTR))
179                 return 0;
180         else if (r >= 0)
181                 return r;
182         else
183                 return -errno;
184 }
185
186 void close_nointr_nofail(int fd) {
187         PROTECT_ERRNO;
188
189         /* like close_nointr() but cannot fail, and guarantees errno
190          * is unchanged */
191
192         assert_se(close_nointr(fd) == 0);
193 }
194
195 void close_many(const int fds[], unsigned n_fd) {
196         unsigned i;
197
198         assert(fds || n_fd <= 0);
199
200         for (i = 0; i < n_fd; i++)
201                 close_nointr_nofail(fds[i]);
202 }
203
204 int unlink_noerrno(const char *path) {
205         PROTECT_ERRNO;
206         int r;
207
208         r = unlink(path);
209         if (r < 0)
210                 return -errno;
211
212         return 0;
213 }
214
215 int parse_boolean(const char *v) {
216         assert(v);
217
218         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
219                 return 1;
220         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
221                 return 0;
222
223         return -EINVAL;
224 }
225
226 int parse_pid(const char *s, pid_t* ret_pid) {
227         unsigned long ul = 0;
228         pid_t pid;
229         int r;
230
231         assert(s);
232         assert(ret_pid);
233
234         r = safe_atolu(s, &ul);
235         if (r < 0)
236                 return r;
237
238         pid = (pid_t) ul;
239
240         if ((unsigned long) pid != ul)
241                 return -ERANGE;
242
243         if (pid <= 0)
244                 return -ERANGE;
245
246         *ret_pid = pid;
247         return 0;
248 }
249
250 int parse_uid(const char *s, uid_t* ret_uid) {
251         unsigned long ul = 0;
252         uid_t uid;
253         int r;
254
255         assert(s);
256         assert(ret_uid);
257
258         r = safe_atolu(s, &ul);
259         if (r < 0)
260                 return r;
261
262         uid = (uid_t) ul;
263
264         if ((unsigned long) uid != ul)
265                 return -ERANGE;
266
267         *ret_uid = uid;
268         return 0;
269 }
270
271 int safe_atou(const char *s, unsigned *ret_u) {
272         char *x = NULL;
273         unsigned long l;
274
275         assert(s);
276         assert(ret_u);
277
278         errno = 0;
279         l = strtoul(s, &x, 0);
280
281         if (!x || x == s || *x || errno)
282                 return errno > 0 ? -errno : -EINVAL;
283
284         if ((unsigned long) (unsigned) l != l)
285                 return -ERANGE;
286
287         *ret_u = (unsigned) l;
288         return 0;
289 }
290
291 int safe_atoi(const char *s, int *ret_i) {
292         char *x = NULL;
293         long l;
294
295         assert(s);
296         assert(ret_i);
297
298         errno = 0;
299         l = strtol(s, &x, 0);
300
301         if (!x || x == s || *x || errno)
302                 return errno > 0 ? -errno : -EINVAL;
303
304         if ((long) (int) l != l)
305                 return -ERANGE;
306
307         *ret_i = (int) l;
308         return 0;
309 }
310
311 int safe_atollu(const char *s, long long unsigned *ret_llu) {
312         char *x = NULL;
313         unsigned long long l;
314
315         assert(s);
316         assert(ret_llu);
317
318         errno = 0;
319         l = strtoull(s, &x, 0);
320
321         if (!x || x == s || *x || errno)
322                 return errno ? -errno : -EINVAL;
323
324         *ret_llu = l;
325         return 0;
326 }
327
328 int safe_atolli(const char *s, long long int *ret_lli) {
329         char *x = NULL;
330         long long l;
331
332         assert(s);
333         assert(ret_lli);
334
335         errno = 0;
336         l = strtoll(s, &x, 0);
337
338         if (!x || x == s || *x || errno)
339                 return errno ? -errno : -EINVAL;
340
341         *ret_lli = l;
342         return 0;
343 }
344
345 int safe_atod(const char *s, double *ret_d) {
346         char *x = NULL;
347         double d = 0;
348
349         assert(s);
350         assert(ret_d);
351
352         RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
353                 errno = 0;
354                 d = strtod(s, &x);
355         }
356
357         if (!x || x == s || *x || errno)
358                 return errno ? -errno : -EINVAL;
359
360         *ret_d = (double) d;
361         return 0;
362 }
363
364 static size_t strcspn_escaped(const char *s, const char *reject) {
365         bool escaped = false;
366         size_t n;
367
368         for (n=0; s[n]; n++) {
369                 if (escaped)
370                         escaped = false;
371                 else if (s[n] == '\\')
372                         escaped = true;
373                 else if (strchr(reject, s[n]))
374                         return n;
375         }
376         return n;
377 }
378
379 /* Split a string into words. */
380 char *split(const char *c, size_t *l, const char *separator, bool quoted, char **state) {
381         char *current;
382
383         current = *state ? *state : (char*) c;
384
385         if (!*current || *c == 0)
386                 return NULL;
387
388         current += strspn(current, separator);
389         if (!*current)
390                 return NULL;
391
392         if (quoted && strchr("\'\"", *current)) {
393                 char quotechar = *(current++);
394                 *l = strcspn_escaped(current, (char[]){quotechar, '\0'});
395                 *state = current+*l+1;
396         } else if (quoted) {
397                 *l = strcspn_escaped(current, separator);
398                 *state = current+*l;
399         } else {
400                 *l = strcspn(current, separator);
401                 *state = current+*l;
402         }
403
404         return (char*) current;
405 }
406
407 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
408         int r;
409         _cleanup_free_ char *line = NULL;
410         long unsigned ppid;
411         const char *p;
412
413         assert(pid >= 0);
414         assert(_ppid);
415
416         if (pid == 0) {
417                 *_ppid = getppid();
418                 return 0;
419         }
420
421         p = procfs_file_alloca(pid, "stat");
422         r = read_one_line_file(p, &line);
423         if (r < 0)
424                 return r;
425
426         /* Let's skip the pid and comm fields. The latter is enclosed
427          * in () but does not escape any () in its value, so let's
428          * skip over it manually */
429
430         p = strrchr(line, ')');
431         if (!p)
432                 return -EIO;
433
434         p++;
435
436         if (sscanf(p, " "
437                    "%*c "  /* state */
438                    "%lu ", /* ppid */
439                    &ppid) != 1)
440                 return -EIO;
441
442         if ((long unsigned) (pid_t) ppid != ppid)
443                 return -ERANGE;
444
445         *_ppid = (pid_t) ppid;
446
447         return 0;
448 }
449
450 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
451         int r;
452         _cleanup_free_ char *line = NULL;
453         const char *p;
454
455         assert(pid >= 0);
456         assert(st);
457
458         p = procfs_file_alloca(pid, "stat");
459         r = read_one_line_file(p, &line);
460         if (r < 0)
461                 return r;
462
463         /* Let's skip the pid and comm fields. The latter is enclosed
464          * in () but does not escape any () in its value, so let's
465          * skip over it manually */
466
467         p = strrchr(line, ')');
468         if (!p)
469                 return -EIO;
470
471         p++;
472
473         if (sscanf(p, " "
474                    "%*c "  /* state */
475                    "%*d "  /* ppid */
476                    "%*d "  /* pgrp */
477                    "%*d "  /* session */
478                    "%*d "  /* tty_nr */
479                    "%*d "  /* tpgid */
480                    "%*u "  /* flags */
481                    "%*u "  /* minflt */
482                    "%*u "  /* cminflt */
483                    "%*u "  /* majflt */
484                    "%*u "  /* cmajflt */
485                    "%*u "  /* utime */
486                    "%*u "  /* stime */
487                    "%*d "  /* cutime */
488                    "%*d "  /* cstime */
489                    "%*d "  /* priority */
490                    "%*d "  /* nice */
491                    "%*d "  /* num_threads */
492                    "%*d "  /* itrealvalue */
493                    "%llu "  /* starttime */,
494                    st) != 1)
495                 return -EIO;
496
497         return 0;
498 }
499
500 int fchmod_umask(int fd, mode_t m) {
501         mode_t u;
502         int r;
503
504         u = umask(0777);
505         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
506         umask(u);
507
508         return r;
509 }
510
511 char *truncate_nl(char *s) {
512         assert(s);
513
514         s[strcspn(s, NEWLINE)] = 0;
515         return s;
516 }
517
518 int get_process_state(pid_t pid) {
519         const char *p;
520         char state;
521         int r;
522         _cleanup_free_ char *line = NULL;
523
524         assert(pid >= 0);
525
526         p = procfs_file_alloca(pid, "stat");
527         r = read_one_line_file(p, &line);
528         if (r < 0)
529                 return r;
530
531         p = strrchr(line, ')');
532         if (!p)
533                 return -EIO;
534
535         p++;
536
537         if (sscanf(p, " %c", &state) != 1)
538                 return -EIO;
539
540         return (unsigned char) state;
541 }
542
543 int get_process_comm(pid_t pid, char **name) {
544         const char *p;
545         int r;
546
547         assert(name);
548         assert(pid >= 0);
549
550         p = procfs_file_alloca(pid, "comm");
551
552         r = read_one_line_file(p, name);
553         if (r == -ENOENT)
554                 return -ESRCH;
555
556         return r;
557 }
558
559 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
560         _cleanup_fclose_ FILE *f = NULL;
561         char *r = NULL, *k;
562         const char *p;
563         int c;
564
565         assert(line);
566         assert(pid >= 0);
567
568         p = procfs_file_alloca(pid, "cmdline");
569
570         f = fopen(p, "re");
571         if (!f)
572                 return -errno;
573
574         if (max_length == 0) {
575                 size_t len = 0, allocated = 0;
576
577                 while ((c = getc(f)) != EOF) {
578
579                         if (!GREEDY_REALLOC(r, allocated, len+2)) {
580                                 free(r);
581                                 return -ENOMEM;
582                         }
583
584                         r[len++] = isprint(c) ? c : ' ';
585                 }
586
587                 if (len > 0)
588                         r[len-1] = 0;
589
590         } else {
591                 bool space = false;
592                 size_t left;
593
594                 r = new(char, max_length);
595                 if (!r)
596                         return -ENOMEM;
597
598                 k = r;
599                 left = max_length;
600                 while ((c = getc(f)) != EOF) {
601
602                         if (isprint(c)) {
603                                 if (space) {
604                                         if (left <= 4)
605                                                 break;
606
607                                         *(k++) = ' ';
608                                         left--;
609                                         space = false;
610                                 }
611
612                                 if (left <= 4)
613                                         break;
614
615                                 *(k++) = (char) c;
616                                 left--;
617                         }  else
618                                 space = true;
619                 }
620
621                 if (left <= 4) {
622                         size_t n = MIN(left-1, 3U);
623                         memcpy(k, "...", n);
624                         k[n] = 0;
625                 } else
626                         *k = 0;
627         }
628
629         /* Kernel threads have no argv[] */
630         if (r == NULL || r[0] == 0) {
631                 _cleanup_free_ char *t = NULL;
632                 int h;
633
634                 free(r);
635
636                 if (!comm_fallback)
637                         return -ENOENT;
638
639                 h = get_process_comm(pid, &t);
640                 if (h < 0)
641                         return h;
642
643                 r = strjoin("[", t, "]", NULL);
644                 if (!r)
645                         return -ENOMEM;
646         }
647
648         *line = r;
649         return 0;
650 }
651
652 int is_kernel_thread(pid_t pid) {
653         const char *p;
654         size_t count;
655         char c;
656         bool eof;
657         FILE *f;
658
659         if (pid == 0)
660                 return 0;
661
662         assert(pid > 0);
663
664         p = procfs_file_alloca(pid, "cmdline");
665         f = fopen(p, "re");
666         if (!f)
667                 return -errno;
668
669         count = fread(&c, 1, 1, f);
670         eof = feof(f);
671         fclose(f);
672
673         /* Kernel threads have an empty cmdline */
674
675         if (count <= 0)
676                 return eof ? 1 : -errno;
677
678         return 0;
679 }
680
681 int get_process_capeff(pid_t pid, char **capeff) {
682         const char *p;
683
684         assert(capeff);
685         assert(pid >= 0);
686
687         p = procfs_file_alloca(pid, "status");
688
689         return get_status_field(p, "\nCapEff:", capeff);
690 }
691
692 int get_process_exe(pid_t pid, char **name) {
693         const char *p;
694         char *d;
695         int r;
696
697         assert(pid >= 0);
698         assert(name);
699
700         p = procfs_file_alloca(pid, "exe");
701
702         r = readlink_malloc(p, name);
703         if (r < 0)
704                 return r == -ENOENT ? -ESRCH : r;
705
706         d = endswith(*name, " (deleted)");
707         if (d)
708                 *d = '\0';
709
710         return 0;
711 }
712
713 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
714         _cleanup_fclose_ FILE *f = NULL;
715         char line[LINE_MAX];
716         const char *p;
717
718         assert(field);
719         assert(uid);
720
721         if (pid == 0)
722                 return getuid();
723
724         p = procfs_file_alloca(pid, "status");
725         f = fopen(p, "re");
726         if (!f)
727                 return -errno;
728
729         FOREACH_LINE(line, f, return -errno) {
730                 char *l;
731
732                 l = strstrip(line);
733
734                 if (startswith(l, field)) {
735                         l += strlen(field);
736                         l += strspn(l, WHITESPACE);
737
738                         l[strcspn(l, WHITESPACE)] = 0;
739
740                         return parse_uid(l, uid);
741                 }
742         }
743
744         return -EIO;
745 }
746
747 int get_process_uid(pid_t pid, uid_t *uid) {
748         return get_process_id(pid, "Uid:", uid);
749 }
750
751 int get_process_gid(pid_t pid, gid_t *gid) {
752         assert_cc(sizeof(uid_t) == sizeof(gid_t));
753         return get_process_id(pid, "Gid:", gid);
754 }
755
756 char *strnappend(const char *s, const char *suffix, size_t b) {
757         size_t a;
758         char *r;
759
760         if (!s && !suffix)
761                 return strdup("");
762
763         if (!s)
764                 return strndup(suffix, b);
765
766         if (!suffix)
767                 return strdup(s);
768
769         assert(s);
770         assert(suffix);
771
772         a = strlen(s);
773         if (b > ((size_t) -1) - a)
774                 return NULL;
775
776         r = new(char, a+b+1);
777         if (!r)
778                 return NULL;
779
780         memcpy(r, s, a);
781         memcpy(r+a, suffix, b);
782         r[a+b] = 0;
783
784         return r;
785 }
786
787 char *strappend(const char *s, const char *suffix) {
788         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
789 }
790
791 int readlink_malloc(const char *p, char **ret) {
792         size_t l = 100;
793         int r;
794
795         assert(p);
796         assert(ret);
797
798         for (;;) {
799                 char *c;
800                 ssize_t n;
801
802                 c = new(char, l);
803                 if (!c)
804                         return -ENOMEM;
805
806                 n = readlink(p, c, l-1);
807                 if (n < 0) {
808                         r = -errno;
809                         free(c);
810                         return r;
811                 }
812
813                 if ((size_t) n < l-1) {
814                         c[n] = 0;
815                         *ret = c;
816                         return 0;
817                 }
818
819                 free(c);
820                 l *= 2;
821         }
822 }
823
824 int readlink_and_make_absolute(const char *p, char **r) {
825         _cleanup_free_ char *target = NULL;
826         char *k;
827         int j;
828
829         assert(p);
830         assert(r);
831
832         j = readlink_malloc(p, &target);
833         if (j < 0)
834                 return j;
835
836         k = file_in_same_dir(p, target);
837         if (!k)
838                 return -ENOMEM;
839
840         *r = k;
841         return 0;
842 }
843
844 int readlink_and_canonicalize(const char *p, char **r) {
845         char *t, *s;
846         int j;
847
848         assert(p);
849         assert(r);
850
851         j = readlink_and_make_absolute(p, &t);
852         if (j < 0)
853                 return j;
854
855         s = canonicalize_file_name(t);
856         if (s) {
857                 free(t);
858                 *r = s;
859         } else
860                 *r = t;
861
862         path_kill_slashes(*r);
863
864         return 0;
865 }
866
867 int reset_all_signal_handlers(void) {
868         int sig;
869
870         for (sig = 1; sig < _NSIG; sig++) {
871                 struct sigaction sa = {
872                         .sa_handler = SIG_DFL,
873                         .sa_flags = SA_RESTART,
874                 };
875
876                 if (sig == SIGKILL || sig == SIGSTOP)
877                         continue;
878
879                 /* On Linux the first two RT signals are reserved by
880                  * glibc, and sigaction() will return EINVAL for them. */
881                 if ((sigaction(sig, &sa, NULL) < 0))
882                         if (errno != EINVAL)
883                                 return -errno;
884         }
885
886         return 0;
887 }
888
889 char *strstrip(char *s) {
890         char *e;
891
892         /* Drops trailing whitespace. Modifies the string in
893          * place. Returns pointer to first non-space character */
894
895         s += strspn(s, WHITESPACE);
896
897         for (e = strchr(s, 0); e > s; e --)
898                 if (!strchr(WHITESPACE, e[-1]))
899                         break;
900
901         *e = 0;
902
903         return s;
904 }
905
906 char *delete_chars(char *s, const char *bad) {
907         char *f, *t;
908
909         /* Drops all whitespace, regardless where in the string */
910
911         for (f = s, t = s; *f; f++) {
912                 if (strchr(bad, *f))
913                         continue;
914
915                 *(t++) = *f;
916         }
917
918         *t = 0;
919
920         return s;
921 }
922
923 bool in_charset(const char *s, const char* charset) {
924         const char *i;
925
926         assert(s);
927         assert(charset);
928
929         for (i = s; *i; i++)
930                 if (!strchr(charset, *i))
931                         return false;
932
933         return true;
934 }
935
936 char *file_in_same_dir(const char *path, const char *filename) {
937         char *e, *r;
938         size_t k;
939
940         assert(path);
941         assert(filename);
942
943         /* This removes the last component of path and appends
944          * filename, unless the latter is absolute anyway or the
945          * former isn't */
946
947         if (path_is_absolute(filename))
948                 return strdup(filename);
949
950         if (!(e = strrchr(path, '/')))
951                 return strdup(filename);
952
953         k = strlen(filename);
954         if (!(r = new(char, e-path+1+k+1)))
955                 return NULL;
956
957         memcpy(r, path, e-path+1);
958         memcpy(r+(e-path)+1, filename, k+1);
959
960         return r;
961 }
962
963 int rmdir_parents(const char *path, const char *stop) {
964         size_t l;
965         int r = 0;
966
967         assert(path);
968         assert(stop);
969
970         l = strlen(path);
971
972         /* Skip trailing slashes */
973         while (l > 0 && path[l-1] == '/')
974                 l--;
975
976         while (l > 0) {
977                 char *t;
978
979                 /* Skip last component */
980                 while (l > 0 && path[l-1] != '/')
981                         l--;
982
983                 /* Skip trailing slashes */
984                 while (l > 0 && path[l-1] == '/')
985                         l--;
986
987                 if (l <= 0)
988                         break;
989
990                 if (!(t = strndup(path, l)))
991                         return -ENOMEM;
992
993                 if (path_startswith(stop, t)) {
994                         free(t);
995                         return 0;
996                 }
997
998                 r = rmdir(t);
999                 free(t);
1000
1001                 if (r < 0)
1002                         if (errno != ENOENT)
1003                                 return -errno;
1004         }
1005
1006         return 0;
1007 }
1008
1009 char hexchar(int x) {
1010         static const char table[16] = "0123456789abcdef";
1011
1012         return table[x & 15];
1013 }
1014
1015 int unhexchar(char c) {
1016
1017         if (c >= '0' && c <= '9')
1018                 return c - '0';
1019
1020         if (c >= 'a' && c <= 'f')
1021                 return c - 'a' + 10;
1022
1023         if (c >= 'A' && c <= 'F')
1024                 return c - 'A' + 10;
1025
1026         return -1;
1027 }
1028
1029 char *hexmem(const void *p, size_t l) {
1030         char *r, *z;
1031         const uint8_t *x;
1032
1033         z = r = malloc(l * 2 + 1);
1034         if (!r)
1035                 return NULL;
1036
1037         for (x = p; x < (const uint8_t*) p + l; x++) {
1038                 *(z++) = hexchar(*x >> 4);
1039                 *(z++) = hexchar(*x & 15);
1040         }
1041
1042         *z = 0;
1043         return r;
1044 }
1045
1046 void *unhexmem(const char *p, size_t l) {
1047         uint8_t *r, *z;
1048         const char *x;
1049
1050         assert(p);
1051
1052         z = r = malloc((l + 1) / 2 + 1);
1053         if (!r)
1054                 return NULL;
1055
1056         for (x = p; x < p + l; x += 2) {
1057                 int a, b;
1058
1059                 a = unhexchar(x[0]);
1060                 if (x+1 < p + l)
1061                         b = unhexchar(x[1]);
1062                 else
1063                         b = 0;
1064
1065                 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1066         }
1067
1068         *z = 0;
1069         return r;
1070 }
1071
1072 char octchar(int x) {
1073         return '0' + (x & 7);
1074 }
1075
1076 int unoctchar(char c) {
1077
1078         if (c >= '0' && c <= '7')
1079                 return c - '0';
1080
1081         return -1;
1082 }
1083
1084 char decchar(int x) {
1085         return '0' + (x % 10);
1086 }
1087
1088 int undecchar(char c) {
1089
1090         if (c >= '0' && c <= '9')
1091                 return c - '0';
1092
1093         return -1;
1094 }
1095
1096 char *cescape(const char *s) {
1097         char *r, *t;
1098         const char *f;
1099
1100         assert(s);
1101
1102         /* Does C style string escaping. */
1103
1104         r = new(char, strlen(s)*4 + 1);
1105         if (!r)
1106                 return NULL;
1107
1108         for (f = s, t = r; *f; f++)
1109
1110                 switch (*f) {
1111
1112                 case '\a':
1113                         *(t++) = '\\';
1114                         *(t++) = 'a';
1115                         break;
1116                 case '\b':
1117                         *(t++) = '\\';
1118                         *(t++) = 'b';
1119                         break;
1120                 case '\f':
1121                         *(t++) = '\\';
1122                         *(t++) = 'f';
1123                         break;
1124                 case '\n':
1125                         *(t++) = '\\';
1126                         *(t++) = 'n';
1127                         break;
1128                 case '\r':
1129                         *(t++) = '\\';
1130                         *(t++) = 'r';
1131                         break;
1132                 case '\t':
1133                         *(t++) = '\\';
1134                         *(t++) = 't';
1135                         break;
1136                 case '\v':
1137                         *(t++) = '\\';
1138                         *(t++) = 'v';
1139                         break;
1140                 case '\\':
1141                         *(t++) = '\\';
1142                         *(t++) = '\\';
1143                         break;
1144                 case '"':
1145                         *(t++) = '\\';
1146                         *(t++) = '"';
1147                         break;
1148                 case '\'':
1149                         *(t++) = '\\';
1150                         *(t++) = '\'';
1151                         break;
1152
1153                 default:
1154                         /* For special chars we prefer octal over
1155                          * hexadecimal encoding, simply because glib's
1156                          * g_strescape() does the same */
1157                         if ((*f < ' ') || (*f >= 127)) {
1158                                 *(t++) = '\\';
1159                                 *(t++) = octchar((unsigned char) *f >> 6);
1160                                 *(t++) = octchar((unsigned char) *f >> 3);
1161                                 *(t++) = octchar((unsigned char) *f);
1162                         } else
1163                                 *(t++) = *f;
1164                         break;
1165                 }
1166
1167         *t = 0;
1168
1169         return r;
1170 }
1171
1172 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1173         char *r, *t;
1174         const char *f;
1175         size_t pl;
1176
1177         assert(s);
1178
1179         /* Undoes C style string escaping, and optionally prefixes it. */
1180
1181         pl = prefix ? strlen(prefix) : 0;
1182
1183         r = new(char, pl+length+1);
1184         if (!r)
1185                 return r;
1186
1187         if (prefix)
1188                 memcpy(r, prefix, pl);
1189
1190         for (f = s, t = r + pl; f < s + length; f++) {
1191
1192                 if (*f != '\\') {
1193                         *(t++) = *f;
1194                         continue;
1195                 }
1196
1197                 f++;
1198
1199                 switch (*f) {
1200
1201                 case 'a':
1202                         *(t++) = '\a';
1203                         break;
1204                 case 'b':
1205                         *(t++) = '\b';
1206                         break;
1207                 case 'f':
1208                         *(t++) = '\f';
1209                         break;
1210                 case 'n':
1211                         *(t++) = '\n';
1212                         break;
1213                 case 'r':
1214                         *(t++) = '\r';
1215                         break;
1216                 case 't':
1217                         *(t++) = '\t';
1218                         break;
1219                 case 'v':
1220                         *(t++) = '\v';
1221                         break;
1222                 case '\\':
1223                         *(t++) = '\\';
1224                         break;
1225                 case '"':
1226                         *(t++) = '"';
1227                         break;
1228                 case '\'':
1229                         *(t++) = '\'';
1230                         break;
1231
1232                 case 's':
1233                         /* This is an extension of the XDG syntax files */
1234                         *(t++) = ' ';
1235                         break;
1236
1237                 case 'x': {
1238                         /* hexadecimal encoding */
1239                         int a, b;
1240
1241                         a = unhexchar(f[1]);
1242                         b = unhexchar(f[2]);
1243
1244                         if (a < 0 || b < 0) {
1245                                 /* Invalid escape code, let's take it literal then */
1246                                 *(t++) = '\\';
1247                                 *(t++) = 'x';
1248                         } else {
1249                                 *(t++) = (char) ((a << 4) | b);
1250                                 f += 2;
1251                         }
1252
1253                         break;
1254                 }
1255
1256                 case '0':
1257                 case '1':
1258                 case '2':
1259                 case '3':
1260                 case '4':
1261                 case '5':
1262                 case '6':
1263                 case '7': {
1264                         /* octal encoding */
1265                         int a, b, c;
1266
1267                         a = unoctchar(f[0]);
1268                         b = unoctchar(f[1]);
1269                         c = unoctchar(f[2]);
1270
1271                         if (a < 0 || b < 0 || c < 0) {
1272                                 /* Invalid escape code, let's take it literal then */
1273                                 *(t++) = '\\';
1274                                 *(t++) = f[0];
1275                         } else {
1276                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1277                                 f += 2;
1278                         }
1279
1280                         break;
1281                 }
1282
1283                 case 0:
1284                         /* premature end of string.*/
1285                         *(t++) = '\\';
1286                         goto finish;
1287
1288                 default:
1289                         /* Invalid escape code, let's take it literal then */
1290                         *(t++) = '\\';
1291                         *(t++) = *f;
1292                         break;
1293                 }
1294         }
1295
1296 finish:
1297         *t = 0;
1298         return r;
1299 }
1300
1301 char *cunescape_length(const char *s, size_t length) {
1302         return cunescape_length_with_prefix(s, length, NULL);
1303 }
1304
1305 char *cunescape(const char *s) {
1306         assert(s);
1307
1308         return cunescape_length(s, strlen(s));
1309 }
1310
1311 char *xescape(const char *s, const char *bad) {
1312         char *r, *t;
1313         const char *f;
1314
1315         /* Escapes all chars in bad, in addition to \ and all special
1316          * chars, in \xFF style escaping. May be reversed with
1317          * cunescape. */
1318
1319         r = new(char, strlen(s) * 4 + 1);
1320         if (!r)
1321                 return NULL;
1322
1323         for (f = s, t = r; *f; f++) {
1324
1325                 if ((*f < ' ') || (*f >= 127) ||
1326                     (*f == '\\') || strchr(bad, *f)) {
1327                         *(t++) = '\\';
1328                         *(t++) = 'x';
1329                         *(t++) = hexchar(*f >> 4);
1330                         *(t++) = hexchar(*f);
1331                 } else
1332                         *(t++) = *f;
1333         }
1334
1335         *t = 0;
1336
1337         return r;
1338 }
1339
1340 char *ascii_strlower(char *t) {
1341         char *p;
1342
1343         assert(t);
1344
1345         for (p = t; *p; p++)
1346                 if (*p >= 'A' && *p <= 'Z')
1347                         *p = *p - 'A' + 'a';
1348
1349         return t;
1350 }
1351
1352 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1353         assert(filename);
1354
1355         return
1356                 filename[0] == '.' ||
1357                 streq(filename, "lost+found") ||
1358                 streq(filename, "aquota.user") ||
1359                 streq(filename, "aquota.group") ||
1360                 endswith(filename, ".rpmnew") ||
1361                 endswith(filename, ".rpmsave") ||
1362                 endswith(filename, ".rpmorig") ||
1363                 endswith(filename, ".dpkg-old") ||
1364                 endswith(filename, ".dpkg-new") ||
1365                 endswith(filename, ".swp");
1366 }
1367
1368 bool ignore_file(const char *filename) {
1369         assert(filename);
1370
1371         if (endswith(filename, "~"))
1372                 return false;
1373
1374         return ignore_file_allow_backup(filename);
1375 }
1376
1377 int fd_nonblock(int fd, bool nonblock) {
1378         int flags;
1379
1380         assert(fd >= 0);
1381
1382         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1383                 return -errno;
1384
1385         if (nonblock)
1386                 flags |= O_NONBLOCK;
1387         else
1388                 flags &= ~O_NONBLOCK;
1389
1390         if (fcntl(fd, F_SETFL, flags) < 0)
1391                 return -errno;
1392
1393         return 0;
1394 }
1395
1396 int fd_cloexec(int fd, bool cloexec) {
1397         int flags;
1398
1399         assert(fd >= 0);
1400
1401         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1402                 return -errno;
1403
1404         if (cloexec)
1405                 flags |= FD_CLOEXEC;
1406         else
1407                 flags &= ~FD_CLOEXEC;
1408
1409         if (fcntl(fd, F_SETFD, flags) < 0)
1410                 return -errno;
1411
1412         return 0;
1413 }
1414
1415 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1416         unsigned i;
1417
1418         assert(n_fdset == 0 || fdset);
1419
1420         for (i = 0; i < n_fdset; i++)
1421                 if (fdset[i] == fd)
1422                         return true;
1423
1424         return false;
1425 }
1426
1427 int close_all_fds(const int except[], unsigned n_except) {
1428         DIR *d;
1429         struct dirent *de;
1430         int r = 0;
1431
1432         assert(n_except == 0 || except);
1433
1434         d = opendir("/proc/self/fd");
1435         if (!d) {
1436                 int fd;
1437                 struct rlimit rl;
1438
1439                 /* When /proc isn't available (for example in chroots)
1440                  * the fallback is brute forcing through the fd
1441                  * table */
1442
1443                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1444                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1445
1446                         if (fd_in_set(fd, except, n_except))
1447                                 continue;
1448
1449                         if (close_nointr(fd) < 0)
1450                                 if (errno != EBADF && r == 0)
1451                                         r = -errno;
1452                 }
1453
1454                 return r;
1455         }
1456
1457         while ((de = readdir(d))) {
1458                 int fd = -1;
1459
1460                 if (ignore_file(de->d_name))
1461                         continue;
1462
1463                 if (safe_atoi(de->d_name, &fd) < 0)
1464                         /* Let's better ignore this, just in case */
1465                         continue;
1466
1467                 if (fd < 3)
1468                         continue;
1469
1470                 if (fd == dirfd(d))
1471                         continue;
1472
1473                 if (fd_in_set(fd, except, n_except))
1474                         continue;
1475
1476                 if (close_nointr(fd) < 0) {
1477                         /* Valgrind has its own FD and doesn't want to have it closed */
1478                         if (errno != EBADF && r == 0)
1479                                 r = -errno;
1480                 }
1481         }
1482
1483         closedir(d);
1484         return r;
1485 }
1486
1487 bool chars_intersect(const char *a, const char *b) {
1488         const char *p;
1489
1490         /* Returns true if any of the chars in a are in b. */
1491         for (p = a; *p; p++)
1492                 if (strchr(b, *p))
1493                         return true;
1494
1495         return false;
1496 }
1497
1498 bool fstype_is_network(const char *fstype) {
1499         static const char table[] =
1500                 "cifs\0"
1501                 "smbfs\0"
1502                 "ncpfs\0"
1503                 "ncp\0"
1504                 "nfs\0"
1505                 "nfs4\0"
1506                 "gfs\0"
1507                 "gfs2\0";
1508
1509         return nulstr_contains(table, fstype);
1510 }
1511
1512 int chvt(int vt) {
1513         _cleanup_close_ int fd;
1514
1515         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1516         if (fd < 0)
1517                 return -errno;
1518
1519         if (vt < 0) {
1520                 int tiocl[2] = {
1521                         TIOCL_GETKMSGREDIRECT,
1522                         0
1523                 };
1524
1525                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1526                         return -errno;
1527
1528                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1529         }
1530
1531         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1532                 return -errno;
1533
1534         return 0;
1535 }
1536
1537 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1538         struct termios old_termios, new_termios;
1539         char c;
1540         char line[LINE_MAX];
1541
1542         assert(f);
1543         assert(ret);
1544
1545         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1546                 new_termios = old_termios;
1547
1548                 new_termios.c_lflag &= ~ICANON;
1549                 new_termios.c_cc[VMIN] = 1;
1550                 new_termios.c_cc[VTIME] = 0;
1551
1552                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1553                         size_t k;
1554
1555                         if (t != (usec_t) -1) {
1556                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1557                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1558                                         return -ETIMEDOUT;
1559                                 }
1560                         }
1561
1562                         k = fread(&c, 1, 1, f);
1563
1564                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1565
1566                         if (k <= 0)
1567                                 return -EIO;
1568
1569                         if (need_nl)
1570                                 *need_nl = c != '\n';
1571
1572                         *ret = c;
1573                         return 0;
1574                 }
1575         }
1576
1577         if (t != (usec_t) -1)
1578                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1579                         return -ETIMEDOUT;
1580
1581         if (!fgets(line, sizeof(line), f))
1582                 return -EIO;
1583
1584         truncate_nl(line);
1585
1586         if (strlen(line) != 1)
1587                 return -EBADMSG;
1588
1589         if (need_nl)
1590                 *need_nl = false;
1591
1592         *ret = line[0];
1593         return 0;
1594 }
1595
1596 int ask(char *ret, const char *replies, const char *text, ...) {
1597
1598         assert(ret);
1599         assert(replies);
1600         assert(text);
1601
1602         for (;;) {
1603                 va_list ap;
1604                 char c;
1605                 int r;
1606                 bool need_nl = true;
1607
1608                 if (on_tty())
1609                         fputs(ANSI_HIGHLIGHT_ON, stdout);
1610
1611                 va_start(ap, text);
1612                 vprintf(text, ap);
1613                 va_end(ap);
1614
1615                 if (on_tty())
1616                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
1617
1618                 fflush(stdout);
1619
1620                 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1621                 if (r < 0) {
1622
1623                         if (r == -EBADMSG) {
1624                                 puts("Bad input, please try again.");
1625                                 continue;
1626                         }
1627
1628                         putchar('\n');
1629                         return r;
1630                 }
1631
1632                 if (need_nl)
1633                         putchar('\n');
1634
1635                 if (strchr(replies, c)) {
1636                         *ret = c;
1637                         return 0;
1638                 }
1639
1640                 puts("Read unexpected character, please try again.");
1641         }
1642 }
1643
1644 int reset_terminal_fd(int fd, bool switch_to_text) {
1645         struct termios termios;
1646         int r = 0;
1647
1648         /* Set terminal to some sane defaults */
1649
1650         assert(fd >= 0);
1651
1652         /* We leave locked terminal attributes untouched, so that
1653          * Plymouth may set whatever it wants to set, and we don't
1654          * interfere with that. */
1655
1656         /* Disable exclusive mode, just in case */
1657         ioctl(fd, TIOCNXCL);
1658
1659         /* Switch to text mode */
1660         if (switch_to_text)
1661                 ioctl(fd, KDSETMODE, KD_TEXT);
1662
1663         /* Enable console unicode mode */
1664         ioctl(fd, KDSKBMODE, K_UNICODE);
1665
1666         if (tcgetattr(fd, &termios) < 0) {
1667                 r = -errno;
1668                 goto finish;
1669         }
1670
1671         /* We only reset the stuff that matters to the software. How
1672          * hardware is set up we don't touch assuming that somebody
1673          * else will do that for us */
1674
1675         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1676         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1677         termios.c_oflag |= ONLCR;
1678         termios.c_cflag |= CREAD;
1679         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1680
1681         termios.c_cc[VINTR]    =   03;  /* ^C */
1682         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1683         termios.c_cc[VERASE]   = 0177;
1684         termios.c_cc[VKILL]    =  025;  /* ^X */
1685         termios.c_cc[VEOF]     =   04;  /* ^D */
1686         termios.c_cc[VSTART]   =  021;  /* ^Q */
1687         termios.c_cc[VSTOP]    =  023;  /* ^S */
1688         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1689         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1690         termios.c_cc[VWERASE]  =  027;  /* ^W */
1691         termios.c_cc[VREPRINT] =  022;  /* ^R */
1692         termios.c_cc[VEOL]     =    0;
1693         termios.c_cc[VEOL2]    =    0;
1694
1695         termios.c_cc[VTIME]  = 0;
1696         termios.c_cc[VMIN]   = 1;
1697
1698         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1699                 r = -errno;
1700
1701 finish:
1702         /* Just in case, flush all crap out */
1703         tcflush(fd, TCIOFLUSH);
1704
1705         return r;
1706 }
1707
1708 int reset_terminal(const char *name) {
1709         int fd, r;
1710
1711         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1712         if (fd < 0)
1713                 return fd;
1714
1715         r = reset_terminal_fd(fd, true);
1716         close_nointr_nofail(fd);
1717
1718         return r;
1719 }
1720
1721 int open_terminal(const char *name, int mode) {
1722         int fd, r;
1723         unsigned c = 0;
1724
1725         /*
1726          * If a TTY is in the process of being closed opening it might
1727          * cause EIO. This is horribly awful, but unlikely to be
1728          * changed in the kernel. Hence we work around this problem by
1729          * retrying a couple of times.
1730          *
1731          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1732          */
1733
1734         assert(!(mode & O_CREAT));
1735
1736         for (;;) {
1737                 fd = open(name, mode, 0);
1738                 if (fd >= 0)
1739                         break;
1740
1741                 if (errno != EIO)
1742                         return -errno;
1743
1744                 /* Max 1s in total */
1745                 if (c >= 20)
1746                         return -errno;
1747
1748                 usleep(50 * USEC_PER_MSEC);
1749                 c++;
1750         }
1751
1752         if (fd < 0)
1753                 return -errno;
1754
1755         r = isatty(fd);
1756         if (r < 0) {
1757                 close_nointr_nofail(fd);
1758                 return -errno;
1759         }
1760
1761         if (!r) {
1762                 close_nointr_nofail(fd);
1763                 return -ENOTTY;
1764         }
1765
1766         return fd;
1767 }
1768
1769 int flush_fd(int fd) {
1770         struct pollfd pollfd = {
1771                 .fd = fd,
1772                 .events = POLLIN,
1773         };
1774
1775         for (;;) {
1776                 char buf[LINE_MAX];
1777                 ssize_t l;
1778                 int r;
1779
1780                 r = poll(&pollfd, 1, 0);
1781                 if (r < 0) {
1782                         if (errno == EINTR)
1783                                 continue;
1784
1785                         return -errno;
1786
1787                 } else if (r == 0)
1788                         return 0;
1789
1790                 l = read(fd, buf, sizeof(buf));
1791                 if (l < 0) {
1792
1793                         if (errno == EINTR)
1794                                 continue;
1795
1796                         if (errno == EAGAIN)
1797                                 return 0;
1798
1799                         return -errno;
1800                 } else if (l == 0)
1801                         return 0;
1802         }
1803 }
1804
1805 int acquire_terminal(
1806                 const char *name,
1807                 bool fail,
1808                 bool force,
1809                 bool ignore_tiocstty_eperm,
1810                 usec_t timeout) {
1811
1812         int fd = -1, notify = -1, r = 0, wd = -1;
1813         usec_t ts = 0;
1814
1815         assert(name);
1816
1817         /* We use inotify to be notified when the tty is closed. We
1818          * create the watch before checking if we can actually acquire
1819          * it, so that we don't lose any event.
1820          *
1821          * Note: strictly speaking this actually watches for the
1822          * device being closed, it does *not* really watch whether a
1823          * tty loses its controlling process. However, unless some
1824          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1825          * its tty otherwise this will not become a problem. As long
1826          * as the administrator makes sure not configure any service
1827          * on the same tty as an untrusted user this should not be a
1828          * problem. (Which he probably should not do anyway.) */
1829
1830         if (timeout != (usec_t) -1)
1831                 ts = now(CLOCK_MONOTONIC);
1832
1833         if (!fail && !force) {
1834                 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1835                 if (notify < 0) {
1836                         r = -errno;
1837                         goto fail;
1838                 }
1839
1840                 wd = inotify_add_watch(notify, name, IN_CLOSE);
1841                 if (wd < 0) {
1842                         r = -errno;
1843                         goto fail;
1844                 }
1845         }
1846
1847         for (;;) {
1848                 struct sigaction sa_old, sa_new = {
1849                         .sa_handler = SIG_IGN,
1850                         .sa_flags = SA_RESTART,
1851                 };
1852
1853                 if (notify >= 0) {
1854                         r = flush_fd(notify);
1855                         if (r < 0)
1856                                 goto fail;
1857                 }
1858
1859                 /* We pass here O_NOCTTY only so that we can check the return
1860                  * value TIOCSCTTY and have a reliable way to figure out if we
1861                  * successfully became the controlling process of the tty */
1862                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1863                 if (fd < 0)
1864                         return fd;
1865
1866                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1867                  * if we already own the tty. */
1868                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1869
1870                 /* First, try to get the tty */
1871                 if (ioctl(fd, TIOCSCTTY, force) < 0)
1872                         r = -errno;
1873
1874                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1875
1876                 /* Sometimes it makes sense to ignore TIOCSCTTY
1877                  * returning EPERM, i.e. when very likely we already
1878                  * are have this controlling terminal. */
1879                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1880                         r = 0;
1881
1882                 if (r < 0 && (force || fail || r != -EPERM)) {
1883                         goto fail;
1884                 }
1885
1886                 if (r >= 0)
1887                         break;
1888
1889                 assert(!fail);
1890                 assert(!force);
1891                 assert(notify >= 0);
1892
1893                 for (;;) {
1894                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1895                         ssize_t l;
1896                         struct inotify_event *e;
1897
1898                         if (timeout != (usec_t) -1) {
1899                                 usec_t n;
1900
1901                                 n = now(CLOCK_MONOTONIC);
1902                                 if (ts + timeout < n) {
1903                                         r = -ETIMEDOUT;
1904                                         goto fail;
1905                                 }
1906
1907                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1908                                 if (r < 0)
1909                                         goto fail;
1910
1911                                 if (r == 0) {
1912                                         r = -ETIMEDOUT;
1913                                         goto fail;
1914                                 }
1915                         }
1916
1917                         l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1918                         if (l < 0) {
1919
1920                                 if (errno == EINTR || errno == EAGAIN)
1921                                         continue;
1922
1923                                 r = -errno;
1924                                 goto fail;
1925                         }
1926
1927                         e = (struct inotify_event*) inotify_buffer;
1928
1929                         while (l > 0) {
1930                                 size_t step;
1931
1932                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1933                                         r = -EIO;
1934                                         goto fail;
1935                                 }
1936
1937                                 step = sizeof(struct inotify_event) + e->len;
1938                                 assert(step <= (size_t) l);
1939
1940                                 e = (struct inotify_event*) ((uint8_t*) e + step);
1941                                 l -= step;
1942                         }
1943
1944                         break;
1945                 }
1946
1947                 /* We close the tty fd here since if the old session
1948                  * ended our handle will be dead. It's important that
1949                  * we do this after sleeping, so that we don't enter
1950                  * an endless loop. */
1951                 close_nointr_nofail(fd);
1952         }
1953
1954         if (notify >= 0)
1955                 close_nointr_nofail(notify);
1956
1957         r = reset_terminal_fd(fd, true);
1958         if (r < 0)
1959                 log_warning("Failed to reset terminal: %s", strerror(-r));
1960
1961         return fd;
1962
1963 fail:
1964         if (fd >= 0)
1965                 close_nointr_nofail(fd);
1966
1967         if (notify >= 0)
1968                 close_nointr_nofail(notify);
1969
1970         return r;
1971 }
1972
1973 int release_terminal(void) {
1974         int r = 0;
1975         struct sigaction sa_old, sa_new = {
1976                 .sa_handler = SIG_IGN,
1977                 .sa_flags = SA_RESTART,
1978         };
1979         _cleanup_close_ int fd;
1980
1981         fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
1982         if (fd < 0)
1983                 return -errno;
1984
1985         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1986          * by our own TIOCNOTTY */
1987         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1988
1989         if (ioctl(fd, TIOCNOTTY) < 0)
1990                 r = -errno;
1991
1992         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1993
1994         return r;
1995 }
1996
1997 int sigaction_many(const struct sigaction *sa, ...) {
1998         va_list ap;
1999         int r = 0, sig;
2000
2001         va_start(ap, sa);
2002         while ((sig = va_arg(ap, int)) > 0)
2003                 if (sigaction(sig, sa, NULL) < 0)
2004                         r = -errno;
2005         va_end(ap);
2006
2007         return r;
2008 }
2009
2010 int ignore_signals(int sig, ...) {
2011         struct sigaction sa = {
2012                 .sa_handler = SIG_IGN,
2013                 .sa_flags = SA_RESTART,
2014         };
2015         va_list ap;
2016         int r = 0;
2017
2018
2019         if (sigaction(sig, &sa, NULL) < 0)
2020                 r = -errno;
2021
2022         va_start(ap, sig);
2023         while ((sig = va_arg(ap, int)) > 0)
2024                 if (sigaction(sig, &sa, NULL) < 0)
2025                         r = -errno;
2026         va_end(ap);
2027
2028         return r;
2029 }
2030
2031 int default_signals(int sig, ...) {
2032         struct sigaction sa = {
2033                 .sa_handler = SIG_DFL,
2034                 .sa_flags = SA_RESTART,
2035         };
2036         va_list ap;
2037         int r = 0;
2038
2039         if (sigaction(sig, &sa, NULL) < 0)
2040                 r = -errno;
2041
2042         va_start(ap, sig);
2043         while ((sig = va_arg(ap, int)) > 0)
2044                 if (sigaction(sig, &sa, NULL) < 0)
2045                         r = -errno;
2046         va_end(ap);
2047
2048         return r;
2049 }
2050
2051 int close_pipe(int p[]) {
2052         int a = 0, b = 0;
2053
2054         assert(p);
2055
2056         if (p[0] >= 0) {
2057                 a = close_nointr(p[0]);
2058                 p[0] = -1;
2059         }
2060
2061         if (p[1] >= 0) {
2062                 b = close_nointr(p[1]);
2063                 p[1] = -1;
2064         }
2065
2066         return a < 0 ? a : b;
2067 }
2068
2069 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2070         uint8_t *p = buf;
2071         ssize_t n = 0;
2072
2073         assert(fd >= 0);
2074         assert(buf);
2075
2076         while (nbytes > 0) {
2077                 ssize_t k;
2078
2079                 k = read(fd, p, nbytes);
2080                 if (k < 0 && errno == EINTR)
2081                         continue;
2082
2083                 if (k < 0 && errno == EAGAIN && do_poll) {
2084
2085                         /* We knowingly ignore any return value here,
2086                          * and expect that any error/EOF is reported
2087                          * via read() */
2088
2089                         fd_wait_for_event(fd, POLLIN, (usec_t) -1);
2090                         continue;
2091                 }
2092
2093                 if (k <= 0)
2094                         return n > 0 ? n : (k < 0 ? -errno : 0);
2095
2096                 p += k;
2097                 nbytes -= k;
2098                 n += k;
2099         }
2100
2101         return n;
2102 }
2103
2104 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2105         const uint8_t *p = buf;
2106         ssize_t n = 0;
2107
2108         assert(fd >= 0);
2109         assert(buf);
2110
2111         while (nbytes > 0) {
2112                 ssize_t k;
2113
2114                 k = write(fd, p, nbytes);
2115                 if (k < 0 && errno == EINTR)
2116                         continue;
2117
2118                 if (k < 0 && errno == EAGAIN && do_poll) {
2119
2120                         /* We knowingly ignore any return value here,
2121                          * and expect that any error/EOF is reported
2122                          * via write() */
2123
2124                         fd_wait_for_event(fd, POLLOUT, (usec_t) -1);
2125                         continue;
2126                 }
2127
2128                 if (k <= 0)
2129                         return n > 0 ? n : (k < 0 ? -errno : 0);
2130
2131                 p += k;
2132                 nbytes -= k;
2133                 n += k;
2134         }
2135
2136         return n;
2137 }
2138
2139 int parse_size(const char *t, off_t base, off_t *size) {
2140
2141         /* Soo, sometimes we want to parse IEC binary suffxies, and
2142          * sometimes SI decimal suffixes. This function can parse
2143          * both. Which one is the right way depends on the
2144          * context. Wikipedia suggests that SI is customary for
2145          * hardrware metrics and network speeds, while IEC is
2146          * customary for most data sizes used by software and volatile
2147          * (RAM) memory. Hence be careful which one you pick!
2148          *
2149          * In either case we use just K, M, G as suffix, and not Ki,
2150          * Mi, Gi or so (as IEC would suggest). That's because that's
2151          * frickin' ugly. But this means you really need to make sure
2152          * to document which base you are parsing when you use this
2153          * call. */
2154
2155         struct table {
2156                 const char *suffix;
2157                 unsigned long long factor;
2158         };
2159
2160         static const struct table iec[] = {
2161                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2162                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2163                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2164                 { "G", 1024ULL*1024ULL*1024ULL },
2165                 { "M", 1024ULL*1024ULL },
2166                 { "K", 1024ULL },
2167                 { "B", 1 },
2168                 { "", 1 },
2169         };
2170
2171         static const struct table si[] = {
2172                 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2173                 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2174                 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2175                 { "G", 1000ULL*1000ULL*1000ULL },
2176                 { "M", 1000ULL*1000ULL },
2177                 { "K", 1000ULL },
2178                 { "B", 1 },
2179                 { "", 1 },
2180         };
2181
2182         const struct table *table;
2183         const char *p;
2184         unsigned long long r = 0;
2185         unsigned n_entries, start_pos = 0;
2186
2187         assert(t);
2188         assert(base == 1000 || base == 1024);
2189         assert(size);
2190
2191         if (base == 1000) {
2192                 table = si;
2193                 n_entries = ELEMENTSOF(si);
2194         } else {
2195                 table = iec;
2196                 n_entries = ELEMENTSOF(iec);
2197         }
2198
2199         p = t;
2200         do {
2201                 long long l;
2202                 unsigned long long l2;
2203                 double frac = 0;
2204                 char *e;
2205                 unsigned i;
2206
2207                 errno = 0;
2208                 l = strtoll(p, &e, 10);
2209
2210                 if (errno > 0)
2211                         return -errno;
2212
2213                 if (l < 0)
2214                         return -ERANGE;
2215
2216                 if (e == p)
2217                         return -EINVAL;
2218
2219                 if (*e == '.') {
2220                         e++;
2221                         if (*e >= '0' && *e <= '9') {
2222                                 char *e2;
2223
2224                                 /* strotoull itself would accept space/+/- */
2225                                 l2 = strtoull(e, &e2, 10);
2226
2227                                 if (errno == ERANGE)
2228                                         return -errno;
2229
2230                                 /* Ignore failure. E.g. 10.M is valid */
2231                                 frac = l2;
2232                                 for (; e < e2; e++)
2233                                         frac /= 10;
2234                         }
2235                 }
2236
2237                 e += strspn(e, WHITESPACE);
2238
2239                 for (i = start_pos; i < n_entries; i++)
2240                         if (startswith(e, table[i].suffix)) {
2241                                 unsigned long long tmp;
2242                                 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2243                                         return -ERANGE;
2244                                 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2245                                 if (tmp > ULLONG_MAX - r)
2246                                         return -ERANGE;
2247
2248                                 r += tmp;
2249                                 if ((unsigned long long) (off_t) r != r)
2250                                         return -ERANGE;
2251
2252                                 p = e + strlen(table[i].suffix);
2253
2254                                 start_pos = i + 1;
2255                                 break;
2256                         }
2257
2258                 if (i >= n_entries)
2259                         return -EINVAL;
2260
2261         } while (*p);
2262
2263         *size = r;
2264
2265         return 0;
2266 }
2267
2268 int make_stdio(int fd) {
2269         int r, s, t;
2270
2271         assert(fd >= 0);
2272
2273         r = dup3(fd, STDIN_FILENO, 0);
2274         s = dup3(fd, STDOUT_FILENO, 0);
2275         t = dup3(fd, STDERR_FILENO, 0);
2276
2277         if (fd >= 3)
2278                 close_nointr_nofail(fd);
2279
2280         if (r < 0 || s < 0 || t < 0)
2281                 return -errno;
2282
2283         /* We rely here that the new fd has O_CLOEXEC not set */
2284
2285         return 0;
2286 }
2287
2288 int make_null_stdio(void) {
2289         int null_fd;
2290
2291         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2292         if (null_fd < 0)
2293                 return -errno;
2294
2295         return make_stdio(null_fd);
2296 }
2297
2298 bool is_device_path(const char *path) {
2299
2300         /* Returns true on paths that refer to a device, either in
2301          * sysfs or in /dev */
2302
2303         return
2304                 path_startswith(path, "/dev/") ||
2305                 path_startswith(path, "/sys/");
2306 }
2307
2308 int dir_is_empty(const char *path) {
2309         _cleanup_closedir_ DIR *d;
2310
2311         d = opendir(path);
2312         if (!d)
2313                 return -errno;
2314
2315         for (;;) {
2316                 struct dirent *de;
2317
2318                 errno = 0;
2319                 de = readdir(d);
2320                 if (!de && errno != 0)
2321                         return -errno;
2322
2323                 if (!de)
2324                         return 1;
2325
2326                 if (!ignore_file(de->d_name))
2327                         return 0;
2328         }
2329 }
2330
2331 char* dirname_malloc(const char *path) {
2332         char *d, *dir, *dir2;
2333
2334         d = strdup(path);
2335         if (!d)
2336                 return NULL;
2337         dir = dirname(d);
2338         assert(dir);
2339
2340         if (dir != d) {
2341                 dir2 = strdup(dir);
2342                 free(d);
2343                 return dir2;
2344         }
2345
2346         return dir;
2347 }
2348
2349 int dev_urandom(void *p, size_t n) {
2350         _cleanup_close_ int fd;
2351         ssize_t k;
2352
2353         fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2354         if (fd < 0)
2355                 return errno == ENOENT ? -ENOSYS : -errno;
2356
2357         k = loop_read(fd, p, n, true);
2358         if (k < 0)
2359                 return (int) k;
2360         if ((size_t) k != n)
2361                 return -EIO;
2362
2363         return 0;
2364 }
2365
2366 void random_bytes(void *p, size_t n) {
2367         static bool srand_called = false;
2368         uint8_t *q;
2369         int r;
2370
2371         r = dev_urandom(p, n);
2372         if (r >= 0)
2373                 return;
2374
2375         /* If some idiot made /dev/urandom unavailable to us, he'll
2376          * get a PRNG instead. */
2377
2378         if (!srand_called) {
2379                 unsigned x = 0;
2380
2381 #ifdef HAVE_SYS_AUXV_H
2382                 /* The kernel provides us with a bit of entropy in
2383                  * auxv, so let's try to make use of that to seed the
2384                  * pseudo-random generator. It's better than
2385                  * nothing... */
2386
2387                 void *auxv;
2388
2389                 auxv = (void*) getauxval(AT_RANDOM);
2390                 if (auxv)
2391                         x ^= *(unsigned*) auxv;
2392 #endif
2393
2394                 x ^= (unsigned) now(CLOCK_REALTIME);
2395                 x ^= (unsigned) gettid();
2396
2397                 srand(x);
2398                 srand_called = true;
2399         }
2400
2401         for (q = p; q < (uint8_t*) p + n; q ++)
2402                 *q = rand();
2403 }
2404
2405 void rename_process(const char name[8]) {
2406         assert(name);
2407
2408         /* This is a like a poor man's setproctitle(). It changes the
2409          * comm field, argv[0], and also the glibc's internally used
2410          * name of the process. For the first one a limit of 16 chars
2411          * applies, to the second one usually one of 10 (i.e. length
2412          * of "/sbin/init"), to the third one one of 7 (i.e. length of
2413          * "systemd"). If you pass a longer string it will be
2414          * truncated */
2415
2416         prctl(PR_SET_NAME, name);
2417
2418         if (program_invocation_name)
2419                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2420
2421         if (saved_argc > 0) {
2422                 int i;
2423
2424                 if (saved_argv[0])
2425                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2426
2427                 for (i = 1; i < saved_argc; i++) {
2428                         if (!saved_argv[i])
2429                                 break;
2430
2431                         memzero(saved_argv[i], strlen(saved_argv[i]));
2432                 }
2433         }
2434 }
2435
2436 void sigset_add_many(sigset_t *ss, ...) {
2437         va_list ap;
2438         int sig;
2439
2440         assert(ss);
2441
2442         va_start(ap, ss);
2443         while ((sig = va_arg(ap, int)) > 0)
2444                 assert_se(sigaddset(ss, sig) == 0);
2445         va_end(ap);
2446 }
2447
2448 char* gethostname_malloc(void) {
2449         struct utsname u;
2450
2451         assert_se(uname(&u) >= 0);
2452
2453         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2454                 return strdup(u.nodename);
2455
2456         return strdup(u.sysname);
2457 }
2458
2459 bool hostname_is_set(void) {
2460         struct utsname u;
2461
2462         assert_se(uname(&u) >= 0);
2463
2464         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2465 }
2466
2467 static char *lookup_uid(uid_t uid) {
2468         long bufsize;
2469         char *name;
2470         _cleanup_free_ char *buf = NULL;
2471         struct passwd pwbuf, *pw = NULL;
2472
2473         /* Shortcut things to avoid NSS lookups */
2474         if (uid == 0)
2475                 return strdup("root");
2476
2477         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2478         if (bufsize <= 0)
2479                 bufsize = 4096;
2480
2481         buf = malloc(bufsize);
2482         if (!buf)
2483                 return NULL;
2484
2485         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2486                 return strdup(pw->pw_name);
2487
2488         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2489                 return NULL;
2490
2491         return name;
2492 }
2493
2494 char* getlogname_malloc(void) {
2495         uid_t uid;
2496         struct stat st;
2497
2498         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2499                 uid = st.st_uid;
2500         else
2501                 uid = getuid();
2502
2503         return lookup_uid(uid);
2504 }
2505
2506 char *getusername_malloc(void) {
2507         const char *e;
2508
2509         e = getenv("USER");
2510         if (e)
2511                 return strdup(e);
2512
2513         return lookup_uid(getuid());
2514 }
2515
2516 int getttyname_malloc(int fd, char **r) {
2517         char path[PATH_MAX], *c;
2518         int k;
2519
2520         assert(r);
2521
2522         k = ttyname_r(fd, path, sizeof(path));
2523         if (k > 0)
2524                 return -k;
2525
2526         char_array_0(path);
2527
2528         c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2529         if (!c)
2530                 return -ENOMEM;
2531
2532         *r = c;
2533         return 0;
2534 }
2535
2536 int getttyname_harder(int fd, char **r) {
2537         int k;
2538         char *s;
2539
2540         k = getttyname_malloc(fd, &s);
2541         if (k < 0)
2542                 return k;
2543
2544         if (streq(s, "tty")) {
2545                 free(s);
2546                 return get_ctty(0, NULL, r);
2547         }
2548
2549         *r = s;
2550         return 0;
2551 }
2552
2553 int get_ctty_devnr(pid_t pid, dev_t *d) {
2554         int r;
2555         _cleanup_free_ char *line = NULL;
2556         const char *p;
2557         unsigned long ttynr;
2558
2559         assert(pid >= 0);
2560
2561         p = procfs_file_alloca(pid, "stat");
2562         r = read_one_line_file(p, &line);
2563         if (r < 0)
2564                 return r;
2565
2566         p = strrchr(line, ')');
2567         if (!p)
2568                 return -EIO;
2569
2570         p++;
2571
2572         if (sscanf(p, " "
2573                    "%*c "  /* state */
2574                    "%*d "  /* ppid */
2575                    "%*d "  /* pgrp */
2576                    "%*d "  /* session */
2577                    "%lu ", /* ttynr */
2578                    &ttynr) != 1)
2579                 return -EIO;
2580
2581         if (major(ttynr) == 0 && minor(ttynr) == 0)
2582                 return -ENOENT;
2583
2584         if (d)
2585                 *d = (dev_t) ttynr;
2586
2587         return 0;
2588 }
2589
2590 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2591         char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2592         _cleanup_free_ char *s = NULL;
2593         const char *p;
2594         dev_t devnr;
2595         int k;
2596
2597         assert(r);
2598
2599         k = get_ctty_devnr(pid, &devnr);
2600         if (k < 0)
2601                 return k;
2602
2603         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2604
2605         k = readlink_malloc(fn, &s);
2606         if (k < 0) {
2607
2608                 if (k != -ENOENT)
2609                         return k;
2610
2611                 /* This is an ugly hack */
2612                 if (major(devnr) == 136) {
2613                         asprintf(&b, "pts/%lu", (unsigned long) minor(devnr));
2614                         goto finish;
2615                 }
2616
2617                 /* Probably something like the ptys which have no
2618                  * symlink in /dev/char. Let's return something
2619                  * vaguely useful. */
2620
2621                 b = strdup(fn + 5);
2622                 goto finish;
2623         }
2624
2625         if (startswith(s, "/dev/"))
2626                 p = s + 5;
2627         else if (startswith(s, "../"))
2628                 p = s + 3;
2629         else
2630                 p = s;
2631
2632         b = strdup(p);
2633
2634 finish:
2635         if (!b)
2636                 return -ENOMEM;
2637
2638         *r = b;
2639         if (_devnr)
2640                 *_devnr = devnr;
2641
2642         return 0;
2643 }
2644
2645 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2646         DIR *d;
2647         int ret = 0;
2648
2649         assert(fd >= 0);
2650
2651         /* This returns the first error we run into, but nevertheless
2652          * tries to go on. This closes the passed fd. */
2653
2654         d = fdopendir(fd);
2655         if (!d) {
2656                 close_nointr_nofail(fd);
2657
2658                 return errno == ENOENT ? 0 : -errno;
2659         }
2660
2661         for (;;) {
2662                 struct dirent *de;
2663                 bool is_dir, keep_around;
2664                 struct stat st;
2665                 int r;
2666
2667                 errno = 0;
2668                 de = readdir(d);
2669                 if (!de && errno != 0) {
2670                         if (ret == 0)
2671                                 ret = -errno;
2672                         break;
2673                 }
2674
2675                 if (!de)
2676                         break;
2677
2678                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2679                         continue;
2680
2681                 if (de->d_type == DT_UNKNOWN ||
2682                     honour_sticky ||
2683                     (de->d_type == DT_DIR && root_dev)) {
2684                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2685                                 if (ret == 0 && errno != ENOENT)
2686                                         ret = -errno;
2687                                 continue;
2688                         }
2689
2690                         is_dir = S_ISDIR(st.st_mode);
2691                         keep_around =
2692                                 honour_sticky &&
2693                                 (st.st_uid == 0 || st.st_uid == getuid()) &&
2694                                 (st.st_mode & S_ISVTX);
2695                 } else {
2696                         is_dir = de->d_type == DT_DIR;
2697                         keep_around = false;
2698                 }
2699
2700                 if (is_dir) {
2701                         int subdir_fd;
2702
2703                         /* if root_dev is set, remove subdirectories only, if device is same as dir */
2704                         if (root_dev && st.st_dev != root_dev->st_dev)
2705                                 continue;
2706
2707                         subdir_fd = openat(fd, de->d_name,
2708                                            O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2709                         if (subdir_fd < 0) {
2710                                 if (ret == 0 && errno != ENOENT)
2711                                         ret = -errno;
2712                                 continue;
2713                         }
2714
2715                         r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2716                         if (r < 0 && ret == 0)
2717                                 ret = r;
2718
2719                         if (!keep_around)
2720                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2721                                         if (ret == 0 && errno != ENOENT)
2722                                                 ret = -errno;
2723                                 }
2724
2725                 } else if (!only_dirs && !keep_around) {
2726
2727                         if (unlinkat(fd, de->d_name, 0) < 0) {
2728                                 if (ret == 0 && errno != ENOENT)
2729                                         ret = -errno;
2730                         }
2731                 }
2732         }
2733
2734         closedir(d);
2735
2736         return ret;
2737 }
2738
2739 _pure_ static int is_temporary_fs(struct statfs *s) {
2740         assert(s);
2741
2742         return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2743                F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2744 }
2745
2746 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2747         struct statfs s;
2748
2749         assert(fd >= 0);
2750
2751         if (fstatfs(fd, &s) < 0) {
2752                 close_nointr_nofail(fd);
2753                 return -errno;
2754         }
2755
2756         /* We refuse to clean disk file systems with this call. This
2757          * is extra paranoia just to be sure we never ever remove
2758          * non-state data */
2759         if (!is_temporary_fs(&s)) {
2760                 log_error("Attempted to remove disk file system, and we can't allow that.");
2761                 close_nointr_nofail(fd);
2762                 return -EPERM;
2763         }
2764
2765         return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2766 }
2767
2768 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2769         int fd, r;
2770         struct statfs s;
2771
2772         assert(path);
2773
2774         /* We refuse to clean the root file system with this
2775          * call. This is extra paranoia to never cause a really
2776          * seriously broken system. */
2777         if (path_equal(path, "/")) {
2778                 log_error("Attempted to remove entire root file system, and we can't allow that.");
2779                 return -EPERM;
2780         }
2781
2782         fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2783         if (fd < 0) {
2784
2785                 if (errno != ENOTDIR)
2786                         return -errno;
2787
2788                 if (!dangerous) {
2789                         if (statfs(path, &s) < 0)
2790                                 return -errno;
2791
2792                         if (!is_temporary_fs(&s)) {
2793                                 log_error("Attempted to remove disk file system, and we can't allow that.");
2794                                 return -EPERM;
2795                         }
2796                 }
2797
2798                 if (delete_root && !only_dirs)
2799                         if (unlink(path) < 0 && errno != ENOENT)
2800                                 return -errno;
2801
2802                 return 0;
2803         }
2804
2805         if (!dangerous) {
2806                 if (fstatfs(fd, &s) < 0) {
2807                         close_nointr_nofail(fd);
2808                         return -errno;
2809                 }
2810
2811                 if (!is_temporary_fs(&s)) {
2812                         log_error("Attempted to remove disk file system, and we can't allow that.");
2813                         close_nointr_nofail(fd);
2814                         return -EPERM;
2815                 }
2816         }
2817
2818         r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2819         if (delete_root) {
2820
2821                 if (honour_sticky && file_is_priv_sticky(path) > 0)
2822                         return r;
2823
2824                 if (rmdir(path) < 0 && errno != ENOENT) {
2825                         if (r == 0)
2826                                 r = -errno;
2827                 }
2828         }
2829
2830         return r;
2831 }
2832
2833 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2834         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2835 }
2836
2837 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2838         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2839 }
2840
2841 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2842         assert(path);
2843
2844         /* Under the assumption that we are running privileged we
2845          * first change the access mode and only then hand out
2846          * ownership to avoid a window where access is too open. */
2847
2848         if (mode != (mode_t) -1)
2849                 if (chmod(path, mode) < 0)
2850                         return -errno;
2851
2852         if (uid != (uid_t) -1 || gid != (gid_t) -1)
2853                 if (chown(path, uid, gid) < 0)
2854                         return -errno;
2855
2856         return 0;
2857 }
2858
2859 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2860         assert(fd >= 0);
2861
2862         /* Under the assumption that we are running privileged we
2863          * first change the access mode and only then hand out
2864          * ownership to avoid a window where access is too open. */
2865
2866         if (mode != (mode_t) -1)
2867                 if (fchmod(fd, mode) < 0)
2868                         return -errno;
2869
2870         if (uid != (uid_t) -1 || gid != (gid_t) -1)
2871                 if (fchown(fd, uid, gid) < 0)
2872                         return -errno;
2873
2874         return 0;
2875 }
2876
2877 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2878         cpu_set_t *r;
2879         unsigned n = 1024;
2880
2881         /* Allocates the cpuset in the right size */
2882
2883         for (;;) {
2884                 if (!(r = CPU_ALLOC(n)))
2885                         return NULL;
2886
2887                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2888                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2889
2890                         if (ncpus)
2891                                 *ncpus = n;
2892
2893                         return r;
2894                 }
2895
2896                 CPU_FREE(r);
2897
2898                 if (errno != EINVAL)
2899                         return NULL;
2900
2901                 n *= 2;
2902         }
2903 }
2904
2905 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2906         static const char status_indent[] = "         "; /* "[" STATUS "] " */
2907         _cleanup_free_ char *s = NULL;
2908         _cleanup_close_ int fd = -1;
2909         struct iovec iovec[6] = {};
2910         int n = 0;
2911         static bool prev_ephemeral;
2912
2913         assert(format);
2914
2915         /* This is independent of logging, as status messages are
2916          * optional and go exclusively to the console. */
2917
2918         if (vasprintf(&s, format, ap) < 0)
2919                 return log_oom();
2920
2921         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2922         if (fd < 0)
2923                 return fd;
2924
2925         if (ellipse) {
2926                 char *e;
2927                 size_t emax, sl;
2928                 int c;
2929
2930                 c = fd_columns(fd);
2931                 if (c <= 0)
2932                         c = 80;
2933
2934                 sl = status ? sizeof(status_indent)-1 : 0;
2935
2936                 emax = c - sl - 1;
2937                 if (emax < 3)
2938                         emax = 3;
2939
2940                 e = ellipsize(s, emax, 75);
2941                 if (e) {
2942                         free(s);
2943                         s = e;
2944                 }
2945         }
2946
2947         if (prev_ephemeral)
2948                 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2949         prev_ephemeral = ephemeral;
2950
2951         if (status) {
2952                 if (!isempty(status)) {
2953                         IOVEC_SET_STRING(iovec[n++], "[");
2954                         IOVEC_SET_STRING(iovec[n++], status);
2955                         IOVEC_SET_STRING(iovec[n++], "] ");
2956                 } else
2957                         IOVEC_SET_STRING(iovec[n++], status_indent);
2958         }
2959
2960         IOVEC_SET_STRING(iovec[n++], s);
2961         if (!ephemeral)
2962                 IOVEC_SET_STRING(iovec[n++], "\n");
2963
2964         if (writev(fd, iovec, n) < 0)
2965                 return -errno;
2966
2967         return 0;
2968 }
2969
2970 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2971         va_list ap;
2972         int r;
2973
2974         assert(format);
2975
2976         va_start(ap, format);
2977         r = status_vprintf(status, ellipse, ephemeral, format, ap);
2978         va_end(ap);
2979
2980         return r;
2981 }
2982
2983 char *replace_env(const char *format, char **env) {
2984         enum {
2985                 WORD,
2986                 CURLY,
2987                 VARIABLE
2988         } state = WORD;
2989
2990         const char *e, *word = format;
2991         char *r = NULL, *k;
2992
2993         assert(format);
2994
2995         for (e = format; *e; e ++) {
2996
2997                 switch (state) {
2998
2999                 case WORD:
3000                         if (*e == '$')
3001                                 state = CURLY;
3002                         break;
3003
3004                 case CURLY:
3005                         if (*e == '{') {
3006                                 if (!(k = strnappend(r, word, e-word-1)))
3007                                         goto fail;
3008
3009                                 free(r);
3010                                 r = k;
3011
3012                                 word = e-1;
3013                                 state = VARIABLE;
3014
3015                         } else if (*e == '$') {
3016                                 if (!(k = strnappend(r, word, e-word)))
3017                                         goto fail;
3018
3019                                 free(r);
3020                                 r = k;
3021
3022                                 word = e+1;
3023                                 state = WORD;
3024                         } else
3025                                 state = WORD;
3026                         break;
3027
3028                 case VARIABLE:
3029                         if (*e == '}') {
3030                                 const char *t;
3031
3032                                 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3033
3034                                 k = strappend(r, t);
3035                                 if (!k)
3036                                         goto fail;
3037
3038                                 free(r);
3039                                 r = k;
3040
3041                                 word = e+1;
3042                                 state = WORD;
3043                         }
3044                         break;
3045                 }
3046         }
3047
3048         if (!(k = strnappend(r, word, e-word)))
3049                 goto fail;
3050
3051         free(r);
3052         return k;
3053
3054 fail:
3055         free(r);
3056         return NULL;
3057 }
3058
3059 char **replace_env_argv(char **argv, char **env) {
3060         char **r, **i;
3061         unsigned k = 0, l = 0;
3062
3063         l = strv_length(argv);
3064
3065         if (!(r = new(char*, l+1)))
3066                 return NULL;
3067
3068         STRV_FOREACH(i, argv) {
3069
3070                 /* If $FOO appears as single word, replace it by the split up variable */
3071                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3072                         char *e;
3073                         char **w, **m;
3074                         unsigned q;
3075
3076                         e = strv_env_get(env, *i+1);
3077                         if (e) {
3078
3079                                 if (!(m = strv_split_quoted(e))) {
3080                                         r[k] = NULL;
3081                                         strv_free(r);
3082                                         return NULL;
3083                                 }
3084                         } else
3085                                 m = NULL;
3086
3087                         q = strv_length(m);
3088                         l = l + q - 1;
3089
3090                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3091                                 r[k] = NULL;
3092                                 strv_free(r);
3093                                 strv_free(m);
3094                                 return NULL;
3095                         }
3096
3097                         r = w;
3098                         if (m) {
3099                                 memcpy(r + k, m, q * sizeof(char*));
3100                                 free(m);
3101                         }
3102
3103                         k += q;
3104                         continue;
3105                 }
3106
3107                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3108                 if (!(r[k++] = replace_env(*i, env))) {
3109                         strv_free(r);
3110                         return NULL;
3111                 }
3112         }
3113
3114         r[k] = NULL;
3115         return r;
3116 }
3117
3118 int fd_columns(int fd) {
3119         struct winsize ws = {};
3120
3121         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3122                 return -errno;
3123
3124         if (ws.ws_col <= 0)
3125                 return -EIO;
3126
3127         return ws.ws_col;
3128 }
3129
3130 unsigned columns(void) {
3131         const char *e;
3132         int c;
3133
3134         if (_likely_(cached_columns > 0))
3135                 return cached_columns;
3136
3137         c = 0;
3138         e = getenv("COLUMNS");
3139         if (e)
3140                 safe_atoi(e, &c);
3141
3142         if (c <= 0)
3143                 c = fd_columns(STDOUT_FILENO);
3144
3145         if (c <= 0)
3146                 c = 80;
3147
3148         cached_columns = c;
3149         return c;
3150 }
3151
3152 int fd_lines(int fd) {
3153         struct winsize ws = {};
3154
3155         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3156                 return -errno;
3157
3158         if (ws.ws_row <= 0)
3159                 return -EIO;
3160
3161         return ws.ws_row;
3162 }
3163
3164 unsigned lines(void) {
3165         const char *e;
3166         unsigned l;
3167
3168         if (_likely_(cached_lines > 0))
3169                 return cached_lines;
3170
3171         l = 0;
3172         e = getenv("LINES");
3173         if (e)
3174                 safe_atou(e, &l);
3175
3176         if (l <= 0)
3177                 l = fd_lines(STDOUT_FILENO);
3178
3179         if (l <= 0)
3180                 l = 24;
3181
3182         cached_lines = l;
3183         return cached_lines;
3184 }
3185
3186 /* intended to be used as a SIGWINCH sighandler */
3187 void columns_lines_cache_reset(int signum) {
3188         cached_columns = 0;
3189         cached_lines = 0;
3190 }
3191
3192 bool on_tty(void) {
3193         static int cached_on_tty = -1;
3194
3195         if (_unlikely_(cached_on_tty < 0))
3196                 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3197
3198         return cached_on_tty;
3199 }
3200
3201 int files_same(const char *filea, const char *fileb) {
3202         struct stat a, b;
3203
3204         if (stat(filea, &a) < 0)
3205                 return -errno;
3206
3207         if (stat(fileb, &b) < 0)
3208                 return -errno;
3209
3210         return a.st_dev == b.st_dev &&
3211                a.st_ino == b.st_ino;
3212 }
3213
3214 int running_in_chroot(void) {
3215         int ret;
3216
3217         ret = files_same("/proc/1/root", "/");
3218         if (ret < 0)
3219                 return ret;
3220
3221         return ret == 0;
3222 }
3223
3224 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3225         size_t x;
3226         char *r;
3227
3228         assert(s);
3229         assert(percent <= 100);
3230         assert(new_length >= 3);
3231
3232         if (old_length <= 3 || old_length <= new_length)
3233                 return strndup(s, old_length);
3234
3235         r = new0(char, new_length+1);
3236         if (!r)
3237                 return NULL;
3238
3239         x = (new_length * percent) / 100;
3240
3241         if (x > new_length - 3)
3242                 x = new_length - 3;
3243
3244         memcpy(r, s, x);
3245         r[x] = '.';
3246         r[x+1] = '.';
3247         r[x+2] = '.';
3248         memcpy(r + x + 3,
3249                s + old_length - (new_length - x - 3),
3250                new_length - x - 3);
3251
3252         return r;
3253 }
3254
3255 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3256         size_t x;
3257         char *e;
3258         const char *i, *j;
3259         unsigned k, len, len2;
3260
3261         assert(s);
3262         assert(percent <= 100);
3263         assert(new_length >= 3);
3264
3265         /* if no multibyte characters use ascii_ellipsize_mem for speed */
3266         if (ascii_is_valid(s))
3267                 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3268
3269         if (old_length <= 3 || old_length <= new_length)
3270                 return strndup(s, old_length);
3271
3272         x = (new_length * percent) / 100;
3273
3274         if (x > new_length - 3)
3275                 x = new_length - 3;
3276
3277         k = 0;
3278         for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3279                 int c;
3280
3281                 c = utf8_encoded_to_unichar(i);
3282                 if (c < 0)
3283                         return NULL;
3284                 k += unichar_iswide(c) ? 2 : 1;
3285         }
3286
3287         if (k > x) /* last character was wide and went over quota */
3288                 x ++;
3289
3290         for (j = s + old_length; k < new_length && j > i; ) {
3291                 int c;
3292
3293                 j = utf8_prev_char(j);
3294                 c = utf8_encoded_to_unichar(j);
3295                 if (c < 0)
3296                         return NULL;
3297                 k += unichar_iswide(c) ? 2 : 1;
3298         }
3299         assert(i <= j);
3300
3301         /* we don't actually need to ellipsize */
3302         if (i == j)
3303                 return memdup(s, old_length + 1);
3304
3305         /* make space for ellipsis */
3306         j = utf8_next_char(j);
3307
3308         len = i - s;
3309         len2 = s + old_length - j;
3310         e = new(char, len + 3 + len2 + 1);
3311         if (!e)
3312                 return NULL;
3313
3314         /*
3315         printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3316                old_length, new_length, x, len, len2, k);
3317         */
3318
3319         memcpy(e, s, len);
3320         e[len]   = 0xe2; /* tri-dot ellipsis: … */
3321         e[len + 1] = 0x80;
3322         e[len + 2] = 0xa6;
3323
3324         memcpy(e + len + 3, j, len2 + 1);
3325
3326         return e;
3327 }
3328
3329 char *ellipsize(const char *s, size_t length, unsigned percent) {
3330         return ellipsize_mem(s, strlen(s), length, percent);
3331 }
3332
3333 int touch(const char *path) {
3334         int fd;
3335
3336         assert(path);
3337
3338         /* This just opens the file for writing, ensuring it
3339          * exists. It doesn't call utimensat() the way /usr/bin/touch
3340          * does it. */
3341
3342         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3343         if (fd < 0)
3344                 return -errno;
3345
3346         close_nointr_nofail(fd);
3347         return 0;
3348 }
3349
3350 char *unquote(const char *s, const char* quotes) {
3351         size_t l;
3352         assert(s);
3353
3354         /* This is rather stupid, simply removes the heading and
3355          * trailing quotes if there is one. Doesn't care about
3356          * escaping or anything. We should make this smarter one
3357          * day...*/
3358
3359         l = strlen(s);
3360         if (l < 2)
3361                 return strdup(s);
3362
3363         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3364                 return strndup(s+1, l-2);
3365
3366         return strdup(s);
3367 }
3368
3369 char *normalize_env_assignment(const char *s) {
3370         _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3371         char *eq, *r;
3372
3373         eq = strchr(s, '=');
3374         if (!eq) {
3375                 char *t;
3376
3377                 r = strdup(s);
3378                 if (!r)
3379                         return NULL;
3380
3381                 t = strstrip(r);
3382                 if (t == r)
3383                         return r;
3384
3385                 memmove(r, t, strlen(t) + 1);
3386                 return r;
3387         }
3388
3389         name = strndup(s, eq - s);
3390         if (!name)
3391                 return NULL;
3392
3393         p = strdup(eq + 1);
3394         if (!p)
3395                 return NULL;
3396
3397         value = unquote(strstrip(p), QUOTES);
3398         if (!value)
3399                 return NULL;
3400
3401         if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3402                 r = NULL;
3403
3404         return r;
3405 }
3406
3407 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3408         siginfo_t dummy;
3409
3410         assert(pid >= 1);
3411
3412         if (!status)
3413                 status = &dummy;
3414
3415         for (;;) {
3416                 zero(*status);
3417
3418                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3419
3420                         if (errno == EINTR)
3421                                 continue;
3422
3423                         return -errno;
3424                 }
3425
3426                 return 0;
3427         }
3428 }
3429
3430 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3431         int r;
3432         siginfo_t status;
3433
3434         assert(name);
3435         assert(pid > 1);
3436
3437         r = wait_for_terminate(pid, &status);
3438         if (r < 0) {
3439                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3440                 return r;
3441         }
3442
3443         if (status.si_code == CLD_EXITED) {
3444                 if (status.si_status != 0) {
3445                         log_warning("%s failed with error code %i.", name, status.si_status);
3446                         return status.si_status;
3447                 }
3448
3449                 log_debug("%s succeeded.", name);
3450                 return 0;
3451
3452         } else if (status.si_code == CLD_KILLED ||
3453                    status.si_code == CLD_DUMPED) {
3454
3455                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3456                 return -EPROTO;
3457         }
3458
3459         log_warning("%s failed due to unknown reason.", name);
3460         return -EPROTO;
3461 }
3462
3463 noreturn void freeze(void) {
3464
3465         /* Make sure nobody waits for us on a socket anymore */
3466         close_all_fds(NULL, 0);
3467
3468         sync();
3469
3470         for (;;)
3471                 pause();
3472 }
3473
3474 bool null_or_empty(struct stat *st) {
3475         assert(st);
3476
3477         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3478                 return true;
3479
3480         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3481                 return true;
3482
3483         return false;
3484 }
3485
3486 int null_or_empty_path(const char *fn) {
3487         struct stat st;
3488
3489         assert(fn);
3490
3491         if (stat(fn, &st) < 0)
3492                 return -errno;
3493
3494         return null_or_empty(&st);
3495 }
3496
3497 DIR *xopendirat(int fd, const char *name, int flags) {
3498         int nfd;
3499         DIR *d;
3500
3501         assert(!(flags & O_CREAT));
3502
3503         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3504         if (nfd < 0)
3505                 return NULL;
3506
3507         d = fdopendir(nfd);
3508         if (!d) {
3509                 close_nointr_nofail(nfd);
3510                 return NULL;
3511         }
3512
3513         return d;
3514 }
3515
3516 int signal_from_string_try_harder(const char *s) {
3517         int signo;
3518         assert(s);
3519
3520         signo = signal_from_string(s);
3521         if (signo <= 0)
3522                 if (startswith(s, "SIG"))
3523                         return signal_from_string(s+3);
3524
3525         return signo;
3526 }
3527
3528 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3529         _cleanup_free_ char *t = NULL, *u = NULL;
3530         size_t enc_len;
3531
3532         u = unquote(tagvalue, "\"\'");
3533         if (!u)
3534                 return NULL;
3535
3536         enc_len = strlen(u) * 4 + 1;
3537         t = new(char, enc_len);
3538         if (!t)
3539                 return NULL;
3540
3541         if (encode_devnode_name(u, t, enc_len) < 0)
3542                 return NULL;
3543
3544         return strjoin("/dev/disk/by-", by, "/", t, NULL);
3545 }
3546
3547 char *fstab_node_to_udev_node(const char *p) {
3548         assert(p);
3549
3550         if (startswith(p, "LABEL="))
3551                 return tag_to_udev_node(p+6, "label");
3552
3553         if (startswith(p, "UUID="))
3554                 return tag_to_udev_node(p+5, "uuid");
3555
3556         if (startswith(p, "PARTUUID="))
3557                 return tag_to_udev_node(p+9, "partuuid");
3558
3559         if (startswith(p, "PARTLABEL="))
3560                 return tag_to_udev_node(p+10, "partlabel");
3561
3562         return strdup(p);
3563 }
3564
3565 bool tty_is_vc(const char *tty) {
3566         assert(tty);
3567
3568         if (startswith(tty, "/dev/"))
3569                 tty += 5;
3570
3571         return vtnr_from_tty(tty) >= 0;
3572 }
3573
3574 bool tty_is_console(const char *tty) {
3575         assert(tty);
3576
3577         if (startswith(tty, "/dev/"))
3578                 tty += 5;
3579
3580         return streq(tty, "console");
3581 }
3582
3583 int vtnr_from_tty(const char *tty) {
3584         int i, r;
3585
3586         assert(tty);
3587
3588         if (startswith(tty, "/dev/"))
3589                 tty += 5;
3590
3591         if (!startswith(tty, "tty") )
3592                 return -EINVAL;
3593
3594         if (tty[3] < '0' || tty[3] > '9')
3595                 return -EINVAL;
3596
3597         r = safe_atoi(tty+3, &i);
3598         if (r < 0)
3599                 return r;
3600
3601         if (i < 0 || i > 63)
3602                 return -EINVAL;
3603
3604         return i;
3605 }
3606
3607 char *resolve_dev_console(char **active) {
3608         char *tty;
3609
3610         /* Resolve where /dev/console is pointing to, if /sys is actually ours
3611          * (i.e. not read-only-mounted which is a sign for container setups) */
3612
3613         if (path_is_read_only_fs("/sys") > 0)
3614                 return NULL;
3615
3616         if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3617                 return NULL;
3618
3619         /* If multiple log outputs are configured the last one is what
3620          * /dev/console points to */
3621         tty = strrchr(*active, ' ');
3622         if (tty)
3623                 tty++;
3624         else
3625                 tty = *active;
3626
3627         if (streq(tty, "tty0")) {
3628                 char *tmp;
3629
3630                 /* Get the active VC (e.g. tty1) */
3631                 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3632                         free(*active);
3633                         tty = *active = tmp;
3634                 }
3635         }
3636
3637         return tty;
3638 }
3639
3640 bool tty_is_vc_resolve(const char *tty) {
3641         _cleanup_free_ char *active = NULL;
3642
3643         assert(tty);
3644
3645         if (startswith(tty, "/dev/"))
3646                 tty += 5;
3647
3648         if (streq(tty, "console")) {
3649                 tty = resolve_dev_console(&active);
3650                 if (!tty)
3651                         return false;
3652         }
3653
3654         return tty_is_vc(tty);
3655 }
3656
3657 const char *default_term_for_tty(const char *tty) {
3658         assert(tty);
3659
3660         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3661 }
3662
3663 bool dirent_is_file(const struct dirent *de) {
3664         assert(de);
3665
3666         if (ignore_file(de->d_name))
3667                 return false;
3668
3669         if (de->d_type != DT_REG &&
3670             de->d_type != DT_LNK &&
3671             de->d_type != DT_UNKNOWN)
3672                 return false;
3673
3674         return true;
3675 }
3676
3677 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3678         assert(de);
3679
3680         if (de->d_type != DT_REG &&
3681             de->d_type != DT_LNK &&
3682             de->d_type != DT_UNKNOWN)
3683                 return false;
3684
3685         if (ignore_file_allow_backup(de->d_name))
3686                 return false;
3687
3688         return endswith(de->d_name, suffix);
3689 }
3690
3691 void execute_directory(const char *directory, DIR *d, usec_t timeout, char *argv[]) {
3692         pid_t executor_pid;
3693         int r;
3694
3695         assert(directory);
3696
3697         /* Executes all binaries in a directory in parallel and waits
3698          * for them to finish. Optionally a timeout is applied. */
3699
3700         executor_pid = fork();
3701         if (executor_pid < 0) {
3702                 log_error("Failed to fork: %m");
3703                 return;
3704
3705         } else if (executor_pid == 0) {
3706                 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
3707                 _cleanup_closedir_ DIR *_d = NULL;
3708                 struct dirent *de;
3709                 sigset_t ss;
3710
3711                 /* We fork this all off from a child process so that
3712                  * we can somewhat cleanly make use of SIGALRM to set
3713                  * a time limit */
3714
3715                 reset_all_signal_handlers();
3716
3717                 assert_se(sigemptyset(&ss) == 0);
3718                 assert_se(sigprocmask(SIG_SETMASK, &ss, NULL) == 0);
3719
3720                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3721
3722                 if (!d) {
3723                         d = _d = opendir(directory);
3724                         if (!d) {
3725                                 if (errno == ENOENT)
3726                                         _exit(EXIT_SUCCESS);
3727
3728                                 log_error("Failed to enumerate directory %s: %m", directory);
3729                                 _exit(EXIT_FAILURE);
3730                         }
3731                 }
3732
3733                 pids = hashmap_new(NULL, NULL);
3734                 if (!pids) {
3735                         log_oom();
3736                         _exit(EXIT_FAILURE);
3737                 }
3738
3739                 FOREACH_DIRENT(de, d, break) {
3740                         _cleanup_free_ char *path = NULL;
3741                         pid_t pid;
3742
3743                         if (!dirent_is_file(de))
3744                                 continue;
3745
3746                         if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3747                                 log_oom();
3748                                 _exit(EXIT_FAILURE);
3749                         }
3750
3751                         pid = fork();
3752                         if (pid < 0) {
3753                                 log_error("Failed to fork: %m");
3754                                 continue;
3755                         } else if (pid == 0) {
3756                                 char *_argv[2];
3757
3758                                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3759
3760                                 if (!argv) {
3761                                         _argv[0] = path;
3762                                         _argv[1] = NULL;
3763                                         argv = _argv;
3764                                 } else
3765                                         argv[0] = path;
3766
3767                                 execv(path, argv);
3768                                 log_error("Failed to execute %s: %m", path);
3769                                 _exit(EXIT_FAILURE);
3770                         }
3771
3772
3773                         log_debug("Spawned %s as " PID_FMT ".", path, pid);
3774
3775                         r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3776                         if (r < 0) {
3777                                 log_oom();
3778                                 _exit(EXIT_FAILURE);
3779                         }
3780
3781                         path = NULL;
3782                 }
3783
3784                 /* Abort execution of this process after the
3785                  * timout. We simply rely on SIGALRM as default action
3786                  * terminating the process, and turn on alarm(). */
3787
3788                 if (timeout != (usec_t) -1)
3789                         alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3790
3791                 while (!hashmap_isempty(pids)) {
3792                         _cleanup_free_ char *path = NULL;
3793                         pid_t pid;
3794
3795                         pid = PTR_TO_UINT(hashmap_first_key(pids));
3796                         assert(pid > 0);
3797
3798                         path = hashmap_remove(pids, UINT_TO_PTR(pid));
3799                         assert(path);
3800
3801                         wait_for_terminate_and_warn(path, pid);
3802                 }
3803
3804                 _exit(EXIT_SUCCESS);
3805         }
3806
3807         wait_for_terminate_and_warn(directory, executor_pid);
3808 }
3809
3810 int kill_and_sigcont(pid_t pid, int sig) {
3811         int r;
3812
3813         r = kill(pid, sig) < 0 ? -errno : 0;
3814
3815         if (r >= 0)
3816                 kill(pid, SIGCONT);
3817
3818         return r;
3819 }
3820
3821 bool nulstr_contains(const char*nulstr, const char *needle) {
3822         const char *i;
3823
3824         if (!nulstr)
3825                 return false;
3826
3827         NULSTR_FOREACH(i, nulstr)
3828                 if (streq(i, needle))
3829                         return true;
3830
3831         return false;
3832 }
3833
3834 bool plymouth_running(void) {
3835         return access("/run/plymouth/pid", F_OK) >= 0;
3836 }
3837
3838 char* strshorten(char *s, size_t l) {
3839         assert(s);
3840
3841         if (l < strlen(s))
3842                 s[l] = 0;
3843
3844         return s;
3845 }
3846
3847 static bool hostname_valid_char(char c) {
3848         return
3849                 (c >= 'a' && c <= 'z') ||
3850                 (c >= 'A' && c <= 'Z') ||
3851                 (c >= '0' && c <= '9') ||
3852                 c == '-' ||
3853                 c == '_' ||
3854                 c == '.';
3855 }
3856
3857 bool hostname_is_valid(const char *s) {
3858         const char *p;
3859         bool dot;
3860
3861         if (isempty(s))
3862                 return false;
3863
3864         for (p = s, dot = true; *p; p++) {
3865                 if (*p == '.') {
3866                         if (dot)
3867                                 return false;
3868
3869                         dot = true;
3870                 } else {
3871                         if (!hostname_valid_char(*p))
3872                                 return false;
3873
3874                         dot = false;
3875                 }
3876         }
3877
3878         if (dot)
3879                 return false;
3880
3881         if (p-s > HOST_NAME_MAX)
3882                 return false;
3883
3884         return true;
3885 }
3886
3887 char* hostname_cleanup(char *s, bool lowercase) {
3888         char *p, *d;
3889         bool dot;
3890
3891         for (p = s, d = s, dot = true; *p; p++) {
3892                 if (*p == '.') {
3893                         if (dot)
3894                                 continue;
3895
3896                         *(d++) = '.';
3897                         dot = true;
3898                 } else if (hostname_valid_char(*p)) {
3899                         *(d++) = lowercase ? tolower(*p) : *p;
3900                         dot = false;
3901                 }
3902
3903         }
3904
3905         if (dot && d > s)
3906                 d[-1] = 0;
3907         else
3908                 *d = 0;
3909
3910         strshorten(s, HOST_NAME_MAX);
3911
3912         return s;
3913 }
3914
3915 int pipe_eof(int fd) {
3916         struct pollfd pollfd = {
3917                 .fd = fd,
3918                 .events = POLLIN|POLLHUP,
3919         };
3920
3921         int r;
3922
3923         r = poll(&pollfd, 1, 0);
3924         if (r < 0)
3925                 return -errno;
3926
3927         if (r == 0)
3928                 return 0;
3929
3930         return pollfd.revents & POLLHUP;
3931 }
3932
3933 int fd_wait_for_event(int fd, int event, usec_t t) {
3934
3935         struct pollfd pollfd = {
3936                 .fd = fd,
3937                 .events = event,
3938         };
3939
3940         struct timespec ts;
3941         int r;
3942
3943         r = ppoll(&pollfd, 1, t == (usec_t) -1 ? NULL : timespec_store(&ts, t), NULL);
3944         if (r < 0)
3945                 return -errno;
3946
3947         if (r == 0)
3948                 return 0;
3949
3950         return pollfd.revents;
3951 }
3952
3953 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3954         FILE *f;
3955         char *t;
3956         const char *fn;
3957         size_t k;
3958         int fd;
3959
3960         assert(path);
3961         assert(_f);
3962         assert(_temp_path);
3963
3964         t = new(char, strlen(path) + 1 + 6 + 1);
3965         if (!t)
3966                 return -ENOMEM;
3967
3968         fn = basename(path);
3969         k = fn - path;
3970         memcpy(t, path, k);
3971         t[k] = '.';
3972         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3973
3974         fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3975         if (fd < 0) {
3976                 free(t);
3977                 return -errno;
3978         }
3979
3980         f = fdopen(fd, "we");
3981         if (!f) {
3982                 unlink(t);
3983                 free(t);
3984                 return -errno;
3985         }
3986
3987         *_f = f;
3988         *_temp_path = t;
3989
3990         return 0;
3991 }
3992
3993 int terminal_vhangup_fd(int fd) {
3994         assert(fd >= 0);
3995
3996         if (ioctl(fd, TIOCVHANGUP) < 0)
3997                 return -errno;
3998
3999         return 0;
4000 }
4001
4002 int terminal_vhangup(const char *name) {
4003         int fd, r;
4004
4005         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4006         if (fd < 0)
4007                 return fd;
4008
4009         r = terminal_vhangup_fd(fd);
4010         close_nointr_nofail(fd);
4011
4012         return r;
4013 }
4014
4015 int vt_disallocate(const char *name) {
4016         int fd, r;
4017         unsigned u;
4018
4019         /* Deallocate the VT if possible. If not possible
4020          * (i.e. because it is the active one), at least clear it
4021          * entirely (including the scrollback buffer) */
4022
4023         if (!startswith(name, "/dev/"))
4024                 return -EINVAL;
4025
4026         if (!tty_is_vc(name)) {
4027                 /* So this is not a VT. I guess we cannot deallocate
4028                  * it then. But let's at least clear the screen */
4029
4030                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4031                 if (fd < 0)
4032                         return fd;
4033
4034                 loop_write(fd,
4035                            "\033[r"    /* clear scrolling region */
4036                            "\033[H"    /* move home */
4037                            "\033[2J",  /* clear screen */
4038                            10, false);
4039                 close_nointr_nofail(fd);
4040
4041                 return 0;
4042         }
4043
4044         if (!startswith(name, "/dev/tty"))
4045                 return -EINVAL;
4046
4047         r = safe_atou(name+8, &u);
4048         if (r < 0)
4049                 return r;
4050
4051         if (u <= 0)
4052                 return -EINVAL;
4053
4054         /* Try to deallocate */
4055         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4056         if (fd < 0)
4057                 return fd;
4058
4059         r = ioctl(fd, VT_DISALLOCATE, u);
4060         close_nointr_nofail(fd);
4061
4062         if (r >= 0)
4063                 return 0;
4064
4065         if (errno != EBUSY)
4066                 return -errno;
4067
4068         /* Couldn't deallocate, so let's clear it fully with
4069          * scrollback */
4070         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4071         if (fd < 0)
4072                 return fd;
4073
4074         loop_write(fd,
4075                    "\033[r"   /* clear scrolling region */
4076                    "\033[H"   /* move home */
4077                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4078                    10, false);
4079         close_nointr_nofail(fd);
4080
4081         return 0;
4082 }
4083
4084 int copy_file(const char *from, const char *to, int flags) {
4085         _cleanup_close_ int fdf = -1;
4086         int r, fdt;
4087
4088         assert(from);
4089         assert(to);
4090
4091         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4092         if (fdf < 0)
4093                 return -errno;
4094
4095         fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
4096         if (fdt < 0)
4097                 return -errno;
4098
4099         for (;;) {
4100                 char buf[PIPE_BUF];
4101                 ssize_t n, k;
4102
4103                 n = read(fdf, buf, sizeof(buf));
4104                 if (n < 0) {
4105                         r = -errno;
4106
4107                         close_nointr(fdt);
4108                         unlink(to);
4109
4110                         return r;
4111                 }
4112
4113                 if (n == 0)
4114                         break;
4115
4116                 errno = 0;
4117                 k = loop_write(fdt, buf, n, false);
4118                 if (n != k) {
4119                         r = k < 0 ? k : (errno ? -errno : -EIO);
4120
4121                         close_nointr(fdt);
4122                         unlink(to);
4123
4124                         return r;
4125                 }
4126         }
4127
4128         r = close_nointr(fdt);
4129
4130         if (r < 0) {
4131                 unlink(to);
4132                 return r;
4133         }
4134
4135         return 0;
4136 }
4137
4138 int symlink_atomic(const char *from, const char *to) {
4139         char *x;
4140         _cleanup_free_ char *t;
4141         const char *fn;
4142         size_t k;
4143         uint64_t u;
4144         unsigned i;
4145         int r;
4146
4147         assert(from);
4148         assert(to);
4149
4150         t = new(char, strlen(to) + 1 + 16 + 1);
4151         if (!t)
4152                 return -ENOMEM;
4153
4154         fn = basename(to);
4155         k = fn-to;
4156         memcpy(t, to, k);
4157         t[k] = '.';
4158         x = stpcpy(t+k+1, fn);
4159
4160         u = random_u64();
4161         for (i = 0; i < 16; i++) {
4162                 *(x++) = hexchar(u & 0xF);
4163                 u >>= 4;
4164         }
4165
4166         *x = 0;
4167
4168         if (symlink(from, t) < 0)
4169                 return -errno;
4170
4171         if (rename(t, to) < 0) {
4172                 r = -errno;
4173                 unlink(t);
4174                 return r;
4175         }
4176
4177         return 0;
4178 }
4179
4180 bool display_is_local(const char *display) {
4181         assert(display);
4182
4183         return
4184                 display[0] == ':' &&
4185                 display[1] >= '0' &&
4186                 display[1] <= '9';
4187 }
4188
4189 int socket_from_display(const char *display, char **path) {
4190         size_t k;
4191         char *f, *c;
4192
4193         assert(display);
4194         assert(path);
4195
4196         if (!display_is_local(display))
4197                 return -EINVAL;
4198
4199         k = strspn(display+1, "0123456789");
4200
4201         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4202         if (!f)
4203                 return -ENOMEM;
4204
4205         c = stpcpy(f, "/tmp/.X11-unix/X");
4206         memcpy(c, display+1, k);
4207         c[k] = 0;
4208
4209         *path = f;
4210
4211         return 0;
4212 }
4213
4214 int get_user_creds(
4215                 const char **username,
4216                 uid_t *uid, gid_t *gid,
4217                 const char **home,
4218                 const char **shell) {
4219
4220         struct passwd *p;
4221         uid_t u;
4222
4223         assert(username);
4224         assert(*username);
4225
4226         /* We enforce some special rules for uid=0: in order to avoid
4227          * NSS lookups for root we hardcode its data. */
4228
4229         if (streq(*username, "root") || streq(*username, "0")) {
4230                 *username = "root";
4231
4232                 if (uid)
4233                         *uid = 0;
4234
4235                 if (gid)
4236                         *gid = 0;
4237
4238                 if (home)
4239                         *home = "/root";
4240
4241                 if (shell)
4242                         *shell = "/bin/sh";
4243
4244                 return 0;
4245         }
4246
4247         if (parse_uid(*username, &u) >= 0) {
4248                 errno = 0;
4249                 p = getpwuid(u);
4250
4251                 /* If there are multiple users with the same id, make
4252                  * sure to leave $USER to the configured value instead
4253                  * of the first occurrence in the database. However if
4254                  * the uid was configured by a numeric uid, then let's
4255                  * pick the real username from /etc/passwd. */
4256                 if (p)
4257                         *username = p->pw_name;
4258         } else {
4259                 errno = 0;
4260                 p = getpwnam(*username);
4261         }
4262
4263         if (!p)
4264                 return errno > 0 ? -errno : -ESRCH;
4265
4266         if (uid)
4267                 *uid = p->pw_uid;
4268
4269         if (gid)
4270                 *gid = p->pw_gid;
4271
4272         if (home)
4273                 *home = p->pw_dir;
4274
4275         if (shell)
4276                 *shell = p->pw_shell;
4277
4278         return 0;
4279 }
4280
4281 char* uid_to_name(uid_t uid) {
4282         struct passwd *p;
4283         char *r;
4284
4285         if (uid == 0)
4286                 return strdup("root");
4287
4288         p = getpwuid(uid);
4289         if (p)
4290                 return strdup(p->pw_name);
4291
4292         if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4293                 return NULL;
4294
4295         return r;
4296 }
4297
4298 char* gid_to_name(gid_t gid) {
4299         struct group *p;
4300         char *r;
4301
4302         if (gid == 0)
4303                 return strdup("root");
4304
4305         p = getgrgid(gid);
4306         if (p)
4307                 return strdup(p->gr_name);
4308
4309         if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4310                 return NULL;
4311
4312         return r;
4313 }
4314
4315 int get_group_creds(const char **groupname, gid_t *gid) {
4316         struct group *g;
4317         gid_t id;
4318
4319         assert(groupname);
4320
4321         /* We enforce some special rules for gid=0: in order to avoid
4322          * NSS lookups for root we hardcode its data. */
4323
4324         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4325                 *groupname = "root";
4326
4327                 if (gid)
4328                         *gid = 0;
4329
4330                 return 0;
4331         }
4332
4333         if (parse_gid(*groupname, &id) >= 0) {
4334                 errno = 0;
4335                 g = getgrgid(id);
4336
4337                 if (g)
4338                         *groupname = g->gr_name;
4339         } else {
4340                 errno = 0;
4341                 g = getgrnam(*groupname);
4342         }
4343
4344         if (!g)
4345                 return errno > 0 ? -errno : -ESRCH;
4346
4347         if (gid)
4348                 *gid = g->gr_gid;
4349
4350         return 0;
4351 }
4352
4353 int in_gid(gid_t gid) {
4354         gid_t *gids;
4355         int ngroups_max, r, i;
4356
4357         if (getgid() == gid)
4358                 return 1;
4359
4360         if (getegid() == gid)
4361                 return 1;
4362
4363         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4364         assert(ngroups_max > 0);
4365
4366         gids = alloca(sizeof(gid_t) * ngroups_max);
4367
4368         r = getgroups(ngroups_max, gids);
4369         if (r < 0)
4370                 return -errno;
4371
4372         for (i = 0; i < r; i++)
4373                 if (gids[i] == gid)
4374                         return 1;
4375
4376         return 0;
4377 }
4378
4379 int in_group(const char *name) {
4380         int r;
4381         gid_t gid;
4382
4383         r = get_group_creds(&name, &gid);
4384         if (r < 0)
4385                 return r;
4386
4387         return in_gid(gid);
4388 }
4389
4390 int glob_exists(const char *path) {
4391         _cleanup_globfree_ glob_t g = {};
4392         int k;
4393
4394         assert(path);
4395
4396         errno = 0;
4397         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4398
4399         if (k == GLOB_NOMATCH)
4400                 return 0;
4401         else if (k == GLOB_NOSPACE)
4402                 return -ENOMEM;
4403         else if (k == 0)
4404                 return !strv_isempty(g.gl_pathv);
4405         else
4406                 return errno ? -errno : -EIO;
4407 }
4408
4409 int glob_extend(char ***strv, const char *path) {
4410         _cleanup_globfree_ glob_t g = {};
4411         int k;
4412         char **p;
4413
4414         errno = 0;
4415         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4416
4417         if (k == GLOB_NOMATCH)
4418                 return -ENOENT;
4419         else if (k == GLOB_NOSPACE)
4420                 return -ENOMEM;
4421         else if (k != 0 || strv_isempty(g.gl_pathv))
4422                 return errno ? -errno : -EIO;
4423
4424         STRV_FOREACH(p, g.gl_pathv) {
4425                 k = strv_extend(strv, *p);
4426                 if (k < 0)
4427                         break;
4428         }
4429
4430         return k;
4431 }
4432
4433 int dirent_ensure_type(DIR *d, struct dirent *de) {
4434         struct stat st;
4435
4436         assert(d);
4437         assert(de);
4438
4439         if (de->d_type != DT_UNKNOWN)
4440                 return 0;
4441
4442         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4443                 return -errno;
4444
4445         de->d_type =
4446                 S_ISREG(st.st_mode)  ? DT_REG  :
4447                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4448                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4449                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4450                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4451                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4452                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4453                                        DT_UNKNOWN;
4454
4455         return 0;
4456 }
4457
4458 int in_search_path(const char *path, char **search) {
4459         char **i;
4460         _cleanup_free_ char *parent = NULL;
4461         int r;
4462
4463         r = path_get_parent(path, &parent);
4464         if (r < 0)
4465                 return r;
4466
4467         STRV_FOREACH(i, search)
4468                 if (path_equal(parent, *i))
4469                         return 1;
4470
4471         return 0;
4472 }
4473
4474 int get_files_in_directory(const char *path, char ***list) {
4475         _cleanup_closedir_ DIR *d = NULL;
4476         size_t bufsize = 0, n = 0;
4477         _cleanup_strv_free_ char **l = NULL;
4478
4479         assert(path);
4480
4481         /* Returns all files in a directory in *list, and the number
4482          * of files as return value. If list is NULL returns only the
4483          * number. */
4484
4485         d = opendir(path);
4486         if (!d)
4487                 return -errno;
4488
4489         for (;;) {
4490                 struct dirent *de;
4491
4492                 errno = 0;
4493                 de = readdir(d);
4494                 if (!de && errno != 0)
4495                         return -errno;
4496                 if (!de)
4497                         break;
4498
4499                 dirent_ensure_type(d, de);
4500
4501                 if (!dirent_is_file(de))
4502                         continue;
4503
4504                 if (list) {
4505                         /* one extra slot is needed for the terminating NULL */
4506                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
4507                                 return -ENOMEM;
4508
4509                         l[n] = strdup(de->d_name);
4510                         if (!l[n])
4511                                 return -ENOMEM;
4512
4513                         l[++n] = NULL;
4514                 } else
4515                         n++;
4516         }
4517
4518         if (list) {
4519                 *list = l;
4520                 l = NULL; /* avoid freeing */
4521         }
4522
4523         return n;
4524 }
4525
4526 char *strjoin(const char *x, ...) {
4527         va_list ap;
4528         size_t l;
4529         char *r, *p;
4530
4531         va_start(ap, x);
4532
4533         if (x) {
4534                 l = strlen(x);
4535
4536                 for (;;) {
4537                         const char *t;
4538                         size_t n;
4539
4540                         t = va_arg(ap, const char *);
4541                         if (!t)
4542                                 break;
4543
4544                         n = strlen(t);
4545                         if (n > ((size_t) -1) - l) {
4546                                 va_end(ap);
4547                                 return NULL;
4548                         }
4549
4550                         l += n;
4551                 }
4552         } else
4553                 l = 0;
4554
4555         va_end(ap);
4556
4557         r = new(char, l+1);
4558         if (!r)
4559                 return NULL;
4560
4561         if (x) {
4562                 p = stpcpy(r, x);
4563
4564                 va_start(ap, x);
4565
4566                 for (;;) {
4567                         const char *t;
4568
4569                         t = va_arg(ap, const char *);
4570                         if (!t)
4571                                 break;
4572
4573                         p = stpcpy(p, t);
4574                 }
4575
4576                 va_end(ap);
4577         } else
4578                 r[0] = 0;
4579
4580         return r;
4581 }
4582
4583 bool is_main_thread(void) {
4584         static thread_local int cached = 0;
4585
4586         if (_unlikely_(cached == 0))
4587                 cached = getpid() == gettid() ? 1 : -1;
4588
4589         return cached > 0;
4590 }
4591
4592 int block_get_whole_disk(dev_t d, dev_t *ret) {
4593         char *p, *s;
4594         int r;
4595         unsigned n, m;
4596
4597         assert(ret);
4598
4599         /* If it has a queue this is good enough for us */
4600         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4601                 return -ENOMEM;
4602
4603         r = access(p, F_OK);
4604         free(p);
4605
4606         if (r >= 0) {
4607                 *ret = d;
4608                 return 0;
4609         }
4610
4611         /* If it is a partition find the originating device */
4612         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4613                 return -ENOMEM;
4614
4615         r = access(p, F_OK);
4616         free(p);
4617
4618         if (r < 0)
4619                 return -ENOENT;
4620
4621         /* Get parent dev_t */
4622         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4623                 return -ENOMEM;
4624
4625         r = read_one_line_file(p, &s);
4626         free(p);
4627
4628         if (r < 0)
4629                 return r;
4630
4631         r = sscanf(s, "%u:%u", &m, &n);
4632         free(s);
4633
4634         if (r != 2)
4635                 return -EINVAL;
4636
4637         /* Only return this if it is really good enough for us. */
4638         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4639                 return -ENOMEM;
4640
4641         r = access(p, F_OK);
4642         free(p);
4643
4644         if (r >= 0) {
4645                 *ret = makedev(m, n);
4646                 return 0;
4647         }
4648
4649         return -ENOENT;
4650 }
4651
4652 int file_is_priv_sticky(const char *p) {
4653         struct stat st;
4654
4655         assert(p);
4656
4657         if (lstat(p, &st) < 0)
4658                 return -errno;
4659
4660         return
4661                 (st.st_uid == 0 || st.st_uid == getuid()) &&
4662                 (st.st_mode & S_ISVTX);
4663 }
4664
4665 static const char *const ioprio_class_table[] = {
4666         [IOPRIO_CLASS_NONE] = "none",
4667         [IOPRIO_CLASS_RT] = "realtime",
4668         [IOPRIO_CLASS_BE] = "best-effort",
4669         [IOPRIO_CLASS_IDLE] = "idle"
4670 };
4671
4672 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4673
4674 static const char *const sigchld_code_table[] = {
4675         [CLD_EXITED] = "exited",
4676         [CLD_KILLED] = "killed",
4677         [CLD_DUMPED] = "dumped",
4678         [CLD_TRAPPED] = "trapped",
4679         [CLD_STOPPED] = "stopped",
4680         [CLD_CONTINUED] = "continued",
4681 };
4682
4683 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4684
4685 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4686         [LOG_FAC(LOG_KERN)] = "kern",
4687         [LOG_FAC(LOG_USER)] = "user",
4688         [LOG_FAC(LOG_MAIL)] = "mail",
4689         [LOG_FAC(LOG_DAEMON)] = "daemon",
4690         [LOG_FAC(LOG_AUTH)] = "auth",
4691         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4692         [LOG_FAC(LOG_LPR)] = "lpr",
4693         [LOG_FAC(LOG_NEWS)] = "news",
4694         [LOG_FAC(LOG_UUCP)] = "uucp",
4695         [LOG_FAC(LOG_CRON)] = "cron",
4696         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4697         [LOG_FAC(LOG_FTP)] = "ftp",
4698         [LOG_FAC(LOG_LOCAL0)] = "local0",
4699         [LOG_FAC(LOG_LOCAL1)] = "local1",
4700         [LOG_FAC(LOG_LOCAL2)] = "local2",
4701         [LOG_FAC(LOG_LOCAL3)] = "local3",
4702         [LOG_FAC(LOG_LOCAL4)] = "local4",
4703         [LOG_FAC(LOG_LOCAL5)] = "local5",
4704         [LOG_FAC(LOG_LOCAL6)] = "local6",
4705         [LOG_FAC(LOG_LOCAL7)] = "local7"
4706 };
4707
4708 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4709
4710 static const char *const log_level_table[] = {
4711         [LOG_EMERG] = "emerg",
4712         [LOG_ALERT] = "alert",
4713         [LOG_CRIT] = "crit",
4714         [LOG_ERR] = "err",
4715         [LOG_WARNING] = "warning",
4716         [LOG_NOTICE] = "notice",
4717         [LOG_INFO] = "info",
4718         [LOG_DEBUG] = "debug"
4719 };
4720
4721 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4722
4723 static const char* const sched_policy_table[] = {
4724         [SCHED_OTHER] = "other",
4725         [SCHED_BATCH] = "batch",
4726         [SCHED_IDLE] = "idle",
4727         [SCHED_FIFO] = "fifo",
4728         [SCHED_RR] = "rr"
4729 };
4730
4731 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4732
4733 static const char* const rlimit_table[_RLIMIT_MAX] = {
4734         [RLIMIT_CPU] = "LimitCPU",
4735         [RLIMIT_FSIZE] = "LimitFSIZE",
4736         [RLIMIT_DATA] = "LimitDATA",
4737         [RLIMIT_STACK] = "LimitSTACK",
4738         [RLIMIT_CORE] = "LimitCORE",
4739         [RLIMIT_RSS] = "LimitRSS",
4740         [RLIMIT_NOFILE] = "LimitNOFILE",
4741         [RLIMIT_AS] = "LimitAS",
4742         [RLIMIT_NPROC] = "LimitNPROC",
4743         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4744         [RLIMIT_LOCKS] = "LimitLOCKS",
4745         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4746         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4747         [RLIMIT_NICE] = "LimitNICE",
4748         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4749         [RLIMIT_RTTIME] = "LimitRTTIME"
4750 };
4751
4752 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4753
4754 static const char* const ip_tos_table[] = {
4755         [IPTOS_LOWDELAY] = "low-delay",
4756         [IPTOS_THROUGHPUT] = "throughput",
4757         [IPTOS_RELIABILITY] = "reliability",
4758         [IPTOS_LOWCOST] = "low-cost",
4759 };
4760
4761 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4762
4763 static const char *const __signal_table[] = {
4764         [SIGHUP] = "HUP",
4765         [SIGINT] = "INT",
4766         [SIGQUIT] = "QUIT",
4767         [SIGILL] = "ILL",
4768         [SIGTRAP] = "TRAP",
4769         [SIGABRT] = "ABRT",
4770         [SIGBUS] = "BUS",
4771         [SIGFPE] = "FPE",
4772         [SIGKILL] = "KILL",
4773         [SIGUSR1] = "USR1",
4774         [SIGSEGV] = "SEGV",
4775         [SIGUSR2] = "USR2",
4776         [SIGPIPE] = "PIPE",
4777         [SIGALRM] = "ALRM",
4778         [SIGTERM] = "TERM",
4779 #ifdef SIGSTKFLT
4780         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4781 #endif
4782         [SIGCHLD] = "CHLD",
4783         [SIGCONT] = "CONT",
4784         [SIGSTOP] = "STOP",
4785         [SIGTSTP] = "TSTP",
4786         [SIGTTIN] = "TTIN",
4787         [SIGTTOU] = "TTOU",
4788         [SIGURG] = "URG",
4789         [SIGXCPU] = "XCPU",
4790         [SIGXFSZ] = "XFSZ",
4791         [SIGVTALRM] = "VTALRM",
4792         [SIGPROF] = "PROF",
4793         [SIGWINCH] = "WINCH",
4794         [SIGIO] = "IO",
4795         [SIGPWR] = "PWR",
4796         [SIGSYS] = "SYS"
4797 };
4798
4799 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4800
4801 const char *signal_to_string(int signo) {
4802         static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4803         const char *name;
4804
4805         name = __signal_to_string(signo);
4806         if (name)
4807                 return name;
4808
4809         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4810                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4811         else
4812                 snprintf(buf, sizeof(buf), "%d", signo);
4813
4814         return buf;
4815 }
4816
4817 int signal_from_string(const char *s) {
4818         int signo;
4819         int offset = 0;
4820         unsigned u;
4821
4822         signo = __signal_from_string(s);
4823         if (signo > 0)
4824                 return signo;
4825
4826         if (startswith(s, "RTMIN+")) {
4827                 s += 6;
4828                 offset = SIGRTMIN;
4829         }
4830         if (safe_atou(s, &u) >= 0) {
4831                 signo = (int) u + offset;
4832                 if (signo > 0 && signo < _NSIG)
4833                         return signo;
4834         }
4835         return -1;
4836 }
4837
4838 bool kexec_loaded(void) {
4839        bool loaded = false;
4840        char *s;
4841
4842        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4843                if (s[0] == '1')
4844                        loaded = true;
4845                free(s);
4846        }
4847        return loaded;
4848 }
4849
4850 int strdup_or_null(const char *a, char **b) {
4851         char *c;
4852
4853         assert(b);
4854
4855         if (!a) {
4856                 *b = NULL;
4857                 return 0;
4858         }
4859
4860         c = strdup(a);
4861         if (!c)
4862                 return -ENOMEM;
4863
4864         *b = c;
4865         return 0;
4866 }
4867
4868 int prot_from_flags(int flags) {
4869
4870         switch (flags & O_ACCMODE) {
4871
4872         case O_RDONLY:
4873                 return PROT_READ;
4874
4875         case O_WRONLY:
4876                 return PROT_WRITE;
4877
4878         case O_RDWR:
4879                 return PROT_READ|PROT_WRITE;
4880
4881         default:
4882                 return -EINVAL;
4883         }
4884 }
4885
4886 char *format_bytes(char *buf, size_t l, off_t t) {
4887         unsigned i;
4888
4889         static const struct {
4890                 const char *suffix;
4891                 off_t factor;
4892         } table[] = {
4893                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4894                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4895                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4896                 { "G", 1024ULL*1024ULL*1024ULL },
4897                 { "M", 1024ULL*1024ULL },
4898                 { "K", 1024ULL },
4899         };
4900
4901         for (i = 0; i < ELEMENTSOF(table); i++) {
4902
4903                 if (t >= table[i].factor) {
4904                         snprintf(buf, l,
4905                                  "%llu.%llu%s",
4906                                  (unsigned long long) (t / table[i].factor),
4907                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4908                                  table[i].suffix);
4909
4910                         goto finish;
4911                 }
4912         }
4913
4914         snprintf(buf, l, "%lluB", (unsigned long long) t);
4915
4916 finish:
4917         buf[l-1] = 0;
4918         return buf;
4919
4920 }
4921
4922 void* memdup(const void *p, size_t l) {
4923         void *r;
4924
4925         assert(p);
4926
4927         r = malloc(l);
4928         if (!r)
4929                 return NULL;
4930
4931         memcpy(r, p, l);
4932         return r;
4933 }
4934
4935 int fd_inc_sndbuf(int fd, size_t n) {
4936         int r, value;
4937         socklen_t l = sizeof(value);
4938
4939         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4940         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4941                 return 0;
4942
4943         /* If we have the privileges we will ignore the kernel limit. */
4944
4945         value = (int) n;
4946         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
4947                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
4948                         return -errno;
4949
4950         return 1;
4951 }
4952
4953 int fd_inc_rcvbuf(int fd, size_t n) {
4954         int r, value;
4955         socklen_t l = sizeof(value);
4956
4957         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4958         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4959                 return 0;
4960
4961         /* If we have the privileges we will ignore the kernel limit. */
4962
4963         value = (int) n;
4964         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
4965                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
4966                         return -errno;
4967         return 1;
4968 }
4969
4970 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4971         pid_t parent_pid, agent_pid;
4972         int fd;
4973         bool stdout_is_tty, stderr_is_tty;
4974         unsigned n, i;
4975         va_list ap;
4976         char **l;
4977
4978         assert(pid);
4979         assert(path);
4980
4981         parent_pid = getpid();
4982
4983         /* Spawns a temporary TTY agent, making sure it goes away when
4984          * we go away */
4985
4986         agent_pid = fork();
4987         if (agent_pid < 0)
4988                 return -errno;
4989
4990         if (agent_pid != 0) {
4991                 *pid = agent_pid;
4992                 return 0;
4993         }
4994
4995         /* In the child:
4996          *
4997          * Make sure the agent goes away when the parent dies */
4998         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4999                 _exit(EXIT_FAILURE);
5000
5001         /* Check whether our parent died before we were able
5002          * to set the death signal */
5003         if (getppid() != parent_pid)
5004                 _exit(EXIT_SUCCESS);
5005
5006         /* Don't leak fds to the agent */
5007         close_all_fds(except, n_except);
5008
5009         stdout_is_tty = isatty(STDOUT_FILENO);
5010         stderr_is_tty = isatty(STDERR_FILENO);
5011
5012         if (!stdout_is_tty || !stderr_is_tty) {
5013                 /* Detach from stdout/stderr. and reopen
5014                  * /dev/tty for them. This is important to
5015                  * ensure that when systemctl is started via
5016                  * popen() or a similar call that expects to
5017                  * read EOF we actually do generate EOF and
5018                  * not delay this indefinitely by because we
5019                  * keep an unused copy of stdin around. */
5020                 fd = open("/dev/tty", O_WRONLY);
5021                 if (fd < 0) {
5022                         log_error("Failed to open /dev/tty: %m");
5023                         _exit(EXIT_FAILURE);
5024                 }
5025
5026                 if (!stdout_is_tty)
5027                         dup2(fd, STDOUT_FILENO);
5028
5029                 if (!stderr_is_tty)
5030                         dup2(fd, STDERR_FILENO);
5031
5032                 if (fd > 2)
5033                         close(fd);
5034         }
5035
5036         /* Count arguments */
5037         va_start(ap, path);
5038         for (n = 0; va_arg(ap, char*); n++)
5039                 ;
5040         va_end(ap);
5041
5042         /* Allocate strv */
5043         l = alloca(sizeof(char *) * (n + 1));
5044
5045         /* Fill in arguments */
5046         va_start(ap, path);
5047         for (i = 0; i <= n; i++)
5048                 l[i] = va_arg(ap, char*);
5049         va_end(ap);
5050
5051         execv(path, l);
5052         _exit(EXIT_FAILURE);
5053 }
5054
5055 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5056         struct rlimit highest, fixed;
5057
5058         assert(rlim);
5059
5060         if (setrlimit(resource, rlim) >= 0)
5061                 return 0;
5062
5063         if (errno != EPERM)
5064                 return -errno;
5065
5066         /* So we failed to set the desired setrlimit, then let's try
5067          * to get as close as we can */
5068         assert_se(getrlimit(resource, &highest) == 0);
5069
5070         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5071         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5072
5073         if (setrlimit(resource, &fixed) < 0)
5074                 return -errno;
5075
5076         return 0;
5077 }
5078
5079 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5080         _cleanup_fclose_ FILE *f = NULL;
5081         char *value = NULL;
5082         int r;
5083         bool done = false;
5084         size_t l;
5085         const char *path;
5086
5087         assert(pid >= 0);
5088         assert(field);
5089         assert(_value);
5090
5091         path = procfs_file_alloca(pid, "environ");
5092
5093         f = fopen(path, "re");
5094         if (!f)
5095                 return -errno;
5096
5097         l = strlen(field);
5098         r = 0;
5099
5100         do {
5101                 char line[LINE_MAX];
5102                 unsigned i;
5103
5104                 for (i = 0; i < sizeof(line)-1; i++) {
5105                         int c;
5106
5107                         c = getc(f);
5108                         if (_unlikely_(c == EOF)) {
5109                                 done = true;
5110                                 break;
5111                         } else if (c == 0)
5112                                 break;
5113
5114                         line[i] = c;
5115                 }
5116                 line[i] = 0;
5117
5118                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5119                         value = strdup(line + l + 1);
5120                         if (!value)
5121                                 return -ENOMEM;
5122
5123                         r = 1;
5124                         break;
5125                 }
5126
5127         } while (!done);
5128
5129         *_value = value;
5130         return r;
5131 }
5132
5133 bool is_valid_documentation_url(const char *url) {
5134         assert(url);
5135
5136         if (startswith(url, "http://") && url[7])
5137                 return true;
5138
5139         if (startswith(url, "https://") && url[8])
5140                 return true;
5141
5142         if (startswith(url, "file:") && url[5])
5143                 return true;
5144
5145         if (startswith(url, "info:") && url[5])
5146                 return true;
5147
5148         if (startswith(url, "man:") && url[4])
5149                 return true;
5150
5151         return false;
5152 }
5153
5154 bool in_initrd(void) {
5155         static int saved = -1;
5156         struct statfs s;
5157
5158         if (saved >= 0)
5159                 return saved;
5160
5161         /* We make two checks here:
5162          *
5163          * 1. the flag file /etc/initrd-release must exist
5164          * 2. the root file system must be a memory file system
5165          *
5166          * The second check is extra paranoia, since misdetecting an
5167          * initrd can have bad bad consequences due the initrd
5168          * emptying when transititioning to the main systemd.
5169          */
5170
5171         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5172                 statfs("/", &s) >= 0 &&
5173                 is_temporary_fs(&s);
5174
5175         return saved;
5176 }
5177
5178 void warn_melody(void) {
5179         _cleanup_close_ int fd = -1;
5180
5181         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5182         if (fd < 0)
5183                 return;
5184
5185         /* Yeah, this is synchronous. Kinda sucks. But well... */
5186
5187         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5188         usleep(125*USEC_PER_MSEC);
5189
5190         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5191         usleep(125*USEC_PER_MSEC);
5192
5193         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5194         usleep(125*USEC_PER_MSEC);
5195
5196         ioctl(fd, KIOCSOUND, 0);
5197 }
5198
5199 int make_console_stdio(void) {
5200         int fd, r;
5201
5202         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5203
5204         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5205         if (fd < 0) {
5206                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5207                 return fd;
5208         }
5209
5210         r = make_stdio(fd);
5211         if (r < 0) {
5212                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5213                 return r;
5214         }
5215
5216         return 0;
5217 }
5218
5219 int get_home_dir(char **_h) {
5220         struct passwd *p;
5221         const char *e;
5222         char *h;
5223         uid_t u;
5224
5225         assert(_h);
5226
5227         /* Take the user specified one */
5228         e = getenv("HOME");
5229         if (e) {
5230                 h = strdup(e);
5231                 if (!h)
5232                         return -ENOMEM;
5233
5234                 *_h = h;
5235                 return 0;
5236         }
5237
5238         /* Hardcode home directory for root to avoid NSS */
5239         u = getuid();
5240         if (u == 0) {
5241                 h = strdup("/root");
5242                 if (!h)
5243                         return -ENOMEM;
5244
5245                 *_h = h;
5246                 return 0;
5247         }
5248
5249         /* Check the database... */
5250         errno = 0;
5251         p = getpwuid(u);
5252         if (!p)
5253                 return errno > 0 ? -errno : -ESRCH;
5254
5255         if (!path_is_absolute(p->pw_dir))
5256                 return -EINVAL;
5257
5258         h = strdup(p->pw_dir);
5259         if (!h)
5260                 return -ENOMEM;
5261
5262         *_h = h;
5263         return 0;
5264 }
5265
5266 int get_shell(char **_s) {
5267         struct passwd *p;
5268         const char *e;
5269         char *s;
5270         uid_t u;
5271
5272         assert(_s);
5273
5274         /* Take the user specified one */
5275         e = getenv("SHELL");
5276         if (e) {
5277                 s = strdup(e);
5278                 if (!s)
5279                         return -ENOMEM;
5280
5281                 *_s = s;
5282                 return 0;
5283         }
5284
5285         /* Hardcode home directory for root to avoid NSS */
5286         u = getuid();
5287         if (u == 0) {
5288                 s = strdup("/bin/sh");
5289                 if (!s)
5290                         return -ENOMEM;
5291
5292                 *_s = s;
5293                 return 0;
5294         }
5295
5296         /* Check the database... */
5297         errno = 0;
5298         p = getpwuid(u);
5299         if (!p)
5300                 return errno > 0 ? -errno : -ESRCH;
5301
5302         if (!path_is_absolute(p->pw_shell))
5303                 return -EINVAL;
5304
5305         s = strdup(p->pw_shell);
5306         if (!s)
5307                 return -ENOMEM;
5308
5309         *_s = s;
5310         return 0;
5311 }
5312
5313 bool filename_is_safe(const char *p) {
5314
5315         if (isempty(p))
5316                 return false;
5317
5318         if (strchr(p, '/'))
5319                 return false;
5320
5321         if (streq(p, "."))
5322                 return false;
5323
5324         if (streq(p, ".."))
5325                 return false;
5326
5327         if (strlen(p) > FILENAME_MAX)
5328                 return false;
5329
5330         return true;
5331 }
5332
5333 bool string_is_safe(const char *p) {
5334         const char *t;
5335
5336         assert(p);
5337
5338         for (t = p; *t; t++) {
5339                 if (*t > 0 && *t < ' ')
5340                         return false;
5341
5342                 if (strchr("\\\"\'", *t))
5343                         return false;
5344         }
5345
5346         return true;
5347 }
5348
5349 /**
5350  * Check if a string contains control characters.
5351  * Spaces and tabs are not considered control characters.
5352  */
5353 bool string_has_cc(const char *p) {
5354         const char *t;
5355
5356         assert(p);
5357
5358         for (t = p; *t; t++)
5359                 if (*t > 0 && *t < ' ' && *t != '\t')
5360                         return true;
5361
5362         return false;
5363 }
5364
5365 bool path_is_safe(const char *p) {
5366
5367         if (isempty(p))
5368                 return false;
5369
5370         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5371                 return false;
5372
5373         if (strlen(p) > PATH_MAX)
5374                 return false;
5375
5376         /* The following two checks are not really dangerous, but hey, they still are confusing */
5377         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5378                 return false;
5379
5380         if (strstr(p, "//"))
5381                 return false;
5382
5383         return true;
5384 }
5385
5386 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5387 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5388                  int (*compar) (const void *, const void *, void *), void *arg) {
5389         size_t l, u, idx;
5390         const void *p;
5391         int comparison;
5392
5393         l = 0;
5394         u = nmemb;
5395         while (l < u) {
5396                 idx = (l + u) / 2;
5397                 p = (void *)(((const char *) base) + (idx * size));
5398                 comparison = compar(key, p, arg);
5399                 if (comparison < 0)
5400                         u = idx;
5401                 else if (comparison > 0)
5402                         l = idx + 1;
5403                 else
5404                         return (void *)p;
5405         }
5406         return NULL;
5407 }
5408
5409 bool is_locale_utf8(void) {
5410         const char *set;
5411         static int cached_answer = -1;
5412
5413         if (cached_answer >= 0)
5414                 goto out;
5415
5416         if (!setlocale(LC_ALL, "")) {
5417                 cached_answer = true;
5418                 goto out;
5419         }
5420
5421         set = nl_langinfo(CODESET);
5422         if (!set) {
5423                 cached_answer = true;
5424                 goto out;
5425         }
5426
5427         if (streq(set, "UTF-8")) {
5428                 cached_answer = true;
5429                 goto out;
5430         }
5431
5432         /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5433          * unset and everything can do to UTF-8 nowadays. */
5434         set = setlocale(LC_CTYPE, NULL);
5435         if (!set) {
5436                 cached_answer = true;
5437                 goto out;
5438         }
5439
5440         /* Check result, but ignore the result if C was set
5441          * explicitly. */
5442         cached_answer =
5443                 streq(set, "C") &&
5444                 !getenv("LC_ALL") &&
5445                 !getenv("LC_CTYPE") &&
5446                 !getenv("LANG");
5447
5448 out:
5449         return (bool) cached_answer;
5450 }
5451
5452 const char *draw_special_char(DrawSpecialChar ch) {
5453         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5454                 /* UTF-8 */ {
5455                         [DRAW_TREE_VERT]          = "\342\224\202 ",            /* │  */
5456                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
5457                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
5458                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5459                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243 ",            /* ‣  */
5460                         [DRAW_BLACK_CIRCLE]       = "\342\227\217 ",            /* ●  */
5461                 },
5462                 /* ASCII fallback */ {
5463                         [DRAW_TREE_VERT]          = "| ",
5464                         [DRAW_TREE_BRANCH]        = "|-",
5465                         [DRAW_TREE_RIGHT]         = "`-",
5466                         [DRAW_TREE_SPACE]         = "  ",
5467                         [DRAW_TRIANGULAR_BULLET]  = "> ",
5468                         [DRAW_BLACK_CIRCLE]       = "* ",
5469                 }
5470         };
5471
5472         return draw_table[!is_locale_utf8()][ch];
5473 }
5474
5475 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5476         const char *f;
5477         char *t, *r;
5478         size_t l, old_len, new_len;
5479
5480         assert(text);
5481         assert(old_string);
5482         assert(new_string);
5483
5484         old_len = strlen(old_string);
5485         new_len = strlen(new_string);
5486
5487         l = strlen(text);
5488         r = new(char, l+1);
5489         if (!r)
5490                 return NULL;
5491
5492         f = text;
5493         t = r;
5494         while (*f) {
5495                 char *a;
5496                 size_t d, nl;
5497
5498                 if (!startswith(f, old_string)) {
5499                         *(t++) = *(f++);
5500                         continue;
5501                 }
5502
5503                 d = t - r;
5504                 nl = l - old_len + new_len;
5505                 a = realloc(r, nl + 1);
5506                 if (!a)
5507                         goto oom;
5508
5509                 l = nl;
5510                 r = a;
5511                 t = r + d;
5512
5513                 t = stpcpy(t, new_string);
5514                 f += old_len;
5515         }
5516
5517         *t = 0;
5518         return r;
5519
5520 oom:
5521         free(r);
5522         return NULL;
5523 }
5524
5525 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5526         const char *i, *begin = NULL;
5527         enum {
5528                 STATE_OTHER,
5529                 STATE_ESCAPE,
5530                 STATE_BRACKET
5531         } state = STATE_OTHER;
5532         char *obuf = NULL;
5533         size_t osz = 0, isz;
5534         FILE *f;
5535
5536         assert(ibuf);
5537         assert(*ibuf);
5538
5539         /* Strips ANSI color and replaces TABs by 8 spaces */
5540
5541         isz = _isz ? *_isz : strlen(*ibuf);
5542
5543         f = open_memstream(&obuf, &osz);
5544         if (!f)
5545                 return NULL;
5546
5547         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5548
5549                 switch (state) {
5550
5551                 case STATE_OTHER:
5552                         if (i >= *ibuf + isz) /* EOT */
5553                                 break;
5554                         else if (*i == '\x1B')
5555                                 state = STATE_ESCAPE;
5556                         else if (*i == '\t')
5557                                 fputs("        ", f);
5558                         else
5559                                 fputc(*i, f);
5560                         break;
5561
5562                 case STATE_ESCAPE:
5563                         if (i >= *ibuf + isz) { /* EOT */
5564                                 fputc('\x1B', f);
5565                                 break;
5566                         } else if (*i == '[') {
5567                                 state = STATE_BRACKET;
5568                                 begin = i + 1;
5569                         } else {
5570                                 fputc('\x1B', f);
5571                                 fputc(*i, f);
5572                                 state = STATE_OTHER;
5573                         }
5574
5575                         break;
5576
5577                 case STATE_BRACKET:
5578
5579                         if (i >= *ibuf + isz || /* EOT */
5580                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5581                                 fputc('\x1B', f);
5582                                 fputc('[', f);
5583                                 state = STATE_OTHER;
5584                                 i = begin-1;
5585                         } else if (*i == 'm')
5586                                 state = STATE_OTHER;
5587                         break;
5588                 }
5589         }
5590
5591         if (ferror(f)) {
5592                 fclose(f);
5593                 free(obuf);
5594                 return NULL;
5595         }
5596
5597         fclose(f);
5598
5599         free(*ibuf);
5600         *ibuf = obuf;
5601
5602         if (_isz)
5603                 *_isz = osz;
5604
5605         return obuf;
5606 }
5607
5608 int on_ac_power(void) {
5609         bool found_offline = false, found_online = false;
5610         _cleanup_closedir_ DIR *d = NULL;
5611
5612         d = opendir("/sys/class/power_supply");
5613         if (!d)
5614                 return -errno;
5615
5616         for (;;) {
5617                 struct dirent *de;
5618                 _cleanup_close_ int fd = -1, device = -1;
5619                 char contents[6];
5620                 ssize_t n;
5621
5622                 errno = 0;
5623                 de = readdir(d);
5624                 if (!de && errno != 0)
5625                         return -errno;
5626
5627                 if (!de)
5628                         break;
5629
5630                 if (ignore_file(de->d_name))
5631                         continue;
5632
5633                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5634                 if (device < 0) {
5635                         if (errno == ENOENT || errno == ENOTDIR)
5636                                 continue;
5637
5638                         return -errno;
5639                 }
5640
5641                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5642                 if (fd < 0) {
5643                         if (errno == ENOENT)
5644                                 continue;
5645
5646                         return -errno;
5647                 }
5648
5649                 n = read(fd, contents, sizeof(contents));
5650                 if (n < 0)
5651                         return -errno;
5652
5653                 if (n != 6 || memcmp(contents, "Mains\n", 6))
5654                         continue;
5655
5656                 close_nointr_nofail(fd);
5657                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5658                 if (fd < 0) {
5659                         if (errno == ENOENT)
5660                                 continue;
5661
5662                         return -errno;
5663                 }
5664
5665                 n = read(fd, contents, sizeof(contents));
5666                 if (n < 0)
5667                         return -errno;
5668
5669                 if (n != 2 || contents[1] != '\n')
5670                         return -EIO;
5671
5672                 if (contents[0] == '1') {
5673                         found_online = true;
5674                         break;
5675                 } else if (contents[0] == '0')
5676                         found_offline = true;
5677                 else
5678                         return -EIO;
5679         }
5680
5681         return found_online || !found_offline;
5682 }
5683
5684 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5685         char **i;
5686
5687         assert(path);
5688         assert(mode);
5689         assert(_f);
5690
5691         if (!path_strv_canonicalize_absolute_uniq(search, NULL))
5692                 return -ENOMEM;
5693
5694         STRV_FOREACH(i, search) {
5695                 _cleanup_free_ char *p = NULL;
5696                 FILE *f;
5697
5698                 p = strjoin(*i, "/", path, NULL);
5699                 if (!p)
5700                         return -ENOMEM;
5701
5702                 f = fopen(p, mode);
5703                 if (f) {
5704                         *_f = f;
5705                         return 0;
5706                 }
5707
5708                 if (errno != ENOENT)
5709                         return -errno;
5710         }
5711
5712         return -ENOENT;
5713 }
5714
5715 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5716         _cleanup_strv_free_ char **copy = NULL;
5717
5718         assert(path);
5719         assert(mode);
5720         assert(_f);
5721
5722         if (path_is_absolute(path)) {
5723                 FILE *f;
5724
5725                 f = fopen(path, mode);
5726                 if (f) {
5727                         *_f = f;
5728                         return 0;
5729                 }
5730
5731                 return -errno;
5732         }
5733
5734         copy = strv_copy((char**) search);
5735         if (!copy)
5736                 return -ENOMEM;
5737
5738         return search_and_fopen_internal(path, mode, copy, _f);
5739 }
5740
5741 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5742         _cleanup_strv_free_ char **s = NULL;
5743
5744         if (path_is_absolute(path)) {
5745                 FILE *f;
5746
5747                 f = fopen(path, mode);
5748                 if (f) {
5749                         *_f = f;
5750                         return 0;
5751                 }
5752
5753                 return -errno;
5754         }
5755
5756         s = strv_split_nulstr(search);
5757         if (!s)
5758                 return -ENOMEM;
5759
5760         return search_and_fopen_internal(path, mode, s, _f);
5761 }
5762
5763 char *strextend(char **x, ...) {
5764         va_list ap;
5765         size_t f, l;
5766         char *r, *p;
5767
5768         assert(x);
5769
5770         l = f = *x ? strlen(*x) : 0;
5771
5772         va_start(ap, x);
5773         for (;;) {
5774                 const char *t;
5775                 size_t n;
5776
5777                 t = va_arg(ap, const char *);
5778                 if (!t)
5779                         break;
5780
5781                 n = strlen(t);
5782                 if (n > ((size_t) -1) - l) {
5783                         va_end(ap);
5784                         return NULL;
5785                 }
5786
5787                 l += n;
5788         }
5789         va_end(ap);
5790
5791         r = realloc(*x, l+1);
5792         if (!r)
5793                 return NULL;
5794
5795         p = r + f;
5796
5797         va_start(ap, x);
5798         for (;;) {
5799                 const char *t;
5800
5801                 t = va_arg(ap, const char *);
5802                 if (!t)
5803                         break;
5804
5805                 p = stpcpy(p, t);
5806         }
5807         va_end(ap);
5808
5809         *p = 0;
5810         *x = r;
5811
5812         return r + l;
5813 }
5814
5815 char *strrep(const char *s, unsigned n) {
5816         size_t l;
5817         char *r, *p;
5818         unsigned i;
5819
5820         assert(s);
5821
5822         l = strlen(s);
5823         p = r = malloc(l * n + 1);
5824         if (!r)
5825                 return NULL;
5826
5827         for (i = 0; i < n; i++)
5828                 p = stpcpy(p, s);
5829
5830         *p = 0;
5831         return r;
5832 }
5833
5834 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5835         size_t a;
5836         void *q;
5837
5838         assert(p);
5839         assert(allocated);
5840
5841         if (*allocated >= need)
5842                 return *p;
5843
5844         a = MAX(64u, need * 2);
5845
5846         /* check for overflows */
5847         if (a < need)
5848                 return NULL;
5849
5850         q = realloc(*p, a);
5851         if (!q)
5852                 return NULL;
5853
5854         *p = q;
5855         *allocated = a;
5856         return q;
5857 }
5858
5859 void* greedy_realloc0(void **p, size_t *allocated, size_t need) {
5860         size_t prev;
5861         uint8_t *q;
5862
5863         assert(p);
5864         assert(allocated);
5865
5866         prev = *allocated;
5867
5868         q = greedy_realloc(p, allocated, need);
5869         if (!q)
5870                 return NULL;
5871
5872         if (*allocated > prev)
5873                 memzero(&q[prev], *allocated - prev);
5874
5875         return q;
5876 }
5877
5878 bool id128_is_valid(const char *s) {
5879         size_t i, l;
5880
5881         l = strlen(s);
5882         if (l == 32) {
5883
5884                 /* Simple formatted 128bit hex string */
5885
5886                 for (i = 0; i < l; i++) {
5887                         char c = s[i];
5888
5889                         if (!(c >= '0' && c <= '9') &&
5890                             !(c >= 'a' && c <= 'z') &&
5891                             !(c >= 'A' && c <= 'Z'))
5892                                 return false;
5893                 }
5894
5895         } else if (l == 36) {
5896
5897                 /* Formatted UUID */
5898
5899                 for (i = 0; i < l; i++) {
5900                         char c = s[i];
5901
5902                         if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5903                                 if (c != '-')
5904                                         return false;
5905                         } else {
5906                                 if (!(c >= '0' && c <= '9') &&
5907                                     !(c >= 'a' && c <= 'z') &&
5908                                     !(c >= 'A' && c <= 'Z'))
5909                                         return false;
5910                         }
5911                 }
5912
5913         } else
5914                 return false;
5915
5916         return true;
5917 }
5918
5919 int split_pair(const char *s, const char *sep, char **l, char **r) {
5920         char *x, *a, *b;
5921
5922         assert(s);
5923         assert(sep);
5924         assert(l);
5925         assert(r);
5926
5927         if (isempty(sep))
5928                 return -EINVAL;
5929
5930         x = strstr(s, sep);
5931         if (!x)
5932                 return -EINVAL;
5933
5934         a = strndup(s, x - s);
5935         if (!a)
5936                 return -ENOMEM;
5937
5938         b = strdup(x + strlen(sep));
5939         if (!b) {
5940                 free(a);
5941                 return -ENOMEM;
5942         }
5943
5944         *l = a;
5945         *r = b;
5946
5947         return 0;
5948 }
5949
5950 int shall_restore_state(void) {
5951         _cleanup_free_ char *line = NULL;
5952         char *w, *state;
5953         size_t l;
5954         int r;
5955
5956         r = proc_cmdline(&line);
5957         if (r < 0)
5958                 return r;
5959         if (r == 0) /* Container ... */
5960                 return 1;
5961
5962         r = 1;
5963
5964         FOREACH_WORD_QUOTED(w, l, line, state) {
5965                 const char *e;
5966                 char n[l+1];
5967                 int k;
5968
5969                 memcpy(n, w, l);
5970                 n[l] = 0;
5971
5972                 e = startswith(n, "systemd.restore_state=");
5973                 if (!e)
5974                         continue;
5975
5976                 k = parse_boolean(e);
5977                 if (k >= 0)
5978                         r = k;
5979         }
5980
5981         return r;
5982 }
5983
5984 int proc_cmdline(char **ret) {
5985         int r;
5986
5987         if (detect_container(NULL) > 0) {
5988                 char *buf = NULL, *p;
5989                 size_t sz = 0;
5990
5991                 r = read_full_file("/proc/1/cmdline", &buf, &sz);
5992                 if (r < 0)
5993                         return r;
5994
5995                 for (p = buf; p + 1 < buf + sz; p++)
5996                         if (*p == 0)
5997                                 *p = ' ';
5998
5999                 *p = 0;
6000                 *ret = buf;
6001                 return 1;
6002         }
6003
6004         r = read_one_line_file("/proc/cmdline", ret);
6005         if (r < 0)
6006                 return r;
6007
6008         return 1;
6009 }
6010
6011 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6012         _cleanup_free_ char *line = NULL;
6013         char *w, *state;
6014         size_t l;
6015         int r;
6016
6017         assert(parse_item);
6018
6019         r = proc_cmdline(&line);
6020         if (r < 0)
6021                 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
6022         if (r <= 0)
6023                 return 0;
6024
6025         FOREACH_WORD_QUOTED(w, l, line, state) {
6026                 char word[l+1], *value;
6027
6028                 memcpy(word, w, l);
6029                 word[l] = 0;
6030
6031                 /* Filter out arguments that are intended only for the
6032                  * initrd */
6033                 if (!in_initrd() && startswith(word, "rd."))
6034                         continue;
6035
6036                 value = strchr(word, '=');
6037                 if (value)
6038                         *(value++) = 0;
6039
6040                 r = parse_item(word, value);
6041                 if (r < 0)
6042                         return r;
6043         }
6044
6045         return 0;
6046 }
6047
6048 int container_get_leader(const char *machine, pid_t *pid) {
6049         _cleanup_free_ char *s = NULL, *class = NULL;
6050         const char *p;
6051         pid_t leader;
6052         int r;
6053
6054         assert(machine);
6055         assert(pid);
6056
6057         p = strappenda("/run/systemd/machines/", machine);
6058         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6059         if (r == -ENOENT)
6060                 return -EHOSTDOWN;
6061         if (r < 0)
6062                 return r;
6063         if (!s)
6064                 return -EIO;
6065
6066         if (!streq_ptr(class, "container"))
6067                 return -EIO;
6068
6069         r = parse_pid(s, &leader);
6070         if (r < 0)
6071                 return r;
6072         if (leader <= 1)
6073                 return -EIO;
6074
6075         *pid = leader;
6076         return 0;
6077 }
6078
6079 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *root_fd) {
6080         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1;
6081         const char *pidns, *mntns, *root;
6082         int rfd;
6083
6084         assert(pid >= 0);
6085         assert(pidns_fd);
6086         assert(mntns_fd);
6087         assert(root_fd);
6088
6089         mntns = procfs_file_alloca(pid, "ns/mnt");
6090         mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6091         if (mntnsfd < 0)
6092                 return -errno;
6093
6094         pidns = procfs_file_alloca(pid, "ns/pid");
6095         pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6096         if (pidnsfd < 0)
6097                 return -errno;
6098
6099         root = procfs_file_alloca(pid, "root");
6100         rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6101         if (rfd < 0)
6102                 return -errno;
6103
6104         *pidns_fd = pidnsfd;
6105         *mntns_fd = mntnsfd;
6106         *root_fd = rfd;
6107         pidnsfd = -1;
6108         mntnsfd = -1;
6109
6110         return 0;
6111 }
6112
6113 int namespace_enter(int pidns_fd, int mntns_fd, int root_fd) {
6114         assert(pidns_fd >= 0);
6115         assert(mntns_fd >= 0);
6116         assert(root_fd >= 0);
6117
6118         if (setns(pidns_fd, CLONE_NEWPID) < 0)
6119                 return -errno;
6120
6121         if (setns(mntns_fd, CLONE_NEWNS) < 0)
6122                 return -errno;
6123
6124         if (fchdir(root_fd) < 0)
6125                 return -errno;
6126
6127         if (chroot(".") < 0)
6128                 return -errno;
6129
6130         if (setresgid(0, 0, 0) < 0)
6131                 return -errno;
6132
6133         if (setresuid(0, 0, 0) < 0)
6134                 return -errno;
6135
6136         return 0;
6137 }
6138
6139 bool pid_is_unwaited(pid_t pid) {
6140         /* Checks whether a PID is still valid at all, including a zombie */
6141
6142         if (pid <= 0)
6143                 return false;
6144
6145         if (kill(pid, 0) >= 0)
6146                 return true;
6147
6148         return errno != ESRCH;
6149 }
6150
6151 bool pid_is_alive(pid_t pid) {
6152         int r;
6153
6154         /* Checks whether a PID is still valid and not a zombie */
6155
6156         if (pid <= 0)
6157                 return false;
6158
6159         r = get_process_state(pid);
6160         if (r == -ENOENT || r == 'Z')
6161                 return false;
6162
6163         return true;
6164 }
6165
6166 int getpeercred(int fd, struct ucred *ucred) {
6167         socklen_t n = sizeof(struct ucred);
6168         struct ucred u;
6169         int r;
6170
6171         assert(fd >= 0);
6172         assert(ucred);
6173
6174         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6175         if (r < 0)
6176                 return -errno;
6177
6178         if (n != sizeof(struct ucred))
6179                 return -EIO;
6180
6181         /* Check if the data is actually useful and not suppressed due
6182          * to namespacing issues */
6183         if (u.pid <= 0)
6184                 return -ENODATA;
6185
6186         *ucred = u;
6187         return 0;
6188 }
6189
6190 int getpeersec(int fd, char **ret) {
6191         socklen_t n = 64;
6192         char *s;
6193         int r;
6194
6195         assert(fd >= 0);
6196         assert(ret);
6197
6198         s = new0(char, n);
6199         if (!s)
6200                 return -ENOMEM;
6201
6202         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6203         if (r < 0) {
6204                 free(s);
6205
6206                 if (errno != ERANGE)
6207                         return -errno;
6208
6209                 s = new0(char, n);
6210                 if (!s)
6211                         return -ENOMEM;
6212
6213                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6214                 if (r < 0) {
6215                         free(s);
6216                         return -errno;
6217                 }
6218         }
6219
6220         if (isempty(s)) {
6221                 free(s);
6222                 return -ENOTSUP;
6223         }
6224
6225         *ret = s;
6226         return 0;
6227 }
6228
6229 /* This is much like like mkostemp() but is subject to umask(). */
6230 int mkostemp_safe(char *pattern, int flags) {
6231         _cleanup_umask_ mode_t u;
6232         int fd;
6233
6234         assert(pattern);
6235
6236         u = umask(077);
6237
6238         fd = mkostemp(pattern, flags);
6239         if (fd < 0)
6240                 return -errno;
6241
6242         return fd;
6243 }
6244
6245 int open_tmpfile(const char *path, int flags) {
6246         char *p;
6247         int fd;
6248
6249         assert(path);
6250
6251 #ifdef O_TMPFILE
6252         /* Try O_TMPFILE first, if it is supported */
6253         fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6254         if (fd >= 0)
6255                 return fd;
6256 #endif
6257
6258         /* Fall back to unguessable name + unlinking */
6259         p = strappenda(path, "/systemd-tmp-XXXXXX");
6260
6261         fd = mkostemp_safe(p, flags);
6262         if (fd < 0)
6263                 return fd;
6264
6265         unlink(p);
6266         return fd;
6267 }
6268
6269 int fd_warn_permissions(const char *path, int fd) {
6270         struct stat st;
6271
6272         if (fstat(fd, &st) < 0)
6273                 return -errno;
6274
6275         if (st.st_mode & 0111)
6276                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6277
6278         if (st.st_mode & 0002)
6279                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6280
6281         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6282                 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
6283
6284         return 0;
6285 }
6286
6287 unsigned long personality_from_string(const char *p) {
6288
6289         /* Parse a personality specifier. We introduce our own
6290          * identifiers that indicate specific ABIs, rather than just
6291          * hints regarding the register size, since we want to keep
6292          * things open for multiple locally supported ABIs for the
6293          * same register size. We try to reuse the ABI identifiers
6294          * used by libseccomp. */
6295
6296 #if defined(__x86_64__)
6297
6298         if (streq(p, "x86"))
6299                 return PER_LINUX32;
6300
6301         if (streq(p, "x86-64"))
6302                 return PER_LINUX;
6303
6304 #elif defined(__i386__)
6305
6306         if (streq(p, "x86"))
6307                 return PER_LINUX;
6308 #endif
6309
6310         /* personality(7) documents that 0xffffffffUL is used for
6311          * querying the current personality, hence let's use that here
6312          * as error indicator. */
6313         return 0xffffffffUL;
6314 }
6315
6316 const char* personality_to_string(unsigned long p) {
6317
6318 #if defined(__x86_64__)
6319
6320         if (p == PER_LINUX32)
6321                 return "x86";
6322
6323         if (p == PER_LINUX)
6324                 return "x86-64";
6325
6326 #elif defined(__i386__)
6327
6328         if (p == PER_LINUX)
6329                 return "x86";
6330 #endif
6331
6332         return NULL;
6333 }
6334
6335 uint64_t physical_memory(void) {
6336         long mem;
6337
6338         /* We return this as uint64_t in case we are running as 32bit
6339          * process on a 64bit kernel with huge amounts of memory */
6340
6341         mem = sysconf(_SC_PHYS_PAGES);
6342         assert(mem > 0);
6343
6344         return (uint64_t) mem * (uint64_t) page_size();
6345 }
6346
6347 char* mount_test_option(const char *haystack, const char *needle) {
6348
6349         struct mntent me = {
6350                 .mnt_opts = (char*) haystack
6351         };
6352
6353         assert(needle);
6354
6355         /* Like glibc's hasmntopt(), but works on a string, not a
6356          * struct mntent */
6357
6358         if (!haystack)
6359                 return NULL;
6360
6361         return hasmntopt(&me, needle);
6362 }