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