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