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