chiark / gitweb /
cc415894a54cd1f0f62b8b5c22365ea03ac55c5a
[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 bool tty_is_vc_resolve(const char *tty) {
3513         char *active = NULL;
3514         bool b;
3515
3516         assert(tty);
3517
3518         if (startswith(tty, "/dev/"))
3519                 tty += 5;
3520
3521         /* Resolve where /dev/console is pointing to, if /sys is
3522          * actually ours (i.e. not read-only-mounted which is a sign
3523          * for container setups) */
3524         if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3525                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3526                         /* If multiple log outputs are configured the
3527                          * last one is what /dev/console points to */
3528                         tty = strrchr(active, ' ');
3529                         if (tty)
3530                                 tty++;
3531                         else
3532                                 tty = active;
3533                 }
3534
3535         b = tty_is_vc(tty);
3536         free(active);
3537
3538         return b;
3539 }
3540
3541 const char *default_term_for_tty(const char *tty) {
3542         assert(tty);
3543
3544         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3545 }
3546
3547 bool dirent_is_file(const struct dirent *de) {
3548         assert(de);
3549
3550         if (ignore_file(de->d_name))
3551                 return false;
3552
3553         if (de->d_type != DT_REG &&
3554             de->d_type != DT_LNK &&
3555             de->d_type != DT_UNKNOWN)
3556                 return false;
3557
3558         return true;
3559 }
3560
3561 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3562         assert(de);
3563
3564         if (de->d_type != DT_REG &&
3565             de->d_type != DT_LNK &&
3566             de->d_type != DT_UNKNOWN)
3567                 return false;
3568
3569         if (ignore_file_allow_backup(de->d_name))
3570                 return false;
3571
3572         return endswith(de->d_name, suffix);
3573 }
3574
3575 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3576         DIR *_d = NULL;
3577         struct dirent *de;
3578         Hashmap *pids = NULL;
3579
3580         assert(directory);
3581
3582         /* Executes all binaries in a directory in parallel and waits
3583          * until all they all finished. */
3584
3585         if (!d) {
3586                 if (!(_d = opendir(directory))) {
3587
3588                         if (errno == ENOENT)
3589                                 return;
3590
3591                         log_error("Failed to enumerate directory %s: %m", directory);
3592                         return;
3593                 }
3594
3595                 d = _d;
3596         }
3597
3598         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3599                 log_error("Failed to allocate set.");
3600                 goto finish;
3601         }
3602
3603         while ((de = readdir(d))) {
3604                 char *path;
3605                 pid_t pid;
3606                 int k;
3607
3608                 if (!dirent_is_file(de))
3609                         continue;
3610
3611                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3612                         log_oom();
3613                         continue;
3614                 }
3615
3616                 if ((pid = fork()) < 0) {
3617                         log_error("Failed to fork: %m");
3618                         free(path);
3619                         continue;
3620                 }
3621
3622                 if (pid == 0) {
3623                         char *_argv[2];
3624                         /* Child */
3625
3626                         if (!argv) {
3627                                 _argv[0] = path;
3628                                 _argv[1] = NULL;
3629                                 argv = _argv;
3630                         } else
3631                                 argv[0] = path;
3632
3633                         execv(path, argv);
3634
3635                         log_error("Failed to execute %s: %m", path);
3636                         _exit(EXIT_FAILURE);
3637                 }
3638
3639                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3640
3641                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3642                         log_error("Failed to add PID to set: %s", strerror(-k));
3643                         free(path);
3644                 }
3645         }
3646
3647         while (!hashmap_isempty(pids)) {
3648                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3649                 siginfo_t si;
3650                 char *path;
3651
3652                 zero(si);
3653                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3654
3655                         if (errno == EINTR)
3656                                 continue;
3657
3658                         log_error("waitid() failed: %m");
3659                         goto finish;
3660                 }
3661
3662                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3663                         if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3664                                 if (si.si_code == CLD_EXITED)
3665                                         log_error("%s exited with exit status %i.", path, si.si_status);
3666                                 else
3667                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3668                         } else
3669                                 log_debug("%s exited successfully.", path);
3670
3671                         free(path);
3672                 }
3673         }
3674
3675 finish:
3676         if (_d)
3677                 closedir(_d);
3678
3679         if (pids)
3680                 hashmap_free_free(pids);
3681 }
3682
3683 int kill_and_sigcont(pid_t pid, int sig) {
3684         int r;
3685
3686         r = kill(pid, sig) < 0 ? -errno : 0;
3687
3688         if (r >= 0)
3689                 kill(pid, SIGCONT);
3690
3691         return r;
3692 }
3693
3694 bool nulstr_contains(const char*nulstr, const char *needle) {
3695         const char *i;
3696
3697         if (!nulstr)
3698                 return false;
3699
3700         NULSTR_FOREACH(i, nulstr)
3701                 if (streq(i, needle))
3702                         return true;
3703
3704         return false;
3705 }
3706
3707 bool plymouth_running(void) {
3708         return access("/run/plymouth/pid", F_OK) >= 0;
3709 }
3710
3711 char* strshorten(char *s, size_t l) {
3712         assert(s);
3713
3714         if (l < strlen(s))
3715                 s[l] = 0;
3716
3717         return s;
3718 }
3719
3720 static bool hostname_valid_char(char c) {
3721         return
3722                 (c >= 'a' && c <= 'z') ||
3723                 (c >= 'A' && c <= 'Z') ||
3724                 (c >= '0' && c <= '9') ||
3725                 c == '-' ||
3726                 c == '_' ||
3727                 c == '.';
3728 }
3729
3730 bool hostname_is_valid(const char *s) {
3731         const char *p;
3732
3733         if (isempty(s))
3734                 return false;
3735
3736         for (p = s; *p; p++)
3737                 if (!hostname_valid_char(*p))
3738                         return false;
3739
3740         if (p-s > HOST_NAME_MAX)
3741                 return false;
3742
3743         return true;
3744 }
3745
3746 char* hostname_cleanup(char *s) {
3747         char *p, *d;
3748
3749         for (p = s, d = s; *p; p++)
3750                 if ((*p >= 'a' && *p <= 'z') ||
3751                     (*p >= 'A' && *p <= 'Z') ||
3752                     (*p >= '0' && *p <= '9') ||
3753                     *p == '-' ||
3754                     *p == '_' ||
3755                     *p == '.')
3756                         *(d++) = *p;
3757
3758         *d = 0;
3759
3760         strshorten(s, HOST_NAME_MAX);
3761         return s;
3762 }
3763
3764 int pipe_eof(int fd) {
3765         struct pollfd pollfd;
3766         int r;
3767
3768         zero(pollfd);
3769         pollfd.fd = fd;
3770         pollfd.events = POLLIN|POLLHUP;
3771
3772         r = poll(&pollfd, 1, 0);
3773         if (r < 0)
3774                 return -errno;
3775
3776         if (r == 0)
3777                 return 0;
3778
3779         return pollfd.revents & POLLHUP;
3780 }
3781
3782 int fd_wait_for_event(int fd, int event, usec_t t) {
3783         struct pollfd pollfd;
3784         int r;
3785
3786         zero(pollfd);
3787         pollfd.fd = fd;
3788         pollfd.events = event;
3789
3790         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3791         if (r < 0)
3792                 return -errno;
3793
3794         if (r == 0)
3795                 return 0;
3796
3797         return pollfd.revents;
3798 }
3799
3800 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3801         FILE *f;
3802         char *t;
3803         const char *fn;
3804         size_t k;
3805         int fd;
3806
3807         assert(path);
3808         assert(_f);
3809         assert(_temp_path);
3810
3811         t = new(char, strlen(path) + 1 + 6 + 1);
3812         if (!t)
3813                 return -ENOMEM;
3814
3815         fn = path_get_file_name(path);
3816         k = fn-path;
3817         memcpy(t, path, k);
3818         t[k] = '.';
3819         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3820
3821         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3822         if (fd < 0) {
3823                 free(t);
3824                 return -errno;
3825         }
3826
3827         f = fdopen(fd, "we");
3828         if (!f) {
3829                 unlink(t);
3830                 free(t);
3831                 return -errno;
3832         }
3833
3834         *_f = f;
3835         *_temp_path = t;
3836
3837         return 0;
3838 }
3839
3840 int terminal_vhangup_fd(int fd) {
3841         assert(fd >= 0);
3842
3843         if (ioctl(fd, TIOCVHANGUP) < 0)
3844                 return -errno;
3845
3846         return 0;
3847 }
3848
3849 int terminal_vhangup(const char *name) {
3850         int fd, r;
3851
3852         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3853         if (fd < 0)
3854                 return fd;
3855
3856         r = terminal_vhangup_fd(fd);
3857         close_nointr_nofail(fd);
3858
3859         return r;
3860 }
3861
3862 int vt_disallocate(const char *name) {
3863         int fd, r;
3864         unsigned u;
3865
3866         /* Deallocate the VT if possible. If not possible
3867          * (i.e. because it is the active one), at least clear it
3868          * entirely (including the scrollback buffer) */
3869
3870         if (!startswith(name, "/dev/"))
3871                 return -EINVAL;
3872
3873         if (!tty_is_vc(name)) {
3874                 /* So this is not a VT. I guess we cannot deallocate
3875                  * it then. But let's at least clear the screen */
3876
3877                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3878                 if (fd < 0)
3879                         return fd;
3880
3881                 loop_write(fd,
3882                            "\033[r"    /* clear scrolling region */
3883                            "\033[H"    /* move home */
3884                            "\033[2J",  /* clear screen */
3885                            10, false);
3886                 close_nointr_nofail(fd);
3887
3888                 return 0;
3889         }
3890
3891         if (!startswith(name, "/dev/tty"))
3892                 return -EINVAL;
3893
3894         r = safe_atou(name+8, &u);
3895         if (r < 0)
3896                 return r;
3897
3898         if (u <= 0)
3899                 return -EINVAL;
3900
3901         /* Try to deallocate */
3902         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3903         if (fd < 0)
3904                 return fd;
3905
3906         r = ioctl(fd, VT_DISALLOCATE, u);
3907         close_nointr_nofail(fd);
3908
3909         if (r >= 0)
3910                 return 0;
3911
3912         if (errno != EBUSY)
3913                 return -errno;
3914
3915         /* Couldn't deallocate, so let's clear it fully with
3916          * scrollback */
3917         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3918         if (fd < 0)
3919                 return fd;
3920
3921         loop_write(fd,
3922                    "\033[r"   /* clear scrolling region */
3923                    "\033[H"   /* move home */
3924                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3925                    10, false);
3926         close_nointr_nofail(fd);
3927
3928         return 0;
3929 }
3930
3931 int copy_file(const char *from, const char *to) {
3932         int r, fdf, fdt;
3933
3934         assert(from);
3935         assert(to);
3936
3937         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3938         if (fdf < 0)
3939                 return -errno;
3940
3941         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
3942         if (fdt < 0) {
3943                 close_nointr_nofail(fdf);
3944                 return -errno;
3945         }
3946
3947         for (;;) {
3948                 char buf[PIPE_BUF];
3949                 ssize_t n, k;
3950
3951                 n = read(fdf, buf, sizeof(buf));
3952                 if (n < 0) {
3953                         r = -errno;
3954
3955                         close_nointr_nofail(fdf);
3956                         close_nointr(fdt);
3957                         unlink(to);
3958
3959                         return r;
3960                 }
3961
3962                 if (n == 0)
3963                         break;
3964
3965                 errno = 0;
3966                 k = loop_write(fdt, buf, n, false);
3967                 if (n != k) {
3968                         r = k < 0 ? k : (errno ? -errno : -EIO);
3969
3970                         close_nointr_nofail(fdf);
3971                         close_nointr(fdt);
3972
3973                         unlink(to);
3974                         return r;
3975                 }
3976         }
3977
3978         close_nointr_nofail(fdf);
3979         r = close_nointr(fdt);
3980
3981         if (r < 0) {
3982                 unlink(to);
3983                 return r;
3984         }
3985
3986         return 0;
3987 }
3988
3989 int symlink_atomic(const char *from, const char *to) {
3990         char *x;
3991         _cleanup_free_ char *t;
3992         const char *fn;
3993         size_t k;
3994         unsigned long long ull;
3995         unsigned i;
3996         int r;
3997
3998         assert(from);
3999         assert(to);
4000
4001         t = new(char, strlen(to) + 1 + 16 + 1);
4002         if (!t)
4003                 return -ENOMEM;
4004
4005         fn = path_get_file_name(to);
4006         k = fn-to;
4007         memcpy(t, to, k);
4008         t[k] = '.';
4009         x = stpcpy(t+k+1, fn);
4010
4011         ull = random_ull();
4012         for (i = 0; i < 16; i++) {
4013                 *(x++) = hexchar(ull & 0xF);
4014                 ull >>= 4;
4015         }
4016
4017         *x = 0;
4018
4019         if (symlink(from, t) < 0)
4020                 return -errno;
4021
4022         if (rename(t, to) < 0) {
4023                 r = -errno;
4024                 unlink(t);
4025                 return r;
4026         }
4027
4028         return 0;
4029 }
4030
4031 bool display_is_local(const char *display) {
4032         assert(display);
4033
4034         return
4035                 display[0] == ':' &&
4036                 display[1] >= '0' &&
4037                 display[1] <= '9';
4038 }
4039
4040 int socket_from_display(const char *display, char **path) {
4041         size_t k;
4042         char *f, *c;
4043
4044         assert(display);
4045         assert(path);
4046
4047         if (!display_is_local(display))
4048                 return -EINVAL;
4049
4050         k = strspn(display+1, "0123456789");
4051
4052         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4053         if (!f)
4054                 return -ENOMEM;
4055
4056         c = stpcpy(f, "/tmp/.X11-unix/X");
4057         memcpy(c, display+1, k);
4058         c[k] = 0;
4059
4060         *path = f;
4061
4062         return 0;
4063 }
4064
4065 int get_user_creds(
4066                 const char **username,
4067                 uid_t *uid, gid_t *gid,
4068                 const char **home,
4069                 const char **shell) {
4070
4071         struct passwd *p;
4072         uid_t u;
4073
4074         assert(username);
4075         assert(*username);
4076
4077         /* We enforce some special rules for uid=0: in order to avoid
4078          * NSS lookups for root we hardcode its data. */
4079
4080         if (streq(*username, "root") || streq(*username, "0")) {
4081                 *username = "root";
4082
4083                 if (uid)
4084                         *uid = 0;
4085
4086                 if (gid)
4087                         *gid = 0;
4088
4089                 if (home)
4090                         *home = "/root";
4091
4092                 if (shell)
4093                         *shell = "/bin/sh";
4094
4095                 return 0;
4096         }
4097
4098         if (parse_uid(*username, &u) >= 0) {
4099                 errno = 0;
4100                 p = getpwuid(u);
4101
4102                 /* If there are multiple users with the same id, make
4103                  * sure to leave $USER to the configured value instead
4104                  * of the first occurrence in the database. However if
4105                  * the uid was configured by a numeric uid, then let's
4106                  * pick the real username from /etc/passwd. */
4107                 if (p)
4108                         *username = p->pw_name;
4109         } else {
4110                 errno = 0;
4111                 p = getpwnam(*username);
4112         }
4113
4114         if (!p)
4115                 return errno != 0 ? -errno : -ESRCH;
4116
4117         if (uid)
4118                 *uid = p->pw_uid;
4119
4120         if (gid)
4121                 *gid = p->pw_gid;
4122
4123         if (home)
4124                 *home = p->pw_dir;
4125
4126         if (shell)
4127                 *shell = p->pw_shell;
4128
4129         return 0;
4130 }
4131
4132 char* uid_to_name(uid_t uid) {
4133         struct passwd *p;
4134         char *r;
4135
4136         if (uid == 0)
4137                 return strdup("root");
4138
4139         p = getpwuid(uid);
4140         if (p)
4141                 return strdup(p->pw_name);
4142
4143         if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4144                 return NULL;
4145
4146         return r;
4147 }
4148
4149 int get_group_creds(const char **groupname, gid_t *gid) {
4150         struct group *g;
4151         gid_t id;
4152
4153         assert(groupname);
4154
4155         /* We enforce some special rules for gid=0: in order to avoid
4156          * NSS lookups for root we hardcode its data. */
4157
4158         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4159                 *groupname = "root";
4160
4161                 if (gid)
4162                         *gid = 0;
4163
4164                 return 0;
4165         }
4166
4167         if (parse_gid(*groupname, &id) >= 0) {
4168                 errno = 0;
4169                 g = getgrgid(id);
4170
4171                 if (g)
4172                         *groupname = g->gr_name;
4173         } else {
4174                 errno = 0;
4175                 g = getgrnam(*groupname);
4176         }
4177
4178         if (!g)
4179                 return errno != 0 ? -errno : -ESRCH;
4180
4181         if (gid)
4182                 *gid = g->gr_gid;
4183
4184         return 0;
4185 }
4186
4187 int in_group(const char *name) {
4188         gid_t gid, *gids;
4189         int ngroups_max, r, i;
4190
4191         r = get_group_creds(&name, &gid);
4192         if (r < 0)
4193                 return r;
4194
4195         if (getgid() == gid)
4196                 return 1;
4197
4198         if (getegid() == gid)
4199                 return 1;
4200
4201         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4202         assert(ngroups_max > 0);
4203
4204         gids = alloca(sizeof(gid_t) * ngroups_max);
4205
4206         r = getgroups(ngroups_max, gids);
4207         if (r < 0)
4208                 return -errno;
4209
4210         for (i = 0; i < r; i++)
4211                 if (gids[i] == gid)
4212                         return 1;
4213
4214         return 0;
4215 }
4216
4217 int glob_exists(const char *path) {
4218         glob_t g;
4219         int r, k;
4220
4221         assert(path);
4222
4223         zero(g);
4224         errno = 0;
4225         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4226
4227         if (k == GLOB_NOMATCH)
4228                 r = 0;
4229         else if (k == GLOB_NOSPACE)
4230                 r = -ENOMEM;
4231         else if (k == 0)
4232                 r = !strv_isempty(g.gl_pathv);
4233         else
4234                 r = errno ? -errno : -EIO;
4235
4236         globfree(&g);
4237
4238         return r;
4239 }
4240
4241 int dirent_ensure_type(DIR *d, struct dirent *de) {
4242         struct stat st;
4243
4244         assert(d);
4245         assert(de);
4246
4247         if (de->d_type != DT_UNKNOWN)
4248                 return 0;
4249
4250         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4251                 return -errno;
4252
4253         de->d_type =
4254                 S_ISREG(st.st_mode)  ? DT_REG  :
4255                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4256                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4257                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4258                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4259                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4260                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4261                                        DT_UNKNOWN;
4262
4263         return 0;
4264 }
4265
4266 int in_search_path(const char *path, char **search) {
4267         char **i, *parent;
4268         int r;
4269
4270         r = path_get_parent(path, &parent);
4271         if (r < 0)
4272                 return r;
4273
4274         r = 0;
4275
4276         STRV_FOREACH(i, search) {
4277                 if (path_equal(parent, *i)) {
4278                         r = 1;
4279                         break;
4280                 }
4281         }
4282
4283         free(parent);
4284
4285         return r;
4286 }
4287
4288 int get_files_in_directory(const char *path, char ***list) {
4289         DIR *d;
4290         int r = 0;
4291         unsigned n = 0;
4292         char **l = NULL;
4293
4294         assert(path);
4295
4296         /* Returns all files in a directory in *list, and the number
4297          * of files as return value. If list is NULL returns only the
4298          * number */
4299
4300         d = opendir(path);
4301         if (!d)
4302                 return -errno;
4303
4304         for (;;) {
4305                 struct dirent *de;
4306                 union dirent_storage buf;
4307                 int k;
4308
4309                 k = readdir_r(d, &buf.de, &de);
4310                 if (k != 0) {
4311                         r = -k;
4312                         goto finish;
4313                 }
4314
4315                 if (!de)
4316                         break;
4317
4318                 dirent_ensure_type(d, de);
4319
4320                 if (!dirent_is_file(de))
4321                         continue;
4322
4323                 if (list) {
4324                         if ((unsigned) r >= n) {
4325                                 char **t;
4326
4327                                 n = MAX(16, 2*r);
4328                                 t = realloc(l, sizeof(char*) * n);
4329                                 if (!t) {
4330                                         r = -ENOMEM;
4331                                         goto finish;
4332                                 }
4333
4334                                 l = t;
4335                         }
4336
4337                         assert((unsigned) r < n);
4338
4339                         l[r] = strdup(de->d_name);
4340                         if (!l[r]) {
4341                                 r = -ENOMEM;
4342                                 goto finish;
4343                         }
4344
4345                         l[++r] = NULL;
4346                 } else
4347                         r++;
4348         }
4349
4350 finish:
4351         if (d)
4352                 closedir(d);
4353
4354         if (r >= 0) {
4355                 if (list)
4356                         *list = l;
4357         } else
4358                 strv_free(l);
4359
4360         return r;
4361 }
4362
4363 char *strjoin(const char *x, ...) {
4364         va_list ap;
4365         size_t l;
4366         char *r, *p;
4367
4368         va_start(ap, x);
4369
4370         if (x) {
4371                 l = strlen(x);
4372
4373                 for (;;) {
4374                         const char *t;
4375                         size_t n;
4376
4377                         t = va_arg(ap, const char *);
4378                         if (!t)
4379                                 break;
4380
4381                         n = strlen(t);
4382                         if (n > ((size_t) -1) - l) {
4383                                 va_end(ap);
4384                                 return NULL;
4385                         }
4386
4387                         l += n;
4388                 }
4389         } else
4390                 l = 0;
4391
4392         va_end(ap);
4393
4394         r = new(char, l+1);
4395         if (!r)
4396                 return NULL;
4397
4398         if (x) {
4399                 p = stpcpy(r, x);
4400
4401                 va_start(ap, x);
4402
4403                 for (;;) {
4404                         const char *t;
4405
4406                         t = va_arg(ap, const char *);
4407                         if (!t)
4408                                 break;
4409
4410                         p = stpcpy(p, t);
4411                 }
4412
4413                 va_end(ap);
4414         } else
4415                 r[0] = 0;
4416
4417         return r;
4418 }
4419
4420 bool is_main_thread(void) {
4421         static __thread int cached = 0;
4422
4423         if (_unlikely_(cached == 0))
4424                 cached = getpid() == gettid() ? 1 : -1;
4425
4426         return cached > 0;
4427 }
4428
4429 int block_get_whole_disk(dev_t d, dev_t *ret) {
4430         char *p, *s;
4431         int r;
4432         unsigned n, m;
4433
4434         assert(ret);
4435
4436         /* If it has a queue this is good enough for us */
4437         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4438                 return -ENOMEM;
4439
4440         r = access(p, F_OK);
4441         free(p);
4442
4443         if (r >= 0) {
4444                 *ret = d;
4445                 return 0;
4446         }
4447
4448         /* If it is a partition find the originating device */
4449         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4450                 return -ENOMEM;
4451
4452         r = access(p, F_OK);
4453         free(p);
4454
4455         if (r < 0)
4456                 return -ENOENT;
4457
4458         /* Get parent dev_t */
4459         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4460                 return -ENOMEM;
4461
4462         r = read_one_line_file(p, &s);
4463         free(p);
4464
4465         if (r < 0)
4466                 return r;
4467
4468         r = sscanf(s, "%u:%u", &m, &n);
4469         free(s);
4470
4471         if (r != 2)
4472                 return -EINVAL;
4473
4474         /* Only return this if it is really good enough for us. */
4475         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4476                 return -ENOMEM;
4477
4478         r = access(p, F_OK);
4479         free(p);
4480
4481         if (r >= 0) {
4482                 *ret = makedev(m, n);
4483                 return 0;
4484         }
4485
4486         return -ENOENT;
4487 }
4488
4489 int file_is_priv_sticky(const char *p) {
4490         struct stat st;
4491
4492         assert(p);
4493
4494         if (lstat(p, &st) < 0)
4495                 return -errno;
4496
4497         return
4498                 (st.st_uid == 0 || st.st_uid == getuid()) &&
4499                 (st.st_mode & S_ISVTX);
4500 }
4501
4502 static const char *const ioprio_class_table[] = {
4503         [IOPRIO_CLASS_NONE] = "none",
4504         [IOPRIO_CLASS_RT] = "realtime",
4505         [IOPRIO_CLASS_BE] = "best-effort",
4506         [IOPRIO_CLASS_IDLE] = "idle"
4507 };
4508
4509 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4510
4511 static const char *const sigchld_code_table[] = {
4512         [CLD_EXITED] = "exited",
4513         [CLD_KILLED] = "killed",
4514         [CLD_DUMPED] = "dumped",
4515         [CLD_TRAPPED] = "trapped",
4516         [CLD_STOPPED] = "stopped",
4517         [CLD_CONTINUED] = "continued",
4518 };
4519
4520 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4521
4522 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4523         [LOG_FAC(LOG_KERN)] = "kern",
4524         [LOG_FAC(LOG_USER)] = "user",
4525         [LOG_FAC(LOG_MAIL)] = "mail",
4526         [LOG_FAC(LOG_DAEMON)] = "daemon",
4527         [LOG_FAC(LOG_AUTH)] = "auth",
4528         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4529         [LOG_FAC(LOG_LPR)] = "lpr",
4530         [LOG_FAC(LOG_NEWS)] = "news",
4531         [LOG_FAC(LOG_UUCP)] = "uucp",
4532         [LOG_FAC(LOG_CRON)] = "cron",
4533         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4534         [LOG_FAC(LOG_FTP)] = "ftp",
4535         [LOG_FAC(LOG_LOCAL0)] = "local0",
4536         [LOG_FAC(LOG_LOCAL1)] = "local1",
4537         [LOG_FAC(LOG_LOCAL2)] = "local2",
4538         [LOG_FAC(LOG_LOCAL3)] = "local3",
4539         [LOG_FAC(LOG_LOCAL4)] = "local4",
4540         [LOG_FAC(LOG_LOCAL5)] = "local5",
4541         [LOG_FAC(LOG_LOCAL6)] = "local6",
4542         [LOG_FAC(LOG_LOCAL7)] = "local7"
4543 };
4544
4545 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4546
4547 static const char *const log_level_table[] = {
4548         [LOG_EMERG] = "emerg",
4549         [LOG_ALERT] = "alert",
4550         [LOG_CRIT] = "crit",
4551         [LOG_ERR] = "err",
4552         [LOG_WARNING] = "warning",
4553         [LOG_NOTICE] = "notice",
4554         [LOG_INFO] = "info",
4555         [LOG_DEBUG] = "debug"
4556 };
4557
4558 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4559
4560 static const char* const sched_policy_table[] = {
4561         [SCHED_OTHER] = "other",
4562         [SCHED_BATCH] = "batch",
4563         [SCHED_IDLE] = "idle",
4564         [SCHED_FIFO] = "fifo",
4565         [SCHED_RR] = "rr"
4566 };
4567
4568 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4569
4570 static const char* const rlimit_table[] = {
4571         [RLIMIT_CPU] = "LimitCPU",
4572         [RLIMIT_FSIZE] = "LimitFSIZE",
4573         [RLIMIT_DATA] = "LimitDATA",
4574         [RLIMIT_STACK] = "LimitSTACK",
4575         [RLIMIT_CORE] = "LimitCORE",
4576         [RLIMIT_RSS] = "LimitRSS",
4577         [RLIMIT_NOFILE] = "LimitNOFILE",
4578         [RLIMIT_AS] = "LimitAS",
4579         [RLIMIT_NPROC] = "LimitNPROC",
4580         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4581         [RLIMIT_LOCKS] = "LimitLOCKS",
4582         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4583         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4584         [RLIMIT_NICE] = "LimitNICE",
4585         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4586         [RLIMIT_RTTIME] = "LimitRTTIME"
4587 };
4588
4589 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4590
4591 static const char* const ip_tos_table[] = {
4592         [IPTOS_LOWDELAY] = "low-delay",
4593         [IPTOS_THROUGHPUT] = "throughput",
4594         [IPTOS_RELIABILITY] = "reliability",
4595         [IPTOS_LOWCOST] = "low-cost",
4596 };
4597
4598 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4599
4600 static const char *const __signal_table[] = {
4601         [SIGHUP] = "HUP",
4602         [SIGINT] = "INT",
4603         [SIGQUIT] = "QUIT",
4604         [SIGILL] = "ILL",
4605         [SIGTRAP] = "TRAP",
4606         [SIGABRT] = "ABRT",
4607         [SIGBUS] = "BUS",
4608         [SIGFPE] = "FPE",
4609         [SIGKILL] = "KILL",
4610         [SIGUSR1] = "USR1",
4611         [SIGSEGV] = "SEGV",
4612         [SIGUSR2] = "USR2",
4613         [SIGPIPE] = "PIPE",
4614         [SIGALRM] = "ALRM",
4615         [SIGTERM] = "TERM",
4616 #ifdef SIGSTKFLT
4617         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4618 #endif
4619         [SIGCHLD] = "CHLD",
4620         [SIGCONT] = "CONT",
4621         [SIGSTOP] = "STOP",
4622         [SIGTSTP] = "TSTP",
4623         [SIGTTIN] = "TTIN",
4624         [SIGTTOU] = "TTOU",
4625         [SIGURG] = "URG",
4626         [SIGXCPU] = "XCPU",
4627         [SIGXFSZ] = "XFSZ",
4628         [SIGVTALRM] = "VTALRM",
4629         [SIGPROF] = "PROF",
4630         [SIGWINCH] = "WINCH",
4631         [SIGIO] = "IO",
4632         [SIGPWR] = "PWR",
4633         [SIGSYS] = "SYS"
4634 };
4635
4636 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4637
4638 const char *signal_to_string(int signo) {
4639         static __thread char buf[12];
4640         const char *name;
4641
4642         name = __signal_to_string(signo);
4643         if (name)
4644                 return name;
4645
4646         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4647                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4648         else
4649                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4650         char_array_0(buf);
4651         return buf;
4652 }
4653
4654 int signal_from_string(const char *s) {
4655         int signo;
4656         int offset = 0;
4657         unsigned u;
4658
4659         signo = __signal_from_string(s);
4660         if (signo > 0)
4661                 return signo;
4662
4663         if (startswith(s, "RTMIN+")) {
4664                 s += 6;
4665                 offset = SIGRTMIN;
4666         }
4667         if (safe_atou(s, &u) >= 0) {
4668                 signo = (int) u + offset;
4669                 if (signo > 0 && signo < _NSIG)
4670                         return signo;
4671         }
4672         return -1;
4673 }
4674
4675 bool kexec_loaded(void) {
4676        bool loaded = false;
4677        char *s;
4678
4679        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4680                if (s[0] == '1')
4681                        loaded = true;
4682                free(s);
4683        }
4684        return loaded;
4685 }
4686
4687 int strdup_or_null(const char *a, char **b) {
4688         char *c;
4689
4690         assert(b);
4691
4692         if (!a) {
4693                 *b = NULL;
4694                 return 0;
4695         }
4696
4697         c = strdup(a);
4698         if (!c)
4699                 return -ENOMEM;
4700
4701         *b = c;
4702         return 0;
4703 }
4704
4705 int prot_from_flags(int flags) {
4706
4707         switch (flags & O_ACCMODE) {
4708
4709         case O_RDONLY:
4710                 return PROT_READ;
4711
4712         case O_WRONLY:
4713                 return PROT_WRITE;
4714
4715         case O_RDWR:
4716                 return PROT_READ|PROT_WRITE;
4717
4718         default:
4719                 return -EINVAL;
4720         }
4721 }
4722
4723 char *format_bytes(char *buf, size_t l, off_t t) {
4724         unsigned i;
4725
4726         static const struct {
4727                 const char *suffix;
4728                 off_t factor;
4729         } table[] = {
4730                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4731                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4732                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4733                 { "G", 1024ULL*1024ULL*1024ULL },
4734                 { "M", 1024ULL*1024ULL },
4735                 { "K", 1024ULL },
4736         };
4737
4738         for (i = 0; i < ELEMENTSOF(table); i++) {
4739
4740                 if (t >= table[i].factor) {
4741                         snprintf(buf, l,
4742                                  "%llu.%llu%s",
4743                                  (unsigned long long) (t / table[i].factor),
4744                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4745                                  table[i].suffix);
4746
4747                         goto finish;
4748                 }
4749         }
4750
4751         snprintf(buf, l, "%lluB", (unsigned long long) t);
4752
4753 finish:
4754         buf[l-1] = 0;
4755         return buf;
4756
4757 }
4758
4759 void* memdup(const void *p, size_t l) {
4760         void *r;
4761
4762         assert(p);
4763
4764         r = malloc(l);
4765         if (!r)
4766                 return NULL;
4767
4768         memcpy(r, p, l);
4769         return r;
4770 }
4771
4772 int fd_inc_sndbuf(int fd, size_t n) {
4773         int r, value;
4774         socklen_t l = sizeof(value);
4775
4776         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4777         if (r >= 0 &&
4778             l == sizeof(value) &&
4779             (size_t) value >= n*2)
4780                 return 0;
4781
4782         value = (int) n;
4783         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4784         if (r < 0)
4785                 return -errno;
4786
4787         return 1;
4788 }
4789
4790 int fd_inc_rcvbuf(int fd, size_t n) {
4791         int r, value;
4792         socklen_t l = sizeof(value);
4793
4794         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4795         if (r >= 0 &&
4796             l == sizeof(value) &&
4797             (size_t) value >= n*2)
4798                 return 0;
4799
4800         value = (int) n;
4801         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4802         if (r < 0)
4803                 return -errno;
4804
4805         return 1;
4806 }
4807
4808 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4809         pid_t parent_pid, agent_pid;
4810         int fd;
4811         bool stdout_is_tty, stderr_is_tty;
4812         unsigned n, i;
4813         va_list ap;
4814         char **l;
4815
4816         assert(pid);
4817         assert(path);
4818
4819         parent_pid = getpid();
4820
4821         /* Spawns a temporary TTY agent, making sure it goes away when
4822          * we go away */
4823
4824         agent_pid = fork();
4825         if (agent_pid < 0)
4826                 return -errno;
4827
4828         if (agent_pid != 0) {
4829                 *pid = agent_pid;
4830                 return 0;
4831         }
4832
4833         /* In the child:
4834          *
4835          * Make sure the agent goes away when the parent dies */
4836         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4837                 _exit(EXIT_FAILURE);
4838
4839         /* Check whether our parent died before we were able
4840          * to set the death signal */
4841         if (getppid() != parent_pid)
4842                 _exit(EXIT_SUCCESS);
4843
4844         /* Don't leak fds to the agent */
4845         close_all_fds(except, n_except);
4846
4847         stdout_is_tty = isatty(STDOUT_FILENO);
4848         stderr_is_tty = isatty(STDERR_FILENO);
4849
4850         if (!stdout_is_tty || !stderr_is_tty) {
4851                 /* Detach from stdout/stderr. and reopen
4852                  * /dev/tty for them. This is important to
4853                  * ensure that when systemctl is started via
4854                  * popen() or a similar call that expects to
4855                  * read EOF we actually do generate EOF and
4856                  * not delay this indefinitely by because we
4857                  * keep an unused copy of stdin around. */
4858                 fd = open("/dev/tty", O_WRONLY);
4859                 if (fd < 0) {
4860                         log_error("Failed to open /dev/tty: %m");
4861                         _exit(EXIT_FAILURE);
4862                 }
4863
4864                 if (!stdout_is_tty)
4865                         dup2(fd, STDOUT_FILENO);
4866
4867                 if (!stderr_is_tty)
4868                         dup2(fd, STDERR_FILENO);
4869
4870                 if (fd > 2)
4871                         close(fd);
4872         }
4873
4874         /* Count arguments */
4875         va_start(ap, path);
4876         for (n = 0; va_arg(ap, char*); n++)
4877                 ;
4878         va_end(ap);
4879
4880         /* Allocate strv */
4881         l = alloca(sizeof(char *) * (n + 1));
4882
4883         /* Fill in arguments */
4884         va_start(ap, path);
4885         for (i = 0; i <= n; i++)
4886                 l[i] = va_arg(ap, char*);
4887         va_end(ap);
4888
4889         execv(path, l);
4890         _exit(EXIT_FAILURE);
4891 }
4892
4893 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4894         struct rlimit highest, fixed;
4895
4896         assert(rlim);
4897
4898         if (setrlimit(resource, rlim) >= 0)
4899                 return 0;
4900
4901         if (errno != EPERM)
4902                 return -errno;
4903
4904         /* So we failed to set the desired setrlimit, then let's try
4905          * to get as close as we can */
4906         assert_se(getrlimit(resource, &highest) == 0);
4907
4908         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4909         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4910
4911         if (setrlimit(resource, &fixed) < 0)
4912                 return -errno;
4913
4914         return 0;
4915 }
4916
4917 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
4918         char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
4919         int r;
4920         FILE *f;
4921         bool done = false;
4922         size_t l;
4923
4924         assert(field);
4925         assert(_value);
4926
4927         if (pid == 0)
4928                 pid = getpid();
4929
4930         snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
4931         char_array_0(path);
4932
4933         f = fopen(path, "re");
4934         if (!f)
4935                 return -errno;
4936
4937         l = strlen(field);
4938         r = 0;
4939
4940         do {
4941                 char line[LINE_MAX];
4942                 unsigned i;
4943
4944                 for (i = 0; i < sizeof(line)-1; i++) {
4945                         int c;
4946
4947                         c = getc(f);
4948                         if (_unlikely_(c == EOF)) {
4949                                 done = true;
4950                                 break;
4951                         } else if (c == 0)
4952                                 break;
4953
4954                         line[i] = c;
4955                 }
4956                 line[i] = 0;
4957
4958                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
4959                         value = strdup(line + l + 1);
4960                         if (!value) {
4961                                 r = -ENOMEM;
4962                                 break;
4963                         }
4964
4965                         r = 1;
4966                         break;
4967                 }
4968
4969         } while (!done);
4970
4971         fclose(f);
4972
4973         if (r >= 0)
4974                 *_value = value;
4975
4976         return r;
4977 }
4978
4979 int can_sleep(const char *type) {
4980         char *w, *state;
4981         size_t l, k;
4982         int r;
4983         _cleanup_free_ char *p = NULL;
4984
4985         assert(type);
4986
4987         /* If /sys is read-only we cannot sleep */
4988         if (access("/sys/power/state", W_OK) < 0)
4989                 return false;
4990
4991         r = read_one_line_file("/sys/power/state", &p);
4992         if (r < 0)
4993                 return false;
4994
4995         k = strlen(type);
4996         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
4997                 if (l == k && memcmp(w, type, l) == 0)
4998                         return true;
4999
5000         return false;
5001 }
5002
5003 int can_sleep_disk(const char *type) {
5004         char *w, *state;
5005         size_t l, k;
5006         int r;
5007         _cleanup_free_ char *p = NULL;
5008
5009         assert(type);
5010
5011         /* If /sys is read-only we cannot sleep */
5012         if (access("/sys/power/state", W_OK) < 0 ||
5013             access("/sys/power/disk", W_OK) < 0)
5014                 return false;
5015
5016         r = read_one_line_file("/sys/power/disk", &p);
5017         if (r < 0)
5018                 return false;
5019
5020         k = strlen(type);
5021         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5022                 if (l == k && memcmp(w, type, l) == 0)
5023                         return true;
5024
5025                 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5026                         return true;
5027         }
5028
5029         return false;
5030 }
5031
5032 bool is_valid_documentation_url(const char *url) {
5033         assert(url);
5034
5035         if (startswith(url, "http://") && url[7])
5036                 return true;
5037
5038         if (startswith(url, "https://") && url[8])
5039                 return true;
5040
5041         if (startswith(url, "file:") && url[5])
5042                 return true;
5043
5044         if (startswith(url, "info:") && url[5])
5045                 return true;
5046
5047         if (startswith(url, "man:") && url[4])
5048                 return true;
5049
5050         return false;
5051 }
5052
5053 bool in_initrd(void) {
5054         static __thread int saved = -1;
5055         struct statfs s;
5056
5057         if (saved >= 0)
5058                 return saved;
5059
5060         /* We make two checks here:
5061          *
5062          * 1. the flag file /etc/initrd-release must exist
5063          * 2. the root file system must be a memory file system
5064          *
5065          * The second check is extra paranoia, since misdetecting an
5066          * initrd can have bad bad consequences due the initrd
5067          * emptying when transititioning to the main systemd.
5068          */
5069
5070         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5071                 statfs("/", &s) >= 0 &&
5072                 is_temporary_fs(&s);
5073
5074         return saved;
5075 }
5076
5077 void warn_melody(void) {
5078         _cleanup_close_ int fd = -1;
5079
5080         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5081         if (fd < 0)
5082                 return;
5083
5084         /* Yeah, this is synchronous. Kinda sucks. But well... */
5085
5086         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5087         usleep(125*USEC_PER_MSEC);
5088
5089         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5090         usleep(125*USEC_PER_MSEC);
5091
5092         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5093         usleep(125*USEC_PER_MSEC);
5094
5095         ioctl(fd, KIOCSOUND, 0);
5096 }
5097
5098 int make_console_stdio(void) {
5099         int fd, r;
5100
5101         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5102
5103         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5104         if (fd < 0) {
5105                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5106                 return fd;
5107         }
5108
5109         r = make_stdio(fd);
5110         if (r < 0) {
5111                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5112                 return r;
5113         }
5114
5115         return 0;
5116 }
5117
5118 int get_home_dir(char **_h) {
5119         char *h;
5120         const char *e;
5121         uid_t u;
5122         struct passwd *p;
5123
5124         assert(_h);
5125
5126         /* Take the user specified one */
5127         e = getenv("HOME");
5128         if (e) {
5129                 h = strdup(e);
5130                 if (!h)
5131                         return -ENOMEM;
5132
5133                 *_h = h;
5134                 return 0;
5135         }
5136
5137         /* Hardcode home directory for root to avoid NSS */
5138         u = getuid();
5139         if (u == 0) {
5140                 h = strdup("/root");
5141                 if (!h)
5142                         return -ENOMEM;
5143
5144                 *_h = h;
5145                 return 0;
5146         }
5147
5148         /* Check the database... */
5149         errno = 0;
5150         p = getpwuid(u);
5151         if (!p)
5152                 return errno ? -errno : -ESRCH;
5153
5154         if (!path_is_absolute(p->pw_dir))
5155                 return -EINVAL;
5156
5157         h = strdup(p->pw_dir);
5158         if (!h)
5159                 return -ENOMEM;
5160
5161         *_h = h;
5162         return 0;
5163 }
5164
5165 int get_shell(char **_sh) {
5166         char *sh;
5167         const char *e;
5168         uid_t u;
5169         struct passwd *p;
5170
5171         assert(_sh);
5172
5173         /* Take the user specified one */
5174         e = getenv("SHELL");
5175         if (e) {
5176                 sh = strdup(e);
5177                 if (!sh)
5178                         return -ENOMEM;
5179
5180                 *_sh = sh;
5181                 return 0;
5182         }
5183
5184         /* Hardcode home directory for root to avoid NSS */
5185         u = getuid();
5186         if (u == 0) {
5187                 sh = strdup("/bin/sh");
5188                 if (!sh)
5189                         return -ENOMEM;
5190
5191                 *_sh = sh;
5192                 return 0;
5193         }
5194
5195         /* Check the database... */
5196         errno = 0;
5197         p = getpwuid(u);
5198         if (!p)
5199                 return errno ? -errno : -ESRCH;
5200
5201         if (!path_is_absolute(p->pw_shell))
5202                 return -EINVAL;
5203
5204         sh = strdup(p->pw_shell);
5205         if (!sh)
5206                 return -ENOMEM;
5207
5208         *_sh = sh;
5209         return 0;
5210 }
5211
5212 void freep(void *p) {
5213         free(*(void**) p);
5214 }
5215
5216 void fclosep(FILE **f) {
5217         if (*f)
5218                 fclose(*f);
5219 }
5220
5221 void pclosep(FILE **f) {
5222         if (*f)
5223                 pclose(*f);
5224 }
5225
5226 void closep(int *fd) {
5227         if (*fd >= 0)
5228                 close_nointr_nofail(*fd);
5229 }
5230
5231 void closedirp(DIR **d) {
5232         if (*d)
5233                 closedir(*d);
5234 }
5235
5236 void umaskp(mode_t *u) {
5237         umask(*u);
5238 }
5239
5240 bool filename_is_safe(const char *p) {
5241
5242         if (isempty(p))
5243                 return false;
5244
5245         if (strchr(p, '/'))
5246                 return false;
5247
5248         if (streq(p, "."))
5249                 return false;
5250
5251         if (streq(p, ".."))
5252                 return false;
5253
5254         if (strlen(p) > FILENAME_MAX)
5255                 return false;
5256
5257         return true;
5258 }
5259
5260 bool string_is_safe(const char *p) {
5261         const char *t;
5262
5263         assert(p);
5264
5265         for (t = p; *t; t++) {
5266                 if (*t > 0 && *t < ' ')
5267                         return false;
5268
5269                 if (strchr("\\\"\'", *t))
5270                         return false;
5271         }
5272
5273         return true;
5274 }
5275
5276 bool string_has_cc(const char *p) {
5277         const char *t;
5278
5279         assert(p);
5280
5281         for (t = p; *t; t++)
5282                 if (*t > 0 && *t < ' ')
5283                         return true;
5284
5285         return false;
5286 }
5287
5288 bool path_is_safe(const char *p) {
5289
5290         if (isempty(p))
5291                 return false;
5292
5293         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5294                 return false;
5295
5296         if (strlen(p) > PATH_MAX)
5297                 return false;
5298
5299         /* The following two checks are not really dangerous, but hey, they still are confusing */
5300         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5301                 return false;
5302
5303         if (strstr(p, "//"))
5304                 return false;
5305
5306         return true;
5307 }
5308
5309 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5310 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5311                  int (*compar) (const void *, const void *, void *), void *arg) {
5312         size_t l, u, idx;
5313         const void *p;
5314         int comparison;
5315
5316         l = 0;
5317         u = nmemb;
5318         while (l < u) {
5319                 idx = (l + u) / 2;
5320                 p = (void *)(((const char *) base) + (idx * size));
5321                 comparison = compar(key, p, arg);
5322                 if (comparison < 0)
5323                         u = idx;
5324                 else if (comparison > 0)
5325                         l = idx + 1;
5326                 else
5327                         return (void *)p;
5328         }
5329         return NULL;
5330 }
5331
5332 bool is_locale_utf8(void) {
5333         const char *set;
5334         static int cached_answer = -1;
5335
5336         if (cached_answer >= 0)
5337                 goto out;
5338
5339         if (!setlocale(LC_ALL, "")) {
5340                 cached_answer = true;
5341                 goto out;
5342         }
5343
5344         set = nl_langinfo(CODESET);
5345         if (!set) {
5346                 cached_answer = true;
5347                 goto out;
5348         }
5349
5350         cached_answer = streq(set, "UTF-8");
5351 out:
5352         return (bool)cached_answer;
5353 }
5354
5355 const char *draw_special_char(DrawSpecialChar ch) {
5356         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5357                 /* UTF-8 */ {
5358                         [DRAW_TREE_VERT]          = "\342\224\202 ",            /* â”‚  */
5359                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* â”œâ”€ */
5360                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* â””─ */
5361                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5362                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243 ",            /* â€£  */
5363                 },
5364                 /* ASCII fallback */ {
5365                         [DRAW_TREE_VERT]          = "| ",
5366                         [DRAW_TREE_BRANCH]        = "|-",
5367                         [DRAW_TREE_RIGHT]         = "`-",
5368                         [DRAW_TREE_SPACE]         = "  ",
5369                         [DRAW_TRIANGULAR_BULLET]  = "> ",
5370                 }
5371         };
5372
5373         return draw_table[!is_locale_utf8()][ch];
5374 }
5375
5376 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5377         const char *f;
5378         char *t, *r;
5379         size_t l, old_len, new_len;
5380
5381         assert(text);
5382         assert(old_string);
5383         assert(new_string);
5384
5385         old_len = strlen(old_string);
5386         new_len = strlen(new_string);
5387
5388         l = strlen(text);
5389         r = new(char, l+1);
5390         if (!r)
5391                 return NULL;
5392
5393         f = text;
5394         t = r;
5395         while (*f) {
5396                 char *a;
5397                 size_t d, nl;
5398
5399                 if (!startswith(f, old_string)) {
5400                         *(t++) = *(f++);
5401                         continue;
5402                 }
5403
5404                 d = t - r;
5405                 nl = l - old_len + new_len;
5406                 a = realloc(r, nl + 1);
5407                 if (!a)
5408                         goto oom;
5409
5410                 l = nl;
5411                 r = a;
5412                 t = r + d;
5413
5414                 t = stpcpy(t, new_string);
5415                 f += old_len;
5416         }
5417
5418         *t = 0;
5419         return r;
5420
5421 oom:
5422         free(r);
5423         return NULL;
5424 }
5425
5426 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5427         const char *i, *begin = NULL;
5428         enum {
5429                 STATE_OTHER,
5430                 STATE_ESCAPE,
5431                 STATE_BRACKET
5432         } state = STATE_OTHER;
5433         char *obuf = NULL;
5434         size_t osz = 0, isz;
5435         FILE *f;
5436
5437         assert(ibuf);
5438         assert(*ibuf);
5439
5440         /* Strips ANSI color and replaces TABs by 8 spaces */
5441
5442         isz = _isz ? *_isz : strlen(*ibuf);
5443
5444         f = open_memstream(&obuf, &osz);
5445         if (!f)
5446                 return NULL;
5447
5448         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5449
5450                 switch (state) {
5451
5452                 case STATE_OTHER:
5453                         if (i >= *ibuf + isz) /* EOT */
5454                                 break;
5455                         else if (*i == '\x1B')
5456                                 state = STATE_ESCAPE;
5457                         else if (*i == '\t')
5458                                 fputs("        ", f);
5459                         else
5460                                 fputc(*i, f);
5461                         break;
5462
5463                 case STATE_ESCAPE:
5464                         if (i >= *ibuf + isz) { /* EOT */
5465                                 fputc('\x1B', f);
5466                                 break;
5467                         } else if (*i == '[') {
5468                                 state = STATE_BRACKET;
5469                                 begin = i + 1;
5470                         } else {
5471                                 fputc('\x1B', f);
5472                                 fputc(*i, f);
5473                                 state = STATE_OTHER;
5474                         }
5475
5476                         break;
5477
5478                 case STATE_BRACKET:
5479
5480                         if (i >= *ibuf + isz || /* EOT */
5481                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5482                                 fputc('\x1B', f);
5483                                 fputc('[', f);
5484                                 state = STATE_OTHER;
5485                                 i = begin-1;
5486                         } else if (*i == 'm')
5487                                 state = STATE_OTHER;
5488                         break;
5489                 }
5490         }
5491
5492         if (ferror(f)) {
5493                 fclose(f);
5494                 free(obuf);
5495                 return NULL;
5496         }
5497
5498         fclose(f);
5499
5500         free(*ibuf);
5501         *ibuf = obuf;
5502
5503         if (_isz)
5504                 *_isz = osz;
5505
5506         return obuf;
5507 }
5508
5509 int on_ac_power(void) {
5510         bool found_offline = false, found_online = false;
5511         _cleanup_closedir_ DIR *d = NULL;
5512
5513         d = opendir("/sys/class/power_supply");
5514         if (!d)
5515                 return -errno;
5516
5517         for (;;) {
5518                 struct dirent *de;
5519                 union dirent_storage buf;
5520                 _cleanup_free_ char *p = NULL;
5521                 _cleanup_close_ int fd = -1, device = -1;
5522                 char contents[6];
5523                 ssize_t n;
5524                 int k;
5525
5526                 k = readdir_r(d, &buf.de, &de);
5527                 if (k != 0)
5528                         return -k;
5529
5530                 if (!de)
5531                         break;
5532
5533                 if (ignore_file(de->d_name))
5534                         continue;
5535
5536                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5537                 if (device < 0) {
5538                         if (errno == ENOENT || errno == ENOTDIR)
5539                                 continue;
5540
5541                         return -errno;
5542                 }
5543
5544                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5545                 if (fd < 0) {
5546                         if (errno == ENOENT)
5547                                 continue;
5548
5549                         return -errno;
5550                 }
5551
5552                 n = read(fd, contents, sizeof(contents));
5553                 if (n < 0)
5554                         return -errno;
5555
5556                 if (n != 6 || memcmp(contents, "Mains\n", 6))
5557                         continue;
5558
5559                 close_nointr_nofail(fd);
5560                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5561                 if (fd < 0) {
5562                         if (errno == ENOENT)
5563                                 continue;
5564
5565                         return -errno;
5566                 }
5567
5568                 n = read(fd, contents, sizeof(contents));
5569                 if (n < 0)
5570                         return -errno;
5571
5572                 if (n != 2 || contents[1] != '\n')
5573                         return -EIO;
5574
5575                 if (contents[0] == '1') {
5576                         found_online = true;
5577                         break;
5578                 } else if (contents[0] == '0')
5579                         found_offline = true;
5580                 else
5581                         return -EIO;
5582         }
5583
5584         return found_online || !found_offline;
5585 }
5586
5587 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5588         char **i;
5589
5590         assert(path);
5591         assert(mode);
5592         assert(_f);
5593
5594         if (!path_strv_canonicalize_uniq(search))
5595                 return -ENOMEM;
5596
5597         STRV_FOREACH(i, search) {
5598                 _cleanup_free_ char *p = NULL;
5599                 FILE *f;
5600
5601                 p = strjoin(*i, "/", path, NULL);
5602                 if (!p)
5603                         return -ENOMEM;
5604
5605                 f = fopen(p, mode);
5606                 if (f) {
5607                         *_f = f;
5608                         return 0;
5609                 }
5610
5611                 if (errno != ENOENT)
5612                         return -errno;
5613         }
5614
5615         return -ENOENT;
5616 }
5617
5618 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5619         _cleanup_strv_free_ char **copy = NULL;
5620
5621         assert(path);
5622         assert(mode);
5623         assert(_f);
5624
5625         if (path_is_absolute(path)) {
5626                 FILE *f;
5627
5628                 f = fopen(path, mode);
5629                 if (f) {
5630                         *_f = f;
5631                         return 0;
5632                 }
5633
5634                 return -errno;
5635         }
5636
5637         copy = strv_copy((char**) search);
5638         if (!copy)
5639                 return -ENOMEM;
5640
5641         return search_and_fopen_internal(path, mode, copy, _f);
5642 }
5643
5644 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5645         _cleanup_strv_free_ char **s = NULL;
5646
5647         if (path_is_absolute(path)) {
5648                 FILE *f;
5649
5650                 f = fopen(path, mode);
5651                 if (f) {
5652                         *_f = f;
5653                         return 0;
5654                 }
5655
5656                 return -errno;
5657         }
5658
5659         s = strv_split_nulstr(search);
5660         if (!s)
5661                 return -ENOMEM;
5662
5663         return search_and_fopen_internal(path, mode, s, _f);
5664 }