chiark / gitweb /
util: be a bit safer in path_is_safe()
[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 mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2770         _cleanup_free_ char *t = NULL;
2771         int r;
2772
2773         assert(path);
2774
2775         r = tempfn_random(path, &t);
2776         if (r < 0)
2777                 return r;
2778
2779         if (mknod(t, mode, dev) < 0)
2780                 return -errno;
2781
2782         if (rename(t, path) < 0) {
2783                 unlink_noerrno(t);
2784                 return -errno;
2785         }
2786
2787         return 0;
2788 }
2789
2790 int mkfifo_atomic(const char *path, mode_t mode) {
2791         _cleanup_free_ char *t = NULL;
2792         int r;
2793
2794         assert(path);
2795
2796         r = tempfn_random(path, &t);
2797         if (r < 0)
2798                 return r;
2799
2800         if (mkfifo(t, mode) < 0)
2801                 return -errno;
2802
2803         if (rename(t, path) < 0) {
2804                 unlink_noerrno(t);
2805                 return -errno;
2806         }
2807
2808         return 0;
2809 }
2810
2811 bool display_is_local(const char *display) {
2812         assert(display);
2813
2814         return
2815                 display[0] == ':' &&
2816                 display[1] >= '0' &&
2817                 display[1] <= '9';
2818 }
2819
2820 int socket_from_display(const char *display, char **path) {
2821         size_t k;
2822         char *f, *c;
2823
2824         assert(display);
2825         assert(path);
2826
2827         if (!display_is_local(display))
2828                 return -EINVAL;
2829
2830         k = strspn(display+1, "0123456789");
2831
2832         f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2833         if (!f)
2834                 return -ENOMEM;
2835
2836         c = stpcpy(f, "/tmp/.X11-unix/X");
2837         memcpy(c, display+1, k);
2838         c[k] = 0;
2839
2840         *path = f;
2841
2842         return 0;
2843 }
2844
2845 int get_user_creds(
2846                 const char **username,
2847                 uid_t *uid, gid_t *gid,
2848                 const char **home,
2849                 const char **shell) {
2850
2851         struct passwd *p;
2852         uid_t u;
2853
2854         assert(username);
2855         assert(*username);
2856
2857         /* We enforce some special rules for uid=0: in order to avoid
2858          * NSS lookups for root we hardcode its data. */
2859
2860         if (streq(*username, "root") || streq(*username, "0")) {
2861                 *username = "root";
2862
2863                 if (uid)
2864                         *uid = 0;
2865
2866                 if (gid)
2867                         *gid = 0;
2868
2869                 if (home)
2870                         *home = "/root";
2871
2872                 if (shell)
2873                         *shell = "/bin/sh";
2874
2875                 return 0;
2876         }
2877
2878         if (parse_uid(*username, &u) >= 0) {
2879                 errno = 0;
2880                 p = getpwuid(u);
2881
2882                 /* If there are multiple users with the same id, make
2883                  * sure to leave $USER to the configured value instead
2884                  * of the first occurrence in the database. However if
2885                  * the uid was configured by a numeric uid, then let's
2886                  * pick the real username from /etc/passwd. */
2887                 if (p)
2888                         *username = p->pw_name;
2889         } else {
2890                 errno = 0;
2891                 p = getpwnam(*username);
2892         }
2893
2894         if (!p)
2895                 return errno > 0 ? -errno : -ESRCH;
2896
2897         if (uid)
2898                 *uid = p->pw_uid;
2899
2900         if (gid)
2901                 *gid = p->pw_gid;
2902
2903         if (home)
2904                 *home = p->pw_dir;
2905
2906         if (shell)
2907                 *shell = p->pw_shell;
2908
2909         return 0;
2910 }
2911
2912 char* uid_to_name(uid_t uid) {
2913         struct passwd *p;
2914         char *r;
2915
2916         if (uid == 0)
2917                 return strdup("root");
2918
2919         p = getpwuid(uid);
2920         if (p)
2921                 return strdup(p->pw_name);
2922
2923         if (asprintf(&r, UID_FMT, uid) < 0)
2924                 return NULL;
2925
2926         return r;
2927 }
2928
2929 char* gid_to_name(gid_t gid) {
2930         struct group *p;
2931         char *r;
2932
2933         if (gid == 0)
2934                 return strdup("root");
2935
2936         p = getgrgid(gid);
2937         if (p)
2938                 return strdup(p->gr_name);
2939
2940         if (asprintf(&r, GID_FMT, gid) < 0)
2941                 return NULL;
2942
2943         return r;
2944 }
2945
2946 int get_group_creds(const char **groupname, gid_t *gid) {
2947         struct group *g;
2948         gid_t id;
2949
2950         assert(groupname);
2951
2952         /* We enforce some special rules for gid=0: in order to avoid
2953          * NSS lookups for root we hardcode its data. */
2954
2955         if (streq(*groupname, "root") || streq(*groupname, "0")) {
2956                 *groupname = "root";
2957
2958                 if (gid)
2959                         *gid = 0;
2960
2961                 return 0;
2962         }
2963
2964         if (parse_gid(*groupname, &id) >= 0) {
2965                 errno = 0;
2966                 g = getgrgid(id);
2967
2968                 if (g)
2969                         *groupname = g->gr_name;
2970         } else {
2971                 errno = 0;
2972                 g = getgrnam(*groupname);
2973         }
2974
2975         if (!g)
2976                 return errno > 0 ? -errno : -ESRCH;
2977
2978         if (gid)
2979                 *gid = g->gr_gid;
2980
2981         return 0;
2982 }
2983
2984 int in_gid(gid_t gid) {
2985         gid_t *gids;
2986         int ngroups_max, r, i;
2987
2988         if (getgid() == gid)
2989                 return 1;
2990
2991         if (getegid() == gid)
2992                 return 1;
2993
2994         ngroups_max = sysconf(_SC_NGROUPS_MAX);
2995         assert(ngroups_max > 0);
2996
2997         gids = alloca(sizeof(gid_t) * ngroups_max);
2998
2999         r = getgroups(ngroups_max, gids);
3000         if (r < 0)
3001                 return -errno;
3002
3003         for (i = 0; i < r; i++)
3004                 if (gids[i] == gid)
3005                         return 1;
3006
3007         return 0;
3008 }
3009
3010 int in_group(const char *name) {
3011         int r;
3012         gid_t gid;
3013
3014         r = get_group_creds(&name, &gid);
3015         if (r < 0)
3016                 return r;
3017
3018         return in_gid(gid);
3019 }
3020
3021 int glob_exists(const char *path) {
3022         _cleanup_globfree_ glob_t g = {};
3023         int k;
3024
3025         assert(path);
3026
3027         errno = 0;
3028         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3029
3030         if (k == GLOB_NOMATCH)
3031                 return 0;
3032         else if (k == GLOB_NOSPACE)
3033                 return -ENOMEM;
3034         else if (k == 0)
3035                 return !strv_isempty(g.gl_pathv);
3036         else
3037                 return errno ? -errno : -EIO;
3038 }
3039
3040 int glob_extend(char ***strv, const char *path) {
3041         _cleanup_globfree_ glob_t g = {};
3042         int k;
3043         char **p;
3044
3045         errno = 0;
3046         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3047
3048         if (k == GLOB_NOMATCH)
3049                 return -ENOENT;
3050         else if (k == GLOB_NOSPACE)
3051                 return -ENOMEM;
3052         else if (k != 0 || strv_isempty(g.gl_pathv))
3053                 return errno ? -errno : -EIO;
3054
3055         STRV_FOREACH(p, g.gl_pathv) {
3056                 k = strv_extend(strv, *p);
3057                 if (k < 0)
3058                         break;
3059         }
3060
3061         return k;
3062 }
3063
3064 int dirent_ensure_type(DIR *d, struct dirent *de) {
3065         struct stat st;
3066
3067         assert(d);
3068         assert(de);
3069
3070         if (de->d_type != DT_UNKNOWN)
3071                 return 0;
3072
3073         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3074                 return -errno;
3075
3076         de->d_type =
3077                 S_ISREG(st.st_mode)  ? DT_REG  :
3078                 S_ISDIR(st.st_mode)  ? DT_DIR  :
3079                 S_ISLNK(st.st_mode)  ? DT_LNK  :
3080                 S_ISFIFO(st.st_mode) ? DT_FIFO :
3081                 S_ISSOCK(st.st_mode) ? DT_SOCK :
3082                 S_ISCHR(st.st_mode)  ? DT_CHR  :
3083                 S_ISBLK(st.st_mode)  ? DT_BLK  :
3084                                        DT_UNKNOWN;
3085
3086         return 0;
3087 }
3088
3089 int get_files_in_directory(const char *path, char ***list) {
3090         _cleanup_closedir_ DIR *d = NULL;
3091         size_t bufsize = 0, n = 0;
3092         _cleanup_strv_free_ char **l = NULL;
3093
3094         assert(path);
3095
3096         /* Returns all files in a directory in *list, and the number
3097          * of files as return value. If list is NULL returns only the
3098          * number. */
3099
3100         d = opendir(path);
3101         if (!d)
3102                 return -errno;
3103
3104         for (;;) {
3105                 struct dirent *de;
3106
3107                 errno = 0;
3108                 de = readdir(d);
3109                 if (!de && errno != 0)
3110                         return -errno;
3111                 if (!de)
3112                         break;
3113
3114                 dirent_ensure_type(d, de);
3115
3116                 if (!dirent_is_file(de))
3117                         continue;
3118
3119                 if (list) {
3120                         /* one extra slot is needed for the terminating NULL */
3121                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
3122                                 return -ENOMEM;
3123
3124                         l[n] = strdup(de->d_name);
3125                         if (!l[n])
3126                                 return -ENOMEM;
3127
3128                         l[++n] = NULL;
3129                 } else
3130                         n++;
3131         }
3132
3133         if (list) {
3134                 *list = l;
3135                 l = NULL; /* avoid freeing */
3136         }
3137
3138         return n;
3139 }
3140
3141 char *strjoin(const char *x, ...) {
3142         va_list ap;
3143         size_t l;
3144         char *r, *p;
3145
3146         va_start(ap, x);
3147
3148         if (x) {
3149                 l = strlen(x);
3150
3151                 for (;;) {
3152                         const char *t;
3153                         size_t n;
3154
3155                         t = va_arg(ap, const char *);
3156                         if (!t)
3157                                 break;
3158
3159                         n = strlen(t);
3160                         if (n > ((size_t) -1) - l) {
3161                                 va_end(ap);
3162                                 return NULL;
3163                         }
3164
3165                         l += n;
3166                 }
3167         } else
3168                 l = 0;
3169
3170         va_end(ap);
3171
3172         r = new(char, l+1);
3173         if (!r)
3174                 return NULL;
3175
3176         if (x) {
3177                 p = stpcpy(r, x);
3178
3179                 va_start(ap, x);
3180
3181                 for (;;) {
3182                         const char *t;
3183
3184                         t = va_arg(ap, const char *);
3185                         if (!t)
3186                                 break;
3187
3188                         p = stpcpy(p, t);
3189                 }
3190
3191                 va_end(ap);
3192         } else
3193                 r[0] = 0;
3194
3195         return r;
3196 }
3197
3198 bool is_main_thread(void) {
3199         static thread_local int cached = 0;
3200
3201         if (_unlikely_(cached == 0))
3202                 cached = getpid() == gettid() ? 1 : -1;
3203
3204         return cached > 0;
3205 }
3206
3207 int block_get_whole_disk(dev_t d, dev_t *ret) {
3208         char *p, *s;
3209         int r;
3210         unsigned n, m;
3211
3212         assert(ret);
3213
3214         /* If it has a queue this is good enough for us */
3215         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3216                 return -ENOMEM;
3217
3218         r = access(p, F_OK);
3219         free(p);
3220
3221         if (r >= 0) {
3222                 *ret = d;
3223                 return 0;
3224         }
3225
3226         /* If it is a partition find the originating device */
3227         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3228                 return -ENOMEM;
3229
3230         r = access(p, F_OK);
3231         free(p);
3232
3233         if (r < 0)
3234                 return -ENOENT;
3235
3236         /* Get parent dev_t */
3237         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3238                 return -ENOMEM;
3239
3240         r = read_one_line_file(p, &s);
3241         free(p);
3242
3243         if (r < 0)
3244                 return r;
3245
3246         r = sscanf(s, "%u:%u", &m, &n);
3247         free(s);
3248
3249         if (r != 2)
3250                 return -EINVAL;
3251
3252         /* Only return this if it is really good enough for us. */
3253         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3254                 return -ENOMEM;
3255
3256         r = access(p, F_OK);
3257         free(p);
3258
3259         if (r >= 0) {
3260                 *ret = makedev(m, n);
3261                 return 0;
3262         }
3263
3264         return -ENOENT;
3265 }
3266
3267 static const char *const ioprio_class_table[] = {
3268         [IOPRIO_CLASS_NONE] = "none",
3269         [IOPRIO_CLASS_RT] = "realtime",
3270         [IOPRIO_CLASS_BE] = "best-effort",
3271         [IOPRIO_CLASS_IDLE] = "idle"
3272 };
3273
3274 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3275
3276 static const char *const sigchld_code_table[] = {
3277         [CLD_EXITED] = "exited",
3278         [CLD_KILLED] = "killed",
3279         [CLD_DUMPED] = "dumped",
3280         [CLD_TRAPPED] = "trapped",
3281         [CLD_STOPPED] = "stopped",
3282         [CLD_CONTINUED] = "continued",
3283 };
3284
3285 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3286
3287 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3288         [LOG_FAC(LOG_KERN)] = "kern",
3289         [LOG_FAC(LOG_USER)] = "user",
3290         [LOG_FAC(LOG_MAIL)] = "mail",
3291         [LOG_FAC(LOG_DAEMON)] = "daemon",
3292         [LOG_FAC(LOG_AUTH)] = "auth",
3293         [LOG_FAC(LOG_SYSLOG)] = "syslog",
3294         [LOG_FAC(LOG_LPR)] = "lpr",
3295         [LOG_FAC(LOG_NEWS)] = "news",
3296         [LOG_FAC(LOG_UUCP)] = "uucp",
3297         [LOG_FAC(LOG_CRON)] = "cron",
3298         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3299         [LOG_FAC(LOG_FTP)] = "ftp",
3300         [LOG_FAC(LOG_LOCAL0)] = "local0",
3301         [LOG_FAC(LOG_LOCAL1)] = "local1",
3302         [LOG_FAC(LOG_LOCAL2)] = "local2",
3303         [LOG_FAC(LOG_LOCAL3)] = "local3",
3304         [LOG_FAC(LOG_LOCAL4)] = "local4",
3305         [LOG_FAC(LOG_LOCAL5)] = "local5",
3306         [LOG_FAC(LOG_LOCAL6)] = "local6",
3307         [LOG_FAC(LOG_LOCAL7)] = "local7"
3308 };
3309
3310 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3311
3312 static const char *const log_level_table[] = {
3313         [LOG_EMERG] = "emerg",
3314         [LOG_ALERT] = "alert",
3315         [LOG_CRIT] = "crit",
3316         [LOG_ERR] = "err",
3317         [LOG_WARNING] = "warning",
3318         [LOG_NOTICE] = "notice",
3319         [LOG_INFO] = "info",
3320         [LOG_DEBUG] = "debug"
3321 };
3322
3323 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3324
3325 static const char* const sched_policy_table[] = {
3326         [SCHED_OTHER] = "other",
3327         [SCHED_BATCH] = "batch",
3328         [SCHED_IDLE] = "idle",
3329         [SCHED_FIFO] = "fifo",
3330         [SCHED_RR] = "rr"
3331 };
3332
3333 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3334
3335 static const char* const rlimit_table[_RLIMIT_MAX] = {
3336         [RLIMIT_CPU] = "LimitCPU",
3337         [RLIMIT_FSIZE] = "LimitFSIZE",
3338         [RLIMIT_DATA] = "LimitDATA",
3339         [RLIMIT_STACK] = "LimitSTACK",
3340         [RLIMIT_CORE] = "LimitCORE",
3341         [RLIMIT_RSS] = "LimitRSS",
3342         [RLIMIT_NOFILE] = "LimitNOFILE",
3343         [RLIMIT_AS] = "LimitAS",
3344         [RLIMIT_NPROC] = "LimitNPROC",
3345         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3346         [RLIMIT_LOCKS] = "LimitLOCKS",
3347         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3348         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3349         [RLIMIT_NICE] = "LimitNICE",
3350         [RLIMIT_RTPRIO] = "LimitRTPRIO",
3351         [RLIMIT_RTTIME] = "LimitRTTIME"
3352 };
3353
3354 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3355
3356 static const char* const ip_tos_table[] = {
3357         [IPTOS_LOWDELAY] = "low-delay",
3358         [IPTOS_THROUGHPUT] = "throughput",
3359         [IPTOS_RELIABILITY] = "reliability",
3360         [IPTOS_LOWCOST] = "low-cost",
3361 };
3362
3363 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3364
3365 static const char *const __signal_table[] = {
3366         [SIGHUP] = "HUP",
3367         [SIGINT] = "INT",
3368         [SIGQUIT] = "QUIT",
3369         [SIGILL] = "ILL",
3370         [SIGTRAP] = "TRAP",
3371         [SIGABRT] = "ABRT",
3372         [SIGBUS] = "BUS",
3373         [SIGFPE] = "FPE",
3374         [SIGKILL] = "KILL",
3375         [SIGUSR1] = "USR1",
3376         [SIGSEGV] = "SEGV",
3377         [SIGUSR2] = "USR2",
3378         [SIGPIPE] = "PIPE",
3379         [SIGALRM] = "ALRM",
3380         [SIGTERM] = "TERM",
3381 #ifdef SIGSTKFLT
3382         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
3383 #endif
3384         [SIGCHLD] = "CHLD",
3385         [SIGCONT] = "CONT",
3386         [SIGSTOP] = "STOP",
3387         [SIGTSTP] = "TSTP",
3388         [SIGTTIN] = "TTIN",
3389         [SIGTTOU] = "TTOU",
3390         [SIGURG] = "URG",
3391         [SIGXCPU] = "XCPU",
3392         [SIGXFSZ] = "XFSZ",
3393         [SIGVTALRM] = "VTALRM",
3394         [SIGPROF] = "PROF",
3395         [SIGWINCH] = "WINCH",
3396         [SIGIO] = "IO",
3397         [SIGPWR] = "PWR",
3398         [SIGSYS] = "SYS"
3399 };
3400
3401 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3402
3403 const char *signal_to_string(int signo) {
3404         static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3405         const char *name;
3406
3407         name = __signal_to_string(signo);
3408         if (name)
3409                 return name;
3410
3411         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3412                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3413         else
3414                 snprintf(buf, sizeof(buf), "%d", signo);
3415
3416         return buf;
3417 }
3418
3419 int signal_from_string(const char *s) {
3420         int signo;
3421         int offset = 0;
3422         unsigned u;
3423
3424         signo = __signal_from_string(s);
3425         if (signo > 0)
3426                 return signo;
3427
3428         if (startswith(s, "RTMIN+")) {
3429                 s += 6;
3430                 offset = SIGRTMIN;
3431         }
3432         if (safe_atou(s, &u) >= 0) {
3433                 signo = (int) u + offset;
3434                 if (signo > 0 && signo < _NSIG)
3435                         return signo;
3436         }
3437         return -EINVAL;
3438 }
3439
3440 bool kexec_loaded(void) {
3441        bool loaded = false;
3442        char *s;
3443
3444        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3445                if (s[0] == '1')
3446                        loaded = true;
3447                free(s);
3448        }
3449        return loaded;
3450 }
3451
3452 int prot_from_flags(int flags) {
3453
3454         switch (flags & O_ACCMODE) {
3455
3456         case O_RDONLY:
3457                 return PROT_READ;
3458
3459         case O_WRONLY:
3460                 return PROT_WRITE;
3461
3462         case O_RDWR:
3463                 return PROT_READ|PROT_WRITE;
3464
3465         default:
3466                 return -EINVAL;
3467         }
3468 }
3469
3470 char *format_bytes(char *buf, size_t l, off_t t) {
3471         unsigned i;
3472
3473         static const struct {
3474                 const char *suffix;
3475                 off_t factor;
3476         } table[] = {
3477                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3478                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3479                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3480                 { "G", 1024ULL*1024ULL*1024ULL },
3481                 { "M", 1024ULL*1024ULL },
3482                 { "K", 1024ULL },
3483         };
3484
3485         if (t == (off_t) -1)
3486                 return NULL;
3487
3488         for (i = 0; i < ELEMENTSOF(table); i++) {
3489
3490                 if (t >= table[i].factor) {
3491                         snprintf(buf, l,
3492                                  "%llu.%llu%s",
3493                                  (unsigned long long) (t / table[i].factor),
3494                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3495                                  table[i].suffix);
3496
3497                         goto finish;
3498                 }
3499         }
3500
3501         snprintf(buf, l, "%lluB", (unsigned long long) t);
3502
3503 finish:
3504         buf[l-1] = 0;
3505         return buf;
3506
3507 }
3508
3509 void* memdup(const void *p, size_t l) {
3510         void *r;
3511
3512         assert(p);
3513
3514         r = malloc(l);
3515         if (!r)
3516                 return NULL;
3517
3518         memcpy(r, p, l);
3519         return r;
3520 }
3521
3522 int fd_inc_sndbuf(int fd, size_t n) {
3523         int r, value;
3524         socklen_t l = sizeof(value);
3525
3526         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3527         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3528                 return 0;
3529
3530         /* If we have the privileges we will ignore the kernel limit. */
3531
3532         value = (int) n;
3533         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3534                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3535                         return -errno;
3536
3537         return 1;
3538 }
3539
3540 int fd_inc_rcvbuf(int fd, size_t n) {
3541         int r, value;
3542         socklen_t l = sizeof(value);
3543
3544         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3545         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3546                 return 0;
3547
3548         /* If we have the privileges we will ignore the kernel limit. */
3549
3550         value = (int) n;
3551         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3552                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3553                         return -errno;
3554         return 1;
3555 }
3556
3557 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3558         bool stdout_is_tty, stderr_is_tty;
3559         pid_t parent_pid, agent_pid;
3560         sigset_t ss, saved_ss;
3561         unsigned n, i;
3562         va_list ap;
3563         char **l;
3564
3565         assert(pid);
3566         assert(path);
3567
3568         /* Spawns a temporary TTY agent, making sure it goes away when
3569          * we go away */
3570
3571         parent_pid = getpid();
3572
3573         /* First we temporarily block all signals, so that the new
3574          * child has them blocked initially. This way, we can be sure
3575          * that SIGTERMs are not lost we might send to the agent. */
3576         assert_se(sigfillset(&ss) >= 0);
3577         assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3578
3579         agent_pid = fork();
3580         if (agent_pid < 0) {
3581                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3582                 return -errno;
3583         }
3584
3585         if (agent_pid != 0) {
3586                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3587                 *pid = agent_pid;
3588                 return 0;
3589         }
3590
3591         /* In the child:
3592          *
3593          * Make sure the agent goes away when the parent dies */
3594         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3595                 _exit(EXIT_FAILURE);
3596
3597         /* Make sure we actually can kill the agent, if we need to, in
3598          * case somebody invoked us from a shell script that trapped
3599          * SIGTERM or so... */
3600         reset_all_signal_handlers();
3601         reset_signal_mask();
3602
3603         /* Check whether our parent died before we were able
3604          * to set the death signal and unblock the signals */
3605         if (getppid() != parent_pid)
3606                 _exit(EXIT_SUCCESS);
3607
3608         /* Don't leak fds to the agent */
3609         close_all_fds(except, n_except);
3610
3611         stdout_is_tty = isatty(STDOUT_FILENO);
3612         stderr_is_tty = isatty(STDERR_FILENO);
3613
3614         if (!stdout_is_tty || !stderr_is_tty) {
3615                 int fd;
3616
3617                 /* Detach from stdout/stderr. and reopen
3618                  * /dev/tty for them. This is important to
3619                  * ensure that when systemctl is started via
3620                  * popen() or a similar call that expects to
3621                  * read EOF we actually do generate EOF and
3622                  * not delay this indefinitely by because we
3623                  * keep an unused copy of stdin around. */
3624                 fd = open("/dev/tty", O_WRONLY);
3625                 if (fd < 0) {
3626                         log_error_errno(errno, "Failed to open /dev/tty: %m");
3627                         _exit(EXIT_FAILURE);
3628                 }
3629
3630                 if (!stdout_is_tty)
3631                         dup2(fd, STDOUT_FILENO);
3632
3633                 if (!stderr_is_tty)
3634                         dup2(fd, STDERR_FILENO);
3635
3636                 if (fd > 2)
3637                         close(fd);
3638         }
3639
3640         /* Count arguments */
3641         va_start(ap, path);
3642         for (n = 0; va_arg(ap, char*); n++)
3643                 ;
3644         va_end(ap);
3645
3646         /* Allocate strv */
3647         l = alloca(sizeof(char *) * (n + 1));
3648
3649         /* Fill in arguments */
3650         va_start(ap, path);
3651         for (i = 0; i <= n; i++)
3652                 l[i] = va_arg(ap, char*);
3653         va_end(ap);
3654
3655         execv(path, l);
3656         _exit(EXIT_FAILURE);
3657 }
3658
3659 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3660         struct rlimit highest, fixed;
3661
3662         assert(rlim);
3663
3664         if (setrlimit(resource, rlim) >= 0)
3665                 return 0;
3666
3667         if (errno != EPERM)
3668                 return -errno;
3669
3670         /* So we failed to set the desired setrlimit, then let's try
3671          * to get as close as we can */
3672         assert_se(getrlimit(resource, &highest) == 0);
3673
3674         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3675         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3676
3677         if (setrlimit(resource, &fixed) < 0)
3678                 return -errno;
3679
3680         return 0;
3681 }
3682
3683 bool http_etag_is_valid(const char *etag) {
3684         if (isempty(etag))
3685                 return false;
3686
3687         if (!endswith(etag, "\""))
3688                 return false;
3689
3690         if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3691                 return false;
3692
3693         return true;
3694 }
3695
3696 bool http_url_is_valid(const char *url) {
3697         const char *p;
3698
3699         if (isempty(url))
3700                 return false;
3701
3702         p = startswith(url, "http://");
3703         if (!p)
3704                 p = startswith(url, "https://");
3705         if (!p)
3706                 return false;
3707
3708         if (isempty(p))
3709                 return false;
3710
3711         return ascii_is_valid(p);
3712 }
3713
3714 bool documentation_url_is_valid(const char *url) {
3715         const char *p;
3716
3717         if (isempty(url))
3718                 return false;
3719
3720         if (http_url_is_valid(url))
3721                 return true;
3722
3723         p = startswith(url, "file:/");
3724         if (!p)
3725                 p = startswith(url, "info:");
3726         if (!p)
3727                 p = startswith(url, "man:");
3728
3729         if (isempty(p))
3730                 return false;
3731
3732         return ascii_is_valid(p);
3733 }
3734
3735 bool in_initrd(void) {
3736         static int saved = -1;
3737         struct statfs s;
3738
3739         if (saved >= 0)
3740                 return saved;
3741
3742         /* We make two checks here:
3743          *
3744          * 1. the flag file /etc/initrd-release must exist
3745          * 2. the root file system must be a memory file system
3746          *
3747          * The second check is extra paranoia, since misdetecting an
3748          * initrd can have bad bad consequences due the initrd
3749          * emptying when transititioning to the main systemd.
3750          */
3751
3752         saved = access("/etc/initrd-release", F_OK) >= 0 &&
3753                 statfs("/", &s) >= 0 &&
3754                 is_temporary_fs(&s);
3755
3756         return saved;
3757 }
3758
3759 int get_home_dir(char **_h) {
3760         struct passwd *p;
3761         const char *e;
3762         char *h;
3763         uid_t u;
3764
3765         assert(_h);
3766
3767         /* Take the user specified one */
3768         e = secure_getenv("HOME");
3769         if (e && path_is_absolute(e)) {
3770                 h = strdup(e);
3771                 if (!h)
3772                         return -ENOMEM;
3773
3774                 *_h = h;
3775                 return 0;
3776         }
3777
3778         /* Hardcode home directory for root to avoid NSS */
3779         u = getuid();
3780         if (u == 0) {
3781                 h = strdup("/root");
3782                 if (!h)
3783                         return -ENOMEM;
3784
3785                 *_h = h;
3786                 return 0;
3787         }
3788
3789         /* Check the database... */
3790         errno = 0;
3791         p = getpwuid(u);
3792         if (!p)
3793                 return errno > 0 ? -errno : -ESRCH;
3794
3795         if (!path_is_absolute(p->pw_dir))
3796                 return -EINVAL;
3797
3798         h = strdup(p->pw_dir);
3799         if (!h)
3800                 return -ENOMEM;
3801
3802         *_h = h;
3803         return 0;
3804 }
3805
3806 int get_shell(char **_s) {
3807         struct passwd *p;
3808         const char *e;
3809         char *s;
3810         uid_t u;
3811
3812         assert(_s);
3813
3814         /* Take the user specified one */
3815         e = getenv("SHELL");
3816         if (e) {
3817                 s = strdup(e);
3818                 if (!s)
3819                         return -ENOMEM;
3820
3821                 *_s = s;
3822                 return 0;
3823         }
3824
3825         /* Hardcode home directory for root to avoid NSS */
3826         u = getuid();
3827         if (u == 0) {
3828                 s = strdup("/bin/sh");
3829                 if (!s)
3830                         return -ENOMEM;
3831
3832                 *_s = s;
3833                 return 0;
3834         }
3835
3836         /* Check the database... */
3837         errno = 0;
3838         p = getpwuid(u);
3839         if (!p)
3840                 return errno > 0 ? -errno : -ESRCH;
3841
3842         if (!path_is_absolute(p->pw_shell))
3843                 return -EINVAL;
3844
3845         s = strdup(p->pw_shell);
3846         if (!s)
3847                 return -ENOMEM;
3848
3849         *_s = s;
3850         return 0;
3851 }
3852
3853 bool filename_is_valid(const char *p) {
3854
3855         if (isempty(p))
3856                 return false;
3857
3858         if (strchr(p, '/'))
3859                 return false;
3860
3861         if (streq(p, "."))
3862                 return false;
3863
3864         if (streq(p, ".."))
3865                 return false;
3866
3867         if (strlen(p) > FILENAME_MAX)
3868                 return false;
3869
3870         return true;
3871 }
3872
3873 bool string_is_safe(const char *p) {
3874         const char *t;
3875
3876         if (!p)
3877                 return false;
3878
3879         for (t = p; *t; t++) {
3880                 if (*t > 0 && *t < ' ')
3881                         return false;
3882
3883                 if (strchr("\\\"\'\0x7f", *t))
3884                         return false;
3885         }
3886
3887         return true;
3888 }
3889
3890 /**
3891  * Check if a string contains control characters. If 'ok' is non-NULL
3892  * it may be a string containing additional CCs to be considered OK.
3893  */
3894 bool string_has_cc(const char *p, const char *ok) {
3895         const char *t;
3896
3897         assert(p);
3898
3899         for (t = p; *t; t++) {
3900                 if (ok && strchr(ok, *t))
3901                         continue;
3902
3903                 if (*t > 0 && *t < ' ')
3904                         return true;
3905
3906                 if (*t == 127)
3907                         return true;
3908         }
3909
3910         return false;
3911 }
3912
3913 bool path_is_safe(const char *p) {
3914
3915         if (isempty(p))
3916                 return false;
3917
3918         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3919                 return false;
3920
3921         if (strlen(p)+1 > PATH_MAX)
3922                 return false;
3923
3924         /* The following two checks are not really dangerous, but hey, they still are confusing */
3925         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3926                 return false;
3927
3928         if (strstr(p, "//"))
3929                 return false;
3930
3931         return true;
3932 }
3933
3934 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3935 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3936                  int (*compar) (const void *, const void *, void *), void *arg) {
3937         size_t l, u, idx;
3938         const void *p;
3939         int comparison;
3940
3941         l = 0;
3942         u = nmemb;
3943         while (l < u) {
3944                 idx = (l + u) / 2;
3945                 p = (void *)(((const char *) base) + (idx * size));
3946                 comparison = compar(key, p, arg);
3947                 if (comparison < 0)
3948                         u = idx;
3949                 else if (comparison > 0)
3950                         l = idx + 1;
3951                 else
3952                         return (void *)p;
3953         }
3954         return NULL;
3955 }
3956
3957 void init_gettext(void) {
3958         setlocale(LC_ALL, "");
3959         textdomain(GETTEXT_PACKAGE);
3960 }
3961
3962 bool is_locale_utf8(void) {
3963         const char *set;
3964         static int cached_answer = -1;
3965
3966         if (cached_answer >= 0)
3967                 goto out;
3968
3969         if (!setlocale(LC_ALL, "")) {
3970                 cached_answer = true;
3971                 goto out;
3972         }
3973
3974         set = nl_langinfo(CODESET);
3975         if (!set) {
3976                 cached_answer = true;
3977                 goto out;
3978         }
3979
3980         if (streq(set, "UTF-8")) {
3981                 cached_answer = true;
3982                 goto out;
3983         }
3984
3985         /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3986          * unset and everything can do to UTF-8 nowadays. */
3987         set = setlocale(LC_CTYPE, NULL);
3988         if (!set) {
3989                 cached_answer = true;
3990                 goto out;
3991         }
3992
3993         /* Check result, but ignore the result if C was set
3994          * explicitly. */
3995         cached_answer =
3996                 streq(set, "C") &&
3997                 !getenv("LC_ALL") &&
3998                 !getenv("LC_CTYPE") &&
3999                 !getenv("LANG");
4000
4001 out:
4002         return (bool) cached_answer;
4003 }
4004
4005 const char *draw_special_char(DrawSpecialChar ch) {
4006         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
4007
4008                 /* UTF-8 */ {
4009                         [DRAW_TREE_VERTICAL]      = "\342\224\202 ",            /* │  */
4010                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
4011                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
4012                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
4013                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243",             /* ‣ */
4014                         [DRAW_BLACK_CIRCLE]       = "\342\227\217",             /* ● */
4015                         [DRAW_ARROW]              = "\342\206\222",             /* → */
4016                         [DRAW_DASH]               = "\342\200\223",             /* – */
4017                 },
4018
4019                 /* ASCII fallback */ {
4020                         [DRAW_TREE_VERTICAL]      = "| ",
4021                         [DRAW_TREE_BRANCH]        = "|-",
4022                         [DRAW_TREE_RIGHT]         = "`-",
4023                         [DRAW_TREE_SPACE]         = "  ",
4024                         [DRAW_TRIANGULAR_BULLET]  = ">",
4025                         [DRAW_BLACK_CIRCLE]       = "*",
4026                         [DRAW_ARROW]              = "->",
4027                         [DRAW_DASH]               = "-",
4028                 }
4029         };
4030
4031         return draw_table[!is_locale_utf8()][ch];
4032 }
4033
4034 char *strreplace(const char *text, const char *old_string, const char *new_string) {
4035         const char *f;
4036         char *t, *r;
4037         size_t l, old_len, new_len;
4038
4039         assert(text);
4040         assert(old_string);
4041         assert(new_string);
4042
4043         old_len = strlen(old_string);
4044         new_len = strlen(new_string);
4045
4046         l = strlen(text);
4047         r = new(char, l+1);
4048         if (!r)
4049                 return NULL;
4050
4051         f = text;
4052         t = r;
4053         while (*f) {
4054                 char *a;
4055                 size_t d, nl;
4056
4057                 if (!startswith(f, old_string)) {
4058                         *(t++) = *(f++);
4059                         continue;
4060                 }
4061
4062                 d = t - r;
4063                 nl = l - old_len + new_len;
4064                 a = realloc(r, nl + 1);
4065                 if (!a)
4066                         goto oom;
4067
4068                 l = nl;
4069                 r = a;
4070                 t = r + d;
4071
4072                 t = stpcpy(t, new_string);
4073                 f += old_len;
4074         }
4075
4076         *t = 0;
4077         return r;
4078
4079 oom:
4080         free(r);
4081         return NULL;
4082 }
4083
4084 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4085         const char *i, *begin = NULL;
4086         enum {
4087                 STATE_OTHER,
4088                 STATE_ESCAPE,
4089                 STATE_BRACKET
4090         } state = STATE_OTHER;
4091         char *obuf = NULL;
4092         size_t osz = 0, isz;
4093         FILE *f;
4094
4095         assert(ibuf);
4096         assert(*ibuf);
4097
4098         /* Strips ANSI color and replaces TABs by 8 spaces */
4099
4100         isz = _isz ? *_isz : strlen(*ibuf);
4101
4102         f = open_memstream(&obuf, &osz);
4103         if (!f)
4104                 return NULL;
4105
4106         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4107
4108                 switch (state) {
4109
4110                 case STATE_OTHER:
4111                         if (i >= *ibuf + isz) /* EOT */
4112                                 break;
4113                         else if (*i == '\x1B')
4114                                 state = STATE_ESCAPE;
4115                         else if (*i == '\t')
4116                                 fputs("        ", f);
4117                         else
4118                                 fputc(*i, f);
4119                         break;
4120
4121                 case STATE_ESCAPE:
4122                         if (i >= *ibuf + isz) { /* EOT */
4123                                 fputc('\x1B', f);
4124                                 break;
4125                         } else if (*i == '[') {
4126                                 state = STATE_BRACKET;
4127                                 begin = i + 1;
4128                         } else {
4129                                 fputc('\x1B', f);
4130                                 fputc(*i, f);
4131                                 state = STATE_OTHER;
4132                         }
4133
4134                         break;
4135
4136                 case STATE_BRACKET:
4137
4138                         if (i >= *ibuf + isz || /* EOT */
4139                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4140                                 fputc('\x1B', f);
4141                                 fputc('[', f);
4142                                 state = STATE_OTHER;
4143                                 i = begin-1;
4144                         } else if (*i == 'm')
4145                                 state = STATE_OTHER;
4146                         break;
4147                 }
4148         }
4149
4150         if (ferror(f)) {
4151                 fclose(f);
4152                 free(obuf);
4153                 return NULL;
4154         }
4155
4156         fclose(f);
4157
4158         free(*ibuf);
4159         *ibuf = obuf;
4160
4161         if (_isz)
4162                 *_isz = osz;
4163
4164         return obuf;
4165 }
4166
4167 int on_ac_power(void) {
4168         bool found_offline = false, found_online = false;
4169         _cleanup_closedir_ DIR *d = NULL;
4170
4171         d = opendir("/sys/class/power_supply");
4172         if (!d)
4173                 return errno == ENOENT ? true : -errno;
4174
4175         for (;;) {
4176                 struct dirent *de;
4177                 _cleanup_close_ int fd = -1, device = -1;
4178                 char contents[6];
4179                 ssize_t n;
4180
4181                 errno = 0;
4182                 de = readdir(d);
4183                 if (!de && errno != 0)
4184                         return -errno;
4185
4186                 if (!de)
4187                         break;
4188
4189                 if (hidden_file(de->d_name))
4190                         continue;
4191
4192                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4193                 if (device < 0) {
4194                         if (errno == ENOENT || errno == ENOTDIR)
4195                                 continue;
4196
4197                         return -errno;
4198                 }
4199
4200                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4201                 if (fd < 0) {
4202                         if (errno == ENOENT)
4203                                 continue;
4204
4205                         return -errno;
4206                 }
4207
4208                 n = read(fd, contents, sizeof(contents));
4209                 if (n < 0)
4210                         return -errno;
4211
4212                 if (n != 6 || memcmp(contents, "Mains\n", 6))
4213                         continue;
4214
4215                 safe_close(fd);
4216                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4217                 if (fd < 0) {
4218                         if (errno == ENOENT)
4219                                 continue;
4220
4221                         return -errno;
4222                 }
4223
4224                 n = read(fd, contents, sizeof(contents));
4225                 if (n < 0)
4226                         return -errno;
4227
4228                 if (n != 2 || contents[1] != '\n')
4229                         return -EIO;
4230
4231                 if (contents[0] == '1') {
4232                         found_online = true;
4233                         break;
4234                 } else if (contents[0] == '0')
4235                         found_offline = true;
4236                 else
4237                         return -EIO;
4238         }
4239
4240         return found_online || !found_offline;
4241 }
4242
4243 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4244         char **i;
4245
4246         assert(path);
4247         assert(mode);
4248         assert(_f);
4249
4250         if (!path_strv_resolve_uniq(search, root))
4251                 return -ENOMEM;
4252
4253         STRV_FOREACH(i, search) {
4254                 _cleanup_free_ char *p = NULL;
4255                 FILE *f;
4256
4257                 if (root)
4258                         p = strjoin(root, *i, "/", path, NULL);
4259                 else
4260                         p = strjoin(*i, "/", path, NULL);
4261                 if (!p)
4262                         return -ENOMEM;
4263
4264                 f = fopen(p, mode);
4265                 if (f) {
4266                         *_f = f;
4267                         return 0;
4268                 }
4269
4270                 if (errno != ENOENT)
4271                         return -errno;
4272         }
4273
4274         return -ENOENT;
4275 }
4276
4277 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4278         _cleanup_strv_free_ char **copy = NULL;
4279
4280         assert(path);
4281         assert(mode);
4282         assert(_f);
4283
4284         if (path_is_absolute(path)) {
4285                 FILE *f;
4286
4287                 f = fopen(path, mode);
4288                 if (f) {
4289                         *_f = f;
4290                         return 0;
4291                 }
4292
4293                 return -errno;
4294         }
4295
4296         copy = strv_copy((char**) search);
4297         if (!copy)
4298                 return -ENOMEM;
4299
4300         return search_and_fopen_internal(path, mode, root, copy, _f);
4301 }
4302
4303 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4304         _cleanup_strv_free_ char **s = NULL;
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         s = strv_split_nulstr(search);
4319         if (!s)
4320                 return -ENOMEM;
4321
4322         return search_and_fopen_internal(path, mode, root, s, _f);
4323 }
4324
4325 char *strextend(char **x, ...) {
4326         va_list ap;
4327         size_t f, l;
4328         char *r, *p;
4329
4330         assert(x);
4331
4332         l = f = *x ? strlen(*x) : 0;
4333
4334         va_start(ap, x);
4335         for (;;) {
4336                 const char *t;
4337                 size_t n;
4338
4339                 t = va_arg(ap, const char *);
4340                 if (!t)
4341                         break;
4342
4343                 n = strlen(t);
4344                 if (n > ((size_t) -1) - l) {
4345                         va_end(ap);
4346                         return NULL;
4347                 }
4348
4349                 l += n;
4350         }
4351         va_end(ap);
4352
4353         r = realloc(*x, l+1);
4354         if (!r)
4355                 return NULL;
4356
4357         p = r + f;
4358
4359         va_start(ap, x);
4360         for (;;) {
4361                 const char *t;
4362
4363                 t = va_arg(ap, const char *);
4364                 if (!t)
4365                         break;
4366
4367                 p = stpcpy(p, t);
4368         }
4369         va_end(ap);
4370
4371         *p = 0;
4372         *x = r;
4373
4374         return r + l;
4375 }
4376
4377 char *strrep(const char *s, unsigned n) {
4378         size_t l;
4379         char *r, *p;
4380         unsigned i;
4381
4382         assert(s);
4383
4384         l = strlen(s);
4385         p = r = malloc(l * n + 1);
4386         if (!r)
4387                 return NULL;
4388
4389         for (i = 0; i < n; i++)
4390                 p = stpcpy(p, s);
4391
4392         *p = 0;
4393         return r;
4394 }
4395
4396 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4397         size_t a, newalloc;
4398         void *q;
4399
4400         assert(p);
4401         assert(allocated);
4402
4403         if (*allocated >= need)
4404                 return *p;
4405
4406         newalloc = MAX(need * 2, 64u / size);
4407         a = newalloc * size;
4408
4409         /* check for overflows */
4410         if (a < size * need)
4411                 return NULL;
4412
4413         q = realloc(*p, a);
4414         if (!q)
4415                 return NULL;
4416
4417         *p = q;
4418         *allocated = newalloc;
4419         return q;
4420 }
4421
4422 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4423         size_t prev;
4424         uint8_t *q;
4425
4426         assert(p);
4427         assert(allocated);
4428
4429         prev = *allocated;
4430
4431         q = greedy_realloc(p, allocated, need, size);
4432         if (!q)
4433                 return NULL;
4434
4435         if (*allocated > prev)
4436                 memzero(q + prev * size, (*allocated - prev) * size);
4437
4438         return q;
4439 }
4440
4441 bool id128_is_valid(const char *s) {
4442         size_t i, l;
4443
4444         l = strlen(s);
4445         if (l == 32) {
4446
4447                 /* Simple formatted 128bit hex string */
4448
4449                 for (i = 0; i < l; i++) {
4450                         char c = s[i];
4451
4452                         if (!(c >= '0' && c <= '9') &&
4453                             !(c >= 'a' && c <= 'z') &&
4454                             !(c >= 'A' && c <= 'Z'))
4455                                 return false;
4456                 }
4457
4458         } else if (l == 36) {
4459
4460                 /* Formatted UUID */
4461
4462                 for (i = 0; i < l; i++) {
4463                         char c = s[i];
4464
4465                         if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4466                                 if (c != '-')
4467                                         return false;
4468                         } else {
4469                                 if (!(c >= '0' && c <= '9') &&
4470                                     !(c >= 'a' && c <= 'z') &&
4471                                     !(c >= 'A' && c <= 'Z'))
4472                                         return false;
4473                         }
4474                 }
4475
4476         } else
4477                 return false;
4478
4479         return true;
4480 }
4481
4482 int split_pair(const char *s, const char *sep, char **l, char **r) {
4483         char *x, *a, *b;
4484
4485         assert(s);
4486         assert(sep);
4487         assert(l);
4488         assert(r);
4489
4490         if (isempty(sep))
4491                 return -EINVAL;
4492
4493         x = strstr(s, sep);
4494         if (!x)
4495                 return -EINVAL;
4496
4497         a = strndup(s, x - s);
4498         if (!a)
4499                 return -ENOMEM;
4500
4501         b = strdup(x + strlen(sep));
4502         if (!b) {
4503                 free(a);
4504                 return -ENOMEM;
4505         }
4506
4507         *l = a;
4508         *r = b;
4509
4510         return 0;
4511 }
4512
4513 int shall_restore_state(void) {
4514         _cleanup_free_ char *value = NULL;
4515         int r;
4516
4517         r = get_proc_cmdline_key("systemd.restore_state=", &value);
4518         if (r < 0)
4519                 return r;
4520         if (r == 0)
4521                 return true;
4522
4523         return parse_boolean(value) != 0;
4524 }
4525
4526 int proc_cmdline(char **ret) {
4527         assert(ret);
4528
4529         if (detect_container(NULL) > 0)
4530                 return get_process_cmdline(1, 0, false, ret);
4531         else
4532                 return read_one_line_file("/proc/cmdline", ret);
4533 }
4534
4535 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4536         _cleanup_free_ char *line = NULL;
4537         const char *p;
4538         int r;
4539
4540         assert(parse_item);
4541
4542         r = proc_cmdline(&line);
4543         if (r < 0)
4544                 return r;
4545
4546         p = line;
4547         for (;;) {
4548                 _cleanup_free_ char *word = NULL;
4549                 char *value = NULL;
4550
4551                 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4552                 if (r < 0)
4553                         return r;
4554                 if (r == 0)
4555                         break;
4556
4557                 /* Filter out arguments that are intended only for the
4558                  * initrd */
4559                 if (!in_initrd() && startswith(word, "rd."))
4560                         continue;
4561
4562                 value = strchr(word, '=');
4563                 if (value)
4564                         *(value++) = 0;
4565
4566                 r = parse_item(word, value);
4567                 if (r < 0)
4568                         return r;
4569         }
4570
4571         return 0;
4572 }
4573
4574 int get_proc_cmdline_key(const char *key, char **value) {
4575         _cleanup_free_ char *line = NULL, *ret = NULL;
4576         bool found = false;
4577         const char *p;
4578         int r;
4579
4580         assert(key);
4581
4582         r = proc_cmdline(&line);
4583         if (r < 0)
4584                 return r;
4585
4586         p = line;
4587         for (;;) {
4588                 _cleanup_free_ char *word = NULL;
4589                 const char *e;
4590
4591                 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4592                 if (r < 0)
4593                         return r;
4594                 if (r == 0)
4595                         break;
4596
4597                 /* Filter out arguments that are intended only for the
4598                  * initrd */
4599                 if (!in_initrd() && startswith(word, "rd."))
4600                         continue;
4601
4602                 if (value) {
4603                         e = startswith(word, key);
4604                         if (!e)
4605                                 continue;
4606
4607                         r = free_and_strdup(&ret, e);
4608                         if (r < 0)
4609                                 return r;
4610
4611                         found = true;
4612                 } else {
4613                         if (streq(word, key))
4614                                 found = true;
4615                 }
4616         }
4617
4618         if (value) {
4619                 *value = ret;
4620                 ret = NULL;
4621         }
4622
4623         return found;
4624
4625 }
4626
4627 int container_get_leader(const char *machine, pid_t *pid) {
4628         _cleanup_free_ char *s = NULL, *class = NULL;
4629         const char *p;
4630         pid_t leader;
4631         int r;
4632
4633         assert(machine);
4634         assert(pid);
4635
4636         p = strjoina("/run/systemd/machines/", machine);
4637         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4638         if (r == -ENOENT)
4639                 return -EHOSTDOWN;
4640         if (r < 0)
4641                 return r;
4642         if (!s)
4643                 return -EIO;
4644
4645         if (!streq_ptr(class, "container"))
4646                 return -EIO;
4647
4648         r = parse_pid(s, &leader);
4649         if (r < 0)
4650                 return r;
4651         if (leader <= 1)
4652                 return -EIO;
4653
4654         *pid = leader;
4655         return 0;
4656 }
4657
4658 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4659         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4660         int rfd = -1;
4661
4662         assert(pid >= 0);
4663
4664         if (mntns_fd) {
4665                 const char *mntns;
4666
4667                 mntns = procfs_file_alloca(pid, "ns/mnt");
4668                 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4669                 if (mntnsfd < 0)
4670                         return -errno;
4671         }
4672
4673         if (pidns_fd) {
4674                 const char *pidns;
4675
4676                 pidns = procfs_file_alloca(pid, "ns/pid");
4677                 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4678                 if (pidnsfd < 0)
4679                         return -errno;
4680         }
4681
4682         if (netns_fd) {
4683                 const char *netns;
4684
4685                 netns = procfs_file_alloca(pid, "ns/net");
4686                 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4687                 if (netnsfd < 0)
4688                         return -errno;
4689         }
4690
4691         if (root_fd) {
4692                 const char *root;
4693
4694                 root = procfs_file_alloca(pid, "root");
4695                 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4696                 if (rfd < 0)
4697                         return -errno;
4698         }
4699
4700         if (pidns_fd)
4701                 *pidns_fd = pidnsfd;
4702
4703         if (mntns_fd)
4704                 *mntns_fd = mntnsfd;
4705
4706         if (netns_fd)
4707                 *netns_fd = netnsfd;
4708
4709         if (root_fd)
4710                 *root_fd = rfd;
4711
4712         pidnsfd = mntnsfd = netnsfd = -1;
4713
4714         return 0;
4715 }
4716
4717 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4718
4719         if (pidns_fd >= 0)
4720                 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4721                         return -errno;
4722
4723         if (mntns_fd >= 0)
4724                 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4725                         return -errno;
4726
4727         if (netns_fd >= 0)
4728                 if (setns(netns_fd, CLONE_NEWNET) < 0)
4729                         return -errno;
4730
4731         if (root_fd >= 0) {
4732                 if (fchdir(root_fd) < 0)
4733                         return -errno;
4734
4735                 if (chroot(".") < 0)
4736                         return -errno;
4737         }
4738
4739         if (setresgid(0, 0, 0) < 0)
4740                 return -errno;
4741
4742         if (setgroups(0, NULL) < 0)
4743                 return -errno;
4744
4745         if (setresuid(0, 0, 0) < 0)
4746                 return -errno;
4747
4748         return 0;
4749 }
4750
4751 int getpeercred(int fd, struct ucred *ucred) {
4752         socklen_t n = sizeof(struct ucred);
4753         struct ucred u;
4754         int r;
4755
4756         assert(fd >= 0);
4757         assert(ucred);
4758
4759         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4760         if (r < 0)
4761                 return -errno;
4762
4763         if (n != sizeof(struct ucred))
4764                 return -EIO;
4765
4766         /* Check if the data is actually useful and not suppressed due
4767          * to namespacing issues */
4768         if (u.pid <= 0)
4769                 return -ENODATA;
4770         if (u.uid == UID_INVALID)
4771                 return -ENODATA;
4772         if (u.gid == GID_INVALID)
4773                 return -ENODATA;
4774
4775         *ucred = u;
4776         return 0;
4777 }
4778
4779 int getpeersec(int fd, char **ret) {
4780         socklen_t n = 64;
4781         char *s;
4782         int r;
4783
4784         assert(fd >= 0);
4785         assert(ret);
4786
4787         s = new0(char, n);
4788         if (!s)
4789                 return -ENOMEM;
4790
4791         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4792         if (r < 0) {
4793                 free(s);
4794
4795                 if (errno != ERANGE)
4796                         return -errno;
4797
4798                 s = new0(char, n);
4799                 if (!s)
4800                         return -ENOMEM;
4801
4802                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4803                 if (r < 0) {
4804                         free(s);
4805                         return -errno;
4806                 }
4807         }
4808
4809         if (isempty(s)) {
4810                 free(s);
4811                 return -EOPNOTSUPP;
4812         }
4813
4814         *ret = s;
4815         return 0;
4816 }
4817
4818 /* This is much like like mkostemp() but is subject to umask(). */
4819 int mkostemp_safe(char *pattern, int flags) {
4820         _cleanup_umask_ mode_t u;
4821         int fd;
4822
4823         assert(pattern);
4824
4825         u = umask(077);
4826
4827         fd = mkostemp(pattern, flags);
4828         if (fd < 0)
4829                 return -errno;
4830
4831         return fd;
4832 }
4833
4834 int open_tmpfile(const char *path, int flags) {
4835         char *p;
4836         int fd;
4837
4838         assert(path);
4839
4840 #ifdef O_TMPFILE
4841         /* Try O_TMPFILE first, if it is supported */
4842         fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
4843         if (fd >= 0)
4844                 return fd;
4845 #endif
4846
4847         /* Fall back to unguessable name + unlinking */
4848         p = strjoina(path, "/systemd-tmp-XXXXXX");
4849
4850         fd = mkostemp_safe(p, flags);
4851         if (fd < 0)
4852                 return fd;
4853
4854         unlink(p);
4855         return fd;
4856 }
4857
4858 int fd_warn_permissions(const char *path, int fd) {
4859         struct stat st;
4860
4861         if (fstat(fd, &st) < 0)
4862                 return -errno;
4863
4864         if (st.st_mode & 0111)
4865                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4866
4867         if (st.st_mode & 0002)
4868                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4869
4870         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4871                 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);
4872
4873         return 0;
4874 }
4875
4876 unsigned long personality_from_string(const char *p) {
4877
4878         /* Parse a personality specifier. We introduce our own
4879          * identifiers that indicate specific ABIs, rather than just
4880          * hints regarding the register size, since we want to keep
4881          * things open for multiple locally supported ABIs for the
4882          * same register size. We try to reuse the ABI identifiers
4883          * used by libseccomp. */
4884
4885 #if defined(__x86_64__)
4886
4887         if (streq(p, "x86"))
4888                 return PER_LINUX32;
4889
4890         if (streq(p, "x86-64"))
4891                 return PER_LINUX;
4892
4893 #elif defined(__i386__)
4894
4895         if (streq(p, "x86"))
4896                 return PER_LINUX;
4897 #endif
4898
4899         /* personality(7) documents that 0xffffffffUL is used for
4900          * querying the current personality, hence let's use that here
4901          * as error indicator. */
4902         return 0xffffffffUL;
4903 }
4904
4905 const char* personality_to_string(unsigned long p) {
4906
4907 #if defined(__x86_64__)
4908
4909         if (p == PER_LINUX32)
4910                 return "x86";
4911
4912         if (p == PER_LINUX)
4913                 return "x86-64";
4914
4915 #elif defined(__i386__)
4916
4917         if (p == PER_LINUX)
4918                 return "x86";
4919 #endif
4920
4921         return NULL;
4922 }
4923
4924 uint64_t physical_memory(void) {
4925         long mem;
4926
4927         /* We return this as uint64_t in case we are running as 32bit
4928          * process on a 64bit kernel with huge amounts of memory */
4929
4930         mem = sysconf(_SC_PHYS_PAGES);
4931         assert(mem > 0);
4932
4933         return (uint64_t) mem * (uint64_t) page_size();
4934 }
4935
4936 void hexdump(FILE *f, const void *p, size_t s) {
4937         const uint8_t *b = p;
4938         unsigned n = 0;
4939
4940         assert(s == 0 || b);
4941
4942         while (s > 0) {
4943                 size_t i;
4944
4945                 fprintf(f, "%04x  ", n);
4946
4947                 for (i = 0; i < 16; i++) {
4948
4949                         if (i >= s)
4950                                 fputs("   ", f);
4951                         else
4952                                 fprintf(f, "%02x ", b[i]);
4953
4954                         if (i == 7)
4955                                 fputc(' ', f);
4956                 }
4957
4958                 fputc(' ', f);
4959
4960                 for (i = 0; i < 16; i++) {
4961
4962                         if (i >= s)
4963                                 fputc(' ', f);
4964                         else
4965                                 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4966                 }
4967
4968                 fputc('\n', f);
4969
4970                 if (s < 16)
4971                         break;
4972
4973                 n += 16;
4974                 b += 16;
4975                 s -= 16;
4976         }
4977 }
4978
4979 int update_reboot_param_file(const char *param) {
4980         int r = 0;
4981
4982         if (param) {
4983
4984                 r = write_string_file(REBOOT_PARAM_FILE, param);
4985                 if (r < 0)
4986                         log_error("Failed to write reboot param to "
4987                                   REBOOT_PARAM_FILE": %s", strerror(-r));
4988         } else
4989                 unlink(REBOOT_PARAM_FILE);
4990
4991         return r;
4992 }
4993
4994 int umount_recursive(const char *prefix, int flags) {
4995         bool again;
4996         int n = 0, r;
4997
4998         /* Try to umount everything recursively below a
4999          * directory. Also, take care of stacked mounts, and keep
5000          * unmounting them until they are gone. */
5001
5002         do {
5003                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5004
5005                 again = false;
5006                 r = 0;
5007
5008                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5009                 if (!proc_self_mountinfo)
5010                         return -errno;
5011
5012                 for (;;) {
5013                         _cleanup_free_ char *path = NULL, *p = NULL;
5014                         int k;
5015
5016                         k = fscanf(proc_self_mountinfo,
5017                                    "%*s "       /* (1) mount id */
5018                                    "%*s "       /* (2) parent id */
5019                                    "%*s "       /* (3) major:minor */
5020                                    "%*s "       /* (4) root */
5021                                    "%ms "       /* (5) mount point */
5022                                    "%*s"        /* (6) mount options */
5023                                    "%*[^-]"     /* (7) optional fields */
5024                                    "- "         /* (8) separator */
5025                                    "%*s "       /* (9) file system type */
5026                                    "%*s"        /* (10) mount source */
5027                                    "%*s"        /* (11) mount options 2 */
5028                                    "%*[^\n]",   /* some rubbish at the end */
5029                                    &path);
5030                         if (k != 1) {
5031                                 if (k == EOF)
5032                                         break;
5033
5034                                 continue;
5035                         }
5036
5037                         r = cunescape(path, UNESCAPE_RELAX, &p);
5038                         if (r < 0)
5039                                 return r;
5040
5041                         if (!path_startswith(p, prefix))
5042                                 continue;
5043
5044                         if (umount2(p, flags) < 0) {
5045                                 r = -errno;
5046                                 continue;
5047                         }
5048
5049                         again = true;
5050                         n++;
5051
5052                         break;
5053                 }
5054
5055         } while (again);
5056
5057         return r ? r : n;
5058 }
5059
5060 static int get_mount_flags(const char *path, unsigned long *flags) {
5061         struct statvfs buf;
5062
5063         if (statvfs(path, &buf) < 0)
5064                 return -errno;
5065         *flags = buf.f_flag;
5066         return 0;
5067 }
5068
5069 int bind_remount_recursive(const char *prefix, bool ro) {
5070         _cleanup_set_free_free_ Set *done = NULL;
5071         _cleanup_free_ char *cleaned = NULL;
5072         int r;
5073
5074         /* Recursively remount a directory (and all its submounts)
5075          * read-only or read-write. If the directory is already
5076          * mounted, we reuse the mount and simply mark it
5077          * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5078          * operation). If it isn't we first make it one. Afterwards we
5079          * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5080          * submounts we can access, too. When mounts are stacked on
5081          * the same mount point we only care for each individual
5082          * "top-level" mount on each point, as we cannot
5083          * influence/access the underlying mounts anyway. We do not
5084          * have any effect on future submounts that might get
5085          * propagated, they migt be writable. This includes future
5086          * submounts that have been triggered via autofs. */
5087
5088         cleaned = strdup(prefix);
5089         if (!cleaned)
5090                 return -ENOMEM;
5091
5092         path_kill_slashes(cleaned);
5093
5094         done = set_new(&string_hash_ops);
5095         if (!done)
5096                 return -ENOMEM;
5097
5098         for (;;) {
5099                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5100                 _cleanup_set_free_free_ Set *todo = NULL;
5101                 bool top_autofs = false;
5102                 char *x;
5103                 unsigned long orig_flags;
5104
5105                 todo = set_new(&string_hash_ops);
5106                 if (!todo)
5107                         return -ENOMEM;
5108
5109                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5110                 if (!proc_self_mountinfo)
5111                         return -errno;
5112
5113                 for (;;) {
5114                         _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5115                         int k;
5116
5117                         k = fscanf(proc_self_mountinfo,
5118                                    "%*s "       /* (1) mount id */
5119                                    "%*s "       /* (2) parent id */
5120                                    "%*s "       /* (3) major:minor */
5121                                    "%*s "       /* (4) root */
5122                                    "%ms "       /* (5) mount point */
5123                                    "%*s"        /* (6) mount options (superblock) */
5124                                    "%*[^-]"     /* (7) optional fields */
5125                                    "- "         /* (8) separator */
5126                                    "%ms "       /* (9) file system type */
5127                                    "%*s"        /* (10) mount source */
5128                                    "%*s"        /* (11) mount options (bind mount) */
5129                                    "%*[^\n]",   /* some rubbish at the end */
5130                                    &path,
5131                                    &type);
5132                         if (k != 2) {
5133                                 if (k == EOF)
5134                                         break;
5135
5136                                 continue;
5137                         }
5138
5139                         r = cunescape(path, UNESCAPE_RELAX, &p);
5140                         if (r < 0)
5141                                 return r;
5142
5143                         /* Let's ignore autofs mounts.  If they aren't
5144                          * triggered yet, we want to avoid triggering
5145                          * them, as we don't make any guarantees for
5146                          * future submounts anyway.  If they are
5147                          * already triggered, then we will find
5148                          * another entry for this. */
5149                         if (streq(type, "autofs")) {
5150                                 top_autofs = top_autofs || path_equal(cleaned, p);
5151                                 continue;
5152                         }
5153
5154                         if (path_startswith(p, cleaned) &&
5155                             !set_contains(done, p)) {
5156
5157                                 r = set_consume(todo, p);
5158                                 p = NULL;
5159
5160                                 if (r == -EEXIST)
5161                                         continue;
5162                                 if (r < 0)
5163                                         return r;
5164                         }
5165                 }
5166
5167                 /* If we have no submounts to process anymore and if
5168                  * the root is either already done, or an autofs, we
5169                  * are done */
5170                 if (set_isempty(todo) &&
5171                     (top_autofs || set_contains(done, cleaned)))
5172                         return 0;
5173
5174                 if (!set_contains(done, cleaned) &&
5175                     !set_contains(todo, cleaned)) {
5176                         /* The prefix directory itself is not yet a
5177                          * mount, make it one. */
5178                         if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5179                                 return -errno;
5180
5181                         orig_flags = 0;
5182                         (void) get_mount_flags(cleaned, &orig_flags);
5183                         orig_flags &= ~MS_RDONLY;
5184
5185                         if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5186                                 return -errno;
5187
5188                         x = strdup(cleaned);
5189                         if (!x)
5190                                 return -ENOMEM;
5191
5192                         r = set_consume(done, x);
5193                         if (r < 0)
5194                                 return r;
5195                 }
5196
5197                 while ((x = set_steal_first(todo))) {
5198
5199                         r = set_consume(done, x);
5200                         if (r == -EEXIST)
5201                                 continue;
5202                         if (r < 0)
5203                                 return r;
5204
5205                         /* Try to reuse the original flag set, but
5206                          * don't care for errors, in case of
5207                          * obstructed mounts */
5208                         orig_flags = 0;
5209                         (void) get_mount_flags(x, &orig_flags);
5210                         orig_flags &= ~MS_RDONLY;
5211
5212                         if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5213
5214                                 /* Deal with mount points that are
5215                                  * obstructed by a later mount */
5216
5217                                 if (errno != ENOENT)
5218                                         return -errno;
5219                         }
5220
5221                 }
5222         }
5223 }
5224
5225 int fflush_and_check(FILE *f) {
5226         assert(f);
5227
5228         errno = 0;
5229         fflush(f);
5230
5231         if (ferror(f))
5232                 return errno ? -errno : -EIO;
5233
5234         return 0;
5235 }
5236
5237 int tempfn_xxxxxx(const char *p, char **ret) {
5238         const char *fn;
5239         char *t;
5240
5241         assert(p);
5242         assert(ret);
5243
5244         /*
5245          * Turns this:
5246          *         /foo/bar/waldo
5247          *
5248          * Into this:
5249          *         /foo/bar/.#waldoXXXXXX
5250          */
5251
5252         fn = basename(p);
5253         if (!filename_is_valid(fn))
5254                 return -EINVAL;
5255
5256         t = new(char, strlen(p) + 2 + 6 + 1);
5257         if (!t)
5258                 return -ENOMEM;
5259
5260         strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5261
5262         *ret = path_kill_slashes(t);
5263         return 0;
5264 }
5265
5266 int tempfn_random(const char *p, char **ret) {
5267         const char *fn;
5268         char *t, *x;
5269         uint64_t u;
5270         unsigned i;
5271
5272         assert(p);
5273         assert(ret);
5274
5275         /*
5276          * Turns this:
5277          *         /foo/bar/waldo
5278          *
5279          * Into this:
5280          *         /foo/bar/.#waldobaa2a261115984a9
5281          */
5282
5283         fn = basename(p);
5284         if (!filename_is_valid(fn))
5285                 return -EINVAL;
5286
5287         t = new(char, strlen(p) + 2 + 16 + 1);
5288         if (!t)
5289                 return -ENOMEM;
5290
5291         x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5292
5293         u = random_u64();
5294         for (i = 0; i < 16; i++) {
5295                 *(x++) = hexchar(u & 0xF);
5296                 u >>= 4;
5297         }
5298
5299         *x = 0;
5300
5301         *ret = path_kill_slashes(t);
5302         return 0;
5303 }
5304
5305 int tempfn_random_child(const char *p, char **ret) {
5306         char *t, *x;
5307         uint64_t u;
5308         unsigned i;
5309
5310         assert(p);
5311         assert(ret);
5312
5313         /* Turns this:
5314          *         /foo/bar/waldo
5315          * Into this:
5316          *         /foo/bar/waldo/.#3c2b6219aa75d7d0
5317          */
5318
5319         t = new(char, strlen(p) + 3 + 16 + 1);
5320         if (!t)
5321                 return -ENOMEM;
5322
5323         x = stpcpy(stpcpy(t, p), "/.#");
5324
5325         u = random_u64();
5326         for (i = 0; i < 16; i++) {
5327                 *(x++) = hexchar(u & 0xF);
5328                 u >>= 4;
5329         }
5330
5331         *x = 0;
5332
5333         *ret = path_kill_slashes(t);
5334         return 0;
5335 }
5336
5337 /* make sure the hostname is not "localhost" */
5338 bool is_localhost(const char *hostname) {
5339         assert(hostname);
5340
5341         /* This tries to identify local host and domain names
5342          * described in RFC6761 plus the redhatism of .localdomain */
5343
5344         return streq(hostname, "localhost") ||
5345                streq(hostname, "localhost.") ||
5346                streq(hostname, "localdomain.") ||
5347                streq(hostname, "localdomain") ||
5348                endswith(hostname, ".localhost") ||
5349                endswith(hostname, ".localhost.") ||
5350                endswith(hostname, ".localdomain") ||
5351                endswith(hostname, ".localdomain.");
5352 }
5353
5354 int take_password_lock(const char *root) {
5355
5356         struct flock flock = {
5357                 .l_type = F_WRLCK,
5358                 .l_whence = SEEK_SET,
5359                 .l_start = 0,
5360                 .l_len = 0,
5361         };
5362
5363         const char *path;
5364         int fd, r;
5365
5366         /* This is roughly the same as lckpwdf(), but not as awful. We
5367          * don't want to use alarm() and signals, hence we implement
5368          * our own trivial version of this.
5369          *
5370          * Note that shadow-utils also takes per-database locks in
5371          * addition to lckpwdf(). However, we don't given that they
5372          * are redundant as they they invoke lckpwdf() first and keep
5373          * it during everything they do. The per-database locks are
5374          * awfully racy, and thus we just won't do them. */
5375
5376         if (root)
5377                 path = strjoina(root, "/etc/.pwd.lock");
5378         else
5379                 path = "/etc/.pwd.lock";
5380
5381         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5382         if (fd < 0)
5383                 return -errno;
5384
5385         r = fcntl(fd, F_SETLKW, &flock);
5386         if (r < 0) {
5387                 safe_close(fd);
5388                 return -errno;
5389         }
5390
5391         return fd;
5392 }
5393
5394 int is_symlink(const char *path) {
5395         struct stat info;
5396
5397         if (lstat(path, &info) < 0)
5398                 return -errno;
5399
5400         return !!S_ISLNK(info.st_mode);
5401 }
5402
5403 int is_dir(const char* path, bool follow) {
5404         struct stat st;
5405         int r;
5406
5407         if (follow)
5408                 r = stat(path, &st);
5409         else
5410                 r = lstat(path, &st);
5411         if (r < 0)
5412                 return -errno;
5413
5414         return !!S_ISDIR(st.st_mode);
5415 }
5416
5417 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5418         _cleanup_free_ char *s = NULL;
5419         size_t allocated = 0, sz = 0;
5420         int r;
5421
5422         enum {
5423                 START,
5424                 VALUE,
5425                 VALUE_ESCAPE,
5426                 SINGLE_QUOTE,
5427                 SINGLE_QUOTE_ESCAPE,
5428                 DOUBLE_QUOTE,
5429                 DOUBLE_QUOTE_ESCAPE,
5430                 SPACE,
5431         } state = START;
5432
5433         assert(p);
5434         assert(*p);
5435         assert(ret);
5436
5437         /* Parses the first word of a string, and returns it in
5438          * *ret. Removes all quotes in the process. When parsing fails
5439          * (because of an uneven number of quotes or similar), leaves
5440          * the pointer *p at the first invalid character. */
5441
5442         for (;;) {
5443                 char c = **p;
5444
5445                 switch (state) {
5446
5447                 case START:
5448                         if (c == 0)
5449                                 goto finish;
5450                         else if (strchr(WHITESPACE, c))
5451                                 break;
5452
5453                         state = VALUE;
5454                         /* fallthrough */
5455
5456                 case VALUE:
5457                         if (c == 0)
5458                                 goto finish;
5459                         else if (c == '\'')
5460                                 state = SINGLE_QUOTE;
5461                         else if (c == '\\')
5462                                 state = VALUE_ESCAPE;
5463                         else if (c == '\"')
5464                                 state = DOUBLE_QUOTE;
5465                         else if (strchr(WHITESPACE, c))
5466                                 state = SPACE;
5467                         else {
5468                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
5469                                         return -ENOMEM;
5470
5471                                 s[sz++] = c;
5472                         }
5473
5474                         break;
5475
5476                 case VALUE_ESCAPE:
5477                         if (c == 0) {
5478                                 if (flags & UNQUOTE_RELAX)
5479                                         goto finish;
5480                                 return -EINVAL;
5481                         }
5482
5483                         if (!GREEDY_REALLOC(s, allocated, sz+7))
5484                                 return -ENOMEM;
5485
5486                         if (flags & UNQUOTE_CUNESCAPE) {
5487                                 uint32_t u;
5488
5489                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
5490                                 if (r < 0)
5491                                         return -EINVAL;
5492
5493                                 (*p) += r - 1;
5494
5495                                 if (c != 0)
5496                                         s[sz++] = c; /* normal explicit char */
5497                                 else
5498                                         sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5499                         } else
5500                                 s[sz++] = c;
5501
5502                         state = VALUE;
5503                         break;
5504
5505                 case SINGLE_QUOTE:
5506                         if (c == 0) {
5507                                 if (flags & UNQUOTE_RELAX)
5508                                         goto finish;
5509                                 return -EINVAL;
5510                         } else if (c == '\'')
5511                                 state = VALUE;
5512                         else if (c == '\\')
5513                                 state = SINGLE_QUOTE_ESCAPE;
5514                         else {
5515                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
5516                                         return -ENOMEM;
5517
5518                                 s[sz++] = c;
5519                         }
5520
5521                         break;
5522
5523                 case SINGLE_QUOTE_ESCAPE:
5524                         if (c == 0) {
5525                                 if (flags & UNQUOTE_RELAX)
5526                                         goto finish;
5527                                 return -EINVAL;
5528                         }
5529
5530                         if (!GREEDY_REALLOC(s, allocated, sz+7))
5531                                 return -ENOMEM;
5532
5533                         if (flags & UNQUOTE_CUNESCAPE) {
5534                                 uint32_t u;
5535
5536                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
5537                                 if (r < 0)
5538                                         return -EINVAL;
5539
5540                                 (*p) += r - 1;
5541
5542                                 if (c != 0)
5543                                         s[sz++] = c;
5544                                 else
5545                                         sz += utf8_encode_unichar(s + sz, u);
5546                         } else
5547                                 s[sz++] = c;
5548
5549                         state = SINGLE_QUOTE;
5550                         break;
5551
5552                 case DOUBLE_QUOTE:
5553                         if (c == 0)
5554                                 return -EINVAL;
5555                         else if (c == '\"')
5556                                 state = VALUE;
5557                         else if (c == '\\')
5558                                 state = DOUBLE_QUOTE_ESCAPE;
5559                         else {
5560                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
5561                                         return -ENOMEM;
5562
5563                                 s[sz++] = c;
5564                         }
5565
5566                         break;
5567
5568                 case DOUBLE_QUOTE_ESCAPE:
5569                         if (c == 0) {
5570                                 if (flags & UNQUOTE_RELAX)
5571                                         goto finish;
5572                                 return -EINVAL;
5573                         }
5574
5575                         if (!GREEDY_REALLOC(s, allocated, sz+7))
5576                                 return -ENOMEM;
5577
5578                         if (flags & UNQUOTE_CUNESCAPE) {
5579                                 uint32_t u;
5580
5581                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
5582                                 if (r < 0)
5583                                         return -EINVAL;
5584
5585                                 (*p) += r - 1;
5586
5587                                 if (c != 0)
5588                                         s[sz++] = c;
5589                                 else
5590                                         sz += utf8_encode_unichar(s + sz, u);
5591                         } else
5592                                 s[sz++] = c;
5593
5594                         state = DOUBLE_QUOTE;
5595                         break;
5596
5597                 case SPACE:
5598                         if (c == 0)
5599                                 goto finish;
5600                         if (!strchr(WHITESPACE, c))
5601                                 goto finish;
5602
5603                         break;
5604                 }
5605
5606                 (*p) ++;
5607         }
5608
5609 finish:
5610         if (!s) {
5611                 *ret = NULL;
5612                 return 0;
5613         }
5614
5615         s[sz] = 0;
5616         *ret = s;
5617         s = NULL;
5618
5619         return 1;
5620 }
5621
5622 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5623         va_list ap;
5624         char **l;
5625         int n = 0, i, c, r;
5626
5627         /* Parses a number of words from a string, stripping any
5628          * quotes if necessary. */
5629
5630         assert(p);
5631
5632         /* Count how many words are expected */
5633         va_start(ap, flags);
5634         for (;;) {
5635                 if (!va_arg(ap, char **))
5636                         break;
5637                 n++;
5638         }
5639         va_end(ap);
5640
5641         if (n <= 0)
5642                 return 0;
5643
5644         /* Read all words into a temporary array */
5645         l = newa0(char*, n);
5646         for (c = 0; c < n; c++) {
5647
5648                 r = unquote_first_word(p, &l[c], flags);
5649                 if (r < 0) {
5650                         int j;
5651
5652                         for (j = 0; j < c; j++)
5653                                 free(l[j]);
5654
5655                         return r;
5656                 }
5657
5658                 if (r == 0)
5659                         break;
5660         }
5661
5662         /* If we managed to parse all words, return them in the passed
5663          * in parameters */
5664         va_start(ap, flags);
5665         for (i = 0; i < n; i++) {
5666                 char **v;
5667
5668                 v = va_arg(ap, char **);
5669                 assert(v);
5670
5671                 *v = l[i];
5672         }
5673         va_end(ap);
5674
5675         return c;
5676 }
5677
5678 int free_and_strdup(char **p, const char *s) {
5679         char *t;
5680
5681         assert(p);
5682
5683         /* Replaces a string pointer with an strdup()ed new string,
5684          * possibly freeing the old one. */
5685
5686         if (s) {
5687                 t = strdup(s);
5688                 if (!t)
5689                         return -ENOMEM;
5690         } else
5691                 t = NULL;
5692
5693         free(*p);
5694         *p = t;
5695
5696         return 0;
5697 }
5698
5699 int sethostname_idempotent(const char *s) {
5700         int r;
5701         char buf[HOST_NAME_MAX + 1] = {};
5702
5703         assert(s);
5704
5705         r = gethostname(buf, sizeof(buf));
5706         if (r < 0)
5707                 return -errno;
5708
5709         if (streq(buf, s))
5710                 return 0;
5711
5712         r = sethostname(s, strlen(s));
5713         if (r < 0)
5714                 return -errno;
5715
5716         return 1;
5717 }
5718
5719 int ptsname_malloc(int fd, char **ret) {
5720         size_t l = 100;
5721
5722         assert(fd >= 0);
5723         assert(ret);
5724
5725         for (;;) {
5726                 char *c;
5727
5728                 c = new(char, l);
5729                 if (!c)
5730                         return -ENOMEM;
5731
5732                 if (ptsname_r(fd, c, l) == 0) {
5733                         *ret = c;
5734                         return 0;
5735                 }
5736                 if (errno != ERANGE) {
5737                         free(c);
5738                         return -errno;
5739                 }
5740
5741                 free(c);
5742                 l *= 2;
5743         }
5744 }
5745
5746 int openpt_in_namespace(pid_t pid, int flags) {
5747         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5748         _cleanup_close_pair_ int pair[2] = { -1, -1 };
5749         union {
5750                 struct cmsghdr cmsghdr;
5751                 uint8_t buf[CMSG_SPACE(sizeof(int))];
5752         } control = {};
5753         struct msghdr mh = {
5754                 .msg_control = &control,
5755                 .msg_controllen = sizeof(control),
5756         };
5757         struct cmsghdr *cmsg;
5758         siginfo_t si;
5759         pid_t child;
5760         int r;
5761
5762         assert(pid > 0);
5763
5764         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5765         if (r < 0)
5766                 return r;
5767
5768         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5769                 return -errno;
5770
5771         child = fork();
5772         if (child < 0)
5773                 return -errno;
5774
5775         if (child == 0) {
5776                 int master;
5777
5778                 pair[0] = safe_close(pair[0]);
5779
5780                 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5781                 if (r < 0)
5782                         _exit(EXIT_FAILURE);
5783
5784                 master = posix_openpt(flags);
5785                 if (master < 0)
5786                         _exit(EXIT_FAILURE);
5787
5788                 cmsg = CMSG_FIRSTHDR(&mh);
5789                 cmsg->cmsg_level = SOL_SOCKET;
5790                 cmsg->cmsg_type = SCM_RIGHTS;
5791                 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5792                 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5793
5794                 mh.msg_controllen = cmsg->cmsg_len;
5795
5796                 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5797                         _exit(EXIT_FAILURE);
5798
5799                 _exit(EXIT_SUCCESS);
5800         }
5801
5802         pair[1] = safe_close(pair[1]);
5803
5804         r = wait_for_terminate(child, &si);
5805         if (r < 0)
5806                 return r;
5807         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5808                 return -EIO;
5809
5810         if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5811                 return -errno;
5812
5813         for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5814                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5815                         int *fds;
5816                         unsigned n_fds;
5817
5818                         fds = (int*) CMSG_DATA(cmsg);
5819                         n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5820
5821                         if (n_fds != 1) {
5822                                 close_many(fds, n_fds);
5823                                 return -EIO;
5824                         }
5825
5826                         return fds[0];
5827                 }
5828
5829         return -EIO;
5830 }
5831
5832 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5833         _cleanup_close_ int fd = -1;
5834         ssize_t l;
5835
5836         /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5837
5838         fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5839         if (fd < 0)
5840                 return -errno;
5841
5842         l = fgetxattr(fd, attribute, value, size);
5843         if (l < 0)
5844                 return -errno;
5845
5846         return l;
5847 }
5848
5849 static int parse_crtime(le64_t le, usec_t *usec) {
5850         uint64_t u;
5851
5852         assert(usec);
5853
5854         u = le64toh(le);
5855         if (u == 0 || u == (uint64_t) -1)
5856                 return -EIO;
5857
5858         *usec = (usec_t) u;
5859         return 0;
5860 }
5861
5862 int fd_getcrtime(int fd, usec_t *usec) {
5863         le64_t le;
5864         ssize_t n;
5865
5866         assert(fd >= 0);
5867         assert(usec);
5868
5869         /* Until Linux gets a real concept of birthtime/creation time,
5870          * let's fake one with xattrs */
5871
5872         n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5873         if (n < 0)
5874                 return -errno;
5875         if (n != sizeof(le))
5876                 return -EIO;
5877
5878         return parse_crtime(le, usec);
5879 }
5880
5881 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5882         le64_t le;
5883         ssize_t n;
5884
5885         n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5886         if (n < 0)
5887                 return -errno;
5888         if (n != sizeof(le))
5889                 return -EIO;
5890
5891         return parse_crtime(le, usec);
5892 }
5893
5894 int path_getcrtime(const char *p, usec_t *usec) {
5895         le64_t le;
5896         ssize_t n;
5897
5898         assert(p);
5899         assert(usec);
5900
5901         n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5902         if (n < 0)
5903                 return -errno;
5904         if (n != sizeof(le))
5905                 return -EIO;
5906
5907         return parse_crtime(le, usec);
5908 }
5909
5910 int fd_setcrtime(int fd, usec_t usec) {
5911         le64_t le;
5912
5913         assert(fd >= 0);
5914
5915         if (usec <= 0)
5916                 usec = now(CLOCK_REALTIME);
5917
5918         le = htole64((uint64_t) usec);
5919         if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5920                 return -errno;
5921
5922         return 0;
5923 }
5924
5925 int chattr_fd(int fd, unsigned value, unsigned mask) {
5926         unsigned old_attr, new_attr;
5927         struct stat st;
5928
5929         assert(fd >= 0);
5930
5931         if (fstat(fd, &st) < 0)
5932                 return -errno;
5933
5934         /* Explicitly check whether this is a regular file or
5935          * directory. If it is anything else (such as a device node or
5936          * fifo), then the ioctl will not hit the file systems but
5937          * possibly drivers, where the ioctl might have different
5938          * effects. Notably, DRM is using the same ioctl() number. */
5939
5940         if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5941                 return -ENOTTY;
5942
5943         if (mask == 0)
5944                 return 0;
5945
5946         if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5947                 return -errno;
5948
5949         new_attr = (old_attr & ~mask) | (value & mask);
5950         if (new_attr == old_attr)
5951                 return 0;
5952
5953         if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5954                 return -errno;
5955
5956         return 1;
5957 }
5958
5959 int chattr_path(const char *p, unsigned value, unsigned mask) {
5960         _cleanup_close_ int fd = -1;
5961
5962         assert(p);
5963
5964         if (mask == 0)
5965                 return 0;
5966
5967         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5968         if (fd < 0)
5969                 return -errno;
5970
5971         return chattr_fd(fd, value, mask);
5972 }
5973
5974 int read_attr_fd(int fd, unsigned *ret) {
5975         struct stat st;
5976
5977         assert(fd >= 0);
5978
5979         if (fstat(fd, &st) < 0)
5980                 return -errno;
5981
5982         if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5983                 return -ENOTTY;
5984
5985         if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5986                 return -errno;
5987
5988         return 0;
5989 }
5990
5991 int read_attr_path(const char *p, unsigned *ret) {
5992         _cleanup_close_ int fd = -1;
5993
5994         assert(p);
5995         assert(ret);
5996
5997         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5998         if (fd < 0)
5999                 return -errno;
6000
6001         return read_attr_fd(fd, ret);
6002 }
6003
6004 int make_lock_file(const char *p, int operation, LockFile *ret) {
6005         _cleanup_close_ int fd = -1;
6006         _cleanup_free_ char *t = NULL;
6007         int r;
6008
6009         /*
6010          * We use UNPOSIX locks if they are available. They have nice
6011          * semantics, and are mostly compatible with NFS. However,
6012          * they are only available on new kernels. When we detect we
6013          * are running on an older kernel, then we fall back to good
6014          * old BSD locks. They also have nice semantics, but are
6015          * slightly problematic on NFS, where they are upgraded to
6016          * POSIX locks, even though locally they are orthogonal to
6017          * POSIX locks.
6018          */
6019
6020         t = strdup(p);
6021         if (!t)
6022                 return -ENOMEM;
6023
6024         for (;;) {
6025                 struct flock fl = {
6026                         .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
6027                         .l_whence = SEEK_SET,
6028                 };
6029                 struct stat st;
6030
6031                 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
6032                 if (fd < 0)
6033                         return -errno;
6034
6035                 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
6036                 if (r < 0) {
6037
6038                         /* If the kernel is too old, use good old BSD locks */
6039                         if (errno == EINVAL)
6040                                 r = flock(fd, operation);
6041
6042                         if (r < 0)
6043                                 return errno == EAGAIN ? -EBUSY : -errno;
6044                 }
6045
6046                 /* If we acquired the lock, let's check if the file
6047                  * still exists in the file system. If not, then the
6048                  * previous exclusive owner removed it and then closed
6049                  * it. In such a case our acquired lock is worthless,
6050                  * hence try again. */
6051
6052                 r = fstat(fd, &st);
6053                 if (r < 0)
6054                         return -errno;
6055                 if (st.st_nlink > 0)
6056                         break;
6057
6058                 fd = safe_close(fd);
6059         }
6060
6061         ret->path = t;
6062         ret->fd = fd;
6063         ret->operation = operation;
6064
6065         fd = -1;
6066         t = NULL;
6067
6068         return r;
6069 }
6070
6071 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
6072         const char *fn;
6073         char *t;
6074
6075         assert(p);
6076         assert(ret);
6077
6078         fn = basename(p);
6079         if (!filename_is_valid(fn))
6080                 return -EINVAL;
6081
6082         t = newa(char, strlen(p) + 2 + 4 + 1);
6083         stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
6084
6085         return make_lock_file(t, operation, ret);
6086 }
6087
6088 void release_lock_file(LockFile *f) {
6089         int r;
6090
6091         if (!f)
6092                 return;
6093
6094         if (f->path) {
6095
6096                 /* If we are the exclusive owner we can safely delete
6097                  * the lock file itself. If we are not the exclusive
6098                  * owner, we can try becoming it. */
6099
6100                 if (f->fd >= 0 &&
6101                     (f->operation & ~LOCK_NB) == LOCK_SH) {
6102                         static const struct flock fl = {
6103                                 .l_type = F_WRLCK,
6104                                 .l_whence = SEEK_SET,
6105                         };
6106
6107                         r = fcntl(f->fd, F_OFD_SETLK, &fl);
6108                         if (r < 0 && errno == EINVAL)
6109                                 r = flock(f->fd, LOCK_EX|LOCK_NB);
6110
6111                         if (r >= 0)
6112                                 f->operation = LOCK_EX|LOCK_NB;
6113                 }
6114
6115                 if ((f->operation & ~LOCK_NB) == LOCK_EX)
6116                         unlink_noerrno(f->path);
6117
6118                 free(f->path);
6119                 f->path = NULL;
6120         }
6121
6122         f->fd = safe_close(f->fd);
6123         f->operation = 0;
6124 }
6125
6126 static size_t nul_length(const uint8_t *p, size_t sz) {
6127         size_t n = 0;
6128
6129         while (sz > 0) {
6130                 if (*p != 0)
6131                         break;
6132
6133                 n++;
6134                 p++;
6135                 sz--;
6136         }
6137
6138         return n;
6139 }
6140
6141 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
6142         const uint8_t *q, *w, *e;
6143         ssize_t l;
6144
6145         q = w = p;
6146         e = q + sz;
6147         while (q < e) {
6148                 size_t n;
6149
6150                 n = nul_length(q, e - q);
6151
6152                 /* If there are more than the specified run length of
6153                  * NUL bytes, or if this is the beginning or the end
6154                  * of the buffer, then seek instead of write */
6155                 if ((n > run_length) ||
6156                     (n > 0 && q == p) ||
6157                     (n > 0 && q + n >= e)) {
6158                         if (q > w) {
6159                                 l = write(fd, w, q - w);
6160                                 if (l < 0)
6161                                         return -errno;
6162                                 if (l != q -w)
6163                                         return -EIO;
6164                         }
6165
6166                         if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6167                                 return -errno;
6168
6169                         q += n;
6170                         w = q;
6171                 } else if (n > 0)
6172                         q += n;
6173                 else
6174                         q ++;
6175         }
6176
6177         if (q > w) {
6178                 l = write(fd, w, q - w);
6179                 if (l < 0)
6180                         return -errno;
6181                 if (l != q - w)
6182                         return -EIO;
6183         }
6184
6185         return q - (const uint8_t*) p;
6186 }
6187
6188 void sigkill_wait(pid_t *pid) {
6189         if (!pid)
6190                 return;
6191         if (*pid <= 1)
6192                 return;
6193
6194         if (kill(*pid, SIGKILL) > 0)
6195                 (void) wait_for_terminate(*pid, NULL);
6196 }
6197
6198 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6199         int a = 0, b = 0, c = 0;
6200         int k;
6201
6202         assert(p);
6203         assert(*p);
6204         assert(priority);
6205
6206         if ((*p)[0] != '<')
6207                 return 0;
6208
6209         if (!strchr(*p, '>'))
6210                 return 0;
6211
6212         if ((*p)[2] == '>') {
6213                 c = undecchar((*p)[1]);
6214                 k = 3;
6215         } else if ((*p)[3] == '>') {
6216                 b = undecchar((*p)[1]);
6217                 c = undecchar((*p)[2]);
6218                 k = 4;
6219         } else if ((*p)[4] == '>') {
6220                 a = undecchar((*p)[1]);
6221                 b = undecchar((*p)[2]);
6222                 c = undecchar((*p)[3]);
6223                 k = 5;
6224         } else
6225                 return 0;
6226
6227         if (a < 0 || b < 0 || c < 0 ||
6228             (!with_facility && (a || b || c > 7)))
6229                 return 0;
6230
6231         if (with_facility)
6232                 *priority = a*100 + b*10 + c;
6233         else
6234                 *priority = (*priority & LOG_FACMASK) | c;
6235
6236         *p += k;
6237         return 1;
6238 }
6239
6240 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6241         size_t i;
6242
6243         if (!key)
6244                 return -1;
6245
6246         for (i = 0; i < len; ++i)
6247                 if (streq_ptr(table[i], key))
6248                         return (ssize_t)i;
6249
6250         return -1;
6251 }
6252
6253 void cmsg_close_all(struct msghdr *mh) {
6254         struct cmsghdr *cmsg;
6255
6256         assert(mh);
6257
6258         for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6259                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6260                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6261 }
6262
6263 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6264         struct stat buf;
6265         int ret;
6266
6267         ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6268         if (ret >= 0)
6269                 return 0;
6270
6271         /* Even though renameat2() exists since Linux 3.15, btrfs added
6272          * support for it later. If it is not implemented, fallback to another
6273          * method. */
6274         if (errno != EINVAL)
6275                 return -errno;
6276
6277         /* The link()/unlink() fallback does not work on directories. But
6278          * renameat() without RENAME_NOREPLACE gives the same semantics on
6279          * directories, except when newpath is an *empty* directory. This is
6280          * good enough. */
6281         ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6282         if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6283                 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6284                 return ret >= 0 ? 0 : -errno;
6285         }
6286
6287         /* If it is not a directory, use the link()/unlink() fallback. */
6288         ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6289         if (ret < 0)
6290                 return -errno;
6291
6292         ret = unlinkat(olddirfd, oldpath, 0);
6293         if (ret < 0) {
6294                 /* backup errno before the following unlinkat() alters it */
6295                 ret = errno;
6296                 (void) unlinkat(newdirfd, newpath, 0);
6297                 errno = ret;
6298                 return -errno;
6299         }
6300
6301         return 0;
6302 }
6303
6304 char *shell_maybe_quote(const char *s) {
6305         const char *p;
6306         char *r, *t;
6307
6308         assert(s);
6309
6310         /* Encloses a string in double quotes if necessary to make it
6311          * OK as shell string. */
6312
6313         for (p = s; *p; p++)
6314                 if (*p <= ' ' ||
6315                     *p >= 127 ||
6316                     strchr(SHELL_NEED_QUOTES, *p))
6317                         break;
6318
6319         if (!*p)
6320                 return strdup(s);
6321
6322         r = new(char, 1+strlen(s)*2+1+1);
6323         if (!r)
6324                 return NULL;
6325
6326         t = r;
6327         *(t++) = '"';
6328         t = mempcpy(t, s, p - s);
6329
6330         for (; *p; p++) {
6331
6332                 if (strchr(SHELL_NEED_ESCAPE, *p))
6333                         *(t++) = '\\';
6334
6335                 *(t++) = *p;
6336         }
6337
6338         *(t++)= '"';
6339         *t = 0;
6340
6341         return r;
6342 }
6343
6344 int parse_mode(const char *s, mode_t *ret) {
6345         char *x;
6346         long l;
6347
6348         assert(s);
6349         assert(ret);
6350
6351         errno = 0;
6352         l = strtol(s, &x, 8);
6353         if (errno != 0)
6354                 return -errno;
6355
6356         if (!x || x == s || *x)
6357                 return -EINVAL;
6358         if (l < 0 || l  > 07777)
6359                 return -ERANGE;
6360
6361         *ret = (mode_t) l;
6362         return 0;
6363 }