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