chiark / gitweb /
f17a473d6c6c3c59186a9eff84275394a1a6d4ce
[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 int get_proc_cmdline_key(const char *key, char **value) {
4366         _cleanup_free_ char *line = NULL, *ret = NULL;
4367         bool found = false;
4368         const char *p;
4369         int r;
4370
4371         assert(key);
4372
4373         r = proc_cmdline(&line);
4374         if (r < 0)
4375                 return r;
4376
4377         p = line;
4378         for (;;) {
4379                 _cleanup_free_ char *word = NULL;
4380                 const char *e;
4381
4382                 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4383                 if (r < 0)
4384                         return r;
4385                 if (r == 0)
4386                         break;
4387
4388                 /* Filter out arguments that are intended only for the
4389                  * initrd */
4390                 if (!in_initrd() && startswith(word, "rd."))
4391                         continue;
4392
4393                 if (value) {
4394                         e = startswith(word, key);
4395                         if (!e)
4396                                 continue;
4397
4398                         r = free_and_strdup(&ret, e);
4399                         if (r < 0)
4400                                 return r;
4401
4402                         found = true;
4403                 } else {
4404                         if (streq(word, key))
4405                                 found = true;
4406                 }
4407         }
4408
4409         if (value) {
4410                 *value = ret;
4411                 ret = NULL;
4412         }
4413
4414         return found;
4415
4416 }
4417
4418 int container_get_leader(const char *machine, pid_t *pid) {
4419         _cleanup_free_ char *s = NULL, *class = NULL;
4420         const char *p;
4421         pid_t leader;
4422         int r;
4423
4424         assert(machine);
4425         assert(pid);
4426
4427         p = strjoina("/run/systemd/machines/", machine);
4428         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4429         if (r == -ENOENT)
4430                 return -EHOSTDOWN;
4431         if (r < 0)
4432                 return r;
4433         if (!s)
4434                 return -EIO;
4435
4436         if (!streq_ptr(class, "container"))
4437                 return -EIO;
4438
4439         r = parse_pid(s, &leader);
4440         if (r < 0)
4441                 return r;
4442         if (leader <= 1)
4443                 return -EIO;
4444
4445         *pid = leader;
4446         return 0;
4447 }
4448
4449 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4450         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4451         int rfd = -1;
4452
4453         assert(pid >= 0);
4454
4455         if (mntns_fd) {
4456                 const char *mntns;
4457
4458                 mntns = procfs_file_alloca(pid, "ns/mnt");
4459                 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4460                 if (mntnsfd < 0)
4461                         return -errno;
4462         }
4463
4464         if (pidns_fd) {
4465                 const char *pidns;
4466
4467                 pidns = procfs_file_alloca(pid, "ns/pid");
4468                 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4469                 if (pidnsfd < 0)
4470                         return -errno;
4471         }
4472
4473         if (netns_fd) {
4474                 const char *netns;
4475
4476                 netns = procfs_file_alloca(pid, "ns/net");
4477                 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4478                 if (netnsfd < 0)
4479                         return -errno;
4480         }
4481
4482         if (root_fd) {
4483                 const char *root;
4484
4485                 root = procfs_file_alloca(pid, "root");
4486                 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4487                 if (rfd < 0)
4488                         return -errno;
4489         }
4490
4491         if (pidns_fd)
4492                 *pidns_fd = pidnsfd;
4493
4494         if (mntns_fd)
4495                 *mntns_fd = mntnsfd;
4496
4497         if (netns_fd)
4498                 *netns_fd = netnsfd;
4499
4500         if (root_fd)
4501                 *root_fd = rfd;
4502
4503         pidnsfd = mntnsfd = netnsfd = -1;
4504
4505         return 0;
4506 }
4507
4508 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4509
4510         if (pidns_fd >= 0)
4511                 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4512                         return -errno;
4513
4514         if (mntns_fd >= 0)
4515                 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4516                         return -errno;
4517
4518         if (netns_fd >= 0)
4519                 if (setns(netns_fd, CLONE_NEWNET) < 0)
4520                         return -errno;
4521
4522         if (root_fd >= 0) {
4523                 if (fchdir(root_fd) < 0)
4524                         return -errno;
4525
4526                 if (chroot(".") < 0)
4527                         return -errno;
4528         }
4529
4530         return reset_uid_gid();
4531 }
4532
4533 int getpeercred(int fd, struct ucred *ucred) {
4534         socklen_t n = sizeof(struct ucred);
4535         struct ucred u;
4536         int r;
4537
4538         assert(fd >= 0);
4539         assert(ucred);
4540
4541         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4542         if (r < 0)
4543                 return -errno;
4544
4545         if (n != sizeof(struct ucred))
4546                 return -EIO;
4547
4548         /* Check if the data is actually useful and not suppressed due
4549          * to namespacing issues */
4550         if (u.pid <= 0)
4551                 return -ENODATA;
4552         if (u.uid == UID_INVALID)
4553                 return -ENODATA;
4554         if (u.gid == GID_INVALID)
4555                 return -ENODATA;
4556
4557         *ucred = u;
4558         return 0;
4559 }
4560
4561 int getpeersec(int fd, char **ret) {
4562         socklen_t n = 64;
4563         char *s;
4564         int r;
4565
4566         assert(fd >= 0);
4567         assert(ret);
4568
4569         s = new0(char, n);
4570         if (!s)
4571                 return -ENOMEM;
4572
4573         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4574         if (r < 0) {
4575                 free(s);
4576
4577                 if (errno != ERANGE)
4578                         return -errno;
4579
4580                 s = new0(char, n);
4581                 if (!s)
4582                         return -ENOMEM;
4583
4584                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4585                 if (r < 0) {
4586                         free(s);
4587                         return -errno;
4588                 }
4589         }
4590
4591         if (isempty(s)) {
4592                 free(s);
4593                 return -EOPNOTSUPP;
4594         }
4595
4596         *ret = s;
4597         return 0;
4598 }
4599
4600 /* This is much like like mkostemp() but is subject to umask(). */
4601 int mkostemp_safe(char *pattern, int flags) {
4602         _cleanup_umask_ mode_t u;
4603         int fd;
4604
4605         assert(pattern);
4606
4607         u = umask(077);
4608
4609         fd = mkostemp(pattern, flags);
4610         if (fd < 0)
4611                 return -errno;
4612
4613         return fd;
4614 }
4615
4616 int open_tmpfile(const char *path, int flags) {
4617         char *p;
4618         int fd;
4619
4620         assert(path);
4621
4622 #ifdef O_TMPFILE
4623         /* Try O_TMPFILE first, if it is supported */
4624         fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4625         if (fd >= 0)
4626                 return fd;
4627 #endif
4628
4629         /* Fall back to unguessable name + unlinking */
4630         p = strjoina(path, "/systemd-tmp-XXXXXX");
4631
4632         fd = mkostemp_safe(p, flags);
4633         if (fd < 0)
4634                 return fd;
4635
4636         unlink(p);
4637         return fd;
4638 }
4639
4640 int fd_warn_permissions(const char *path, int fd) {
4641         struct stat st;
4642
4643         if (fstat(fd, &st) < 0)
4644                 return -errno;
4645
4646         if (st.st_mode & 0111)
4647                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4648
4649         if (st.st_mode & 0002)
4650                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4651
4652         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4653                 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);
4654
4655         return 0;
4656 }
4657
4658 /// UNNEEDED by elogind
4659 #if 0
4660 unsigned long personality_from_string(const char *p) {
4661
4662         /* Parse a personality specifier. We introduce our own
4663          * identifiers that indicate specific ABIs, rather than just
4664          * hints regarding the register size, since we want to keep
4665          * things open for multiple locally supported ABIs for the
4666          * same register size. We try to reuse the ABI identifiers
4667          * used by libseccomp. */
4668
4669 #if defined(__x86_64__)
4670
4671         if (streq(p, "x86"))
4672                 return PER_LINUX32;
4673
4674         if (streq(p, "x86-64"))
4675                 return PER_LINUX;
4676
4677 #elif defined(__i386__)
4678
4679         if (streq(p, "x86"))
4680                 return PER_LINUX;
4681 #endif
4682
4683         return PERSONALITY_INVALID;
4684 }
4685 #endif // 0
4686
4687 const char* personality_to_string(unsigned long p) {
4688
4689 #if defined(__x86_64__)
4690
4691         if (p == PER_LINUX32)
4692                 return "x86";
4693
4694         if (p == PER_LINUX)
4695                 return "x86-64";
4696
4697 #elif defined(__i386__)
4698
4699         if (p == PER_LINUX)
4700                 return "x86";
4701 #endif
4702
4703         return NULL;
4704 }
4705
4706 uint64_t physical_memory(void) {
4707         long mem;
4708
4709         /* We return this as uint64_t in case we are running as 32bit
4710          * process on a 64bit kernel with huge amounts of memory */
4711
4712         mem = sysconf(_SC_PHYS_PAGES);
4713         assert(mem > 0);
4714
4715         return (uint64_t) mem * (uint64_t) page_size();
4716 }
4717
4718 /// UNNEEDED by elogind
4719 #if 0
4720 void hexdump(FILE *f, const void *p, size_t s) {
4721         const uint8_t *b = p;
4722         unsigned n = 0;
4723
4724         assert(s == 0 || b);
4725
4726         while (s > 0) {
4727                 size_t i;
4728
4729                 fprintf(f, "%04x  ", n);
4730
4731                 for (i = 0; i < 16; i++) {
4732
4733                         if (i >= s)
4734                                 fputs("   ", f);
4735                         else
4736                                 fprintf(f, "%02x ", b[i]);
4737
4738                         if (i == 7)
4739                                 fputc(' ', f);
4740                 }
4741
4742                 fputc(' ', f);
4743
4744                 for (i = 0; i < 16; i++) {
4745
4746                         if (i >= s)
4747                                 fputc(' ', f);
4748                         else
4749                                 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4750                 }
4751
4752                 fputc('\n', f);
4753
4754                 if (s < 16)
4755                         break;
4756
4757                 n += 16;
4758                 b += 16;
4759                 s -= 16;
4760         }
4761 }
4762 #endif // 0
4763
4764 int update_reboot_param_file(const char *param) {
4765         int r = 0;
4766
4767         if (param) {
4768
4769                 r = write_string_file(REBOOT_PARAM_FILE, param, WRITE_STRING_FILE_CREATE);
4770                 if (r < 0)
4771                         log_error("Failed to write reboot param to "
4772                                   REBOOT_PARAM_FILE": %s", strerror(-r));
4773         } else
4774                 unlink(REBOOT_PARAM_FILE);
4775
4776         return r;
4777 }
4778
4779 int umount_recursive(const char *prefix, int flags) {
4780         bool again;
4781         int n = 0, r;
4782
4783         /* Try to umount everything recursively below a
4784          * directory. Also, take care of stacked mounts, and keep
4785          * unmounting them until they are gone. */
4786
4787         do {
4788                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4789
4790                 again = false;
4791                 r = 0;
4792
4793                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4794                 if (!proc_self_mountinfo)
4795                         return -errno;
4796
4797                 for (;;) {
4798                         _cleanup_free_ char *path = NULL, *p = NULL;
4799                         int k;
4800
4801                         k = fscanf(proc_self_mountinfo,
4802                                    "%*s "       /* (1) mount id */
4803                                    "%*s "       /* (2) parent id */
4804                                    "%*s "       /* (3) major:minor */
4805                                    "%*s "       /* (4) root */
4806                                    "%ms "       /* (5) mount point */
4807                                    "%*s"        /* (6) mount options */
4808                                    "%*[^-]"     /* (7) optional fields */
4809                                    "- "         /* (8) separator */
4810                                    "%*s "       /* (9) file system type */
4811                                    "%*s"        /* (10) mount source */
4812                                    "%*s"        /* (11) mount options 2 */
4813                                    "%*[^\n]",   /* some rubbish at the end */
4814                                    &path);
4815                         if (k != 1) {
4816                                 if (k == EOF)
4817                                         break;
4818
4819                                 continue;
4820                         }
4821
4822                         r = cunescape(path, UNESCAPE_RELAX, &p);
4823                         if (r < 0)
4824                                 return r;
4825
4826                         if (!path_startswith(p, prefix))
4827                                 continue;
4828
4829                         if (umount2(p, flags) < 0) {
4830                                 r = -errno;
4831                                 continue;
4832                         }
4833
4834                         again = true;
4835                         n++;
4836
4837                         break;
4838                 }
4839
4840         } while (again);
4841
4842         return r ? r : n;
4843 }
4844
4845 static int get_mount_flags(const char *path, unsigned long *flags) {
4846         struct statvfs buf;
4847
4848         if (statvfs(path, &buf) < 0)
4849                 return -errno;
4850         *flags = buf.f_flag;
4851         return 0;
4852 }
4853
4854 int bind_remount_recursive(const char *prefix, bool ro) {
4855         _cleanup_set_free_free_ Set *done = NULL;
4856         _cleanup_free_ char *cleaned = NULL;
4857         int r;
4858
4859         /* Recursively remount a directory (and all its submounts)
4860          * read-only or read-write. If the directory is already
4861          * mounted, we reuse the mount and simply mark it
4862          * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4863          * operation). If it isn't we first make it one. Afterwards we
4864          * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4865          * submounts we can access, too. When mounts are stacked on
4866          * the same mount point we only care for each individual
4867          * "top-level" mount on each point, as we cannot
4868          * influence/access the underlying mounts anyway. We do not
4869          * have any effect on future submounts that might get
4870          * propagated, they migt be writable. This includes future
4871          * submounts that have been triggered via autofs. */
4872
4873         cleaned = strdup(prefix);
4874         if (!cleaned)
4875                 return -ENOMEM;
4876
4877         path_kill_slashes(cleaned);
4878
4879         done = set_new(&string_hash_ops);
4880         if (!done)
4881                 return -ENOMEM;
4882
4883         for (;;) {
4884                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4885                 _cleanup_set_free_free_ Set *todo = NULL;
4886                 bool top_autofs = false;
4887                 char *x;
4888                 unsigned long orig_flags;
4889
4890                 todo = set_new(&string_hash_ops);
4891                 if (!todo)
4892                         return -ENOMEM;
4893
4894                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4895                 if (!proc_self_mountinfo)
4896                         return -errno;
4897
4898                 for (;;) {
4899                         _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
4900                         int k;
4901
4902                         k = fscanf(proc_self_mountinfo,
4903                                    "%*s "       /* (1) mount id */
4904                                    "%*s "       /* (2) parent id */
4905                                    "%*s "       /* (3) major:minor */
4906                                    "%*s "       /* (4) root */
4907                                    "%ms "       /* (5) mount point */
4908                                    "%*s"        /* (6) mount options (superblock) */
4909                                    "%*[^-]"     /* (7) optional fields */
4910                                    "- "         /* (8) separator */
4911                                    "%ms "       /* (9) file system type */
4912                                    "%*s"        /* (10) mount source */
4913                                    "%*s"        /* (11) mount options (bind mount) */
4914                                    "%*[^\n]",   /* some rubbish at the end */
4915                                    &path,
4916                                    &type);
4917                         if (k != 2) {
4918                                 if (k == EOF)
4919                                         break;
4920
4921                                 continue;
4922                         }
4923
4924                         r = cunescape(path, UNESCAPE_RELAX, &p);
4925                         if (r < 0)
4926                                 return r;
4927
4928                         /* Let's ignore autofs mounts.  If they aren't
4929                          * triggered yet, we want to avoid triggering
4930                          * them, as we don't make any guarantees for
4931                          * future submounts anyway.  If they are
4932                          * already triggered, then we will find
4933                          * another entry for this. */
4934                         if (streq(type, "autofs")) {
4935                                 top_autofs = top_autofs || path_equal(cleaned, p);
4936                                 continue;
4937                         }
4938
4939                         if (path_startswith(p, cleaned) &&
4940                             !set_contains(done, p)) {
4941
4942                                 r = set_consume(todo, p);
4943                                 p = NULL;
4944
4945                                 if (r == -EEXIST)
4946                                         continue;
4947                                 if (r < 0)
4948                                         return r;
4949                         }
4950                 }
4951
4952                 /* If we have no submounts to process anymore and if
4953                  * the root is either already done, or an autofs, we
4954                  * are done */
4955                 if (set_isempty(todo) &&
4956                     (top_autofs || set_contains(done, cleaned)))
4957                         return 0;
4958
4959                 if (!set_contains(done, cleaned) &&
4960                     !set_contains(todo, cleaned)) {
4961                         /* The prefix directory itself is not yet a
4962                          * mount, make it one. */
4963                         if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
4964                                 return -errno;
4965
4966                         orig_flags = 0;
4967                         (void) get_mount_flags(cleaned, &orig_flags);
4968                         orig_flags &= ~MS_RDONLY;
4969
4970                         if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
4971                                 return -errno;
4972
4973                         x = strdup(cleaned);
4974                         if (!x)
4975                                 return -ENOMEM;
4976
4977                         r = set_consume(done, x);
4978                         if (r < 0)
4979                                 return r;
4980                 }
4981
4982                 while ((x = set_steal_first(todo))) {
4983
4984                         r = set_consume(done, x);
4985                         if (r == -EEXIST || r == 0)
4986                                 continue;
4987                         if (r < 0)
4988                                 return r;
4989
4990                         /* Try to reuse the original flag set, but
4991                          * don't care for errors, in case of
4992                          * obstructed mounts */
4993                         orig_flags = 0;
4994                         (void) get_mount_flags(x, &orig_flags);
4995                         orig_flags &= ~MS_RDONLY;
4996
4997                         if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
4998
4999                                 /* Deal with mount points that are
5000                                  * obstructed by a later mount */
5001
5002                                 if (errno != ENOENT)
5003                                         return -errno;
5004                         }
5005
5006                 }
5007         }
5008 }
5009
5010 int fflush_and_check(FILE *f) {
5011         assert(f);
5012
5013         errno = 0;
5014         fflush(f);
5015
5016         if (ferror(f))
5017                 return errno ? -errno : -EIO;
5018
5019         return 0;
5020 }
5021
5022 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
5023         const char *fn;
5024         char *t;
5025
5026         assert(p);
5027         assert(ret);
5028
5029         /*
5030          * Turns this:
5031          *         /foo/bar/waldo
5032          *
5033          * Into this:
5034          *         /foo/bar/.#<extra>waldoXXXXXX
5035          */
5036
5037         fn = basename(p);
5038         if (!filename_is_valid(fn))
5039                 return -EINVAL;
5040
5041         if (extra == NULL)
5042                 extra = "";
5043
5044         t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
5045         if (!t)
5046                 return -ENOMEM;
5047
5048         strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
5049
5050         *ret = path_kill_slashes(t);
5051         return 0;
5052 }
5053
5054 int tempfn_random(const char *p, const char *extra, char **ret) {
5055         const char *fn;
5056         char *t, *x;
5057         uint64_t u;
5058         unsigned i;
5059
5060         assert(p);
5061         assert(ret);
5062
5063         /*
5064          * Turns this:
5065          *         /foo/bar/waldo
5066          *
5067          * Into this:
5068          *         /foo/bar/.#<extra>waldobaa2a261115984a9
5069          */
5070
5071         fn = basename(p);
5072         if (!filename_is_valid(fn))
5073                 return -EINVAL;
5074
5075         if (!extra)
5076                 extra = "";
5077
5078         t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
5079         if (!t)
5080                 return -ENOMEM;
5081
5082         x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
5083
5084         u = random_u64();
5085         for (i = 0; i < 16; i++) {
5086                 *(x++) = hexchar(u & 0xF);
5087                 u >>= 4;
5088         }
5089
5090         *x = 0;
5091
5092         *ret = path_kill_slashes(t);
5093         return 0;
5094 }
5095
5096 /// UNNEEDED by elogind
5097 #if 0
5098 int tempfn_random_child(const char *p, const char *extra, char **ret) {
5099         char *t, *x;
5100         uint64_t u;
5101         unsigned i;
5102
5103         assert(p);
5104         assert(ret);
5105
5106         /* Turns this:
5107          *         /foo/bar/waldo
5108          * Into this:
5109          *         /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5110          */
5111
5112         if (!extra)
5113                 extra = "";
5114
5115         t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
5116         if (!t)
5117                 return -ENOMEM;
5118
5119         x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
5120
5121         u = random_u64();
5122         for (i = 0; i < 16; i++) {
5123                 *(x++) = hexchar(u & 0xF);
5124                 u >>= 4;
5125         }
5126
5127         *x = 0;
5128
5129         *ret = path_kill_slashes(t);
5130         return 0;
5131 }
5132
5133 int take_password_lock(const char *root) {
5134
5135         struct flock flock = {
5136                 .l_type = F_WRLCK,
5137                 .l_whence = SEEK_SET,
5138                 .l_start = 0,
5139                 .l_len = 0,
5140         };
5141
5142         const char *path;
5143         int fd, r;
5144
5145         /* This is roughly the same as lckpwdf(), but not as awful. We
5146          * don't want to use alarm() and signals, hence we implement
5147          * our own trivial version of this.
5148          *
5149          * Note that shadow-utils also takes per-database locks in
5150          * addition to lckpwdf(). However, we don't given that they
5151          * are redundant as they they invoke lckpwdf() first and keep
5152          * it during everything they do. The per-database locks are
5153          * awfully racy, and thus we just won't do them. */
5154
5155         if (root)
5156                 path = strjoina(root, "/etc/.pwd.lock");
5157         else
5158                 path = "/etc/.pwd.lock";
5159
5160         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5161         if (fd < 0)
5162                 return -errno;
5163
5164         r = fcntl(fd, F_SETLKW, &flock);
5165         if (r < 0) {
5166                 safe_close(fd);
5167                 return -errno;
5168         }
5169
5170         return fd;
5171 }
5172 #endif // 0
5173
5174 int is_symlink(const char *path) {
5175         struct stat info;
5176
5177         if (lstat(path, &info) < 0)
5178                 return -errno;
5179
5180         return !!S_ISLNK(info.st_mode);
5181 }
5182
5183 int is_dir(const char* path, bool follow) {
5184         struct stat st;
5185         int r;
5186
5187         if (follow)
5188                 r = stat(path, &st);
5189         else
5190                 r = lstat(path, &st);
5191         if (r < 0)
5192                 return -errno;
5193
5194         return !!S_ISDIR(st.st_mode);
5195 }
5196
5197 /// UNNEEDED by elogind
5198 #if 0
5199 int is_device_node(const char *path) {
5200         struct stat info;
5201
5202         if (lstat(path, &info) < 0)
5203                 return -errno;
5204
5205         return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5206 }
5207 #endif // 0
5208
5209 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5210         _cleanup_free_ char *s = NULL;
5211         size_t allocated = 0, sz = 0;
5212         int r;
5213
5214         enum {
5215                 START,
5216                 VALUE,
5217                 VALUE_ESCAPE,
5218                 SINGLE_QUOTE,
5219                 SINGLE_QUOTE_ESCAPE,
5220                 DOUBLE_QUOTE,
5221                 DOUBLE_QUOTE_ESCAPE,
5222                 SPACE,
5223         } state = START;
5224
5225         assert(p);
5226         assert(*p);
5227         assert(ret);
5228
5229         /* Parses the first word of a string, and returns it in
5230          * *ret. Removes all quotes in the process. When parsing fails
5231          * (because of an uneven number of quotes or similar), leaves
5232          * the pointer *p at the first invalid character. */
5233
5234         for (;;) {
5235                 char c = **p;
5236
5237                 switch (state) {
5238
5239                 case START:
5240                         if (c == 0)
5241                                 goto finish;
5242                         else if (strchr(WHITESPACE, c))
5243                                 break;
5244
5245                         state = VALUE;
5246                         /* fallthrough */
5247
5248                 case VALUE:
5249                         if (c == 0)
5250                                 goto finish;
5251                         else if (c == '\'')
5252                                 state = SINGLE_QUOTE;
5253                         else if (c == '\\')
5254                                 state = VALUE_ESCAPE;
5255                         else if (c == '\"')
5256                                 state = DOUBLE_QUOTE;
5257                         else if (strchr(WHITESPACE, c))
5258                                 state = SPACE;
5259                         else {
5260                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
5261                                         return -ENOMEM;
5262
5263                                 s[sz++] = c;
5264                         }
5265
5266                         break;
5267
5268                 case SINGLE_QUOTE:
5269                         if (c == 0) {
5270                                 if (flags & UNQUOTE_RELAX)
5271                                         goto finish;
5272                                 return -EINVAL;
5273                         } else if (c == '\'')
5274                                 state = VALUE;
5275                         else if (c == '\\')
5276                                 state = SINGLE_QUOTE_ESCAPE;
5277                         else {
5278                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
5279                                         return -ENOMEM;
5280
5281                                 s[sz++] = c;
5282                         }
5283
5284                         break;
5285
5286                 case DOUBLE_QUOTE:
5287                         if (c == 0)
5288                                 return -EINVAL;
5289                         else if (c == '\"')
5290                                 state = VALUE;
5291                         else if (c == '\\')
5292                                 state = DOUBLE_QUOTE_ESCAPE;
5293                         else {
5294                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
5295                                         return -ENOMEM;
5296
5297                                 s[sz++] = c;
5298                         }
5299
5300                         break;
5301
5302                 case SINGLE_QUOTE_ESCAPE:
5303                 case DOUBLE_QUOTE_ESCAPE:
5304                 case VALUE_ESCAPE:
5305                         if (!GREEDY_REALLOC(s, allocated, sz+7))
5306                                 return -ENOMEM;
5307
5308                         if (c == 0) {
5309                                 if ((flags & UNQUOTE_CUNESCAPE_RELAX) &&
5310                                     (state == VALUE_ESCAPE || flags & UNQUOTE_RELAX)) {
5311                                         /* If we find an unquoted trailing backslash and we're in
5312                                          * UNQUOTE_CUNESCAPE_RELAX mode, keep it verbatim in the
5313                                          * output.
5314                                          *
5315                                          * Unbalanced quotes will only be allowed in UNQUOTE_RELAX
5316                                          * mode, UNQUOTE_CUNESCAP_RELAX mode does not allow them.
5317                                          */
5318                                         s[sz++] = '\\';
5319                                         goto finish;
5320                                 }
5321                                 if (flags & UNQUOTE_RELAX)
5322                                         goto finish;
5323                                 return -EINVAL;
5324                         }
5325
5326                         if (flags & UNQUOTE_CUNESCAPE) {
5327                                 uint32_t u;
5328
5329                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
5330                                 if (r < 0) {
5331                                         if (flags & UNQUOTE_CUNESCAPE_RELAX) {
5332                                                 s[sz++] = '\\';
5333                                                 s[sz++] = c;
5334                                                 goto end_escape;
5335                                         }
5336                                         return -EINVAL;
5337                                 }
5338
5339                                 (*p) += r - 1;
5340
5341                                 if (c != 0)
5342                                         s[sz++] = c; /* normal explicit char */
5343                                 else
5344                                         sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5345                         } else
5346                                 s[sz++] = c;
5347
5348 end_escape:
5349                         state = (state == SINGLE_QUOTE_ESCAPE) ? SINGLE_QUOTE :
5350                                 (state == DOUBLE_QUOTE_ESCAPE) ? DOUBLE_QUOTE :
5351                                 VALUE;
5352                         break;
5353
5354                 case SPACE:
5355                         if (c == 0)
5356                                 goto finish;
5357                         if (!strchr(WHITESPACE, c))
5358                                 goto finish;
5359
5360                         break;
5361                 }
5362
5363                 (*p) ++;
5364         }
5365
5366 finish:
5367         if (!s) {
5368                 *ret = NULL;
5369                 return 0;
5370         }
5371
5372         s[sz] = 0;
5373         *ret = s;
5374         s = NULL;
5375
5376         return 1;
5377 }
5378
5379 int unquote_first_word_and_warn(
5380                 const char **p,
5381                 char **ret,
5382                 UnquoteFlags flags,
5383                 const char *unit,
5384                 const char *filename,
5385                 unsigned line,
5386                 const char *rvalue) {
5387         /* Try to unquote it, if it fails, warn about it and try again but this
5388          * time using UNQUOTE_CUNESCAPE_RELAX to keep the backslashes verbatim
5389          * in invalid escape sequences. */
5390         const char *save;
5391         int r;
5392
5393         save = *p;
5394         r = unquote_first_word(p, ret, flags);
5395         if (r < 0 && !(flags&UNQUOTE_CUNESCAPE_RELAX)) {
5396                 /* Retry it with UNQUOTE_CUNESCAPE_RELAX. */
5397                 *p = save;
5398                 r = unquote_first_word(p, ret, flags|UNQUOTE_CUNESCAPE_RELAX);
5399                 if (r < 0)
5400                         log_syntax(unit, LOG_ERR, filename, line, EINVAL,
5401                                    "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue);
5402                 else
5403                         log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
5404                                    "Invalid escape sequences in command line: \"%s\"", rvalue);
5405         }
5406         return r;
5407 }
5408
5409 /// UNNEEDED by elogind
5410 #if 0
5411 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5412         va_list ap;
5413         char **l;
5414         int n = 0, i, c, r;
5415
5416         /* Parses a number of words from a string, stripping any
5417          * quotes if necessary. */
5418
5419         assert(p);
5420
5421         /* Count how many words are expected */
5422         va_start(ap, flags);
5423         for (;;) {
5424                 if (!va_arg(ap, char **))
5425                         break;
5426                 n++;
5427         }
5428         va_end(ap);
5429
5430         if (n <= 0)
5431                 return 0;
5432
5433         /* Read all words into a temporary array */
5434         l = newa0(char*, n);
5435         for (c = 0; c < n; c++) {
5436
5437                 r = unquote_first_word(p, &l[c], flags);
5438                 if (r < 0) {
5439                         int j;
5440
5441                         for (j = 0; j < c; j++)
5442                                 free(l[j]);
5443
5444                         return r;
5445                 }
5446
5447                 if (r == 0)
5448                         break;
5449         }
5450
5451         /* If we managed to parse all words, return them in the passed
5452          * in parameters */
5453         va_start(ap, flags);
5454         for (i = 0; i < n; i++) {
5455                 char **v;
5456
5457                 v = va_arg(ap, char **);
5458                 assert(v);
5459
5460                 *v = l[i];
5461         }
5462         va_end(ap);
5463
5464         return c;
5465 }
5466 #endif // 0
5467
5468 int free_and_strdup(char **p, const char *s) {
5469         char *t;
5470
5471         assert(p);
5472
5473         /* Replaces a string pointer with an strdup()ed new string,
5474          * possibly freeing the old one. */
5475
5476         if (streq_ptr(*p, s))
5477                 return 0;
5478
5479         if (s) {
5480                 t = strdup(s);
5481                 if (!t)
5482                         return -ENOMEM;
5483         } else
5484                 t = NULL;
5485
5486         free(*p);
5487         *p = t;
5488
5489         return 1;
5490 }
5491
5492 int ptsname_malloc(int fd, char **ret) {
5493         size_t l = 100;
5494
5495         assert(fd >= 0);
5496         assert(ret);
5497
5498         for (;;) {
5499                 char *c;
5500
5501                 c = new(char, l);
5502                 if (!c)
5503                         return -ENOMEM;
5504
5505                 if (ptsname_r(fd, c, l) == 0) {
5506                         *ret = c;
5507                         return 0;
5508                 }
5509                 if (errno != ERANGE) {
5510                         free(c);
5511                         return -errno;
5512                 }
5513
5514                 free(c);
5515                 l *= 2;
5516         }
5517 }
5518
5519 /// UNNEEDED by elogind
5520 #if 0
5521 int openpt_in_namespace(pid_t pid, int flags) {
5522         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5523         _cleanup_close_pair_ int pair[2] = { -1, -1 };
5524         union {
5525                 struct cmsghdr cmsghdr;
5526                 uint8_t buf[CMSG_SPACE(sizeof(int))];
5527         } control = {};
5528         struct msghdr mh = {
5529                 .msg_control = &control,
5530                 .msg_controllen = sizeof(control),
5531         };
5532         struct cmsghdr *cmsg;
5533         siginfo_t si;
5534         pid_t child;
5535         int r;
5536
5537         assert(pid > 0);
5538
5539         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5540         if (r < 0)
5541                 return r;
5542
5543         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5544                 return -errno;
5545
5546         child = fork();
5547         if (child < 0)
5548                 return -errno;
5549
5550         if (child == 0) {
5551                 int master;
5552
5553                 pair[0] = safe_close(pair[0]);
5554
5555                 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5556                 if (r < 0)
5557                         _exit(EXIT_FAILURE);
5558
5559                 master = posix_openpt(flags);
5560                 if (master < 0)
5561                         _exit(EXIT_FAILURE);
5562
5563                 cmsg = CMSG_FIRSTHDR(&mh);
5564                 cmsg->cmsg_level = SOL_SOCKET;
5565                 cmsg->cmsg_type = SCM_RIGHTS;
5566                 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5567                 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5568
5569                 mh.msg_controllen = cmsg->cmsg_len;
5570
5571                 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5572                         _exit(EXIT_FAILURE);
5573
5574                 _exit(EXIT_SUCCESS);
5575         }
5576
5577         pair[1] = safe_close(pair[1]);
5578
5579         r = wait_for_terminate(child, &si);
5580         if (r < 0)
5581                 return r;
5582         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5583                 return -EIO;
5584
5585         if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5586                 return -errno;
5587
5588         CMSG_FOREACH(cmsg, &mh)
5589                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5590                         int *fds;
5591                         unsigned n_fds;
5592
5593                         fds = (int*) CMSG_DATA(cmsg);
5594                         n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5595
5596                         if (n_fds != 1) {
5597                                 close_many(fds, n_fds);
5598                                 return -EIO;
5599                         }
5600
5601                         return fds[0];
5602                 }
5603
5604         return -EIO;
5605 }
5606 #endif // 0
5607
5608 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5609         _cleanup_close_ int fd = -1;
5610         ssize_t l;
5611
5612         /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5613
5614         fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5615         if (fd < 0)
5616                 return -errno;
5617
5618         l = fgetxattr(fd, attribute, value, size);
5619         if (l < 0)
5620                 return -errno;
5621
5622         return l;
5623 }
5624
5625 static int parse_crtime(le64_t le, usec_t *usec) {
5626         uint64_t u;
5627
5628         assert(usec);
5629
5630         u = le64toh(le);
5631         if (u == 0 || u == (uint64_t) -1)
5632                 return -EIO;
5633
5634         *usec = (usec_t) u;
5635         return 0;
5636 }
5637
5638 int fd_getcrtime(int fd, usec_t *usec) {
5639         le64_t le;
5640         ssize_t n;
5641
5642         assert(fd >= 0);
5643         assert(usec);
5644
5645         /* Until Linux gets a real concept of birthtime/creation time,
5646          * let's fake one with xattrs */
5647
5648         n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5649         if (n < 0)
5650                 return -errno;
5651         if (n != sizeof(le))
5652                 return -EIO;
5653
5654         return parse_crtime(le, usec);
5655 }
5656
5657 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5658         le64_t le;
5659         ssize_t n;
5660
5661         n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5662         if (n < 0)
5663                 return -errno;
5664         if (n != sizeof(le))
5665                 return -EIO;
5666
5667         return parse_crtime(le, usec);
5668 }
5669
5670 /// UNNEEDED by elogind
5671 #if 0
5672 int path_getcrtime(const char *p, usec_t *usec) {
5673         le64_t le;
5674         ssize_t n;
5675
5676         assert(p);
5677         assert(usec);
5678
5679         n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5680         if (n < 0)
5681                 return -errno;
5682         if (n != sizeof(le))
5683                 return -EIO;
5684
5685         return parse_crtime(le, usec);
5686 }
5687 #endif // 0
5688
5689 int fd_setcrtime(int fd, usec_t usec) {
5690         le64_t le;
5691
5692         assert(fd >= 0);
5693
5694         if (usec <= 0)
5695                 usec = now(CLOCK_REALTIME);
5696
5697         le = htole64((uint64_t) usec);
5698         if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5699                 return -errno;
5700
5701         return 0;
5702 }
5703
5704 int same_fd(int a, int b) {
5705         struct stat sta, stb;
5706         pid_t pid;
5707         int r, fa, fb;
5708
5709         assert(a >= 0);
5710         assert(b >= 0);
5711
5712         /* Compares two file descriptors. Note that semantics are
5713          * quite different depending on whether we have kcmp() or we
5714          * don't. If we have kcmp() this will only return true for
5715          * dup()ed file descriptors, but not otherwise. If we don't
5716          * have kcmp() this will also return true for two fds of the same
5717          * file, created by separate open() calls. Since we use this
5718          * call mostly for filtering out duplicates in the fd store
5719          * this difference hopefully doesn't matter too much. */
5720
5721         if (a == b)
5722                 return true;
5723
5724         /* Try to use kcmp() if we have it. */
5725         pid = getpid();
5726         r = kcmp(pid, pid, KCMP_FILE, a, b);
5727         if (r == 0)
5728                 return true;
5729         if (r > 0)
5730                 return false;
5731         if (errno != ENOSYS)
5732                 return -errno;
5733
5734         /* We don't have kcmp(), use fstat() instead. */
5735         if (fstat(a, &sta) < 0)
5736                 return -errno;
5737
5738         if (fstat(b, &stb) < 0)
5739                 return -errno;
5740
5741         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
5742                 return false;
5743
5744         /* We consider all device fds different, since two device fds
5745          * might refer to quite different device contexts even though
5746          * they share the same inode and backing dev_t. */
5747
5748         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
5749                 return false;
5750
5751         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
5752                 return false;
5753
5754         /* The fds refer to the same inode on disk, let's also check
5755          * if they have the same fd flags. This is useful to
5756          * distinguish the read and write side of a pipe created with
5757          * pipe(). */
5758         fa = fcntl(a, F_GETFL);
5759         if (fa < 0)
5760                 return -errno;
5761
5762         fb = fcntl(b, F_GETFL);
5763         if (fb < 0)
5764                 return -errno;
5765
5766         return fa == fb;
5767 }
5768
5769 int chattr_fd(int fd, unsigned value, unsigned mask) {
5770         unsigned old_attr, new_attr;
5771         struct stat st;
5772
5773         assert(fd >= 0);
5774
5775         if (fstat(fd, &st) < 0)
5776                 return -errno;
5777
5778         /* Explicitly check whether this is a regular file or
5779          * directory. If it is anything else (such as a device node or
5780          * fifo), then the ioctl will not hit the file systems but
5781          * possibly drivers, where the ioctl might have different
5782          * effects. Notably, DRM is using the same ioctl() number. */
5783
5784         if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5785                 return -ENOTTY;
5786
5787         if (mask == 0)
5788                 return 0;
5789
5790         if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5791                 return -errno;
5792
5793         new_attr = (old_attr & ~mask) | (value & mask);
5794         if (new_attr == old_attr)
5795                 return 0;
5796
5797         if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5798                 return -errno;
5799
5800         return 1;
5801 }
5802
5803 int chattr_path(const char *p, unsigned value, unsigned mask) {
5804         _cleanup_close_ int fd = -1;
5805
5806         assert(p);
5807
5808         if (mask == 0)
5809                 return 0;
5810
5811         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5812         if (fd < 0)
5813                 return -errno;
5814
5815         return chattr_fd(fd, value, mask);
5816 }
5817
5818 int read_attr_fd(int fd, unsigned *ret) {
5819         struct stat st;
5820
5821         assert(fd >= 0);
5822
5823         if (fstat(fd, &st) < 0)
5824                 return -errno;
5825
5826         if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5827                 return -ENOTTY;
5828
5829         if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5830                 return -errno;
5831
5832         return 0;
5833 }
5834
5835 int read_attr_path(const char *p, unsigned *ret) {
5836         _cleanup_close_ int fd = -1;
5837
5838         assert(p);
5839         assert(ret);
5840
5841         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5842         if (fd < 0)
5843                 return -errno;
5844
5845         return read_attr_fd(fd, ret);
5846 }
5847
5848 /// UNNEEDED by elogind
5849 #if 0
5850 static size_t nul_length(const uint8_t *p, size_t sz) {
5851         size_t n = 0;
5852
5853         while (sz > 0) {
5854                 if (*p != 0)
5855                         break;
5856
5857                 n++;
5858                 p++;
5859                 sz--;
5860         }
5861
5862         return n;
5863 }
5864
5865 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
5866         const uint8_t *q, *w, *e;
5867         ssize_t l;
5868
5869         q = w = p;
5870         e = q + sz;
5871         while (q < e) {
5872                 size_t n;
5873
5874                 n = nul_length(q, e - q);
5875
5876                 /* If there are more than the specified run length of
5877                  * NUL bytes, or if this is the beginning or the end
5878                  * of the buffer, then seek instead of write */
5879                 if ((n > run_length) ||
5880                     (n > 0 && q == p) ||
5881                     (n > 0 && q + n >= e)) {
5882                         if (q > w) {
5883                                 l = write(fd, w, q - w);
5884                                 if (l < 0)
5885                                         return -errno;
5886                                 if (l != q -w)
5887                                         return -EIO;
5888                         }
5889
5890                         if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
5891                                 return -errno;
5892
5893                         q += n;
5894                         w = q;
5895                 } else if (n > 0)
5896                         q += n;
5897                 else
5898                         q ++;
5899         }
5900
5901         if (q > w) {
5902                 l = write(fd, w, q - w);
5903                 if (l < 0)
5904                         return -errno;
5905                 if (l != q - w)
5906                         return -EIO;
5907         }
5908
5909         return q - (const uint8_t*) p;
5910 }
5911 #endif // 0
5912
5913 void sigkill_wait(pid_t *pid) {
5914         if (!pid)
5915                 return;
5916         if (*pid <= 1)
5917                 return;
5918
5919         if (kill(*pid, SIGKILL) > 0)
5920                 (void) wait_for_terminate(*pid, NULL);
5921 }
5922
5923 /// UNNEEDED by elogind
5924 #if 0
5925 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
5926         int a = 0, b = 0, c = 0;
5927         int k;
5928
5929         assert(p);
5930         assert(*p);
5931         assert(priority);
5932
5933         if ((*p)[0] != '<')
5934                 return 0;
5935
5936         if (!strchr(*p, '>'))
5937                 return 0;
5938
5939         if ((*p)[2] == '>') {
5940                 c = undecchar((*p)[1]);
5941                 k = 3;
5942         } else if ((*p)[3] == '>') {
5943                 b = undecchar((*p)[1]);
5944                 c = undecchar((*p)[2]);
5945                 k = 4;
5946         } else if ((*p)[4] == '>') {
5947                 a = undecchar((*p)[1]);
5948                 b = undecchar((*p)[2]);
5949                 c = undecchar((*p)[3]);
5950                 k = 5;
5951         } else
5952                 return 0;
5953
5954         if (a < 0 || b < 0 || c < 0 ||
5955             (!with_facility && (a || b || c > 7)))
5956                 return 0;
5957
5958         if (with_facility)
5959                 *priority = a*100 + b*10 + c;
5960         else
5961                 *priority = (*priority & LOG_FACMASK) | c;
5962
5963         *p += k;
5964         return 1;
5965 }
5966 #endif // 0
5967
5968 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
5969         size_t i;
5970
5971         if (!key)
5972                 return -1;
5973
5974         for (i = 0; i < len; ++i)
5975                 if (streq_ptr(table[i], key))
5976                         return (ssize_t)i;
5977
5978         return -1;
5979 }
5980
5981 void cmsg_close_all(struct msghdr *mh) {
5982         struct cmsghdr *cmsg;
5983
5984         assert(mh);
5985
5986         CMSG_FOREACH(cmsg, mh)
5987                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
5988                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
5989 }
5990
5991 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
5992         struct stat buf;
5993         int ret;
5994
5995         ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
5996         if (ret >= 0)
5997                 return 0;
5998
5999         /* Even though renameat2() exists since Linux 3.15, btrfs added
6000          * support for it later. If it is not implemented, fallback to another
6001          * method. */
6002         if (errno != EINVAL)
6003                 return -errno;
6004
6005         /* The link()/unlink() fallback does not work on directories. But
6006          * renameat() without RENAME_NOREPLACE gives the same semantics on
6007          * directories, except when newpath is an *empty* directory. This is
6008          * good enough. */
6009         ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6010         if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6011                 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6012                 return ret >= 0 ? 0 : -errno;
6013         }
6014
6015         /* If it is not a directory, use the link()/unlink() fallback. */
6016         ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6017         if (ret < 0)
6018                 return -errno;
6019
6020         ret = unlinkat(olddirfd, oldpath, 0);
6021         if (ret < 0) {
6022                 /* backup errno before the following unlinkat() alters it */
6023                 ret = errno;
6024                 (void) unlinkat(newdirfd, newpath, 0);
6025                 errno = ret;
6026                 return -errno;
6027         }
6028
6029         return 0;
6030 }
6031
6032 char *shell_maybe_quote(const char *s) {
6033         const char *p;
6034         char *r, *t;
6035
6036         assert(s);
6037
6038         /* Encloses a string in double quotes if necessary to make it
6039          * OK as shell string. */
6040
6041         for (p = s; *p; p++)
6042                 if (*p <= ' ' ||
6043                     *p >= 127 ||
6044                     strchr(SHELL_NEED_QUOTES, *p))
6045                         break;
6046
6047         if (!*p)
6048                 return strdup(s);
6049
6050         r = new(char, 1+strlen(s)*2+1+1);
6051         if (!r)
6052                 return NULL;
6053
6054         t = r;
6055         *(t++) = '"';
6056         t = mempcpy(t, s, p - s);
6057
6058         for (; *p; p++) {
6059
6060                 if (strchr(SHELL_NEED_ESCAPE, *p))
6061                         *(t++) = '\\';
6062
6063                 *(t++) = *p;
6064         }
6065
6066         *(t++)= '"';
6067         *t = 0;
6068
6069         return r;
6070 }
6071
6072 int parse_mode(const char *s, mode_t *ret) {
6073         char *x;
6074         long l;
6075
6076         assert(s);
6077         assert(ret);
6078
6079         errno = 0;
6080         l = strtol(s, &x, 8);
6081         if (errno != 0)
6082                 return -errno;
6083
6084         if (!x || x == s || *x)
6085                 return -EINVAL;
6086         if (l < 0 || l  > 07777)
6087                 return -ERANGE;
6088
6089         *ret = (mode_t) l;
6090         return 0;
6091 }
6092
6093 int mount_move_root(const char *path) {
6094         assert(path);
6095
6096         if (chdir(path) < 0)
6097                 return -errno;
6098
6099         if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
6100                 return -errno;
6101
6102         if (chroot(".") < 0)
6103                 return -errno;
6104
6105         if (chdir("/") < 0)
6106                 return -errno;
6107
6108         return 0;
6109 }
6110
6111 int reset_uid_gid(void) {
6112
6113         if (setgroups(0, NULL) < 0)
6114                 return -errno;
6115
6116         if (setresgid(0, 0, 0) < 0)
6117                 return -errno;
6118
6119         if (setresuid(0, 0, 0) < 0)
6120                 return -errno;
6121
6122         return 0;
6123 }