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