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