chiark / gitweb /
Use initalization instead of explicit zeroing
[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 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         globfree(&g);
4343
4344         return r;
4345 }
4346
4347 int dirent_ensure_type(DIR *d, struct dirent *de) {
4348         struct stat st;
4349
4350         assert(d);
4351         assert(de);
4352
4353         if (de->d_type != DT_UNKNOWN)
4354                 return 0;
4355
4356         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4357                 return -errno;
4358
4359         de->d_type =
4360                 S_ISREG(st.st_mode)  ? DT_REG  :
4361                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4362                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4363                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4364                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4365                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4366                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4367                                        DT_UNKNOWN;
4368
4369         return 0;
4370 }
4371
4372 int in_search_path(const char *path, char **search) {
4373         char **i, *parent;
4374         int r;
4375
4376         r = path_get_parent(path, &parent);
4377         if (r < 0)
4378                 return r;
4379
4380         r = 0;
4381
4382         STRV_FOREACH(i, search) {
4383                 if (path_equal(parent, *i)) {
4384                         r = 1;
4385                         break;
4386                 }
4387         }
4388
4389         free(parent);
4390
4391         return r;
4392 }
4393
4394 int get_files_in_directory(const char *path, char ***list) {
4395         DIR *d;
4396         int r = 0;
4397         unsigned n = 0;
4398         char **l = NULL;
4399
4400         assert(path);
4401
4402         /* Returns all files in a directory in *list, and the number
4403          * of files as return value. If list is NULL returns only the
4404          * number */
4405
4406         d = opendir(path);
4407         if (!d)
4408                 return -errno;
4409
4410         for (;;) {
4411                 struct dirent *de;
4412                 union dirent_storage buf;
4413                 int k;
4414
4415                 k = readdir_r(d, &buf.de, &de);
4416                 if (k != 0) {
4417                         r = -k;
4418                         goto finish;
4419                 }
4420
4421                 if (!de)
4422                         break;
4423
4424                 dirent_ensure_type(d, de);
4425
4426                 if (!dirent_is_file(de))
4427                         continue;
4428
4429                 if (list) {
4430                         if ((unsigned) r >= n) {
4431                                 char **t;
4432
4433                                 n = MAX(16, 2*r);
4434                                 t = realloc(l, sizeof(char*) * n);
4435                                 if (!t) {
4436                                         r = -ENOMEM;
4437                                         goto finish;
4438                                 }
4439
4440                                 l = t;
4441                         }
4442
4443                         assert((unsigned) r < n);
4444
4445                         l[r] = strdup(de->d_name);
4446                         if (!l[r]) {
4447                                 r = -ENOMEM;
4448                                 goto finish;
4449                         }
4450
4451                         l[++r] = NULL;
4452                 } else
4453                         r++;
4454         }
4455
4456 finish:
4457         if (d)
4458                 closedir(d);
4459
4460         if (r >= 0) {
4461                 if (list)
4462                         *list = l;
4463         } else
4464                 strv_free(l);
4465
4466         return r;
4467 }
4468
4469 char *strjoin(const char *x, ...) {
4470         va_list ap;
4471         size_t l;
4472         char *r, *p;
4473
4474         va_start(ap, x);
4475
4476         if (x) {
4477                 l = strlen(x);
4478
4479                 for (;;) {
4480                         const char *t;
4481                         size_t n;
4482
4483                         t = va_arg(ap, const char *);
4484                         if (!t)
4485                                 break;
4486
4487                         n = strlen(t);
4488                         if (n > ((size_t) -1) - l) {
4489                                 va_end(ap);
4490                                 return NULL;
4491                         }
4492
4493                         l += n;
4494                 }
4495         } else
4496                 l = 0;
4497
4498         va_end(ap);
4499
4500         r = new(char, l+1);
4501         if (!r)
4502                 return NULL;
4503
4504         if (x) {
4505                 p = stpcpy(r, x);
4506
4507                 va_start(ap, x);
4508
4509                 for (;;) {
4510                         const char *t;
4511
4512                         t = va_arg(ap, const char *);
4513                         if (!t)
4514                                 break;
4515
4516                         p = stpcpy(p, t);
4517                 }
4518
4519                 va_end(ap);
4520         } else
4521                 r[0] = 0;
4522
4523         return r;
4524 }
4525
4526 bool is_main_thread(void) {
4527         static __thread int cached = 0;
4528
4529         if (_unlikely_(cached == 0))
4530                 cached = getpid() == gettid() ? 1 : -1;
4531
4532         return cached > 0;
4533 }
4534
4535 int block_get_whole_disk(dev_t d, dev_t *ret) {
4536         char *p, *s;
4537         int r;
4538         unsigned n, m;
4539
4540         assert(ret);
4541
4542         /* If it has a queue this is good enough for us */
4543         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4544                 return -ENOMEM;
4545
4546         r = access(p, F_OK);
4547         free(p);
4548
4549         if (r >= 0) {
4550                 *ret = d;
4551                 return 0;
4552         }
4553
4554         /* If it is a partition find the originating device */
4555         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4556                 return -ENOMEM;
4557
4558         r = access(p, F_OK);
4559         free(p);
4560
4561         if (r < 0)
4562                 return -ENOENT;
4563
4564         /* Get parent dev_t */
4565         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4566                 return -ENOMEM;
4567
4568         r = read_one_line_file(p, &s);
4569         free(p);
4570
4571         if (r < 0)
4572                 return r;
4573
4574         r = sscanf(s, "%u:%u", &m, &n);
4575         free(s);
4576
4577         if (r != 2)
4578                 return -EINVAL;
4579
4580         /* Only return this if it is really good enough for us. */
4581         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4582                 return -ENOMEM;
4583
4584         r = access(p, F_OK);
4585         free(p);
4586
4587         if (r >= 0) {
4588                 *ret = makedev(m, n);
4589                 return 0;
4590         }
4591
4592         return -ENOENT;
4593 }
4594
4595 int file_is_priv_sticky(const char *p) {
4596         struct stat st;
4597
4598         assert(p);
4599
4600         if (lstat(p, &st) < 0)
4601                 return -errno;
4602
4603         return
4604                 (st.st_uid == 0 || st.st_uid == getuid()) &&
4605                 (st.st_mode & S_ISVTX);
4606 }
4607
4608 static const char *const ioprio_class_table[] = {
4609         [IOPRIO_CLASS_NONE] = "none",
4610         [IOPRIO_CLASS_RT] = "realtime",
4611         [IOPRIO_CLASS_BE] = "best-effort",
4612         [IOPRIO_CLASS_IDLE] = "idle"
4613 };
4614
4615 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4616
4617 static const char *const sigchld_code_table[] = {
4618         [CLD_EXITED] = "exited",
4619         [CLD_KILLED] = "killed",
4620         [CLD_DUMPED] = "dumped",
4621         [CLD_TRAPPED] = "trapped",
4622         [CLD_STOPPED] = "stopped",
4623         [CLD_CONTINUED] = "continued",
4624 };
4625
4626 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4627
4628 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4629         [LOG_FAC(LOG_KERN)] = "kern",
4630         [LOG_FAC(LOG_USER)] = "user",
4631         [LOG_FAC(LOG_MAIL)] = "mail",
4632         [LOG_FAC(LOG_DAEMON)] = "daemon",
4633         [LOG_FAC(LOG_AUTH)] = "auth",
4634         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4635         [LOG_FAC(LOG_LPR)] = "lpr",
4636         [LOG_FAC(LOG_NEWS)] = "news",
4637         [LOG_FAC(LOG_UUCP)] = "uucp",
4638         [LOG_FAC(LOG_CRON)] = "cron",
4639         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4640         [LOG_FAC(LOG_FTP)] = "ftp",
4641         [LOG_FAC(LOG_LOCAL0)] = "local0",
4642         [LOG_FAC(LOG_LOCAL1)] = "local1",
4643         [LOG_FAC(LOG_LOCAL2)] = "local2",
4644         [LOG_FAC(LOG_LOCAL3)] = "local3",
4645         [LOG_FAC(LOG_LOCAL4)] = "local4",
4646         [LOG_FAC(LOG_LOCAL5)] = "local5",
4647         [LOG_FAC(LOG_LOCAL6)] = "local6",
4648         [LOG_FAC(LOG_LOCAL7)] = "local7"
4649 };
4650
4651 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4652
4653 static const char *const log_level_table[] = {
4654         [LOG_EMERG] = "emerg",
4655         [LOG_ALERT] = "alert",
4656         [LOG_CRIT] = "crit",
4657         [LOG_ERR] = "err",
4658         [LOG_WARNING] = "warning",
4659         [LOG_NOTICE] = "notice",
4660         [LOG_INFO] = "info",
4661         [LOG_DEBUG] = "debug"
4662 };
4663
4664 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4665
4666 static const char* const sched_policy_table[] = {
4667         [SCHED_OTHER] = "other",
4668         [SCHED_BATCH] = "batch",
4669         [SCHED_IDLE] = "idle",
4670         [SCHED_FIFO] = "fifo",
4671         [SCHED_RR] = "rr"
4672 };
4673
4674 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4675
4676 static const char* const rlimit_table[] = {
4677         [RLIMIT_CPU] = "LimitCPU",
4678         [RLIMIT_FSIZE] = "LimitFSIZE",
4679         [RLIMIT_DATA] = "LimitDATA",
4680         [RLIMIT_STACK] = "LimitSTACK",
4681         [RLIMIT_CORE] = "LimitCORE",
4682         [RLIMIT_RSS] = "LimitRSS",
4683         [RLIMIT_NOFILE] = "LimitNOFILE",
4684         [RLIMIT_AS] = "LimitAS",
4685         [RLIMIT_NPROC] = "LimitNPROC",
4686         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4687         [RLIMIT_LOCKS] = "LimitLOCKS",
4688         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4689         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4690         [RLIMIT_NICE] = "LimitNICE",
4691         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4692         [RLIMIT_RTTIME] = "LimitRTTIME"
4693 };
4694
4695 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4696
4697 static const char* const ip_tos_table[] = {
4698         [IPTOS_LOWDELAY] = "low-delay",
4699         [IPTOS_THROUGHPUT] = "throughput",
4700         [IPTOS_RELIABILITY] = "reliability",
4701         [IPTOS_LOWCOST] = "low-cost",
4702 };
4703
4704 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4705
4706 static const char *const __signal_table[] = {
4707         [SIGHUP] = "HUP",
4708         [SIGINT] = "INT",
4709         [SIGQUIT] = "QUIT",
4710         [SIGILL] = "ILL",
4711         [SIGTRAP] = "TRAP",
4712         [SIGABRT] = "ABRT",
4713         [SIGBUS] = "BUS",
4714         [SIGFPE] = "FPE",
4715         [SIGKILL] = "KILL",
4716         [SIGUSR1] = "USR1",
4717         [SIGSEGV] = "SEGV",
4718         [SIGUSR2] = "USR2",
4719         [SIGPIPE] = "PIPE",
4720         [SIGALRM] = "ALRM",
4721         [SIGTERM] = "TERM",
4722 #ifdef SIGSTKFLT
4723         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4724 #endif
4725         [SIGCHLD] = "CHLD",
4726         [SIGCONT] = "CONT",
4727         [SIGSTOP] = "STOP",
4728         [SIGTSTP] = "TSTP",
4729         [SIGTTIN] = "TTIN",
4730         [SIGTTOU] = "TTOU",
4731         [SIGURG] = "URG",
4732         [SIGXCPU] = "XCPU",
4733         [SIGXFSZ] = "XFSZ",
4734         [SIGVTALRM] = "VTALRM",
4735         [SIGPROF] = "PROF",
4736         [SIGWINCH] = "WINCH",
4737         [SIGIO] = "IO",
4738         [SIGPWR] = "PWR",
4739         [SIGSYS] = "SYS"
4740 };
4741
4742 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4743
4744 const char *signal_to_string(int signo) {
4745         static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4746         const char *name;
4747
4748         name = __signal_to_string(signo);
4749         if (name)
4750                 return name;
4751
4752         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4753                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4754         else
4755                 snprintf(buf, sizeof(buf), "%d", signo);
4756
4757         return buf;
4758 }
4759
4760 int signal_from_string(const char *s) {
4761         int signo;
4762         int offset = 0;
4763         unsigned u;
4764
4765         signo = __signal_from_string(s);
4766         if (signo > 0)
4767                 return signo;
4768
4769         if (startswith(s, "RTMIN+")) {
4770                 s += 6;
4771                 offset = SIGRTMIN;
4772         }
4773         if (safe_atou(s, &u) >= 0) {
4774                 signo = (int) u + offset;
4775                 if (signo > 0 && signo < _NSIG)
4776                         return signo;
4777         }
4778         return -1;
4779 }
4780
4781 bool kexec_loaded(void) {
4782        bool loaded = false;
4783        char *s;
4784
4785        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4786                if (s[0] == '1')
4787                        loaded = true;
4788                free(s);
4789        }
4790        return loaded;
4791 }
4792
4793 int strdup_or_null(const char *a, char **b) {
4794         char *c;
4795
4796         assert(b);
4797
4798         if (!a) {
4799                 *b = NULL;
4800                 return 0;
4801         }
4802
4803         c = strdup(a);
4804         if (!c)
4805                 return -ENOMEM;
4806
4807         *b = c;
4808         return 0;
4809 }
4810
4811 int prot_from_flags(int flags) {
4812
4813         switch (flags & O_ACCMODE) {
4814
4815         case O_RDONLY:
4816                 return PROT_READ;
4817
4818         case O_WRONLY:
4819                 return PROT_WRITE;
4820
4821         case O_RDWR:
4822                 return PROT_READ|PROT_WRITE;
4823
4824         default:
4825                 return -EINVAL;
4826         }
4827 }
4828
4829 char *format_bytes(char *buf, size_t l, off_t t) {
4830         unsigned i;
4831
4832         static const struct {
4833                 const char *suffix;
4834                 off_t factor;
4835         } table[] = {
4836                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4837                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4838                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4839                 { "G", 1024ULL*1024ULL*1024ULL },
4840                 { "M", 1024ULL*1024ULL },
4841                 { "K", 1024ULL },
4842         };
4843
4844         for (i = 0; i < ELEMENTSOF(table); i++) {
4845
4846                 if (t >= table[i].factor) {
4847                         snprintf(buf, l,
4848                                  "%llu.%llu%s",
4849                                  (unsigned long long) (t / table[i].factor),
4850                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4851                                  table[i].suffix);
4852
4853                         goto finish;
4854                 }
4855         }
4856
4857         snprintf(buf, l, "%lluB", (unsigned long long) t);
4858
4859 finish:
4860         buf[l-1] = 0;
4861         return buf;
4862
4863 }
4864
4865 void* memdup(const void *p, size_t l) {
4866         void *r;
4867
4868         assert(p);
4869
4870         r = malloc(l);
4871         if (!r)
4872                 return NULL;
4873
4874         memcpy(r, p, l);
4875         return r;
4876 }
4877
4878 int fd_inc_sndbuf(int fd, size_t n) {
4879         int r, value;
4880         socklen_t l = sizeof(value);
4881
4882         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4883         if (r >= 0 &&
4884             l == sizeof(value) &&
4885             (size_t) value >= n*2)
4886                 return 0;
4887
4888         value = (int) n;
4889         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4890         if (r < 0)
4891                 return -errno;
4892
4893         return 1;
4894 }
4895
4896 int fd_inc_rcvbuf(int fd, size_t n) {
4897         int r, value;
4898         socklen_t l = sizeof(value);
4899
4900         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4901         if (r >= 0 &&
4902             l == sizeof(value) &&
4903             (size_t) value >= n*2)
4904                 return 0;
4905
4906         value = (int) n;
4907         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4908         if (r < 0)
4909                 return -errno;
4910
4911         return 1;
4912 }
4913
4914 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4915         pid_t parent_pid, agent_pid;
4916         int fd;
4917         bool stdout_is_tty, stderr_is_tty;
4918         unsigned n, i;
4919         va_list ap;
4920         char **l;
4921
4922         assert(pid);
4923         assert(path);
4924
4925         parent_pid = getpid();
4926
4927         /* Spawns a temporary TTY agent, making sure it goes away when
4928          * we go away */
4929
4930         agent_pid = fork();
4931         if (agent_pid < 0)
4932                 return -errno;
4933
4934         if (agent_pid != 0) {
4935                 *pid = agent_pid;
4936                 return 0;
4937         }
4938
4939         /* In the child:
4940          *
4941          * Make sure the agent goes away when the parent dies */
4942         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4943                 _exit(EXIT_FAILURE);
4944
4945         /* Check whether our parent died before we were able
4946          * to set the death signal */
4947         if (getppid() != parent_pid)
4948                 _exit(EXIT_SUCCESS);
4949
4950         /* Don't leak fds to the agent */
4951         close_all_fds(except, n_except);
4952
4953         stdout_is_tty = isatty(STDOUT_FILENO);
4954         stderr_is_tty = isatty(STDERR_FILENO);
4955
4956         if (!stdout_is_tty || !stderr_is_tty) {
4957                 /* Detach from stdout/stderr. and reopen
4958                  * /dev/tty for them. This is important to
4959                  * ensure that when systemctl is started via
4960                  * popen() or a similar call that expects to
4961                  * read EOF we actually do generate EOF and
4962                  * not delay this indefinitely by because we
4963                  * keep an unused copy of stdin around. */
4964                 fd = open("/dev/tty", O_WRONLY);
4965                 if (fd < 0) {
4966                         log_error("Failed to open /dev/tty: %m");
4967                         _exit(EXIT_FAILURE);
4968                 }
4969
4970                 if (!stdout_is_tty)
4971                         dup2(fd, STDOUT_FILENO);
4972
4973                 if (!stderr_is_tty)
4974                         dup2(fd, STDERR_FILENO);
4975
4976                 if (fd > 2)
4977                         close(fd);
4978         }
4979
4980         /* Count arguments */
4981         va_start(ap, path);
4982         for (n = 0; va_arg(ap, char*); n++)
4983                 ;
4984         va_end(ap);
4985
4986         /* Allocate strv */
4987         l = alloca(sizeof(char *) * (n + 1));
4988
4989         /* Fill in arguments */
4990         va_start(ap, path);
4991         for (i = 0; i <= n; i++)
4992                 l[i] = va_arg(ap, char*);
4993         va_end(ap);
4994
4995         execv(path, l);
4996         _exit(EXIT_FAILURE);
4997 }
4998
4999 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5000         struct rlimit highest, fixed;
5001
5002         assert(rlim);
5003
5004         if (setrlimit(resource, rlim) >= 0)
5005                 return 0;
5006
5007         if (errno != EPERM)
5008                 return -errno;
5009
5010         /* So we failed to set the desired setrlimit, then let's try
5011          * to get as close as we can */
5012         assert_se(getrlimit(resource, &highest) == 0);
5013
5014         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5015         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5016
5017         if (setrlimit(resource, &fixed) < 0)
5018                 return -errno;
5019
5020         return 0;
5021 }
5022
5023 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5024         char path[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/environ")], *value = NULL;
5025         int r;
5026         FILE *f;
5027         bool done = false;
5028         size_t l;
5029
5030         assert(field);
5031         assert(_value);
5032
5033         if (pid == 0)
5034                 pid = getpid();
5035
5036         snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5037
5038         f = fopen(path, "re");
5039         if (!f)
5040                 return -errno;
5041
5042         l = strlen(field);
5043         r = 0;
5044
5045         do {
5046                 char line[LINE_MAX];
5047                 unsigned i;
5048
5049                 for (i = 0; i < sizeof(line)-1; i++) {
5050                         int c;
5051
5052                         c = getc(f);
5053                         if (_unlikely_(c == EOF)) {
5054                                 done = true;
5055                                 break;
5056                         } else if (c == 0)
5057                                 break;
5058
5059                         line[i] = c;
5060                 }
5061                 line[i] = 0;
5062
5063                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5064                         value = strdup(line + l + 1);
5065                         if (!value) {
5066                                 r = -ENOMEM;
5067                                 break;
5068                         }
5069
5070                         r = 1;
5071                         break;
5072                 }
5073
5074         } while (!done);
5075
5076         fclose(f);
5077
5078         if (r >= 0)
5079                 *_value = value;
5080
5081         return r;
5082 }
5083
5084 int can_sleep(const char *type) {
5085         char *w, *state;
5086         size_t l, k;
5087         int r;
5088         _cleanup_free_ char *p = NULL;
5089
5090         assert(type);
5091
5092         /* If /sys is read-only we cannot sleep */
5093         if (access("/sys/power/state", W_OK) < 0)
5094                 return false;
5095
5096         r = read_one_line_file("/sys/power/state", &p);
5097         if (r < 0)
5098                 return false;
5099
5100         k = strlen(type);
5101         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5102                 if (l == k && memcmp(w, type, l) == 0)
5103                         return true;
5104
5105         return false;
5106 }
5107
5108 int can_sleep_disk(const char *type) {
5109         char *w, *state;
5110         size_t l, k;
5111         int r;
5112         _cleanup_free_ char *p = NULL;
5113
5114         assert(type);
5115
5116         /* If /sys is read-only we cannot sleep */
5117         if (access("/sys/power/state", W_OK) < 0 ||
5118             access("/sys/power/disk", W_OK) < 0)
5119                 return false;
5120
5121         r = read_one_line_file("/sys/power/disk", &p);
5122         if (r < 0)
5123                 return false;
5124
5125         k = strlen(type);
5126         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5127                 if (l == k && memcmp(w, type, l) == 0)
5128                         return true;
5129
5130                 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5131                         return true;
5132         }
5133
5134         return false;
5135 }
5136
5137 bool is_valid_documentation_url(const char *url) {
5138         assert(url);
5139
5140         if (startswith(url, "http://") && url[7])
5141                 return true;
5142
5143         if (startswith(url, "https://") && url[8])
5144                 return true;
5145
5146         if (startswith(url, "file:") && url[5])
5147                 return true;
5148
5149         if (startswith(url, "info:") && url[5])
5150                 return true;
5151
5152         if (startswith(url, "man:") && url[4])
5153                 return true;
5154
5155         return false;
5156 }
5157
5158 bool in_initrd(void) {
5159         static __thread int saved = -1;
5160         struct statfs s;
5161
5162         if (saved >= 0)
5163                 return saved;
5164
5165         /* We make two checks here:
5166          *
5167          * 1. the flag file /etc/initrd-release must exist
5168          * 2. the root file system must be a memory file system
5169          *
5170          * The second check is extra paranoia, since misdetecting an
5171          * initrd can have bad bad consequences due the initrd
5172          * emptying when transititioning to the main systemd.
5173          */
5174
5175         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5176                 statfs("/", &s) >= 0 &&
5177                 is_temporary_fs(&s);
5178
5179         return saved;
5180 }
5181
5182 void warn_melody(void) {
5183         _cleanup_close_ int fd = -1;
5184
5185         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5186         if (fd < 0)
5187                 return;
5188
5189         /* Yeah, this is synchronous. Kinda sucks. But well... */
5190
5191         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5192         usleep(125*USEC_PER_MSEC);
5193
5194         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5195         usleep(125*USEC_PER_MSEC);
5196
5197         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5198         usleep(125*USEC_PER_MSEC);
5199
5200         ioctl(fd, KIOCSOUND, 0);
5201 }
5202
5203 int make_console_stdio(void) {
5204         int fd, r;
5205
5206         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5207
5208         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5209         if (fd < 0) {
5210                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5211                 return fd;
5212         }
5213
5214         r = make_stdio(fd);
5215         if (r < 0) {
5216                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5217                 return r;
5218         }
5219
5220         return 0;
5221 }
5222
5223 int get_home_dir(char **_h) {
5224         char *h;
5225         const char *e;
5226         uid_t u;
5227         struct passwd *p;
5228
5229         assert(_h);
5230
5231         /* Take the user specified one */
5232         e = getenv("HOME");
5233         if (e) {
5234                 h = strdup(e);
5235                 if (!h)
5236                         return -ENOMEM;
5237
5238                 *_h = h;
5239                 return 0;
5240         }
5241
5242         /* Hardcode home directory for root to avoid NSS */
5243         u = getuid();
5244         if (u == 0) {
5245                 h = strdup("/root");
5246                 if (!h)
5247                         return -ENOMEM;
5248
5249                 *_h = h;
5250                 return 0;
5251         }
5252
5253         /* Check the database... */
5254         errno = 0;
5255         p = getpwuid(u);
5256         if (!p)
5257                 return errno ? -errno : -ESRCH;
5258
5259         if (!path_is_absolute(p->pw_dir))
5260                 return -EINVAL;
5261
5262         h = strdup(p->pw_dir);
5263         if (!h)
5264                 return -ENOMEM;
5265
5266         *_h = h;
5267         return 0;
5268 }
5269
5270 void fclosep(FILE **f) {
5271         if (*f)
5272                 fclose(*f);
5273 }
5274
5275 void pclosep(FILE **f) {
5276         if (*f)
5277                 pclose(*f);
5278 }
5279
5280 void closep(int *fd) {
5281         if (*fd >= 0)
5282                 close_nointr_nofail(*fd);
5283 }
5284
5285 void closedirp(DIR **d) {
5286         if (*d)
5287                 closedir(*d);
5288 }
5289
5290 bool filename_is_safe(const char *p) {
5291
5292         if (isempty(p))
5293                 return false;
5294
5295         if (strchr(p, '/'))
5296                 return false;
5297
5298         if (streq(p, "."))
5299                 return false;
5300
5301         if (streq(p, ".."))
5302                 return false;
5303
5304         if (strlen(p) > FILENAME_MAX)
5305                 return false;
5306
5307         return true;
5308 }
5309
5310 bool string_is_safe(const char *p) {
5311         const char *t;
5312
5313         assert(p);
5314
5315         for (t = p; *t; t++) {
5316                 if (*t > 0 && *t < ' ')
5317                         return false;
5318
5319                 if (strchr("\\\"\'", *t))
5320                         return false;
5321         }
5322
5323         return true;
5324 }
5325
5326 bool string_has_cc(const char *p) {
5327         const char *t;
5328
5329         assert(p);
5330
5331         for (t = p; *t; t++)
5332                 if (*t > 0 && *t < ' ')
5333                         return true;
5334
5335         return false;
5336 }
5337
5338 bool path_is_safe(const char *p) {
5339
5340         if (isempty(p))
5341                 return false;
5342
5343         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5344                 return false;
5345
5346         if (strlen(p) > PATH_MAX)
5347                 return false;
5348
5349         /* The following two checks are not really dangerous, but hey, they still are confusing */
5350         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5351                 return false;
5352
5353         if (strstr(p, "//"))
5354                 return false;
5355
5356         return true;
5357 }
5358
5359 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5360 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5361                  int (*compar) (const void *, const void *, void *), void *arg) {
5362         size_t l, u, idx;
5363         const void *p;
5364         int comparison;
5365
5366         l = 0;
5367         u = nmemb;
5368         while (l < u) {
5369                 idx = (l + u) / 2;
5370                 p = (void *)(((const char *) base) + (idx * size));
5371                 comparison = compar(key, p, arg);
5372                 if (comparison < 0)
5373                         u = idx;
5374                 else if (comparison > 0)
5375                         l = idx + 1;
5376                 else
5377                         return (void *)p;
5378         }
5379         return NULL;
5380 }
5381
5382 bool is_locale_utf8(void) {
5383         const char *set;
5384         static int cached_answer = -1;
5385
5386         if (cached_answer >= 0)
5387                 goto out;
5388
5389         if (!setlocale(LC_ALL, "")) {
5390                 cached_answer = true;
5391                 goto out;
5392         }
5393
5394         set = nl_langinfo(CODESET);
5395         if (!set) {
5396                 cached_answer = true;
5397                 goto out;
5398         }
5399
5400         cached_answer = streq(set, "UTF-8");
5401 out:
5402         return (bool)cached_answer;
5403 }
5404
5405 const char *draw_special_char(DrawSpecialChar ch) {
5406         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5407                 /* UTF-8 */ {
5408                         [DRAW_TREE_VERT]          = "\342\224\202 ",            /* â”‚  */
5409                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* â”œâ”€ */
5410                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* â””─ */
5411                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5412                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243 ",            /* â€£  */
5413                 },
5414                 /* ASCII fallback */ {
5415                         [DRAW_TREE_VERT]          = "| ",
5416                         [DRAW_TREE_BRANCH]        = "|-",
5417                         [DRAW_TREE_RIGHT]         = "`-",
5418                         [DRAW_TREE_SPACE]         = "  ",
5419                         [DRAW_TRIANGULAR_BULLET]  = "> ",
5420                 }
5421         };
5422
5423         return draw_table[!is_locale_utf8()][ch];
5424 }
5425
5426 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5427         const char *f;
5428         char *t, *r;
5429         size_t l, old_len, new_len;
5430
5431         assert(text);
5432         assert(old_string);
5433         assert(new_string);
5434
5435         old_len = strlen(old_string);
5436         new_len = strlen(new_string);
5437
5438         l = strlen(text);
5439         r = new(char, l+1);
5440         if (!r)
5441                 return NULL;
5442
5443         f = text;
5444         t = r;
5445         while (*f) {
5446                 char *a;
5447                 size_t d, nl;
5448
5449                 if (!startswith(f, old_string)) {
5450                         *(t++) = *(f++);
5451                         continue;
5452                 }
5453
5454                 d = t - r;
5455                 nl = l - old_len + new_len;
5456                 a = realloc(r, nl + 1);
5457                 if (!a)
5458                         goto oom;
5459
5460                 l = nl;
5461                 r = a;
5462                 t = r + d;
5463
5464                 t = stpcpy(t, new_string);
5465                 f += old_len;
5466         }
5467
5468         *t = 0;
5469         return r;
5470
5471 oom:
5472         free(r);
5473         return NULL;
5474 }
5475
5476 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5477         const char *i, *begin = NULL;
5478         enum {
5479                 STATE_OTHER,
5480                 STATE_ESCAPE,
5481                 STATE_BRACKET
5482         } state = STATE_OTHER;
5483         char *obuf = NULL;
5484         size_t osz = 0, isz;
5485         FILE *f;
5486
5487         assert(ibuf);
5488         assert(*ibuf);
5489
5490         /* Strips ANSI color and replaces TABs by 8 spaces */
5491
5492         isz = _isz ? *_isz : strlen(*ibuf);
5493
5494         f = open_memstream(&obuf, &osz);
5495         if (!f)
5496                 return NULL;
5497
5498         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5499
5500                 switch (state) {
5501
5502                 case STATE_OTHER:
5503                         if (i >= *ibuf + isz) /* EOT */
5504                                 break;
5505                         else if (*i == '\x1B')
5506                                 state = STATE_ESCAPE;
5507                         else if (*i == '\t')
5508                                 fputs("        ", f);
5509                         else
5510                                 fputc(*i, f);
5511                         break;
5512
5513                 case STATE_ESCAPE:
5514                         if (i >= *ibuf + isz) { /* EOT */
5515                                 fputc('\x1B', f);
5516                                 break;
5517                         } else if (*i == '[') {
5518                                 state = STATE_BRACKET;
5519                                 begin = i + 1;
5520                         } else {
5521                                 fputc('\x1B', f);
5522                                 fputc(*i, f);
5523                                 state = STATE_OTHER;
5524                         }
5525
5526                         break;
5527
5528                 case STATE_BRACKET:
5529
5530                         if (i >= *ibuf + isz || /* EOT */
5531                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5532                                 fputc('\x1B', f);
5533                                 fputc('[', f);
5534                                 state = STATE_OTHER;
5535                                 i = begin-1;
5536                         } else if (*i == 'm')
5537                                 state = STATE_OTHER;
5538                         break;
5539                 }
5540         }
5541
5542         if (ferror(f)) {
5543                 fclose(f);
5544                 free(obuf);
5545                 return NULL;
5546         }
5547
5548         fclose(f);
5549
5550         free(*ibuf);
5551         *ibuf = obuf;
5552
5553         if (_isz)
5554                 *_isz = osz;
5555
5556         return obuf;
5557 }
5558
5559 int on_ac_power(void) {
5560         bool found_offline = false, found_online = false;
5561         _cleanup_closedir_ DIR *d = NULL;
5562
5563         d = opendir("/sys/class/power_supply");
5564         if (!d)
5565                 return -errno;
5566
5567         for (;;) {
5568                 struct dirent *de;
5569                 union dirent_storage buf;
5570                 _cleanup_close_ int fd = -1, device = -1;
5571                 char contents[6];
5572                 ssize_t n;
5573                 int k;
5574
5575                 k = readdir_r(d, &buf.de, &de);
5576                 if (k != 0)
5577                         return -k;
5578
5579                 if (!de)
5580                         break;
5581
5582                 if (ignore_file(de->d_name))
5583                         continue;
5584
5585                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5586                 if (device < 0) {
5587                         if (errno == ENOENT || errno == ENOTDIR)
5588                                 continue;
5589
5590                         return -errno;
5591                 }
5592
5593                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5594                 if (fd < 0) {
5595                         if (errno == ENOENT)
5596                                 continue;
5597
5598                         return -errno;
5599                 }
5600
5601                 n = read(fd, contents, sizeof(contents));
5602                 if (n < 0)
5603                         return -errno;
5604
5605                 if (n != 6 || memcmp(contents, "Mains\n", 6))
5606                         continue;
5607
5608                 close_nointr_nofail(fd);
5609                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5610                 if (fd < 0) {
5611                         if (errno == ENOENT)
5612                                 continue;
5613
5614                         return -errno;
5615                 }
5616
5617                 n = read(fd, contents, sizeof(contents));
5618                 if (n < 0)
5619                         return -errno;
5620
5621                 if (n != 2 || contents[1] != '\n')
5622                         return -EIO;
5623
5624                 if (contents[0] == '1') {
5625                         found_online = true;
5626                         break;
5627                 } else if (contents[0] == '0')
5628                         found_offline = true;
5629                 else
5630                         return -EIO;
5631         }
5632
5633         return found_online || !found_offline;
5634 }
5635
5636 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5637         char **i;
5638
5639         assert(path);
5640         assert(mode);
5641         assert(_f);
5642
5643         if (!path_strv_canonicalize_uniq(search))
5644                 return -ENOMEM;
5645
5646         STRV_FOREACH(i, search) {
5647                 _cleanup_free_ char *p = NULL;
5648                 FILE *f;
5649
5650                 p = strjoin(*i, "/", path, NULL);
5651                 if (!p)
5652                         return -ENOMEM;
5653
5654                 f = fopen(p, mode);
5655                 if (f) {
5656                         *_f = f;
5657                         return 0;
5658                 }
5659
5660                 if (errno != ENOENT)
5661                         return -errno;
5662         }
5663
5664         return -ENOENT;
5665 }
5666
5667 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5668         _cleanup_strv_free_ char **copy = NULL;
5669
5670         assert(path);
5671         assert(mode);
5672         assert(_f);
5673
5674         if (path_is_absolute(path)) {
5675                 FILE *f;
5676
5677                 f = fopen(path, mode);
5678                 if (f) {
5679                         *_f = f;
5680                         return 0;
5681                 }
5682
5683                 return -errno;
5684         }
5685
5686         copy = strv_copy((char**) search);
5687         if (!copy)
5688                 return -ENOMEM;
5689
5690         return search_and_fopen_internal(path, mode, copy, _f);
5691 }
5692
5693 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5694         _cleanup_strv_free_ char **s = NULL;
5695
5696         if (path_is_absolute(path)) {
5697                 FILE *f;
5698
5699                 f = fopen(path, mode);
5700                 if (f) {
5701                         *_f = f;
5702                         return 0;
5703                 }
5704
5705                 return -errno;
5706         }
5707
5708         s = strv_split_nulstr(search);
5709         if (!s)
5710                 return -ENOMEM;
5711
5712         return search_and_fopen_internal(path, mode, s, _f);
5713 }
5714
5715 int create_tmp_dir(char template[], char** dir_name) {
5716         int r = 0;
5717         char *d, *dt;
5718
5719         assert(dir_name);
5720
5721         RUN_WITH_UMASK(0077) {
5722                 d = mkdtemp(template);
5723         }
5724         if (!d) {
5725                 log_error("Can't create directory %s: %m", template);
5726                 return -errno;
5727         }
5728
5729         dt = strjoin(d, "/tmp", NULL);
5730         if (!dt) {
5731                 r = log_oom();
5732                 goto fail3;
5733         }
5734
5735         RUN_WITH_UMASK(0000) {
5736                 r = mkdir(dt, 0777);
5737         }
5738         if (r < 0) {
5739                 log_error("Can't create directory %s: %m", dt);
5740                 r = -errno;
5741                 goto fail2;
5742         }
5743         log_debug("Created temporary directory %s", dt);
5744
5745         r = chmod(dt, 0777 | S_ISVTX);
5746         if (r < 0) {
5747                 log_error("Failed to chmod %s: %m", dt);
5748                 r = -errno;
5749                 goto fail1;
5750         }
5751         log_debug("Set sticky bit on %s", dt);
5752
5753         *dir_name = dt;
5754
5755         return 0;
5756 fail1:
5757         rmdir(dt);
5758 fail2:
5759         free(dt);
5760 fail3:
5761         rmdir(template);
5762         return r;
5763 }
5764
5765 char *strextend(char **x, ...) {
5766         va_list ap;
5767         size_t f, l;
5768         char *r, *p;
5769
5770         assert(x);
5771
5772         l = f = *x ? strlen(*x) : 0;
5773
5774         va_start(ap, x);
5775         for (;;) {
5776                 const char *t;
5777                 size_t n;
5778
5779                 t = va_arg(ap, const char *);
5780                 if (!t)
5781                         break;
5782
5783                 n = strlen(t);
5784                 if (n > ((size_t) -1) - l) {
5785                         va_end(ap);
5786                         return NULL;
5787                 }
5788
5789                 l += n;
5790         }
5791         va_end(ap);
5792
5793         r = realloc(*x, l+1);
5794         if (!r)
5795                 return NULL;
5796
5797         p = r + f;
5798
5799         va_start(ap, x);
5800         for (;;) {
5801                 const char *t;
5802
5803                 t = va_arg(ap, const char *);
5804                 if (!t)
5805                         break;
5806
5807                 p = stpcpy(p, t);
5808         }
5809         va_end(ap);
5810
5811         *p = 0;
5812         *x = r;
5813
5814         return r + l;
5815 }
5816
5817 char *strrep(const char *s, unsigned n) {
5818         size_t l;
5819         char *r, *p;
5820         unsigned i;
5821
5822         assert(s);
5823
5824         l = strlen(s);
5825         p = r = malloc(l * n + 1);
5826         if (!r)
5827                 return NULL;
5828
5829         for (i = 0; i < n; i++)
5830                 p = stpcpy(p, s);
5831
5832         *p = 0;
5833         return r;
5834 }
5835
5836 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5837         size_t a;
5838         void *q;
5839
5840         if (*allocated >= need)
5841                 return *p;
5842
5843         a = MAX(64u, need * 2);
5844         q = realloc(*p, a);
5845         if (!q)
5846                 return NULL;
5847
5848         *p = q;
5849         *allocated = a;
5850         return q;
5851 }