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