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