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