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