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