chiark / gitweb /
journald: turn off COW for journal files on btrfs
[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 void execute_directory(const char *directory, DIR *d, usec_t timeout, char *argv[]) {
4041         pid_t executor_pid;
4042         int r;
4043
4044         assert(directory);
4045
4046         /* Executes all binaries in a directory in parallel and waits
4047          * for them to finish. Optionally a timeout is applied. */
4048
4049         executor_pid = fork();
4050         if (executor_pid < 0) {
4051                 log_error_errno(errno, "Failed to fork: %m");
4052                 return;
4053
4054         } else if (executor_pid == 0) {
4055                 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
4056                 _cleanup_closedir_ DIR *_d = NULL;
4057                 struct dirent *de;
4058
4059                 /* We fork this all off from a child process so that
4060                  * we can somewhat cleanly make use of SIGALRM to set
4061                  * a time limit */
4062
4063                 reset_all_signal_handlers();
4064                 reset_signal_mask();
4065
4066                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4067
4068                 if (!d) {
4069                         d = _d = opendir(directory);
4070                         if (!d) {
4071                                 if (errno == ENOENT)
4072                                         _exit(EXIT_SUCCESS);
4073
4074                                 log_error_errno(errno, "Failed to enumerate directory %s: %m", directory);
4075                                 _exit(EXIT_FAILURE);
4076                         }
4077                 }
4078
4079                 pids = hashmap_new(NULL);
4080                 if (!pids) {
4081                         log_oom();
4082                         _exit(EXIT_FAILURE);
4083                 }
4084
4085                 FOREACH_DIRENT(de, d, break) {
4086                         _cleanup_free_ char *path = NULL;
4087                         pid_t pid;
4088
4089                         if (!dirent_is_file(de))
4090                                 continue;
4091
4092                         path = strjoin(directory, "/", de->d_name, NULL);
4093                         if (!path) {
4094                                 log_oom();
4095                                 _exit(EXIT_FAILURE);
4096                         }
4097
4098                         pid = fork();
4099                         if (pid < 0) {
4100                                 log_error_errno(errno, "Failed to fork: %m");
4101                                 continue;
4102                         } else if (pid == 0) {
4103                                 char *_argv[2];
4104
4105                                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4106
4107                                 if (!argv) {
4108                                         _argv[0] = path;
4109                                         _argv[1] = NULL;
4110                                         argv = _argv;
4111                                 } else
4112                                         argv[0] = path;
4113
4114                                 execv(path, argv);
4115                                 log_error_errno(errno, "Failed to execute %s: %m", path);
4116                                 _exit(EXIT_FAILURE);
4117                         }
4118
4119                         log_debug("Spawned %s as " PID_FMT ".", path, pid);
4120
4121                         r = hashmap_put(pids, UINT_TO_PTR(pid), path);
4122                         if (r < 0) {
4123                                 log_oom();
4124                                 _exit(EXIT_FAILURE);
4125                         }
4126
4127                         path = NULL;
4128                 }
4129
4130                 /* Abort execution of this process after the
4131                  * timout. We simply rely on SIGALRM as default action
4132                  * terminating the process, and turn on alarm(). */
4133
4134                 if (timeout != USEC_INFINITY)
4135                         alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
4136
4137                 while (!hashmap_isempty(pids)) {
4138                         _cleanup_free_ char *path = NULL;
4139                         pid_t pid;
4140
4141                         pid = PTR_TO_UINT(hashmap_first_key(pids));
4142                         assert(pid > 0);
4143
4144                         path = hashmap_remove(pids, UINT_TO_PTR(pid));
4145                         assert(path);
4146
4147                         wait_for_terminate_and_warn(path, pid, true);
4148                 }
4149
4150                 _exit(EXIT_SUCCESS);
4151         }
4152
4153         wait_for_terminate_and_warn(directory, executor_pid, true);
4154 }
4155
4156 int kill_and_sigcont(pid_t pid, int sig) {
4157         int r;
4158
4159         r = kill(pid, sig) < 0 ? -errno : 0;
4160
4161         if (r >= 0)
4162                 kill(pid, SIGCONT);
4163
4164         return r;
4165 }
4166
4167 bool nulstr_contains(const char*nulstr, const char *needle) {
4168         const char *i;
4169
4170         if (!nulstr)
4171                 return false;
4172
4173         NULSTR_FOREACH(i, nulstr)
4174                 if (streq(i, needle))
4175                         return true;
4176
4177         return false;
4178 }
4179
4180 bool plymouth_running(void) {
4181         return access("/run/plymouth/pid", F_OK) >= 0;
4182 }
4183
4184 char* strshorten(char *s, size_t l) {
4185         assert(s);
4186
4187         if (l < strlen(s))
4188                 s[l] = 0;
4189
4190         return s;
4191 }
4192
4193 static bool hostname_valid_char(char c) {
4194         return
4195                 (c >= 'a' && c <= 'z') ||
4196                 (c >= 'A' && c <= 'Z') ||
4197                 (c >= '0' && c <= '9') ||
4198                 c == '-' ||
4199                 c == '_' ||
4200                 c == '.';
4201 }
4202
4203 bool hostname_is_valid(const char *s) {
4204         const char *p;
4205         bool dot;
4206
4207         if (isempty(s))
4208                 return false;
4209
4210         for (p = s, dot = true; *p; p++) {
4211                 if (*p == '.') {
4212                         if (dot)
4213                                 return false;
4214
4215                         dot = true;
4216                 } else {
4217                         if (!hostname_valid_char(*p))
4218                                 return false;
4219
4220                         dot = false;
4221                 }
4222         }
4223
4224         if (dot)
4225                 return false;
4226
4227         if (p-s > HOST_NAME_MAX)
4228                 return false;
4229
4230         return true;
4231 }
4232
4233 char* hostname_cleanup(char *s, bool lowercase) {
4234         char *p, *d;
4235         bool dot;
4236
4237         for (p = s, d = s, dot = true; *p; p++) {
4238                 if (*p == '.') {
4239                         if (dot)
4240                                 continue;
4241
4242                         *(d++) = '.';
4243                         dot = true;
4244                 } else if (hostname_valid_char(*p)) {
4245                         *(d++) = lowercase ? tolower(*p) : *p;
4246                         dot = false;
4247                 }
4248
4249         }
4250
4251         if (dot && d > s)
4252                 d[-1] = 0;
4253         else
4254                 *d = 0;
4255
4256         strshorten(s, HOST_NAME_MAX);
4257
4258         return s;
4259 }
4260
4261 bool machine_name_is_valid(const char *s) {
4262
4263         if (!hostname_is_valid(s))
4264                 return false;
4265
4266         /* Machine names should be useful hostnames, but also be
4267          * useful in unit names, hence we enforce a stricter length
4268          * limitation. */
4269
4270         if (strlen(s) > 64)
4271                 return false;
4272
4273         return true;
4274 }
4275
4276 bool image_name_is_valid(const char *s) {
4277         if (!filename_is_valid(s))
4278                 return false;
4279
4280         if (string_has_cc(s, NULL))
4281                 return false;
4282
4283         if (!utf8_is_valid(s))
4284                 return false;
4285
4286         /* Temporary files for atomically creating new files */
4287         if (startswith(s, ".#"))
4288                 return false;
4289
4290         return true;
4291 }
4292
4293 int pipe_eof(int fd) {
4294         struct pollfd pollfd = {
4295                 .fd = fd,
4296                 .events = POLLIN|POLLHUP,
4297         };
4298
4299         int r;
4300
4301         r = poll(&pollfd, 1, 0);
4302         if (r < 0)
4303                 return -errno;
4304
4305         if (r == 0)
4306                 return 0;
4307
4308         return pollfd.revents & POLLHUP;
4309 }
4310
4311 int fd_wait_for_event(int fd, int event, usec_t t) {
4312
4313         struct pollfd pollfd = {
4314                 .fd = fd,
4315                 .events = event,
4316         };
4317
4318         struct timespec ts;
4319         int r;
4320
4321         r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
4322         if (r < 0)
4323                 return -errno;
4324
4325         if (r == 0)
4326                 return 0;
4327
4328         return pollfd.revents;
4329 }
4330
4331 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4332         FILE *f;
4333         char *t;
4334         int r, fd;
4335
4336         assert(path);
4337         assert(_f);
4338         assert(_temp_path);
4339
4340         r = tempfn_xxxxxx(path, &t);
4341         if (r < 0)
4342                 return r;
4343
4344         fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
4345         if (fd < 0) {
4346                 free(t);
4347                 return -errno;
4348         }
4349
4350         f = fdopen(fd, "we");
4351         if (!f) {
4352                 unlink(t);
4353                 free(t);
4354                 return -errno;
4355         }
4356
4357         *_f = f;
4358         *_temp_path = t;
4359
4360         return 0;
4361 }
4362
4363 int terminal_vhangup_fd(int fd) {
4364         assert(fd >= 0);
4365
4366         if (ioctl(fd, TIOCVHANGUP) < 0)
4367                 return -errno;
4368
4369         return 0;
4370 }
4371
4372 int terminal_vhangup(const char *name) {
4373         _cleanup_close_ int fd;
4374
4375         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4376         if (fd < 0)
4377                 return fd;
4378
4379         return terminal_vhangup_fd(fd);
4380 }
4381
4382 int vt_disallocate(const char *name) {
4383         int fd, r;
4384         unsigned u;
4385
4386         /* Deallocate the VT if possible. If not possible
4387          * (i.e. because it is the active one), at least clear it
4388          * entirely (including the scrollback buffer) */
4389
4390         if (!startswith(name, "/dev/"))
4391                 return -EINVAL;
4392
4393         if (!tty_is_vc(name)) {
4394                 /* So this is not a VT. I guess we cannot deallocate
4395                  * it then. But let's at least clear the screen */
4396
4397                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4398                 if (fd < 0)
4399                         return fd;
4400
4401                 loop_write(fd,
4402                            "\033[r"    /* clear scrolling region */
4403                            "\033[H"    /* move home */
4404                            "\033[2J",  /* clear screen */
4405                            10, false);
4406                 safe_close(fd);
4407
4408                 return 0;
4409         }
4410
4411         if (!startswith(name, "/dev/tty"))
4412                 return -EINVAL;
4413
4414         r = safe_atou(name+8, &u);
4415         if (r < 0)
4416                 return r;
4417
4418         if (u <= 0)
4419                 return -EINVAL;
4420
4421         /* Try to deallocate */
4422         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4423         if (fd < 0)
4424                 return fd;
4425
4426         r = ioctl(fd, VT_DISALLOCATE, u);
4427         safe_close(fd);
4428
4429         if (r >= 0)
4430                 return 0;
4431
4432         if (errno != EBUSY)
4433                 return -errno;
4434
4435         /* Couldn't deallocate, so let's clear it fully with
4436          * scrollback */
4437         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4438         if (fd < 0)
4439                 return fd;
4440
4441         loop_write(fd,
4442                    "\033[r"   /* clear scrolling region */
4443                    "\033[H"   /* move home */
4444                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4445                    10, false);
4446         safe_close(fd);
4447
4448         return 0;
4449 }
4450
4451 int symlink_atomic(const char *from, const char *to) {
4452         _cleanup_free_ char *t = NULL;
4453         int r;
4454
4455         assert(from);
4456         assert(to);
4457
4458         r = tempfn_random(to, &t);
4459         if (r < 0)
4460                 return r;
4461
4462         if (symlink(from, t) < 0)
4463                 return -errno;
4464
4465         if (rename(t, to) < 0) {
4466                 unlink_noerrno(t);
4467                 return -errno;
4468         }
4469
4470         return 0;
4471 }
4472
4473 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4474         _cleanup_free_ char *t = NULL;
4475         int r;
4476
4477         assert(path);
4478
4479         r = tempfn_random(path, &t);
4480         if (r < 0)
4481                 return r;
4482
4483         if (mknod(t, mode, dev) < 0)
4484                 return -errno;
4485
4486         if (rename(t, path) < 0) {
4487                 unlink_noerrno(t);
4488                 return -errno;
4489         }
4490
4491         return 0;
4492 }
4493
4494 int mkfifo_atomic(const char *path, mode_t mode) {
4495         _cleanup_free_ char *t = NULL;
4496         int r;
4497
4498         assert(path);
4499
4500         r = tempfn_random(path, &t);
4501         if (r < 0)
4502                 return r;
4503
4504         if (mkfifo(t, mode) < 0)
4505                 return -errno;
4506
4507         if (rename(t, path) < 0) {
4508                 unlink_noerrno(t);
4509                 return -errno;
4510         }
4511
4512         return 0;
4513 }
4514
4515 bool display_is_local(const char *display) {
4516         assert(display);
4517
4518         return
4519                 display[0] == ':' &&
4520                 display[1] >= '0' &&
4521                 display[1] <= '9';
4522 }
4523
4524 int socket_from_display(const char *display, char **path) {
4525         size_t k;
4526         char *f, *c;
4527
4528         assert(display);
4529         assert(path);
4530
4531         if (!display_is_local(display))
4532                 return -EINVAL;
4533
4534         k = strspn(display+1, "0123456789");
4535
4536         f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4537         if (!f)
4538                 return -ENOMEM;
4539
4540         c = stpcpy(f, "/tmp/.X11-unix/X");
4541         memcpy(c, display+1, k);
4542         c[k] = 0;
4543
4544         *path = f;
4545
4546         return 0;
4547 }
4548
4549 int get_user_creds(
4550                 const char **username,
4551                 uid_t *uid, gid_t *gid,
4552                 const char **home,
4553                 const char **shell) {
4554
4555         struct passwd *p;
4556         uid_t u;
4557
4558         assert(username);
4559         assert(*username);
4560
4561         /* We enforce some special rules for uid=0: in order to avoid
4562          * NSS lookups for root we hardcode its data. */
4563
4564         if (streq(*username, "root") || streq(*username, "0")) {
4565                 *username = "root";
4566
4567                 if (uid)
4568                         *uid = 0;
4569
4570                 if (gid)
4571                         *gid = 0;
4572
4573                 if (home)
4574                         *home = "/root";
4575
4576                 if (shell)
4577                         *shell = "/bin/sh";
4578
4579                 return 0;
4580         }
4581
4582         if (parse_uid(*username, &u) >= 0) {
4583                 errno = 0;
4584                 p = getpwuid(u);
4585
4586                 /* If there are multiple users with the same id, make
4587                  * sure to leave $USER to the configured value instead
4588                  * of the first occurrence in the database. However if
4589                  * the uid was configured by a numeric uid, then let's
4590                  * pick the real username from /etc/passwd. */
4591                 if (p)
4592                         *username = p->pw_name;
4593         } else {
4594                 errno = 0;
4595                 p = getpwnam(*username);
4596         }
4597
4598         if (!p)
4599                 return errno > 0 ? -errno : -ESRCH;
4600
4601         if (uid)
4602                 *uid = p->pw_uid;
4603
4604         if (gid)
4605                 *gid = p->pw_gid;
4606
4607         if (home)
4608                 *home = p->pw_dir;
4609
4610         if (shell)
4611                 *shell = p->pw_shell;
4612
4613         return 0;
4614 }
4615
4616 char* uid_to_name(uid_t uid) {
4617         struct passwd *p;
4618         char *r;
4619
4620         if (uid == 0)
4621                 return strdup("root");
4622
4623         p = getpwuid(uid);
4624         if (p)
4625                 return strdup(p->pw_name);
4626
4627         if (asprintf(&r, UID_FMT, uid) < 0)
4628                 return NULL;
4629
4630         return r;
4631 }
4632
4633 char* gid_to_name(gid_t gid) {
4634         struct group *p;
4635         char *r;
4636
4637         if (gid == 0)
4638                 return strdup("root");
4639
4640         p = getgrgid(gid);
4641         if (p)
4642                 return strdup(p->gr_name);
4643
4644         if (asprintf(&r, GID_FMT, gid) < 0)
4645                 return NULL;
4646
4647         return r;
4648 }
4649
4650 int get_group_creds(const char **groupname, gid_t *gid) {
4651         struct group *g;
4652         gid_t id;
4653
4654         assert(groupname);
4655
4656         /* We enforce some special rules for gid=0: in order to avoid
4657          * NSS lookups for root we hardcode its data. */
4658
4659         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4660                 *groupname = "root";
4661
4662                 if (gid)
4663                         *gid = 0;
4664
4665                 return 0;
4666         }
4667
4668         if (parse_gid(*groupname, &id) >= 0) {
4669                 errno = 0;
4670                 g = getgrgid(id);
4671
4672                 if (g)
4673                         *groupname = g->gr_name;
4674         } else {
4675                 errno = 0;
4676                 g = getgrnam(*groupname);
4677         }
4678
4679         if (!g)
4680                 return errno > 0 ? -errno : -ESRCH;
4681
4682         if (gid)
4683                 *gid = g->gr_gid;
4684
4685         return 0;
4686 }
4687
4688 int in_gid(gid_t gid) {
4689         gid_t *gids;
4690         int ngroups_max, r, i;
4691
4692         if (getgid() == gid)
4693                 return 1;
4694
4695         if (getegid() == gid)
4696                 return 1;
4697
4698         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4699         assert(ngroups_max > 0);
4700
4701         gids = alloca(sizeof(gid_t) * ngroups_max);
4702
4703         r = getgroups(ngroups_max, gids);
4704         if (r < 0)
4705                 return -errno;
4706
4707         for (i = 0; i < r; i++)
4708                 if (gids[i] == gid)
4709                         return 1;
4710
4711         return 0;
4712 }
4713
4714 int in_group(const char *name) {
4715         int r;
4716         gid_t gid;
4717
4718         r = get_group_creds(&name, &gid);
4719         if (r < 0)
4720                 return r;
4721
4722         return in_gid(gid);
4723 }
4724
4725 int glob_exists(const char *path) {
4726         _cleanup_globfree_ glob_t g = {};
4727         int k;
4728
4729         assert(path);
4730
4731         errno = 0;
4732         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4733
4734         if (k == GLOB_NOMATCH)
4735                 return 0;
4736         else if (k == GLOB_NOSPACE)
4737                 return -ENOMEM;
4738         else if (k == 0)
4739                 return !strv_isempty(g.gl_pathv);
4740         else
4741                 return errno ? -errno : -EIO;
4742 }
4743
4744 int glob_extend(char ***strv, const char *path) {
4745         _cleanup_globfree_ glob_t g = {};
4746         int k;
4747         char **p;
4748
4749         errno = 0;
4750         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4751
4752         if (k == GLOB_NOMATCH)
4753                 return -ENOENT;
4754         else if (k == GLOB_NOSPACE)
4755                 return -ENOMEM;
4756         else if (k != 0 || strv_isempty(g.gl_pathv))
4757                 return errno ? -errno : -EIO;
4758
4759         STRV_FOREACH(p, g.gl_pathv) {
4760                 k = strv_extend(strv, *p);
4761                 if (k < 0)
4762                         break;
4763         }
4764
4765         return k;
4766 }
4767
4768 int dirent_ensure_type(DIR *d, struct dirent *de) {
4769         struct stat st;
4770
4771         assert(d);
4772         assert(de);
4773
4774         if (de->d_type != DT_UNKNOWN)
4775                 return 0;
4776
4777         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4778                 return -errno;
4779
4780         de->d_type =
4781                 S_ISREG(st.st_mode)  ? DT_REG  :
4782                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4783                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4784                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4785                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4786                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4787                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4788                                        DT_UNKNOWN;
4789
4790         return 0;
4791 }
4792
4793 int get_files_in_directory(const char *path, char ***list) {
4794         _cleanup_closedir_ DIR *d = NULL;
4795         size_t bufsize = 0, n = 0;
4796         _cleanup_strv_free_ char **l = NULL;
4797
4798         assert(path);
4799
4800         /* Returns all files in a directory in *list, and the number
4801          * of files as return value. If list is NULL returns only the
4802          * number. */
4803
4804         d = opendir(path);
4805         if (!d)
4806                 return -errno;
4807
4808         for (;;) {
4809                 struct dirent *de;
4810
4811                 errno = 0;
4812                 de = readdir(d);
4813                 if (!de && errno != 0)
4814                         return -errno;
4815                 if (!de)
4816                         break;
4817
4818                 dirent_ensure_type(d, de);
4819
4820                 if (!dirent_is_file(de))
4821                         continue;
4822
4823                 if (list) {
4824                         /* one extra slot is needed for the terminating NULL */
4825                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
4826                                 return -ENOMEM;
4827
4828                         l[n] = strdup(de->d_name);
4829                         if (!l[n])
4830                                 return -ENOMEM;
4831
4832                         l[++n] = NULL;
4833                 } else
4834                         n++;
4835         }
4836
4837         if (list) {
4838                 *list = l;
4839                 l = NULL; /* avoid freeing */
4840         }
4841
4842         return n;
4843 }
4844
4845 char *strjoin(const char *x, ...) {
4846         va_list ap;
4847         size_t l;
4848         char *r, *p;
4849
4850         va_start(ap, x);
4851
4852         if (x) {
4853                 l = strlen(x);
4854
4855                 for (;;) {
4856                         const char *t;
4857                         size_t n;
4858
4859                         t = va_arg(ap, const char *);
4860                         if (!t)
4861                                 break;
4862
4863                         n = strlen(t);
4864                         if (n > ((size_t) -1) - l) {
4865                                 va_end(ap);
4866                                 return NULL;
4867                         }
4868
4869                         l += n;
4870                 }
4871         } else
4872                 l = 0;
4873
4874         va_end(ap);
4875
4876         r = new(char, l+1);
4877         if (!r)
4878                 return NULL;
4879
4880         if (x) {
4881                 p = stpcpy(r, x);
4882
4883                 va_start(ap, x);
4884
4885                 for (;;) {
4886                         const char *t;
4887
4888                         t = va_arg(ap, const char *);
4889                         if (!t)
4890                                 break;
4891
4892                         p = stpcpy(p, t);
4893                 }
4894
4895                 va_end(ap);
4896         } else
4897                 r[0] = 0;
4898
4899         return r;
4900 }
4901
4902 bool is_main_thread(void) {
4903         static thread_local int cached = 0;
4904
4905         if (_unlikely_(cached == 0))
4906                 cached = getpid() == gettid() ? 1 : -1;
4907
4908         return cached > 0;
4909 }
4910
4911 int block_get_whole_disk(dev_t d, dev_t *ret) {
4912         char *p, *s;
4913         int r;
4914         unsigned n, m;
4915
4916         assert(ret);
4917
4918         /* If it has a queue this is good enough for us */
4919         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4920                 return -ENOMEM;
4921
4922         r = access(p, F_OK);
4923         free(p);
4924
4925         if (r >= 0) {
4926                 *ret = d;
4927                 return 0;
4928         }
4929
4930         /* If it is a partition find the originating device */
4931         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4932                 return -ENOMEM;
4933
4934         r = access(p, F_OK);
4935         free(p);
4936
4937         if (r < 0)
4938                 return -ENOENT;
4939
4940         /* Get parent dev_t */
4941         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4942                 return -ENOMEM;
4943
4944         r = read_one_line_file(p, &s);
4945         free(p);
4946
4947         if (r < 0)
4948                 return r;
4949
4950         r = sscanf(s, "%u:%u", &m, &n);
4951         free(s);
4952
4953         if (r != 2)
4954                 return -EINVAL;
4955
4956         /* Only return this if it is really good enough for us. */
4957         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4958                 return -ENOMEM;
4959
4960         r = access(p, F_OK);
4961         free(p);
4962
4963         if (r >= 0) {
4964                 *ret = makedev(m, n);
4965                 return 0;
4966         }
4967
4968         return -ENOENT;
4969 }
4970
4971 static const char *const ioprio_class_table[] = {
4972         [IOPRIO_CLASS_NONE] = "none",
4973         [IOPRIO_CLASS_RT] = "realtime",
4974         [IOPRIO_CLASS_BE] = "best-effort",
4975         [IOPRIO_CLASS_IDLE] = "idle"
4976 };
4977
4978 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4979
4980 static const char *const sigchld_code_table[] = {
4981         [CLD_EXITED] = "exited",
4982         [CLD_KILLED] = "killed",
4983         [CLD_DUMPED] = "dumped",
4984         [CLD_TRAPPED] = "trapped",
4985         [CLD_STOPPED] = "stopped",
4986         [CLD_CONTINUED] = "continued",
4987 };
4988
4989 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4990
4991 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4992         [LOG_FAC(LOG_KERN)] = "kern",
4993         [LOG_FAC(LOG_USER)] = "user",
4994         [LOG_FAC(LOG_MAIL)] = "mail",
4995         [LOG_FAC(LOG_DAEMON)] = "daemon",
4996         [LOG_FAC(LOG_AUTH)] = "auth",
4997         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4998         [LOG_FAC(LOG_LPR)] = "lpr",
4999         [LOG_FAC(LOG_NEWS)] = "news",
5000         [LOG_FAC(LOG_UUCP)] = "uucp",
5001         [LOG_FAC(LOG_CRON)] = "cron",
5002         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5003         [LOG_FAC(LOG_FTP)] = "ftp",
5004         [LOG_FAC(LOG_LOCAL0)] = "local0",
5005         [LOG_FAC(LOG_LOCAL1)] = "local1",
5006         [LOG_FAC(LOG_LOCAL2)] = "local2",
5007         [LOG_FAC(LOG_LOCAL3)] = "local3",
5008         [LOG_FAC(LOG_LOCAL4)] = "local4",
5009         [LOG_FAC(LOG_LOCAL5)] = "local5",
5010         [LOG_FAC(LOG_LOCAL6)] = "local6",
5011         [LOG_FAC(LOG_LOCAL7)] = "local7"
5012 };
5013
5014 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5015
5016 static const char *const log_level_table[] = {
5017         [LOG_EMERG] = "emerg",
5018         [LOG_ALERT] = "alert",
5019         [LOG_CRIT] = "crit",
5020         [LOG_ERR] = "err",
5021         [LOG_WARNING] = "warning",
5022         [LOG_NOTICE] = "notice",
5023         [LOG_INFO] = "info",
5024         [LOG_DEBUG] = "debug"
5025 };
5026
5027 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5028
5029 static const char* const sched_policy_table[] = {
5030         [SCHED_OTHER] = "other",
5031         [SCHED_BATCH] = "batch",
5032         [SCHED_IDLE] = "idle",
5033         [SCHED_FIFO] = "fifo",
5034         [SCHED_RR] = "rr"
5035 };
5036
5037 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5038
5039 static const char* const rlimit_table[_RLIMIT_MAX] = {
5040         [RLIMIT_CPU] = "LimitCPU",
5041         [RLIMIT_FSIZE] = "LimitFSIZE",
5042         [RLIMIT_DATA] = "LimitDATA",
5043         [RLIMIT_STACK] = "LimitSTACK",
5044         [RLIMIT_CORE] = "LimitCORE",
5045         [RLIMIT_RSS] = "LimitRSS",
5046         [RLIMIT_NOFILE] = "LimitNOFILE",
5047         [RLIMIT_AS] = "LimitAS",
5048         [RLIMIT_NPROC] = "LimitNPROC",
5049         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5050         [RLIMIT_LOCKS] = "LimitLOCKS",
5051         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5052         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5053         [RLIMIT_NICE] = "LimitNICE",
5054         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5055         [RLIMIT_RTTIME] = "LimitRTTIME"
5056 };
5057
5058 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5059
5060 static const char* const ip_tos_table[] = {
5061         [IPTOS_LOWDELAY] = "low-delay",
5062         [IPTOS_THROUGHPUT] = "throughput",
5063         [IPTOS_RELIABILITY] = "reliability",
5064         [IPTOS_LOWCOST] = "low-cost",
5065 };
5066
5067 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5068
5069 static const char *const __signal_table[] = {
5070         [SIGHUP] = "HUP",
5071         [SIGINT] = "INT",
5072         [SIGQUIT] = "QUIT",
5073         [SIGILL] = "ILL",
5074         [SIGTRAP] = "TRAP",
5075         [SIGABRT] = "ABRT",
5076         [SIGBUS] = "BUS",
5077         [SIGFPE] = "FPE",
5078         [SIGKILL] = "KILL",
5079         [SIGUSR1] = "USR1",
5080         [SIGSEGV] = "SEGV",
5081         [SIGUSR2] = "USR2",
5082         [SIGPIPE] = "PIPE",
5083         [SIGALRM] = "ALRM",
5084         [SIGTERM] = "TERM",
5085 #ifdef SIGSTKFLT
5086         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5087 #endif
5088         [SIGCHLD] = "CHLD",
5089         [SIGCONT] = "CONT",
5090         [SIGSTOP] = "STOP",
5091         [SIGTSTP] = "TSTP",
5092         [SIGTTIN] = "TTIN",
5093         [SIGTTOU] = "TTOU",
5094         [SIGURG] = "URG",
5095         [SIGXCPU] = "XCPU",
5096         [SIGXFSZ] = "XFSZ",
5097         [SIGVTALRM] = "VTALRM",
5098         [SIGPROF] = "PROF",
5099         [SIGWINCH] = "WINCH",
5100         [SIGIO] = "IO",
5101         [SIGPWR] = "PWR",
5102         [SIGSYS] = "SYS"
5103 };
5104
5105 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5106
5107 const char *signal_to_string(int signo) {
5108         static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
5109         const char *name;
5110
5111         name = __signal_to_string(signo);
5112         if (name)
5113                 return name;
5114
5115         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5116                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
5117         else
5118                 snprintf(buf, sizeof(buf), "%d", signo);
5119
5120         return buf;
5121 }
5122
5123 int signal_from_string(const char *s) {
5124         int signo;
5125         int offset = 0;
5126         unsigned u;
5127
5128         signo = __signal_from_string(s);
5129         if (signo > 0)
5130                 return signo;
5131
5132         if (startswith(s, "RTMIN+")) {
5133                 s += 6;
5134                 offset = SIGRTMIN;
5135         }
5136         if (safe_atou(s, &u) >= 0) {
5137                 signo = (int) u + offset;
5138                 if (signo > 0 && signo < _NSIG)
5139                         return signo;
5140         }
5141         return -EINVAL;
5142 }
5143
5144 bool kexec_loaded(void) {
5145        bool loaded = false;
5146        char *s;
5147
5148        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5149                if (s[0] == '1')
5150                        loaded = true;
5151                free(s);
5152        }
5153        return loaded;
5154 }
5155
5156 int prot_from_flags(int flags) {
5157
5158         switch (flags & O_ACCMODE) {
5159
5160         case O_RDONLY:
5161                 return PROT_READ;
5162
5163         case O_WRONLY:
5164                 return PROT_WRITE;
5165
5166         case O_RDWR:
5167                 return PROT_READ|PROT_WRITE;
5168
5169         default:
5170                 return -EINVAL;
5171         }
5172 }
5173
5174 char *format_bytes(char *buf, size_t l, off_t t) {
5175         unsigned i;
5176
5177         static const struct {
5178                 const char *suffix;
5179                 off_t factor;
5180         } table[] = {
5181                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5182                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5183                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5184                 { "G", 1024ULL*1024ULL*1024ULL },
5185                 { "M", 1024ULL*1024ULL },
5186                 { "K", 1024ULL },
5187         };
5188
5189         if (t == (off_t) -1)
5190                 return NULL;
5191
5192         for (i = 0; i < ELEMENTSOF(table); i++) {
5193
5194                 if (t >= table[i].factor) {
5195                         snprintf(buf, l,
5196                                  "%llu.%llu%s",
5197                                  (unsigned long long) (t / table[i].factor),
5198                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5199                                  table[i].suffix);
5200
5201                         goto finish;
5202                 }
5203         }
5204
5205         snprintf(buf, l, "%lluB", (unsigned long long) t);
5206
5207 finish:
5208         buf[l-1] = 0;
5209         return buf;
5210
5211 }
5212
5213 void* memdup(const void *p, size_t l) {
5214         void *r;
5215
5216         assert(p);
5217
5218         r = malloc(l);
5219         if (!r)
5220                 return NULL;
5221
5222         memcpy(r, p, l);
5223         return r;
5224 }
5225
5226 int fd_inc_sndbuf(int fd, size_t n) {
5227         int r, value;
5228         socklen_t l = sizeof(value);
5229
5230         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5231         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5232                 return 0;
5233
5234         /* If we have the privileges we will ignore the kernel limit. */
5235
5236         value = (int) n;
5237         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5238                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5239                         return -errno;
5240
5241         return 1;
5242 }
5243
5244 int fd_inc_rcvbuf(int fd, size_t n) {
5245         int r, value;
5246         socklen_t l = sizeof(value);
5247
5248         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5249         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5250                 return 0;
5251
5252         /* If we have the privileges we will ignore the kernel limit. */
5253
5254         value = (int) n;
5255         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5256                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5257                         return -errno;
5258         return 1;
5259 }
5260
5261 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5262         bool stdout_is_tty, stderr_is_tty;
5263         pid_t parent_pid, agent_pid;
5264         sigset_t ss, saved_ss;
5265         unsigned n, i;
5266         va_list ap;
5267         char **l;
5268
5269         assert(pid);
5270         assert(path);
5271
5272         /* Spawns a temporary TTY agent, making sure it goes away when
5273          * we go away */
5274
5275         parent_pid = getpid();
5276
5277         /* First we temporarily block all signals, so that the new
5278          * child has them blocked initially. This way, we can be sure
5279          * that SIGTERMs are not lost we might send to the agent. */
5280         assert_se(sigfillset(&ss) >= 0);
5281         assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
5282
5283         agent_pid = fork();
5284         if (agent_pid < 0) {
5285                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5286                 return -errno;
5287         }
5288
5289         if (agent_pid != 0) {
5290                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5291                 *pid = agent_pid;
5292                 return 0;
5293         }
5294
5295         /* In the child:
5296          *
5297          * Make sure the agent goes away when the parent dies */
5298         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5299                 _exit(EXIT_FAILURE);
5300
5301         /* Make sure we actually can kill the agent, if we need to, in
5302          * case somebody invoked us from a shell script that trapped
5303          * SIGTERM or so... */
5304         reset_all_signal_handlers();
5305         reset_signal_mask();
5306
5307         /* Check whether our parent died before we were able
5308          * to set the death signal and unblock the signals */
5309         if (getppid() != parent_pid)
5310                 _exit(EXIT_SUCCESS);
5311
5312         /* Don't leak fds to the agent */
5313         close_all_fds(except, n_except);
5314
5315         stdout_is_tty = isatty(STDOUT_FILENO);
5316         stderr_is_tty = isatty(STDERR_FILENO);
5317
5318         if (!stdout_is_tty || !stderr_is_tty) {
5319                 int fd;
5320
5321                 /* Detach from stdout/stderr. and reopen
5322                  * /dev/tty for them. This is important to
5323                  * ensure that when systemctl is started via
5324                  * popen() or a similar call that expects to
5325                  * read EOF we actually do generate EOF and
5326                  * not delay this indefinitely by because we
5327                  * keep an unused copy of stdin around. */
5328                 fd = open("/dev/tty", O_WRONLY);
5329                 if (fd < 0) {
5330                         log_error_errno(errno, "Failed to open /dev/tty: %m");
5331                         _exit(EXIT_FAILURE);
5332                 }
5333
5334                 if (!stdout_is_tty)
5335                         dup2(fd, STDOUT_FILENO);
5336
5337                 if (!stderr_is_tty)
5338                         dup2(fd, STDERR_FILENO);
5339
5340                 if (fd > 2)
5341                         close(fd);
5342         }
5343
5344         /* Count arguments */
5345         va_start(ap, path);
5346         for (n = 0; va_arg(ap, char*); n++)
5347                 ;
5348         va_end(ap);
5349
5350         /* Allocate strv */
5351         l = alloca(sizeof(char *) * (n + 1));
5352
5353         /* Fill in arguments */
5354         va_start(ap, path);
5355         for (i = 0; i <= n; i++)
5356                 l[i] = va_arg(ap, char*);
5357         va_end(ap);
5358
5359         execv(path, l);
5360         _exit(EXIT_FAILURE);
5361 }
5362
5363 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5364         struct rlimit highest, fixed;
5365
5366         assert(rlim);
5367
5368         if (setrlimit(resource, rlim) >= 0)
5369                 return 0;
5370
5371         if (errno != EPERM)
5372                 return -errno;
5373
5374         /* So we failed to set the desired setrlimit, then let's try
5375          * to get as close as we can */
5376         assert_se(getrlimit(resource, &highest) == 0);
5377
5378         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5379         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5380
5381         if (setrlimit(resource, &fixed) < 0)
5382                 return -errno;
5383
5384         return 0;
5385 }
5386
5387 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5388         _cleanup_fclose_ FILE *f = NULL;
5389         char *value = NULL;
5390         int r;
5391         bool done = false;
5392         size_t l;
5393         const char *path;
5394
5395         assert(pid >= 0);
5396         assert(field);
5397         assert(_value);
5398
5399         path = procfs_file_alloca(pid, "environ");
5400
5401         f = fopen(path, "re");
5402         if (!f)
5403                 return -errno;
5404
5405         l = strlen(field);
5406         r = 0;
5407
5408         do {
5409                 char line[LINE_MAX];
5410                 unsigned i;
5411
5412                 for (i = 0; i < sizeof(line)-1; i++) {
5413                         int c;
5414
5415                         c = getc(f);
5416                         if (_unlikely_(c == EOF)) {
5417                                 done = true;
5418                                 break;
5419                         } else if (c == 0)
5420                                 break;
5421
5422                         line[i] = c;
5423                 }
5424                 line[i] = 0;
5425
5426                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5427                         value = strdup(line + l + 1);
5428                         if (!value)
5429                                 return -ENOMEM;
5430
5431                         r = 1;
5432                         break;
5433                 }
5434
5435         } while (!done);
5436
5437         *_value = value;
5438         return r;
5439 }
5440
5441 bool is_valid_documentation_url(const char *url) {
5442         assert(url);
5443
5444         if (startswith(url, "http://") && url[7])
5445                 return true;
5446
5447         if (startswith(url, "https://") && url[8])
5448                 return true;
5449
5450         if (startswith(url, "file:") && url[5])
5451                 return true;
5452
5453         if (startswith(url, "info:") && url[5])
5454                 return true;
5455
5456         if (startswith(url, "man:") && url[4])
5457                 return true;
5458
5459         return false;
5460 }
5461
5462 bool in_initrd(void) {
5463         static int saved = -1;
5464         struct statfs s;
5465
5466         if (saved >= 0)
5467                 return saved;
5468
5469         /* We make two checks here:
5470          *
5471          * 1. the flag file /etc/initrd-release must exist
5472          * 2. the root file system must be a memory file system
5473          *
5474          * The second check is extra paranoia, since misdetecting an
5475          * initrd can have bad bad consequences due the initrd
5476          * emptying when transititioning to the main systemd.
5477          */
5478
5479         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5480                 statfs("/", &s) >= 0 &&
5481                 is_temporary_fs(&s);
5482
5483         return saved;
5484 }
5485
5486 void warn_melody(void) {
5487         _cleanup_close_ int fd = -1;
5488
5489         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5490         if (fd < 0)
5491                 return;
5492
5493         /* Yeah, this is synchronous. Kinda sucks. But well... */
5494
5495         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5496         usleep(125*USEC_PER_MSEC);
5497
5498         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5499         usleep(125*USEC_PER_MSEC);
5500
5501         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5502         usleep(125*USEC_PER_MSEC);
5503
5504         ioctl(fd, KIOCSOUND, 0);
5505 }
5506
5507 int make_console_stdio(void) {
5508         int fd, r;
5509
5510         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5511
5512         fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5513         if (fd < 0)
5514                 return log_error_errno(fd, "Failed to acquire terminal: %m");
5515
5516         r = make_stdio(fd);
5517         if (r < 0)
5518                 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5519
5520         return 0;
5521 }
5522
5523 int get_home_dir(char **_h) {
5524         struct passwd *p;
5525         const char *e;
5526         char *h;
5527         uid_t u;
5528
5529         assert(_h);
5530
5531         /* Take the user specified one */
5532         e = secure_getenv("HOME");
5533         if (e && path_is_absolute(e)) {
5534                 h = strdup(e);
5535                 if (!h)
5536                         return -ENOMEM;
5537
5538                 *_h = h;
5539                 return 0;
5540         }
5541
5542         /* Hardcode home directory for root to avoid NSS */
5543         u = getuid();
5544         if (u == 0) {
5545                 h = strdup("/root");
5546                 if (!h)
5547                         return -ENOMEM;
5548
5549                 *_h = h;
5550                 return 0;
5551         }
5552
5553         /* Check the database... */
5554         errno = 0;
5555         p = getpwuid(u);
5556         if (!p)
5557                 return errno > 0 ? -errno : -ESRCH;
5558
5559         if (!path_is_absolute(p->pw_dir))
5560                 return -EINVAL;
5561
5562         h = strdup(p->pw_dir);
5563         if (!h)
5564                 return -ENOMEM;
5565
5566         *_h = h;
5567         return 0;
5568 }
5569
5570 int get_shell(char **_s) {
5571         struct passwd *p;
5572         const char *e;
5573         char *s;
5574         uid_t u;
5575
5576         assert(_s);
5577
5578         /* Take the user specified one */
5579         e = getenv("SHELL");
5580         if (e) {
5581                 s = strdup(e);
5582                 if (!s)
5583                         return -ENOMEM;
5584
5585                 *_s = s;
5586                 return 0;
5587         }
5588
5589         /* Hardcode home directory for root to avoid NSS */
5590         u = getuid();
5591         if (u == 0) {
5592                 s = strdup("/bin/sh");
5593                 if (!s)
5594                         return -ENOMEM;
5595
5596                 *_s = s;
5597                 return 0;
5598         }
5599
5600         /* Check the database... */
5601         errno = 0;
5602         p = getpwuid(u);
5603         if (!p)
5604                 return errno > 0 ? -errno : -ESRCH;
5605
5606         if (!path_is_absolute(p->pw_shell))
5607                 return -EINVAL;
5608
5609         s = strdup(p->pw_shell);
5610         if (!s)
5611                 return -ENOMEM;
5612
5613         *_s = s;
5614         return 0;
5615 }
5616
5617 bool filename_is_valid(const char *p) {
5618
5619         if (isempty(p))
5620                 return false;
5621
5622         if (strchr(p, '/'))
5623                 return false;
5624
5625         if (streq(p, "."))
5626                 return false;
5627
5628         if (streq(p, ".."))
5629                 return false;
5630
5631         if (strlen(p) > FILENAME_MAX)
5632                 return false;
5633
5634         return true;
5635 }
5636
5637 bool string_is_safe(const char *p) {
5638         const char *t;
5639
5640         if (!p)
5641                 return false;
5642
5643         for (t = p; *t; t++) {
5644                 if (*t > 0 && *t < ' ')
5645                         return false;
5646
5647                 if (strchr("\\\"\'\0x7f", *t))
5648                         return false;
5649         }
5650
5651         return true;
5652 }
5653
5654 /**
5655  * Check if a string contains control characters. If 'ok' is non-NULL
5656  * it may be a string containing additional CCs to be considered OK.
5657  */
5658 bool string_has_cc(const char *p, const char *ok) {
5659         const char *t;
5660
5661         assert(p);
5662
5663         for (t = p; *t; t++) {
5664                 if (ok && strchr(ok, *t))
5665                         continue;
5666
5667                 if (*t > 0 && *t < ' ')
5668                         return true;
5669
5670                 if (*t == 127)
5671                         return true;
5672         }
5673
5674         return false;
5675 }
5676
5677 bool path_is_safe(const char *p) {
5678
5679         if (isempty(p))
5680                 return false;
5681
5682         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5683                 return false;
5684
5685         if (strlen(p) > PATH_MAX)
5686                 return false;
5687
5688         /* The following two checks are not really dangerous, but hey, they still are confusing */
5689         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5690                 return false;
5691
5692         if (strstr(p, "//"))
5693                 return false;
5694
5695         return true;
5696 }
5697
5698 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5699 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5700                  int (*compar) (const void *, const void *, void *), void *arg) {
5701         size_t l, u, idx;
5702         const void *p;
5703         int comparison;
5704
5705         l = 0;
5706         u = nmemb;
5707         while (l < u) {
5708                 idx = (l + u) / 2;
5709                 p = (void *)(((const char *) base) + (idx * size));
5710                 comparison = compar(key, p, arg);
5711                 if (comparison < 0)
5712                         u = idx;
5713                 else if (comparison > 0)
5714                         l = idx + 1;
5715                 else
5716                         return (void *)p;
5717         }
5718         return NULL;
5719 }
5720
5721 bool is_locale_utf8(void) {
5722         const char *set;
5723         static int cached_answer = -1;
5724
5725         if (cached_answer >= 0)
5726                 goto out;
5727
5728         if (!setlocale(LC_ALL, "")) {
5729                 cached_answer = true;
5730                 goto out;
5731         }
5732
5733         set = nl_langinfo(CODESET);
5734         if (!set) {
5735                 cached_answer = true;
5736                 goto out;
5737         }
5738
5739         if (streq(set, "UTF-8")) {
5740                 cached_answer = true;
5741                 goto out;
5742         }
5743
5744         /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5745          * unset and everything can do to UTF-8 nowadays. */
5746         set = setlocale(LC_CTYPE, NULL);
5747         if (!set) {
5748                 cached_answer = true;
5749                 goto out;
5750         }
5751
5752         /* Check result, but ignore the result if C was set
5753          * explicitly. */
5754         cached_answer =
5755                 streq(set, "C") &&
5756                 !getenv("LC_ALL") &&
5757                 !getenv("LC_CTYPE") &&
5758                 !getenv("LANG");
5759
5760 out:
5761         return (bool) cached_answer;
5762 }
5763
5764 const char *draw_special_char(DrawSpecialChar ch) {
5765         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5766
5767                 /* UTF-8 */ {
5768                         [DRAW_TREE_VERTICAL]      = "\342\224\202 ",            /* │  */
5769                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
5770                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
5771                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5772                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243",             /* ‣ */
5773                         [DRAW_BLACK_CIRCLE]       = "\342\227\217",             /* ● */
5774                         [DRAW_ARROW]              = "\342\206\222",             /* → */
5775                         [DRAW_DASH]               = "\342\200\223",             /* – */
5776                 },
5777
5778                 /* ASCII fallback */ {
5779                         [DRAW_TREE_VERTICAL]      = "| ",
5780                         [DRAW_TREE_BRANCH]        = "|-",
5781                         [DRAW_TREE_RIGHT]         = "`-",
5782                         [DRAW_TREE_SPACE]         = "  ",
5783                         [DRAW_TRIANGULAR_BULLET]  = ">",
5784                         [DRAW_BLACK_CIRCLE]       = "*",
5785                         [DRAW_ARROW]              = "->",
5786                         [DRAW_DASH]               = "-",
5787                 }
5788         };
5789
5790         return draw_table[!is_locale_utf8()][ch];
5791 }
5792
5793 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5794         const char *f;
5795         char *t, *r;
5796         size_t l, old_len, new_len;
5797
5798         assert(text);
5799         assert(old_string);
5800         assert(new_string);
5801
5802         old_len = strlen(old_string);
5803         new_len = strlen(new_string);
5804
5805         l = strlen(text);
5806         r = new(char, l+1);
5807         if (!r)
5808                 return NULL;
5809
5810         f = text;
5811         t = r;
5812         while (*f) {
5813                 char *a;
5814                 size_t d, nl;
5815
5816                 if (!startswith(f, old_string)) {
5817                         *(t++) = *(f++);
5818                         continue;
5819                 }
5820
5821                 d = t - r;
5822                 nl = l - old_len + new_len;
5823                 a = realloc(r, nl + 1);
5824                 if (!a)
5825                         goto oom;
5826
5827                 l = nl;
5828                 r = a;
5829                 t = r + d;
5830
5831                 t = stpcpy(t, new_string);
5832                 f += old_len;
5833         }
5834
5835         *t = 0;
5836         return r;
5837
5838 oom:
5839         free(r);
5840         return NULL;
5841 }
5842
5843 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5844         const char *i, *begin = NULL;
5845         enum {
5846                 STATE_OTHER,
5847                 STATE_ESCAPE,
5848                 STATE_BRACKET
5849         } state = STATE_OTHER;
5850         char *obuf = NULL;
5851         size_t osz = 0, isz;
5852         FILE *f;
5853
5854         assert(ibuf);
5855         assert(*ibuf);
5856
5857         /* Strips ANSI color and replaces TABs by 8 spaces */
5858
5859         isz = _isz ? *_isz : strlen(*ibuf);
5860
5861         f = open_memstream(&obuf, &osz);
5862         if (!f)
5863                 return NULL;
5864
5865         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5866
5867                 switch (state) {
5868
5869                 case STATE_OTHER:
5870                         if (i >= *ibuf + isz) /* EOT */
5871                                 break;
5872                         else if (*i == '\x1B')
5873                                 state = STATE_ESCAPE;
5874                         else if (*i == '\t')
5875                                 fputs("        ", f);
5876                         else
5877                                 fputc(*i, f);
5878                         break;
5879
5880                 case STATE_ESCAPE:
5881                         if (i >= *ibuf + isz) { /* EOT */
5882                                 fputc('\x1B', f);
5883                                 break;
5884                         } else if (*i == '[') {
5885                                 state = STATE_BRACKET;
5886                                 begin = i + 1;
5887                         } else {
5888                                 fputc('\x1B', f);
5889                                 fputc(*i, f);
5890                                 state = STATE_OTHER;
5891                         }
5892
5893                         break;
5894
5895                 case STATE_BRACKET:
5896
5897                         if (i >= *ibuf + isz || /* EOT */
5898                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5899                                 fputc('\x1B', f);
5900                                 fputc('[', f);
5901                                 state = STATE_OTHER;
5902                                 i = begin-1;
5903                         } else if (*i == 'm')
5904                                 state = STATE_OTHER;
5905                         break;
5906                 }
5907         }
5908
5909         if (ferror(f)) {
5910                 fclose(f);
5911                 free(obuf);
5912                 return NULL;
5913         }
5914
5915         fclose(f);
5916
5917         free(*ibuf);
5918         *ibuf = obuf;
5919
5920         if (_isz)
5921                 *_isz = osz;
5922
5923         return obuf;
5924 }
5925
5926 int on_ac_power(void) {
5927         bool found_offline = false, found_online = false;
5928         _cleanup_closedir_ DIR *d = NULL;
5929
5930         d = opendir("/sys/class/power_supply");
5931         if (!d)
5932                 return -errno;
5933
5934         for (;;) {
5935                 struct dirent *de;
5936                 _cleanup_close_ int fd = -1, device = -1;
5937                 char contents[6];
5938                 ssize_t n;
5939
5940                 errno = 0;
5941                 de = readdir(d);
5942                 if (!de && errno != 0)
5943                         return -errno;
5944
5945                 if (!de)
5946                         break;
5947
5948                 if (hidden_file(de->d_name))
5949                         continue;
5950
5951                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5952                 if (device < 0) {
5953                         if (errno == ENOENT || errno == ENOTDIR)
5954                                 continue;
5955
5956                         return -errno;
5957                 }
5958
5959                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5960                 if (fd < 0) {
5961                         if (errno == ENOENT)
5962                                 continue;
5963
5964                         return -errno;
5965                 }
5966
5967                 n = read(fd, contents, sizeof(contents));
5968                 if (n < 0)
5969                         return -errno;
5970
5971                 if (n != 6 || memcmp(contents, "Mains\n", 6))
5972                         continue;
5973
5974                 safe_close(fd);
5975                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5976                 if (fd < 0) {
5977                         if (errno == ENOENT)
5978                                 continue;
5979
5980                         return -errno;
5981                 }
5982
5983                 n = read(fd, contents, sizeof(contents));
5984                 if (n < 0)
5985                         return -errno;
5986
5987                 if (n != 2 || contents[1] != '\n')
5988                         return -EIO;
5989
5990                 if (contents[0] == '1') {
5991                         found_online = true;
5992                         break;
5993                 } else if (contents[0] == '0')
5994                         found_offline = true;
5995                 else
5996                         return -EIO;
5997         }
5998
5999         return found_online || !found_offline;
6000 }
6001
6002 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
6003         char **i;
6004
6005         assert(path);
6006         assert(mode);
6007         assert(_f);
6008
6009         if (!path_strv_resolve_uniq(search, root))
6010                 return -ENOMEM;
6011
6012         STRV_FOREACH(i, search) {
6013                 _cleanup_free_ char *p = NULL;
6014                 FILE *f;
6015
6016                 if (root)
6017                         p = strjoin(root, *i, "/", path, NULL);
6018                 else
6019                         p = strjoin(*i, "/", path, NULL);
6020                 if (!p)
6021                         return -ENOMEM;
6022
6023                 f = fopen(p, mode);
6024                 if (f) {
6025                         *_f = f;
6026                         return 0;
6027                 }
6028
6029                 if (errno != ENOENT)
6030                         return -errno;
6031         }
6032
6033         return -ENOENT;
6034 }
6035
6036 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
6037         _cleanup_strv_free_ char **copy = NULL;
6038
6039         assert(path);
6040         assert(mode);
6041         assert(_f);
6042
6043         if (path_is_absolute(path)) {
6044                 FILE *f;
6045
6046                 f = fopen(path, mode);
6047                 if (f) {
6048                         *_f = f;
6049                         return 0;
6050                 }
6051
6052                 return -errno;
6053         }
6054
6055         copy = strv_copy((char**) search);
6056         if (!copy)
6057                 return -ENOMEM;
6058
6059         return search_and_fopen_internal(path, mode, root, copy, _f);
6060 }
6061
6062 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
6063         _cleanup_strv_free_ char **s = NULL;
6064
6065         if (path_is_absolute(path)) {
6066                 FILE *f;
6067
6068                 f = fopen(path, mode);
6069                 if (f) {
6070                         *_f = f;
6071                         return 0;
6072                 }
6073
6074                 return -errno;
6075         }
6076
6077         s = strv_split_nulstr(search);
6078         if (!s)
6079                 return -ENOMEM;
6080
6081         return search_and_fopen_internal(path, mode, root, s, _f);
6082 }
6083
6084 char *strextend(char **x, ...) {
6085         va_list ap;
6086         size_t f, l;
6087         char *r, *p;
6088
6089         assert(x);
6090
6091         l = f = *x ? strlen(*x) : 0;
6092
6093         va_start(ap, x);
6094         for (;;) {
6095                 const char *t;
6096                 size_t n;
6097
6098                 t = va_arg(ap, const char *);
6099                 if (!t)
6100                         break;
6101
6102                 n = strlen(t);
6103                 if (n > ((size_t) -1) - l) {
6104                         va_end(ap);
6105                         return NULL;
6106                 }
6107
6108                 l += n;
6109         }
6110         va_end(ap);
6111
6112         r = realloc(*x, l+1);
6113         if (!r)
6114                 return NULL;
6115
6116         p = r + f;
6117
6118         va_start(ap, x);
6119         for (;;) {
6120                 const char *t;
6121
6122                 t = va_arg(ap, const char *);
6123                 if (!t)
6124                         break;
6125
6126                 p = stpcpy(p, t);
6127         }
6128         va_end(ap);
6129
6130         *p = 0;
6131         *x = r;
6132
6133         return r + l;
6134 }
6135
6136 char *strrep(const char *s, unsigned n) {
6137         size_t l;
6138         char *r, *p;
6139         unsigned i;
6140
6141         assert(s);
6142
6143         l = strlen(s);
6144         p = r = malloc(l * n + 1);
6145         if (!r)
6146                 return NULL;
6147
6148         for (i = 0; i < n; i++)
6149                 p = stpcpy(p, s);
6150
6151         *p = 0;
6152         return r;
6153 }
6154
6155 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
6156         size_t a, newalloc;
6157         void *q;
6158
6159         assert(p);
6160         assert(allocated);
6161
6162         if (*allocated >= need)
6163                 return *p;
6164
6165         newalloc = MAX(need * 2, 64u / size);
6166         a = newalloc * size;
6167
6168         /* check for overflows */
6169         if (a < size * need)
6170                 return NULL;
6171
6172         q = realloc(*p, a);
6173         if (!q)
6174                 return NULL;
6175
6176         *p = q;
6177         *allocated = newalloc;
6178         return q;
6179 }
6180
6181 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
6182         size_t prev;
6183         uint8_t *q;
6184
6185         assert(p);
6186         assert(allocated);
6187
6188         prev = *allocated;
6189
6190         q = greedy_realloc(p, allocated, need, size);
6191         if (!q)
6192                 return NULL;
6193
6194         if (*allocated > prev)
6195                 memzero(q + prev * size, (*allocated - prev) * size);
6196
6197         return q;
6198 }
6199
6200 bool id128_is_valid(const char *s) {
6201         size_t i, l;
6202
6203         l = strlen(s);
6204         if (l == 32) {
6205
6206                 /* Simple formatted 128bit hex string */
6207
6208                 for (i = 0; i < l; i++) {
6209                         char c = s[i];
6210
6211                         if (!(c >= '0' && c <= '9') &&
6212                             !(c >= 'a' && c <= 'z') &&
6213                             !(c >= 'A' && c <= 'Z'))
6214                                 return false;
6215                 }
6216
6217         } else if (l == 36) {
6218
6219                 /* Formatted UUID */
6220
6221                 for (i = 0; i < l; i++) {
6222                         char c = s[i];
6223
6224                         if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6225                                 if (c != '-')
6226                                         return false;
6227                         } else {
6228                                 if (!(c >= '0' && c <= '9') &&
6229                                     !(c >= 'a' && c <= 'z') &&
6230                                     !(c >= 'A' && c <= 'Z'))
6231                                         return false;
6232                         }
6233                 }
6234
6235         } else
6236                 return false;
6237
6238         return true;
6239 }
6240
6241 int split_pair(const char *s, const char *sep, char **l, char **r) {
6242         char *x, *a, *b;
6243
6244         assert(s);
6245         assert(sep);
6246         assert(l);
6247         assert(r);
6248
6249         if (isempty(sep))
6250                 return -EINVAL;
6251
6252         x = strstr(s, sep);
6253         if (!x)
6254                 return -EINVAL;
6255
6256         a = strndup(s, x - s);
6257         if (!a)
6258                 return -ENOMEM;
6259
6260         b = strdup(x + strlen(sep));
6261         if (!b) {
6262                 free(a);
6263                 return -ENOMEM;
6264         }
6265
6266         *l = a;
6267         *r = b;
6268
6269         return 0;
6270 }
6271
6272 int shall_restore_state(void) {
6273         _cleanup_free_ char *value = NULL;
6274         int r;
6275
6276         r = get_proc_cmdline_key("systemd.restore_state=", &value);
6277         if (r < 0)
6278                 return r;
6279         if (r == 0)
6280                 return true;
6281
6282         return parse_boolean(value) != 0;
6283 }
6284
6285 int proc_cmdline(char **ret) {
6286         assert(ret);
6287
6288         if (detect_container(NULL) > 0)
6289                 return get_process_cmdline(1, 0, false, ret);
6290         else
6291                 return read_one_line_file("/proc/cmdline", ret);
6292 }
6293
6294 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6295         _cleanup_free_ char *line = NULL;
6296         const char *p;
6297         int r;
6298
6299         assert(parse_item);
6300
6301         r = proc_cmdline(&line);
6302         if (r < 0)
6303                 return r;
6304
6305         p = line;
6306         for (;;) {
6307                 _cleanup_free_ char *word = NULL;
6308                 char *value = NULL;
6309
6310                 r = unquote_first_word(&p, &word, true);
6311                 if (r < 0)
6312                         return r;
6313                 if (r == 0)
6314                         break;
6315
6316                 /* Filter out arguments that are intended only for the
6317                  * initrd */
6318                 if (!in_initrd() && startswith(word, "rd."))
6319                         continue;
6320
6321                 value = strchr(word, '=');
6322                 if (value)
6323                         *(value++) = 0;
6324
6325                 r = parse_item(word, value);
6326                 if (r < 0)
6327                         return r;
6328         }
6329
6330         return 0;
6331 }
6332
6333 int get_proc_cmdline_key(const char *key, char **value) {
6334         _cleanup_free_ char *line = NULL, *ret = NULL;
6335         bool found = false;
6336         const char *p;
6337         int r;
6338
6339         assert(key);
6340
6341         r = proc_cmdline(&line);
6342         if (r < 0)
6343                 return r;
6344
6345         p = line;
6346         for (;;) {
6347                 _cleanup_free_ char *word = NULL;
6348                 const char *e;
6349
6350                 r = unquote_first_word(&p, &word, true);
6351                 if (r < 0)
6352                         return r;
6353                 if (r == 0)
6354                         break;
6355
6356                 /* Filter out arguments that are intended only for the
6357                  * initrd */
6358                 if (!in_initrd() && startswith(word, "rd."))
6359                         continue;
6360
6361                 if (value) {
6362                         e = startswith(word, key);
6363                         if (!e)
6364                                 continue;
6365
6366                         r = free_and_strdup(&ret, e);
6367                         if (r < 0)
6368                                 return r;
6369
6370                         found = true;
6371                 } else {
6372                         if (streq(word, key))
6373                                 found = true;
6374                 }
6375         }
6376
6377         if (value) {
6378                 *value = ret;
6379                 ret = NULL;
6380         }
6381
6382         return found;
6383
6384 }
6385
6386 int container_get_leader(const char *machine, pid_t *pid) {
6387         _cleanup_free_ char *s = NULL, *class = NULL;
6388         const char *p;
6389         pid_t leader;
6390         int r;
6391
6392         assert(machine);
6393         assert(pid);
6394
6395         p = strappenda("/run/systemd/machines/", machine);
6396         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6397         if (r == -ENOENT)
6398                 return -EHOSTDOWN;
6399         if (r < 0)
6400                 return r;
6401         if (!s)
6402                 return -EIO;
6403
6404         if (!streq_ptr(class, "container"))
6405                 return -EIO;
6406
6407         r = parse_pid(s, &leader);
6408         if (r < 0)
6409                 return r;
6410         if (leader <= 1)
6411                 return -EIO;
6412
6413         *pid = leader;
6414         return 0;
6415 }
6416
6417 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6418         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
6419         int rfd = -1;
6420
6421         assert(pid >= 0);
6422
6423         if (mntns_fd) {
6424                 const char *mntns;
6425
6426                 mntns = procfs_file_alloca(pid, "ns/mnt");
6427                 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6428                 if (mntnsfd < 0)
6429                         return -errno;
6430         }
6431
6432         if (pidns_fd) {
6433                 const char *pidns;
6434
6435                 pidns = procfs_file_alloca(pid, "ns/pid");
6436                 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6437                 if (pidnsfd < 0)
6438                         return -errno;
6439         }
6440
6441         if (netns_fd) {
6442                 const char *netns;
6443
6444                 netns = procfs_file_alloca(pid, "ns/net");
6445                 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6446                 if (netnsfd < 0)
6447                         return -errno;
6448         }
6449
6450         if (root_fd) {
6451                 const char *root;
6452
6453                 root = procfs_file_alloca(pid, "root");
6454                 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6455                 if (rfd < 0)
6456                         return -errno;
6457         }
6458
6459         if (pidns_fd)
6460                 *pidns_fd = pidnsfd;
6461
6462         if (mntns_fd)
6463                 *mntns_fd = mntnsfd;
6464
6465         if (netns_fd)
6466                 *netns_fd = netnsfd;
6467
6468         if (root_fd)
6469                 *root_fd = rfd;
6470
6471         pidnsfd = mntnsfd = netnsfd = -1;
6472
6473         return 0;
6474 }
6475
6476 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
6477
6478         if (pidns_fd >= 0)
6479                 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6480                         return -errno;
6481
6482         if (mntns_fd >= 0)
6483                 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6484                         return -errno;
6485
6486         if (netns_fd >= 0)
6487                 if (setns(netns_fd, CLONE_NEWNET) < 0)
6488                         return -errno;
6489
6490         if (root_fd >= 0) {
6491                 if (fchdir(root_fd) < 0)
6492                         return -errno;
6493
6494                 if (chroot(".") < 0)
6495                         return -errno;
6496         }
6497
6498         if (setresgid(0, 0, 0) < 0)
6499                 return -errno;
6500
6501         if (setgroups(0, NULL) < 0)
6502                 return -errno;
6503
6504         if (setresuid(0, 0, 0) < 0)
6505                 return -errno;
6506
6507         return 0;
6508 }
6509
6510 bool pid_is_unwaited(pid_t pid) {
6511         /* Checks whether a PID is still valid at all, including a zombie */
6512
6513         if (pid <= 0)
6514                 return false;
6515
6516         if (kill(pid, 0) >= 0)
6517                 return true;
6518
6519         return errno != ESRCH;
6520 }
6521
6522 bool pid_is_alive(pid_t pid) {
6523         int r;
6524
6525         /* Checks whether a PID is still valid and not a zombie */
6526
6527         if (pid <= 0)
6528                 return false;
6529
6530         r = get_process_state(pid);
6531         if (r == -ENOENT || r == 'Z')
6532                 return false;
6533
6534         return true;
6535 }
6536
6537 int getpeercred(int fd, struct ucred *ucred) {
6538         socklen_t n = sizeof(struct ucred);
6539         struct ucred u;
6540         int r;
6541
6542         assert(fd >= 0);
6543         assert(ucred);
6544
6545         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6546         if (r < 0)
6547                 return -errno;
6548
6549         if (n != sizeof(struct ucred))
6550                 return -EIO;
6551
6552         /* Check if the data is actually useful and not suppressed due
6553          * to namespacing issues */
6554         if (u.pid <= 0)
6555                 return -ENODATA;
6556         if (u.uid == UID_INVALID)
6557                 return -ENODATA;
6558         if (u.gid == GID_INVALID)
6559                 return -ENODATA;
6560
6561         *ucred = u;
6562         return 0;
6563 }
6564
6565 int getpeersec(int fd, char **ret) {
6566         socklen_t n = 64;
6567         char *s;
6568         int r;
6569
6570         assert(fd >= 0);
6571         assert(ret);
6572
6573         s = new0(char, n);
6574         if (!s)
6575                 return -ENOMEM;
6576
6577         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6578         if (r < 0) {
6579                 free(s);
6580
6581                 if (errno != ERANGE)
6582                         return -errno;
6583
6584                 s = new0(char, n);
6585                 if (!s)
6586                         return -ENOMEM;
6587
6588                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6589                 if (r < 0) {
6590                         free(s);
6591                         return -errno;
6592                 }
6593         }
6594
6595         if (isempty(s)) {
6596                 free(s);
6597                 return -ENOTSUP;
6598         }
6599
6600         *ret = s;
6601         return 0;
6602 }
6603
6604 /* This is much like like mkostemp() but is subject to umask(). */
6605 int mkostemp_safe(char *pattern, int flags) {
6606         _cleanup_umask_ mode_t u;
6607         int fd;
6608
6609         assert(pattern);
6610
6611         u = umask(077);
6612
6613         fd = mkostemp(pattern, flags);
6614         if (fd < 0)
6615                 return -errno;
6616
6617         return fd;
6618 }
6619
6620 int open_tmpfile(const char *path, int flags) {
6621         char *p;
6622         int fd;
6623
6624         assert(path);
6625
6626 #ifdef O_TMPFILE
6627         /* Try O_TMPFILE first, if it is supported */
6628         fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6629         if (fd >= 0)
6630                 return fd;
6631 #endif
6632
6633         /* Fall back to unguessable name + unlinking */
6634         p = strappenda(path, "/systemd-tmp-XXXXXX");
6635
6636         fd = mkostemp_safe(p, flags);
6637         if (fd < 0)
6638                 return fd;
6639
6640         unlink(p);
6641         return fd;
6642 }
6643
6644 int fd_warn_permissions(const char *path, int fd) {
6645         struct stat st;
6646
6647         if (fstat(fd, &st) < 0)
6648                 return -errno;
6649
6650         if (st.st_mode & 0111)
6651                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6652
6653         if (st.st_mode & 0002)
6654                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6655
6656         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6657                 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);
6658
6659         return 0;
6660 }
6661
6662 unsigned long personality_from_string(const char *p) {
6663
6664         /* Parse a personality specifier. We introduce our own
6665          * identifiers that indicate specific ABIs, rather than just
6666          * hints regarding the register size, since we want to keep
6667          * things open for multiple locally supported ABIs for the
6668          * same register size. We try to reuse the ABI identifiers
6669          * used by libseccomp. */
6670
6671 #if defined(__x86_64__)
6672
6673         if (streq(p, "x86"))
6674                 return PER_LINUX32;
6675
6676         if (streq(p, "x86-64"))
6677                 return PER_LINUX;
6678
6679 #elif defined(__i386__)
6680
6681         if (streq(p, "x86"))
6682                 return PER_LINUX;
6683 #endif
6684
6685         /* personality(7) documents that 0xffffffffUL is used for
6686          * querying the current personality, hence let's use that here
6687          * as error indicator. */
6688         return 0xffffffffUL;
6689 }
6690
6691 const char* personality_to_string(unsigned long p) {
6692
6693 #if defined(__x86_64__)
6694
6695         if (p == PER_LINUX32)
6696                 return "x86";
6697
6698         if (p == PER_LINUX)
6699                 return "x86-64";
6700
6701 #elif defined(__i386__)
6702
6703         if (p == PER_LINUX)
6704                 return "x86";
6705 #endif
6706
6707         return NULL;
6708 }
6709
6710 uint64_t physical_memory(void) {
6711         long mem;
6712
6713         /* We return this as uint64_t in case we are running as 32bit
6714          * process on a 64bit kernel with huge amounts of memory */
6715
6716         mem = sysconf(_SC_PHYS_PAGES);
6717         assert(mem > 0);
6718
6719         return (uint64_t) mem * (uint64_t) page_size();
6720 }
6721
6722 char* mount_test_option(const char *haystack, const char *needle) {
6723
6724         struct mntent me = {
6725                 .mnt_opts = (char*) haystack
6726         };
6727
6728         assert(needle);
6729
6730         /* Like glibc's hasmntopt(), but works on a string, not a
6731          * struct mntent */
6732
6733         if (!haystack)
6734                 return NULL;
6735
6736         return hasmntopt(&me, needle);
6737 }
6738
6739 void hexdump(FILE *f, const void *p, size_t s) {
6740         const uint8_t *b = p;
6741         unsigned n = 0;
6742
6743         assert(s == 0 || b);
6744
6745         while (s > 0) {
6746                 size_t i;
6747
6748                 fprintf(f, "%04x  ", n);
6749
6750                 for (i = 0; i < 16; i++) {
6751
6752                         if (i >= s)
6753                                 fputs("   ", f);
6754                         else
6755                                 fprintf(f, "%02x ", b[i]);
6756
6757                         if (i == 7)
6758                                 fputc(' ', f);
6759                 }
6760
6761                 fputc(' ', f);
6762
6763                 for (i = 0; i < 16; i++) {
6764
6765                         if (i >= s)
6766                                 fputc(' ', f);
6767                         else
6768                                 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6769                 }
6770
6771                 fputc('\n', f);
6772
6773                 if (s < 16)
6774                         break;
6775
6776                 n += 16;
6777                 b += 16;
6778                 s -= 16;
6779         }
6780 }
6781
6782 int update_reboot_param_file(const char *param) {
6783         int r = 0;
6784
6785         if (param) {
6786
6787                 r = write_string_file(REBOOT_PARAM_FILE, param);
6788                 if (r < 0)
6789                         log_error("Failed to write reboot param to "
6790                                   REBOOT_PARAM_FILE": %s", strerror(-r));
6791         } else
6792                 unlink(REBOOT_PARAM_FILE);
6793
6794         return r;
6795 }
6796
6797 int umount_recursive(const char *prefix, int flags) {
6798         bool again;
6799         int n = 0, r;
6800
6801         /* Try to umount everything recursively below a
6802          * directory. Also, take care of stacked mounts, and keep
6803          * unmounting them until they are gone. */
6804
6805         do {
6806                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6807
6808                 again = false;
6809                 r = 0;
6810
6811                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6812                 if (!proc_self_mountinfo)
6813                         return -errno;
6814
6815                 for (;;) {
6816                         _cleanup_free_ char *path = NULL, *p = NULL;
6817                         int k;
6818
6819                         k = fscanf(proc_self_mountinfo,
6820                                    "%*s "       /* (1) mount id */
6821                                    "%*s "       /* (2) parent id */
6822                                    "%*s "       /* (3) major:minor */
6823                                    "%*s "       /* (4) root */
6824                                    "%ms "       /* (5) mount point */
6825                                    "%*s"        /* (6) mount options */
6826                                    "%*[^-]"     /* (7) optional fields */
6827                                    "- "         /* (8) separator */
6828                                    "%*s "       /* (9) file system type */
6829                                    "%*s"        /* (10) mount source */
6830                                    "%*s"        /* (11) mount options 2 */
6831                                    "%*[^\n]",   /* some rubbish at the end */
6832                                    &path);
6833                         if (k != 1) {
6834                                 if (k == EOF)
6835                                         break;
6836
6837                                 continue;
6838                         }
6839
6840                         p = cunescape(path);
6841                         if (!p)
6842                                 return -ENOMEM;
6843
6844                         if (!path_startswith(p, prefix))
6845                                 continue;
6846
6847                         if (umount2(p, flags) < 0) {
6848                                 r = -errno;
6849                                 continue;
6850                         }
6851
6852                         again = true;
6853                         n++;
6854
6855                         break;
6856                 }
6857
6858         } while (again);
6859
6860         return r ? r : n;
6861 }
6862
6863 static int get_mount_flags(const char *path, unsigned long *flags) {
6864         struct statvfs buf;
6865
6866         if (statvfs(path, &buf) < 0)
6867                 return -errno;
6868         *flags = buf.f_flag;
6869         return 0;
6870 }
6871
6872 int bind_remount_recursive(const char *prefix, bool ro) {
6873         _cleanup_set_free_free_ Set *done = NULL;
6874         _cleanup_free_ char *cleaned = NULL;
6875         int r;
6876
6877         /* Recursively remount a directory (and all its submounts)
6878          * read-only or read-write. If the directory is already
6879          * mounted, we reuse the mount and simply mark it
6880          * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6881          * operation). If it isn't we first make it one. Afterwards we
6882          * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6883          * submounts we can access, too. When mounts are stacked on
6884          * the same mount point we only care for each individual
6885          * "top-level" mount on each point, as we cannot
6886          * influence/access the underlying mounts anyway. We do not
6887          * have any effect on future submounts that might get
6888          * propagated, they migt be writable. This includes future
6889          * submounts that have been triggered via autofs. */
6890
6891         cleaned = strdup(prefix);
6892         if (!cleaned)
6893                 return -ENOMEM;
6894
6895         path_kill_slashes(cleaned);
6896
6897         done = set_new(&string_hash_ops);
6898         if (!done)
6899                 return -ENOMEM;
6900
6901         for (;;) {
6902                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6903                 _cleanup_set_free_free_ Set *todo = NULL;
6904                 bool top_autofs = false;
6905                 char *x;
6906                 unsigned long orig_flags;
6907
6908                 todo = set_new(&string_hash_ops);
6909                 if (!todo)
6910                         return -ENOMEM;
6911
6912                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6913                 if (!proc_self_mountinfo)
6914                         return -errno;
6915
6916                 for (;;) {
6917                         _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6918                         int k;
6919
6920                         k = fscanf(proc_self_mountinfo,
6921                                    "%*s "       /* (1) mount id */
6922                                    "%*s "       /* (2) parent id */
6923                                    "%*s "       /* (3) major:minor */
6924                                    "%*s "       /* (4) root */
6925                                    "%ms "       /* (5) mount point */
6926                                    "%*s"        /* (6) mount options (superblock) */
6927                                    "%*[^-]"     /* (7) optional fields */
6928                                    "- "         /* (8) separator */
6929                                    "%ms "       /* (9) file system type */
6930                                    "%*s"        /* (10) mount source */
6931                                    "%*s"        /* (11) mount options (bind mount) */
6932                                    "%*[^\n]",   /* some rubbish at the end */
6933                                    &path,
6934                                    &type);
6935                         if (k != 2) {
6936                                 if (k == EOF)
6937                                         break;
6938
6939                                 continue;
6940                         }
6941
6942                         p = cunescape(path);
6943                         if (!p)
6944                                 return -ENOMEM;
6945
6946                         /* Let's ignore autofs mounts.  If they aren't
6947                          * triggered yet, we want to avoid triggering
6948                          * them, as we don't make any guarantees for
6949                          * future submounts anyway.  If they are
6950                          * already triggered, then we will find
6951                          * another entry for this. */
6952                         if (streq(type, "autofs")) {
6953                                 top_autofs = top_autofs || path_equal(cleaned, p);
6954                                 continue;
6955                         }
6956
6957                         if (path_startswith(p, cleaned) &&
6958                             !set_contains(done, p)) {
6959
6960                                 r = set_consume(todo, p);
6961                                 p = NULL;
6962
6963                                 if (r == -EEXIST)
6964                                         continue;
6965                                 if (r < 0)
6966                                         return r;
6967                         }
6968                 }
6969
6970                 /* If we have no submounts to process anymore and if
6971                  * the root is either already done, or an autofs, we
6972                  * are done */
6973                 if (set_isempty(todo) &&
6974                     (top_autofs || set_contains(done, cleaned)))
6975                         return 0;
6976
6977                 if (!set_contains(done, cleaned) &&
6978                     !set_contains(todo, cleaned)) {
6979                         /* The prefix directory itself is not yet a
6980                          * mount, make it one. */
6981                         if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6982                                 return -errno;
6983
6984                         orig_flags = 0;
6985                         (void) get_mount_flags(cleaned, &orig_flags);
6986                         orig_flags &= ~MS_RDONLY;
6987
6988                         if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6989                                 return -errno;
6990
6991                         x = strdup(cleaned);
6992                         if (!x)
6993                                 return -ENOMEM;
6994
6995                         r = set_consume(done, x);
6996                         if (r < 0)
6997                                 return r;
6998                 }
6999
7000                 while ((x = set_steal_first(todo))) {
7001
7002                         r = set_consume(done, x);
7003                         if (r == -EEXIST)
7004                                 continue;
7005                         if (r < 0)
7006                                 return r;
7007
7008                         /* Try to reuse the original flag set, but
7009                          * don't care for errors, in case of
7010                          * obstructed mounts */
7011                         orig_flags = 0;
7012                         (void) get_mount_flags(x, &orig_flags);
7013                         orig_flags &= ~MS_RDONLY;
7014
7015                         if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
7016
7017                                 /* Deal with mount points that are
7018                                  * obstructed by a later mount */
7019
7020                                 if (errno != ENOENT)
7021                                         return -errno;
7022                         }
7023
7024                 }
7025         }
7026 }
7027
7028 int fflush_and_check(FILE *f) {
7029         assert(f);
7030
7031         errno = 0;
7032         fflush(f);
7033
7034         if (ferror(f))
7035                 return errno ? -errno : -EIO;
7036
7037         return 0;
7038 }
7039
7040 int tempfn_xxxxxx(const char *p, char **ret) {
7041         const char *fn;
7042         char *t;
7043
7044         assert(p);
7045         assert(ret);
7046
7047         /*
7048          * Turns this:
7049          *         /foo/bar/waldo
7050          *
7051          * Into this:
7052          *         /foo/bar/.#waldoXXXXXX
7053          */
7054
7055         fn = basename(p);
7056         if (!filename_is_valid(fn))
7057                 return -EINVAL;
7058
7059         t = new(char, strlen(p) + 2 + 6 + 1);
7060         if (!t)
7061                 return -ENOMEM;
7062
7063         strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
7064
7065         *ret = path_kill_slashes(t);
7066         return 0;
7067 }
7068
7069 int tempfn_random(const char *p, char **ret) {
7070         const char *fn;
7071         char *t, *x;
7072         uint64_t u;
7073         unsigned i;
7074
7075         assert(p);
7076         assert(ret);
7077
7078         /*
7079          * Turns this:
7080          *         /foo/bar/waldo
7081          *
7082          * Into this:
7083          *         /foo/bar/.#waldobaa2a261115984a9
7084          */
7085
7086         fn = basename(p);
7087         if (!filename_is_valid(fn))
7088                 return -EINVAL;
7089
7090         t = new(char, strlen(p) + 2 + 16 + 1);
7091         if (!t)
7092                 return -ENOMEM;
7093
7094         x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
7095
7096         u = random_u64();
7097         for (i = 0; i < 16; i++) {
7098                 *(x++) = hexchar(u & 0xF);
7099                 u >>= 4;
7100         }
7101
7102         *x = 0;
7103
7104         *ret = path_kill_slashes(t);
7105         return 0;
7106 }
7107
7108 int tempfn_random_child(const char *p, char **ret) {
7109         char *t, *x;
7110         uint64_t u;
7111         unsigned i;
7112
7113         assert(p);
7114         assert(ret);
7115
7116         /* Turns this:
7117          *         /foo/bar/waldo
7118          * Into this:
7119          *         /foo/bar/waldo/.#3c2b6219aa75d7d0
7120          */
7121
7122         t = new(char, strlen(p) + 3 + 16 + 1);
7123         if (!t)
7124                 return -ENOMEM;
7125
7126         x = stpcpy(stpcpy(t, p), "/.#");
7127
7128         u = random_u64();
7129         for (i = 0; i < 16; i++) {
7130                 *(x++) = hexchar(u & 0xF);
7131                 u >>= 4;
7132         }
7133
7134         *x = 0;
7135
7136         *ret = path_kill_slashes(t);
7137         return 0;
7138 }
7139
7140 /* make sure the hostname is not "localhost" */
7141 bool is_localhost(const char *hostname) {
7142         assert(hostname);
7143
7144         /* This tries to identify local host and domain names
7145          * described in RFC6761 plus the redhatism of .localdomain */
7146
7147         return streq(hostname, "localhost") ||
7148                streq(hostname, "localhost.") ||
7149                streq(hostname, "localdomain.") ||
7150                streq(hostname, "localdomain") ||
7151                endswith(hostname, ".localhost") ||
7152                endswith(hostname, ".localhost.") ||
7153                endswith(hostname, ".localdomain") ||
7154                endswith(hostname, ".localdomain.");
7155 }
7156
7157 int take_password_lock(const char *root) {
7158
7159         struct flock flock = {
7160                 .l_type = F_WRLCK,
7161                 .l_whence = SEEK_SET,
7162                 .l_start = 0,
7163                 .l_len = 0,
7164         };
7165
7166         const char *path;
7167         int fd, r;
7168
7169         /* This is roughly the same as lckpwdf(), but not as awful. We
7170          * don't want to use alarm() and signals, hence we implement
7171          * our own trivial version of this.
7172          *
7173          * Note that shadow-utils also takes per-database locks in
7174          * addition to lckpwdf(). However, we don't given that they
7175          * are redundant as they they invoke lckpwdf() first and keep
7176          * it during everything they do. The per-database locks are
7177          * awfully racy, and thus we just won't do them. */
7178
7179         if (root)
7180                 path = strappenda(root, "/etc/.pwd.lock");
7181         else
7182                 path = "/etc/.pwd.lock";
7183
7184         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
7185         if (fd < 0)
7186                 return -errno;
7187
7188         r = fcntl(fd, F_SETLKW, &flock);
7189         if (r < 0) {
7190                 safe_close(fd);
7191                 return -errno;
7192         }
7193
7194         return fd;
7195 }
7196
7197 int is_symlink(const char *path) {
7198         struct stat info;
7199
7200         if (lstat(path, &info) < 0)
7201                 return -errno;
7202
7203         return !!S_ISLNK(info.st_mode);
7204 }
7205
7206 int is_dir(const char* path, bool follow) {
7207         struct stat st;
7208         int r;
7209
7210         if (follow)
7211                 r = stat(path, &st);
7212         else
7213                 r = lstat(path, &st);
7214         if (r < 0)
7215                 return -errno;
7216
7217         return !!S_ISDIR(st.st_mode);
7218 }
7219
7220 int unquote_first_word(const char **p, char **ret, bool relax) {
7221         _cleanup_free_ char *s = NULL;
7222         size_t allocated = 0, sz = 0;
7223
7224         enum {
7225                 START,
7226                 VALUE,
7227                 VALUE_ESCAPE,
7228                 SINGLE_QUOTE,
7229                 SINGLE_QUOTE_ESCAPE,
7230                 DOUBLE_QUOTE,
7231                 DOUBLE_QUOTE_ESCAPE,
7232                 SPACE,
7233         } state = START;
7234
7235         assert(p);
7236         assert(*p);
7237         assert(ret);
7238
7239         /* Parses the first word of a string, and returns it in
7240          * *ret. Removes all quotes in the process. When parsing fails
7241          * (because of an uneven number of quotes or similar), leaves
7242          * the pointer *p at the first invalid character. */
7243
7244         for (;;) {
7245                 char c = **p;
7246
7247                 switch (state) {
7248
7249                 case START:
7250                         if (c == 0)
7251                                 goto finish;
7252                         else if (strchr(WHITESPACE, c))
7253                                 break;
7254
7255                         state = VALUE;
7256                         /* fallthrough */
7257
7258                 case VALUE:
7259                         if (c == 0)
7260                                 goto finish;
7261                         else if (c == '\'')
7262                                 state = SINGLE_QUOTE;
7263                         else if (c == '\\')
7264                                 state = VALUE_ESCAPE;
7265                         else if (c == '\"')
7266                                 state = DOUBLE_QUOTE;
7267                         else if (strchr(WHITESPACE, c))
7268                                 state = SPACE;
7269                         else {
7270                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7271                                         return -ENOMEM;
7272
7273                                 s[sz++] = c;
7274                         }
7275
7276                         break;
7277
7278                 case VALUE_ESCAPE:
7279                         if (c == 0) {
7280                                 if (relax)
7281                                         goto finish;
7282                                 return -EINVAL;
7283                         }
7284
7285                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7286                                 return -ENOMEM;
7287
7288                         s[sz++] = c;
7289                         state = VALUE;
7290
7291                         break;
7292
7293                 case SINGLE_QUOTE:
7294                         if (c == 0) {
7295                                 if (relax)
7296                                         goto finish;
7297                                 return -EINVAL;
7298                         } else if (c == '\'')
7299                                 state = VALUE;
7300                         else if (c == '\\')
7301                                 state = SINGLE_QUOTE_ESCAPE;
7302                         else {
7303                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7304                                         return -ENOMEM;
7305
7306                                 s[sz++] = c;
7307                         }
7308
7309                         break;
7310
7311                 case SINGLE_QUOTE_ESCAPE:
7312                         if (c == 0) {
7313                                 if (relax)
7314                                         goto finish;
7315                                 return -EINVAL;
7316                         }
7317
7318                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7319                                 return -ENOMEM;
7320
7321                         s[sz++] = c;
7322                         state = SINGLE_QUOTE;
7323                         break;
7324
7325                 case DOUBLE_QUOTE:
7326                         if (c == 0)
7327                                 return -EINVAL;
7328                         else if (c == '\"')
7329                                 state = VALUE;
7330                         else if (c == '\\')
7331                                 state = DOUBLE_QUOTE_ESCAPE;
7332                         else {
7333                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
7334                                         return -ENOMEM;
7335
7336                                 s[sz++] = c;
7337                         }
7338
7339                         break;
7340
7341                 case DOUBLE_QUOTE_ESCAPE:
7342                         if (c == 0) {
7343                                 if (relax)
7344                                         goto finish;
7345                                 return -EINVAL;
7346                         }
7347
7348                         if (!GREEDY_REALLOC(s, allocated, sz+2))
7349                                 return -ENOMEM;
7350
7351                         s[sz++] = c;
7352                         state = DOUBLE_QUOTE;
7353                         break;
7354
7355                 case SPACE:
7356                         if (c == 0)
7357                                 goto finish;
7358                         if (!strchr(WHITESPACE, c))
7359                                 goto finish;
7360
7361                         break;
7362                 }
7363
7364                 (*p) ++;
7365         }
7366
7367 finish:
7368         if (!s) {
7369                 *ret = NULL;
7370                 return 0;
7371         }
7372
7373         s[sz] = 0;
7374         *ret = s;
7375         s = NULL;
7376
7377         return 1;
7378 }
7379
7380 int unquote_many_words(const char **p, ...) {
7381         va_list ap;
7382         char **l;
7383         int n = 0, i, c, r;
7384
7385         /* Parses a number of words from a string, stripping any
7386          * quotes if necessary. */
7387
7388         assert(p);
7389
7390         /* Count how many words are expected */
7391         va_start(ap, p);
7392         for (;;) {
7393                 if (!va_arg(ap, char **))
7394                         break;
7395                 n++;
7396         }
7397         va_end(ap);
7398
7399         if (n <= 0)
7400                 return 0;
7401
7402         /* Read all words into a temporary array */
7403         l = newa0(char*, n);
7404         for (c = 0; c < n; c++) {
7405
7406                 r = unquote_first_word(p, &l[c], false);
7407                 if (r < 0) {
7408                         int j;
7409
7410                         for (j = 0; j < c; j++)
7411                                 free(l[j]);
7412
7413                         return r;
7414                 }
7415
7416                 if (r == 0)
7417                         break;
7418         }
7419
7420         /* If we managed to parse all words, return them in the passed
7421          * in parameters */
7422         va_start(ap, p);
7423         for (i = 0; i < n; i++) {
7424                 char **v;
7425
7426                 v = va_arg(ap, char **);
7427                 assert(v);
7428
7429                 *v = l[i];
7430         }
7431         va_end(ap);
7432
7433         return c;
7434 }
7435
7436 int free_and_strdup(char **p, const char *s) {
7437         char *t;
7438
7439         assert(p);
7440
7441         /* Replaces a string pointer with an strdup()ed new string,
7442          * possibly freeing the old one. */
7443
7444         if (s) {
7445                 t = strdup(s);
7446                 if (!t)
7447                         return -ENOMEM;
7448         } else
7449                 t = NULL;
7450
7451         free(*p);
7452         *p = t;
7453
7454         return 0;
7455 }
7456
7457 int sethostname_idempotent(const char *s) {
7458         int r;
7459         char buf[HOST_NAME_MAX + 1] = {};
7460
7461         assert(s);
7462
7463         r = gethostname(buf, sizeof(buf));
7464         if (r < 0)
7465                 return -errno;
7466
7467         if (streq(buf, s))
7468                 return 0;
7469
7470         r = sethostname(s, strlen(s));
7471         if (r < 0)
7472                 return -errno;
7473
7474         return 1;
7475 }
7476
7477 int ptsname_malloc(int fd, char **ret) {
7478         size_t l = 100;
7479
7480         assert(fd >= 0);
7481         assert(ret);
7482
7483         for (;;) {
7484                 char *c;
7485
7486                 c = new(char, l);
7487                 if (!c)
7488                         return -ENOMEM;
7489
7490                 if (ptsname_r(fd, c, l) == 0) {
7491                         *ret = c;
7492                         return 0;
7493                 }
7494                 if (errno != ERANGE) {
7495                         free(c);
7496                         return -errno;
7497                 }
7498
7499                 free(c);
7500                 l *= 2;
7501         }
7502 }
7503
7504 int openpt_in_namespace(pid_t pid, int flags) {
7505         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7506         _cleanup_close_pair_ int pair[2] = { -1, -1 };
7507         union {
7508                 struct cmsghdr cmsghdr;
7509                 uint8_t buf[CMSG_SPACE(sizeof(int))];
7510         } control = {};
7511         struct msghdr mh = {
7512                 .msg_control = &control,
7513                 .msg_controllen = sizeof(control),
7514         };
7515         struct cmsghdr *cmsg;
7516         siginfo_t si;
7517         pid_t child;
7518         int r;
7519
7520         assert(pid > 0);
7521
7522         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7523         if (r < 0)
7524                 return r;
7525
7526         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7527                 return -errno;
7528
7529         child = fork();
7530         if (child < 0)
7531                 return -errno;
7532
7533         if (child == 0) {
7534                 int master;
7535
7536                 pair[0] = safe_close(pair[0]);
7537
7538                 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7539                 if (r < 0)
7540                         _exit(EXIT_FAILURE);
7541
7542                 master = posix_openpt(flags);
7543                 if (master < 0)
7544                         _exit(EXIT_FAILURE);
7545
7546                 cmsg = CMSG_FIRSTHDR(&mh);
7547                 cmsg->cmsg_level = SOL_SOCKET;
7548                 cmsg->cmsg_type = SCM_RIGHTS;
7549                 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7550                 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7551
7552                 mh.msg_controllen = cmsg->cmsg_len;
7553
7554                 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7555                         _exit(EXIT_FAILURE);
7556
7557                 _exit(EXIT_SUCCESS);
7558         }
7559
7560         pair[1] = safe_close(pair[1]);
7561
7562         r = wait_for_terminate(child, &si);
7563         if (r < 0)
7564                 return r;
7565         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7566                 return -EIO;
7567
7568         if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7569                 return -errno;
7570
7571         for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7572                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7573                         int *fds;
7574                         unsigned n_fds;
7575
7576                         fds = (int*) CMSG_DATA(cmsg);
7577                         n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7578
7579                         if (n_fds != 1) {
7580                                 close_many(fds, n_fds);
7581                                 return -EIO;
7582                         }
7583
7584                         return fds[0];
7585                 }
7586
7587         return -EIO;
7588 }
7589
7590 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7591         _cleanup_close_ int fd = -1;
7592         ssize_t l;
7593
7594         /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7595
7596         fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7597         if (fd < 0)
7598                 return -errno;
7599
7600         l = fgetxattr(fd, attribute, value, size);
7601         if (l < 0)
7602                 return -errno;
7603
7604         return l;
7605 }
7606
7607 static int parse_crtime(le64_t le, usec_t *usec) {
7608         uint64_t u;
7609
7610         assert(usec);
7611
7612         u = le64toh(le);
7613         if (u == 0 || u == (uint64_t) -1)
7614                 return -EIO;
7615
7616         *usec = (usec_t) u;
7617         return 0;
7618 }
7619
7620 int fd_getcrtime(int fd, usec_t *usec) {
7621         le64_t le;
7622         ssize_t n;
7623
7624         assert(fd >= 0);
7625         assert(usec);
7626
7627         /* Until Linux gets a real concept of birthtime/creation time,
7628          * let's fake one with xattrs */
7629
7630         n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7631         if (n < 0)
7632                 return -errno;
7633         if (n != sizeof(le))
7634                 return -EIO;
7635
7636         return parse_crtime(le, usec);
7637 }
7638
7639 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7640         le64_t le;
7641         ssize_t n;
7642
7643         n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7644         if (n < 0)
7645                 return -errno;
7646         if (n != sizeof(le))
7647                 return -EIO;
7648
7649         return parse_crtime(le, usec);
7650 }
7651
7652 int path_getcrtime(const char *p, usec_t *usec) {
7653         le64_t le;
7654         ssize_t n;
7655
7656         assert(p);
7657         assert(usec);
7658
7659         n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7660         if (n < 0)
7661                 return -errno;
7662         if (n != sizeof(le))
7663                 return -EIO;
7664
7665         return parse_crtime(le, usec);
7666 }
7667
7668 int fd_setcrtime(int fd, usec_t usec) {
7669         le64_t le;
7670
7671         assert(fd >= 0);
7672
7673         le = htole64((uint64_t) usec);
7674         if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7675                 return -errno;
7676
7677         return 0;
7678 }
7679
7680 int same_fd(int a, int b) {
7681         struct stat sta, stb;
7682         pid_t pid;
7683         int r, fa, fb;
7684
7685         assert(a >= 0);
7686         assert(b >= 0);
7687
7688         /* Compares two file descriptors. Note that semantics are
7689          * quite different depending on whether we have kcmp() or we
7690          * don't. If we have kcmp() this will only return true for
7691          * dup()ed file descriptors, but not otherwise. If we don't
7692          * have kcmp() this will also return true for two fds of the same
7693          * file, created by separate open() calls. Since we use this
7694          * call mostly for filtering out duplicates in the fd store
7695          * this difference hopefully doesn't matter too much. */
7696
7697         if (a == b)
7698                 return true;
7699
7700         /* Try to use kcmp() if we have it. */
7701         pid = getpid();
7702         r = kcmp(pid, pid, KCMP_FILE, a, b);
7703         if (r == 0)
7704                 return true;
7705         if (r > 0)
7706                 return false;
7707         if (errno != ENOSYS)
7708                 return -errno;
7709
7710         /* We don't have kcmp(), use fstat() instead. */
7711         if (fstat(a, &sta) < 0)
7712                 return -errno;
7713
7714         if (fstat(b, &stb) < 0)
7715                 return -errno;
7716
7717         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
7718                 return false;
7719
7720         /* We consider all device fds different, since two device fds
7721          * might refer to quite different device contexts even though
7722          * they share the same inode and backing dev_t. */
7723
7724         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
7725                 return false;
7726
7727         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
7728                 return false;
7729
7730         /* The fds refer to the same inode on disk, let's also check
7731          * if they have the same fd flags. This is useful to
7732          * distuingish the read and write side of a pipe created with
7733          * pipe(). */
7734         fa = fcntl(a, F_GETFL);
7735         if (fa < 0)
7736                 return -errno;
7737
7738         fb = fcntl(b, F_GETFL);
7739         if (fb < 0)
7740                 return -errno;
7741
7742         return fa == fb;
7743 }
7744
7745 int chattr_fd(int fd, bool b, int mask) {
7746         int old_attr, new_attr;
7747
7748         assert(fd >= 0);
7749
7750         if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7751                 return -errno;
7752
7753         if (b)
7754                 new_attr = old_attr | mask;
7755         else
7756                 new_attr = old_attr & ~mask;
7757
7758         if (new_attr == old_attr)
7759                 return 0;
7760
7761         if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7762                 return -errno;
7763
7764         return 0;
7765 }
7766
7767 int chattr_path(const char *p, bool b, int mask) {
7768         _cleanup_close_ int fd = -1;
7769
7770         fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7771         if (fd < 0)
7772                 return -errno;
7773
7774         return chattr_fd(fd, b, mask);
7775 }