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