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