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