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