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