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