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