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