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