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