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