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