1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
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.
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.
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/>.
29 //#include <libintl.h>
31 #include <linux/magic.h>
32 //#include <linux/sched.h>
34 #include <netinet/ip.h>
43 //#include <sys/file.h>
44 //#include <sys/ioctl.h>
45 //#include <sys/mman.h>
46 //#include <sys/mount.h>
47 //#include <sys/personality.h>
48 #include <sys/prctl.h>
49 //#include <sys/resource.h>
50 //#include <sys/stat.h>
51 //#include <sys/statvfs.h>
52 //#include <sys/time.h>
53 //#include <sys/types.h>
54 //#include <sys/utsname.h>
55 //#include <sys/vfs.h>
56 //#include <sys/wait.h>
57 #include <sys/xattr.h>
61 /* When we include libgen.h because we need dirname() we immediately
62 * undefine basename() since libgen.h defines it as a macro to the
63 * POSIX version which is really broken. We prefer GNU basename(). */
67 #ifdef HAVE_SYS_AUXV_H
71 /* We include linux/fs.h as last of the system headers, as it
72 * otherwise conflicts with sys/mount.h. Yay, Linux is great! */
73 //#include <linux/fs.h>
77 //#include "device-nodes.h"
78 //#include "env-util.h"
79 //#include "exit-status.h"
81 //#include "formats-util.h"
84 #include "hostname-util.h"
88 //#include "missing.h"
90 #include "path-util.h"
91 #include "process-util.h"
92 #include "random-util.h"
93 #include "signal-util.h"
94 #include "sparse-endian.h"
96 //#include "terminal-util.h"
102 /* Put this test here for a lack of better place */
103 assert_cc(EAGAIN == EWOULDBLOCK);
106 char **saved_argv = NULL;
108 size_t page_size(void) {
109 static thread_local size_t pgsz = 0;
112 if (_likely_(pgsz > 0))
115 r = sysconf(_SC_PAGESIZE);
122 int strcmp_ptr(const char *a, const char *b) {
124 /* Like strcmp(), but tries to make sense of NULL pointers */
137 bool streq_ptr(const char *a, const char *b) {
138 return strcmp_ptr(a, b) == 0;
141 char* endswith(const char *s, const char *postfix) {
148 pl = strlen(postfix);
151 return (char*) s + sl;
156 if (memcmp(s + sl - pl, postfix, pl) != 0)
159 return (char*) s + sl - pl;
162 char* endswith_no_case(const char *s, const char *postfix) {
169 pl = strlen(postfix);
172 return (char*) s + sl;
177 if (strcasecmp(s + sl - pl, postfix) != 0)
180 return (char*) s + sl - pl;
183 char* first_word(const char *s, const char *word) {
190 /* Checks if the string starts with the specified word, either
191 * followed by NUL or by whitespace. Returns a pointer to the
192 * NUL or the first character after the whitespace. */
203 if (memcmp(s, word, wl) != 0)
210 if (!strchr(WHITESPACE, *p))
213 p += strspn(p, WHITESPACE);
217 size_t cescape_char(char c, char *buf) {
218 char * buf_old = buf;
264 /* For special chars we prefer octal over
265 * hexadecimal encoding, simply because glib's
266 * g_strescape() does the same */
267 if ((c < ' ') || (c >= 127)) {
269 *(buf++) = octchar((unsigned char) c >> 6);
270 *(buf++) = octchar((unsigned char) c >> 3);
271 *(buf++) = octchar((unsigned char) c);
277 return buf - buf_old;
280 int close_nointr(int fd) {
287 * Just ignore EINTR; a retry loop is the wrong thing to do on
290 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
291 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
292 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
293 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
301 int safe_close(int fd) {
304 * Like close_nointr() but cannot fail. Guarantees errno is
305 * unchanged. Is a NOP with negative fds passed, and returns
306 * -1, so that it can be used in this syntax:
308 * fd = safe_close(fd);
314 /* The kernel might return pretty much any error code
315 * via close(), but the fd will be closed anyway. The
316 * only condition we want to check for here is whether
317 * the fd was invalid at all... */
319 assert_se(close_nointr(fd) != -EBADF);
325 void close_many(const int fds[], unsigned n_fd) {
328 assert(fds || n_fd <= 0);
330 for (i = 0; i < n_fd; i++)
334 int fclose_nointr(FILE *f) {
337 /* Same as close_nointr(), but for fclose() */
348 FILE* safe_fclose(FILE *f) {
350 /* Same as safe_close(), but for fclose() */
355 assert_se(fclose_nointr(f) != EBADF);
361 DIR* safe_closedir(DIR *d) {
366 assert_se(closedir(d) >= 0 || errno != EBADF);
372 int unlink_noerrno(const char *path) {
383 int parse_boolean(const char *v) {
386 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
388 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
394 int parse_pid(const char *s, pid_t* ret_pid) {
395 unsigned long ul = 0;
402 r = safe_atolu(s, &ul);
408 if ((unsigned long) pid != ul)
418 bool uid_is_valid(uid_t uid) {
420 /* Some libc APIs use UID_INVALID as special placeholder */
421 if (uid == (uid_t) 0xFFFFFFFF)
424 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
425 if (uid == (uid_t) 0xFFFF)
431 int parse_uid(const char *s, uid_t* ret_uid) {
432 unsigned long ul = 0;
438 r = safe_atolu(s, &ul);
444 if ((unsigned long) uid != ul)
447 if (!uid_is_valid(uid))
448 return -ENXIO; /* we return ENXIO instead of EINVAL
449 * here, to make it easy to distuingish
450 * invalid numeric uids invalid
459 int safe_atou(const char *s, unsigned *ret_u) {
467 l = strtoul(s, &x, 0);
469 if (!x || x == s || *x || errno)
470 return errno > 0 ? -errno : -EINVAL;
472 if ((unsigned long) (unsigned) l != l)
475 *ret_u = (unsigned) l;
479 int safe_atoi(const char *s, int *ret_i) {
487 l = strtol(s, &x, 0);
489 if (!x || x == s || *x || errno)
490 return errno > 0 ? -errno : -EINVAL;
492 if ((long) (int) l != l)
499 int safe_atou8(const char *s, uint8_t *ret) {
507 l = strtoul(s, &x, 0);
509 if (!x || x == s || *x || errno)
510 return errno > 0 ? -errno : -EINVAL;
512 if ((unsigned long) (uint8_t) l != l)
519 int safe_atou16(const char *s, uint16_t *ret) {
527 l = strtoul(s, &x, 0);
529 if (!x || x == s || *x || errno)
530 return errno > 0 ? -errno : -EINVAL;
532 if ((unsigned long) (uint16_t) l != l)
539 int safe_atoi16(const char *s, int16_t *ret) {
547 l = strtol(s, &x, 0);
549 if (!x || x == s || *x || errno)
550 return errno > 0 ? -errno : -EINVAL;
552 if ((long) (int16_t) l != l)
559 int safe_atollu(const char *s, long long unsigned *ret_llu) {
561 unsigned long long l;
567 l = strtoull(s, &x, 0);
569 if (!x || x == s || *x || errno)
570 return errno ? -errno : -EINVAL;
576 int safe_atolli(const char *s, long long int *ret_lli) {
584 l = strtoll(s, &x, 0);
586 if (!x || x == s || *x || errno)
587 return errno ? -errno : -EINVAL;
593 int safe_atod(const char *s, double *ret_d) {
601 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
602 if (loc == (locale_t) 0)
606 d = strtod_l(s, &x, loc);
608 if (!x || x == s || *x || errno) {
610 return errno ? -errno : -EINVAL;
618 static size_t strcspn_escaped(const char *s, const char *reject) {
619 bool escaped = false;
622 for (n=0; s[n]; n++) {
625 else if (s[n] == '\\')
627 else if (strchr(reject, s[n]))
631 /* if s ends in \, return index of previous char */
635 /* Split a string into words. */
636 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
642 assert(**state == '\0');
646 current += strspn(current, separator);
652 if (quoted && strchr("\'\"", *current)) {
653 char quotechars[2] = {*current, '\0'};
655 *l = strcspn_escaped(current + 1, quotechars);
656 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
657 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
658 /* right quote missing or garbage at the end */
662 *state = current++ + *l + 2;
664 *l = strcspn_escaped(current, separator);
665 if (current[*l] && !strchr(separator, current[*l])) {
666 /* unfinished escape */
670 *state = current + *l;
672 *l = strcspn(current, separator);
673 *state = current + *l;
679 int fchmod_umask(int fd, mode_t m) {
684 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
690 char *truncate_nl(char *s) {
693 s[strcspn(s, NEWLINE)] = 0;
697 char *strnappend(const char *s, const char *suffix, size_t b) {
705 return strndup(suffix, b);
714 if (b > ((size_t) -1) - a)
717 r = new(char, a+b+1);
722 memcpy(r+a, suffix, b);
728 char *strappend(const char *s, const char *suffix) {
729 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
732 int readlinkat_malloc(int fd, const char *p, char **ret) {
747 n = readlinkat(fd, p, c, l-1);
754 if ((size_t) n < l-1) {
765 int readlink_malloc(const char *p, char **ret) {
766 return readlinkat_malloc(AT_FDCWD, p, ret);
769 /// UNNEEDED by elogind
771 int readlink_value(const char *p, char **ret) {
772 _cleanup_free_ char *link = NULL;
776 r = readlink_malloc(p, &link);
780 value = basename(link);
784 value = strdup(value);
794 int readlink_and_make_absolute(const char *p, char **r) {
795 _cleanup_free_ char *target = NULL;
802 j = readlink_malloc(p, &target);
806 k = file_in_same_dir(p, target);
814 /// UNNEEDED by elogind
816 int readlink_and_canonicalize(const char *p, char **r) {
823 j = readlink_and_make_absolute(p, &t);
827 s = canonicalize_file_name(t);
834 path_kill_slashes(*r);
840 char *strstrip(char *s) {
843 /* Drops trailing whitespace. Modifies the string in
844 * place. Returns pointer to first non-space character */
846 s += strspn(s, WHITESPACE);
848 for (e = strchr(s, 0); e > s; e --)
849 if (!strchr(WHITESPACE, e[-1]))
857 /// UNNEEDED by elogind
859 char *delete_chars(char *s, const char *bad) {
862 /* Drops all whitespace, regardless where in the string */
864 for (f = s, t = s; *f; f++) {
877 char *file_in_same_dir(const char *path, const char *filename) {
884 /* This removes the last component of path and appends
885 * filename, unless the latter is absolute anyway or the
888 if (path_is_absolute(filename))
889 return strdup(filename);
891 e = strrchr(path, '/');
893 return strdup(filename);
895 k = strlen(filename);
896 ret = new(char, (e + 1 - path) + k + 1);
900 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
904 /// UNNEEDED by elogind
906 int rmdir_parents(const char *path, const char *stop) {
915 /* Skip trailing slashes */
916 while (l > 0 && path[l-1] == '/')
922 /* Skip last component */
923 while (l > 0 && path[l-1] != '/')
926 /* Skip trailing slashes */
927 while (l > 0 && path[l-1] == '/')
933 if (!(t = strndup(path, l)))
936 if (path_startswith(stop, t)) {
953 char hexchar(int x) {
954 static const char table[16] = "0123456789abcdef";
956 return table[x & 15];
959 int unhexchar(char c) {
961 if (c >= '0' && c <= '9')
964 if (c >= 'a' && c <= 'f')
967 if (c >= 'A' && c <= 'F')
973 char *hexmem(const void *p, size_t l) {
977 z = r = malloc(l * 2 + 1);
981 for (x = p; x < (const uint8_t*) p + l; x++) {
982 *(z++) = hexchar(*x >> 4);
983 *(z++) = hexchar(*x & 15);
990 int unhexmem(const char *p, size_t l, void **mem, size_t *len) {
991 _cleanup_free_ uint8_t *r = NULL;
999 z = r = malloc((l + 1) / 2 + 1);
1003 for (x = p; x < p + l; x += 2) {
1006 a = unhexchar(x[0]);
1009 else if (x+1 < p + l) {
1010 b = unhexchar(x[1]);
1016 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1028 /* https://tools.ietf.org/html/rfc4648#section-6
1029 * Notice that base32hex differs from base32 in the alphabet it uses.
1030 * The distinction is that the base32hex representation preserves the
1031 * order of the underlying data when compared as bytestrings, this is
1032 * useful when representing NSEC3 hashes, as one can then verify the
1033 * order of hashes directly from their representation. */
1034 char base32hexchar(int x) {
1035 static const char table[32] = "0123456789"
1036 "ABCDEFGHIJKLMNOPQRSTUV";
1038 return table[x & 31];
1041 int unbase32hexchar(char c) {
1044 if (c >= '0' && c <= '9')
1047 offset = '9' - '0' + 1;
1049 if (c >= 'A' && c <= 'V')
1050 return c - 'A' + offset;
1055 char *base32hexmem(const void *p, size_t l, bool padding) {
1061 /* five input bytes makes eight output bytes, padding is added so we must round up */
1062 len = 8 * (l + 4) / 5;
1064 /* same, but round down as there is no padding */
1083 z = r = malloc(len + 1);
1087 for (x = p; x < (const uint8_t*) p + (l / 5) * 5; x += 5) {
1088 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ
1089 x[3] == QQQQQQQQ; x[4] == WWWWWWWW */
1090 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
1091 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
1092 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
1093 *(z++) = base32hexchar((x[1] & 1) << 4 | x[2] >> 4); /* 000YZZZZ */
1094 *(z++) = base32hexchar((x[2] & 15) << 1 | x[3] >> 7); /* 000ZZZZQ */
1095 *(z++) = base32hexchar((x[3] & 127) >> 2); /* 000QQQQQ */
1096 *(z++) = base32hexchar((x[3] & 3) << 3 | x[4] >> 5); /* 000QQWWW */
1097 *(z++) = base32hexchar((x[4] & 31)); /* 000WWWWW */
1102 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
1103 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
1104 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
1105 *(z++) = base32hexchar((x[1] & 1) << 4 | x[2] >> 4); /* 000YZZZZ */
1106 *(z++) = base32hexchar((x[2] & 15) << 1 | x[3] >> 7); /* 000ZZZZQ */
1107 *(z++) = base32hexchar((x[3] & 127) >> 2); /* 000QQQQQ */
1108 *(z++) = base32hexchar((x[3] & 3) << 3); /* 000QQ000 */
1115 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
1116 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
1117 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
1118 *(z++) = base32hexchar((x[1] & 1) << 4 | x[2] >> 4); /* 000YZZZZ */
1119 *(z++) = base32hexchar((x[2] & 15) << 1); /* 000ZZZZ0 */
1129 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
1130 *(z++) = base32hexchar((x[0] & 7) << 2 | x[1] >> 6); /* 000XXXYY */
1131 *(z++) = base32hexchar((x[1] & 63) >> 1); /* 000YYYYY */
1132 *(z++) = base32hexchar((x[1] & 1) << 4); /* 000Y0000 */
1143 *(z++) = base32hexchar(x[0] >> 3); /* 000XXXXX */
1144 *(z++) = base32hexchar((x[0] & 7) << 2); /* 000XXX00 */
1161 int unbase32hexmem(const char *p, size_t l, bool padding, void **mem, size_t *_len) {
1162 _cleanup_free_ uint8_t *r = NULL;
1163 int a, b, c, d, e, f, g, h;
1171 /* padding ensures any base32hex input has input divisible by 8 */
1172 if (padding && l % 8 != 0)
1176 /* strip the padding */
1177 while (l > 0 && p[l - 1] == '=' && pad < 7) {
1183 /* a group of eight input bytes needs five output bytes, in case of
1184 padding we need to add some extra bytes */
1206 z = r = malloc(len + 1);
1210 for (x = p; x < p + (l / 8) * 8; x += 8) {
1211 /* a == 000XXXXX; b == 000YYYYY; c == 000ZZZZZ; d == 000WWWWW
1212 e == 000SSSSS; f == 000QQQQQ; g == 000VVVVV; h == 000RRRRR */
1213 a = unbase32hexchar(x[0]);
1217 b = unbase32hexchar(x[1]);
1221 c = unbase32hexchar(x[2]);
1225 d = unbase32hexchar(x[3]);
1229 e = unbase32hexchar(x[4]);
1233 f = unbase32hexchar(x[5]);
1237 g = unbase32hexchar(x[6]);
1241 h = unbase32hexchar(x[7]);
1245 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
1246 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
1247 *(z++) = (uint8_t) d << 4 | (uint8_t) e >> 1; /* WWWWSSSS */
1248 *(z++) = (uint8_t) e << 7 | (uint8_t) f << 2 | (uint8_t) g >> 3; /* SQQQQQVV */
1249 *(z++) = (uint8_t) g << 5 | (uint8_t) h; /* VVVRRRRR */
1254 a = unbase32hexchar(x[0]);
1258 b = unbase32hexchar(x[1]);
1262 c = unbase32hexchar(x[2]);
1266 d = unbase32hexchar(x[3]);
1270 e = unbase32hexchar(x[4]);
1274 f = unbase32hexchar(x[5]);
1278 g = unbase32hexchar(x[6]);
1286 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
1287 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
1288 *(z++) = (uint8_t) d << 4 | (uint8_t) e >> 1; /* WWWWSSSS */
1289 *(z++) = (uint8_t) e << 7 | (uint8_t) f << 2 | (uint8_t) g >> 3; /* SQQQQQVV */
1293 a = unbase32hexchar(x[0]);
1297 b = unbase32hexchar(x[1]);
1301 c = unbase32hexchar(x[2]);
1305 d = unbase32hexchar(x[3]);
1309 e = unbase32hexchar(x[4]);
1317 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
1318 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
1319 *(z++) = (uint8_t) d << 4 | (uint8_t) e >> 1; /* WWWWSSSS */
1323 a = unbase32hexchar(x[0]);
1327 b = unbase32hexchar(x[1]);
1331 c = unbase32hexchar(x[2]);
1335 d = unbase32hexchar(x[3]);
1343 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
1344 *(z++) = (uint8_t) b << 6 | (uint8_t) c << 1 | (uint8_t) d >> 4; /* YYZZZZZW */
1348 a = unbase32hexchar(x[0]);
1352 b = unbase32hexchar(x[1]);
1360 *(z++) = (uint8_t) a << 3 | (uint8_t) b >> 2; /* XXXXXYYY */
1378 /* https://tools.ietf.org/html/rfc4648#section-4 */
1379 char base64char(int x) {
1380 static const char table[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1381 "abcdefghijklmnopqrstuvwxyz"
1383 return table[x & 63];
1386 int unbase64char(char c) {
1389 if (c >= 'A' && c <= 'Z')
1392 offset = 'Z' - 'A' + 1;
1394 if (c >= 'a' && c <= 'z')
1395 return c - 'a' + offset;
1397 offset += 'z' - 'a' + 1;
1399 if (c >= '0' && c <= '9')
1400 return c - '0' + offset;
1402 offset += '9' - '0' + 1;
1415 char *base64mem(const void *p, size_t l) {
1419 /* three input bytes makes four output bytes, padding is added so we must round up */
1420 z = r = malloc(4 * (l + 2) / 3 + 1);
1424 for (x = p; x < (const uint8_t*) p + (l / 3) * 3; x += 3) {
1425 /* x[0] == XXXXXXXX; x[1] == YYYYYYYY; x[2] == ZZZZZZZZ */
1426 *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */
1427 *(z++) = base64char((x[0] & 3) << 4 | x[1] >> 4); /* 00XXYYYY */
1428 *(z++) = base64char((x[1] & 15) << 2 | x[2] >> 6); /* 00YYYYZZ */
1429 *(z++) = base64char(x[2] & 63); /* 00ZZZZZZ */
1434 *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */
1435 *(z++) = base64char((x[0] & 3) << 4 | x[1] >> 4); /* 00XXYYYY */
1436 *(z++) = base64char((x[1] & 15) << 2); /* 00YYYY00 */
1441 *(z++) = base64char(x[0] >> 2); /* 00XXXXXX */
1442 *(z++) = base64char((x[0] & 3) << 4); /* 00XX0000 */
1453 int unbase64mem(const char *p, size_t l, void **mem, size_t *_len) {
1454 _cleanup_free_ uint8_t *r = NULL;
1462 /* padding ensures any base63 input has input divisible by 4 */
1466 /* strip the padding */
1467 if (l > 0 && p[l - 1] == '=')
1469 if (l > 0 && p[l - 1] == '=')
1472 /* a group of four input bytes needs three output bytes, in case of
1473 padding we need to add two or three extra bytes */
1474 len = (l / 4) * 3 + (l % 4 ? (l % 4) - 1 : 0);
1476 z = r = malloc(len + 1);
1480 for (x = p; x < p + (l / 4) * 4; x += 4) {
1481 /* a == 00XXXXXX; b == 00YYYYYY; c == 00ZZZZZZ; d == 00WWWWWW */
1482 a = unbase64char(x[0]);
1486 b = unbase64char(x[1]);
1490 c = unbase64char(x[2]);
1494 d = unbase64char(x[3]);
1498 *(z++) = (uint8_t) a << 2 | (uint8_t) b >> 4; /* XXXXXXYY */
1499 *(z++) = (uint8_t) b << 4 | (uint8_t) c >> 2; /* YYYYZZZZ */
1500 *(z++) = (uint8_t) c << 6 | (uint8_t) d; /* ZZWWWWWW */
1505 a = unbase64char(x[0]);
1509 b = unbase64char(x[1]);
1513 c = unbase64char(x[2]);
1521 *(z++) = (uint8_t) a << 2 | (uint8_t) b >> 4; /* XXXXXXYY */
1522 *(z++) = (uint8_t) b << 4 | (uint8_t) c >> 2; /* YYYYZZZZ */
1526 a = unbase64char(x[0]);
1530 b = unbase64char(x[1]);
1538 *(z++) = (uint8_t) a << 2 | (uint8_t) (b >> 4); /* XXXXXXYY */
1557 char octchar(int x) {
1558 return '0' + (x & 7);
1561 int unoctchar(char c) {
1563 if (c >= '0' && c <= '7')
1569 char decchar(int x) {
1570 return '0' + (x % 10);
1573 int undecchar(char c) {
1575 if (c >= '0' && c <= '9')
1581 char *cescape(const char *s) {
1587 /* Does C style string escaping. May be reversed with
1590 r = new(char, strlen(s)*4 + 1);
1594 for (f = s, t = r; *f; f++)
1595 t += cescape_char(*f, t);
1602 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1609 /* Unescapes C style. Returns the unescaped character in ret,
1610 * unless we encountered a \u sequence in which case the full
1611 * unicode character is returned in ret_unicode, instead. */
1613 if (length != (size_t) -1 && length < 1)
1650 /* This is an extension of the XDG syntax files */
1655 /* hexadecimal encoding */
1658 if (length != (size_t) -1 && length < 3)
1661 a = unhexchar(p[1]);
1665 b = unhexchar(p[2]);
1669 /* Don't allow NUL bytes */
1670 if (a == 0 && b == 0)
1673 *ret = (char) ((a << 4U) | b);
1679 /* C++11 style 16bit unicode */
1685 if (length != (size_t) -1 && length < 5)
1688 for (i = 0; i < 4; i++) {
1689 a[i] = unhexchar(p[1 + i]);
1694 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1696 /* Don't allow 0 chars */
1715 /* C++11 style 32bit unicode */
1721 if (length != (size_t) -1 && length < 9)
1724 for (i = 0; i < 8; i++) {
1725 a[i] = unhexchar(p[1 + i]);
1730 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1731 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1733 /* Don't allow 0 chars */
1737 /* Don't allow invalid code points */
1738 if (!unichar_is_valid(c))
1763 /* octal encoding */
1767 if (length != (size_t) -1 && length < 3)
1770 a = unoctchar(p[0]);
1774 b = unoctchar(p[1]);
1778 c = unoctchar(p[2]);
1782 /* don't allow NUL bytes */
1783 if (a == 0 && b == 0 && c == 0)
1786 /* Don't allow bytes above 255 */
1787 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1803 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1811 /* Undoes C style string escaping, and optionally prefixes it. */
1813 pl = prefix ? strlen(prefix) : 0;
1815 r = new(char, pl+length+1);
1820 memcpy(r, prefix, pl);
1822 for (f = s, t = r + pl; f < s + length; f++) {
1828 remaining = s + length - f;
1829 assert(remaining > 0);
1832 /* A literal literal, copy verbatim */
1837 if (remaining == 1) {
1838 if (flags & UNESCAPE_RELAX) {
1839 /* A trailing backslash, copy verbatim */
1848 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1850 if (flags & UNESCAPE_RELAX) {
1851 /* Invalid escape code, let's take it literal then */
1861 /* Non-Unicode? Let's encode this directly */
1864 /* Unicode? Then let's encode this in UTF-8 */
1865 t += utf8_encode_unichar(t, u);
1876 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1877 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1880 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1881 return cunescape_length(s, strlen(s), flags, ret);
1884 char *xescape(const char *s, const char *bad) {
1888 /* Escapes all chars in bad, in addition to \ and all special
1889 * chars, in \xFF style escaping. May be reversed with
1892 r = new(char, strlen(s) * 4 + 1);
1896 for (f = s, t = r; *f; f++) {
1898 if ((*f < ' ') || (*f >= 127) ||
1899 (*f == '\\') || strchr(bad, *f)) {
1902 *(t++) = hexchar(*f >> 4);
1903 *(t++) = hexchar(*f);
1913 /// UNNEEDED by elogind
1915 char *ascii_strlower(char *t) {
1920 for (p = t; *p; p++)
1921 if (*p >= 'A' && *p <= 'Z')
1922 *p = *p - 'A' + 'a';
1928 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1932 filename[0] == '.' ||
1933 streq(filename, "lost+found") ||
1934 streq(filename, "aquota.user") ||
1935 streq(filename, "aquota.group") ||
1936 endswith(filename, ".rpmnew") ||
1937 endswith(filename, ".rpmsave") ||
1938 endswith(filename, ".rpmorig") ||
1939 endswith(filename, ".dpkg-old") ||
1940 endswith(filename, ".dpkg-new") ||
1941 endswith(filename, ".dpkg-tmp") ||
1942 endswith(filename, ".dpkg-dist") ||
1943 endswith(filename, ".dpkg-bak") ||
1944 endswith(filename, ".dpkg-backup") ||
1945 endswith(filename, ".dpkg-remove") ||
1946 endswith(filename, ".swp");
1949 bool hidden_file(const char *filename) {
1952 if (endswith(filename, "~"))
1955 return hidden_file_allow_backup(filename);
1958 int fd_nonblock(int fd, bool nonblock) {
1963 flags = fcntl(fd, F_GETFL, 0);
1968 nflags = flags | O_NONBLOCK;
1970 nflags = flags & ~O_NONBLOCK;
1972 if (nflags == flags)
1975 if (fcntl(fd, F_SETFL, nflags) < 0)
1981 int fd_cloexec(int fd, bool cloexec) {
1986 flags = fcntl(fd, F_GETFD, 0);
1991 nflags = flags | FD_CLOEXEC;
1993 nflags = flags & ~FD_CLOEXEC;
1995 if (nflags == flags)
1998 if (fcntl(fd, F_SETFD, nflags) < 0)
2004 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
2007 assert(n_fdset == 0 || fdset);
2009 for (i = 0; i < n_fdset; i++)
2016 int close_all_fds(const int except[], unsigned n_except) {
2017 _cleanup_closedir_ DIR *d = NULL;
2021 assert(n_except == 0 || except);
2023 d = opendir("/proc/self/fd");
2028 /* When /proc isn't available (for example in chroots)
2029 * the fallback is brute forcing through the fd
2032 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
2033 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
2035 if (fd_in_set(fd, except, n_except))
2038 if (close_nointr(fd) < 0)
2039 if (errno != EBADF && r == 0)
2046 while ((de = readdir(d))) {
2049 if (hidden_file(de->d_name))
2052 if (safe_atoi(de->d_name, &fd) < 0)
2053 /* Let's better ignore this, just in case */
2062 if (fd_in_set(fd, except, n_except))
2065 if (close_nointr(fd) < 0) {
2066 /* Valgrind has its own FD and doesn't want to have it closed */
2067 if (errno != EBADF && r == 0)
2075 bool chars_intersect(const char *a, const char *b) {
2078 /* Returns true if any of the chars in a are in b. */
2079 for (p = a; *p; p++)
2086 /// UNNEEDED by elogind
2088 bool fstype_is_network(const char *fstype) {
2089 static const char table[] =
2104 x = startswith(fstype, "fuse.");
2108 return nulstr_contains(table, fstype);
2112 int flush_fd(int fd) {
2113 struct pollfd pollfd = {
2123 r = poll(&pollfd, 1, 0);
2133 l = read(fd, buf, sizeof(buf));
2139 if (errno == EAGAIN)
2148 void safe_close_pair(int p[]) {
2152 /* Special case pairs which use the same fd in both
2154 p[0] = p[1] = safe_close(p[0]);
2158 p[0] = safe_close(p[0]);
2159 p[1] = safe_close(p[1]);
2162 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2169 /* If called with nbytes == 0, let's call read() at least
2170 * once, to validate the operation */
2172 if (nbytes > (size_t) SSIZE_MAX)
2178 k = read(fd, p, nbytes);
2183 if (errno == EAGAIN && do_poll) {
2185 /* We knowingly ignore any return value here,
2186 * and expect that any error/EOF is reported
2189 (void) fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2193 return n > 0 ? n : -errno;
2199 assert((size_t) k <= nbytes);
2204 } while (nbytes > 0);
2209 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
2212 n = loop_read(fd, buf, nbytes, do_poll);
2215 if ((size_t) n != nbytes)
2221 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2222 const uint8_t *p = buf;
2227 if (nbytes > (size_t) SSIZE_MAX)
2233 k = write(fd, p, nbytes);
2238 if (errno == EAGAIN && do_poll) {
2239 /* We knowingly ignore any return value here,
2240 * and expect that any error/EOF is reported
2243 (void) fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2250 if (_unlikely_(nbytes > 0 && k == 0)) /* Can't really happen */
2253 assert((size_t) k <= nbytes);
2257 } while (nbytes > 0);
2262 int parse_size(const char *t, uint64_t base, uint64_t *size) {
2264 /* Soo, sometimes we want to parse IEC binary suffixes, and
2265 * sometimes SI decimal suffixes. This function can parse
2266 * both. Which one is the right way depends on the
2267 * context. Wikipedia suggests that SI is customary for
2268 * hardware metrics and network speeds, while IEC is
2269 * customary for most data sizes used by software and volatile
2270 * (RAM) memory. Hence be careful which one you pick!
2272 * In either case we use just K, M, G as suffix, and not Ki,
2273 * Mi, Gi or so (as IEC would suggest). That's because that's
2274 * frickin' ugly. But this means you really need to make sure
2275 * to document which base you are parsing when you use this
2280 unsigned long long factor;
2283 static const struct table iec[] = {
2284 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2285 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2286 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2287 { "G", 1024ULL*1024ULL*1024ULL },
2288 { "M", 1024ULL*1024ULL },
2294 static const struct table si[] = {
2295 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2296 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2297 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2298 { "G", 1000ULL*1000ULL*1000ULL },
2299 { "M", 1000ULL*1000ULL },
2305 const struct table *table;
2307 unsigned long long r = 0;
2308 unsigned n_entries, start_pos = 0;
2311 assert(base == 1000 || base == 1024);
2316 n_entries = ELEMENTSOF(si);
2319 n_entries = ELEMENTSOF(iec);
2324 unsigned long long l, tmp;
2329 p += strspn(p, WHITESPACE);
2334 l = strtoull(p, &e, 10);
2343 /* strtoull() itself would accept space/+/- */
2344 if (*e >= '0' && *e <= '9') {
2345 unsigned long long l2;
2348 l2 = strtoull(e, &e2, 10);
2352 /* Ignore failure. E.g. 10.M is valid */
2359 e += strspn(e, WHITESPACE);
2361 for (i = start_pos; i < n_entries; i++)
2362 if (startswith(e, table[i].suffix))
2368 if (l + (frac > 0) > ULLONG_MAX / table[i].factor)
2371 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2372 if (tmp > ULLONG_MAX - r)
2376 if ((unsigned long long) (uint64_t) r != r)
2379 p = e + strlen(table[i].suffix);
2390 bool is_device_path(const char *path) {
2392 /* Returns true on paths that refer to a device, either in
2393 * sysfs or in /dev */
2396 path_startswith(path, "/dev/") ||
2397 path_startswith(path, "/sys/");
2400 /// UNNEEDED by elogind
2402 int dir_is_empty(const char *path) {
2403 _cleanup_closedir_ DIR *d;
2414 if (!de && errno != 0)
2420 if (!hidden_file(de->d_name))
2425 char* dirname_malloc(const char *path) {
2426 char *d, *dir, *dir2;
2443 void rename_process(const char name[8]) {
2446 /* This is a like a poor man's setproctitle(). It changes the
2447 * comm field, argv[0], and also the glibc's internally used
2448 * name of the process. For the first one a limit of 16 chars
2449 * applies, to the second one usually one of 10 (i.e. length
2450 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2451 * "systemd"). If you pass a longer string it will be
2454 prctl(PR_SET_NAME, name);
2456 if (program_invocation_name)
2457 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2459 if (saved_argc > 0) {
2463 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2465 for (i = 1; i < saved_argc; i++) {
2469 memzero(saved_argv[i], strlen(saved_argv[i]));
2475 char *lookup_uid(uid_t uid) {
2478 _cleanup_free_ char *buf = NULL;
2479 struct passwd pwbuf, *pw = NULL;
2481 /* Shortcut things to avoid NSS lookups */
2483 return strdup("root");
2485 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2489 buf = malloc(bufsize);
2493 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2494 return strdup(pw->pw_name);
2496 if (asprintf(&name, UID_FMT, uid) < 0)
2502 /// UNNEEDED by elogind
2504 char* getlogname_malloc(void) {
2508 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2513 return lookup_uid(uid);
2516 char *getusername_malloc(void) {
2523 return lookup_uid(getuid());
2527 bool is_temporary_fs(const struct statfs *s) {
2530 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2531 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2534 int fd_is_temporary_fs(int fd) {
2537 if (fstatfs(fd, &s) < 0)
2540 return is_temporary_fs(&s);
2543 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2546 /* Under the assumption that we are running privileged we
2547 * first change the access mode and only then hand out
2548 * ownership to avoid a window where access is too open. */
2550 if (mode != MODE_INVALID)
2551 if (chmod(path, mode) < 0)
2554 if (uid != UID_INVALID || gid != GID_INVALID)
2555 if (chown(path, uid, gid) < 0)
2561 /// UNNEEDED by elogind
2563 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2566 /* Under the assumption that we are running privileged we
2567 * first change the access mode and only then hand out
2568 * ownership to avoid a window where access is too open. */
2570 if (mode != MODE_INVALID)
2571 if (fchmod(fd, mode) < 0)
2574 if (uid != UID_INVALID || gid != GID_INVALID)
2575 if (fchown(fd, uid, gid) < 0)
2583 int files_same(const char *filea, const char *fileb) {
2586 if (stat(filea, &a) < 0)
2589 if (stat(fileb, &b) < 0)
2592 return a.st_dev == b.st_dev &&
2593 a.st_ino == b.st_ino;
2596 int running_in_chroot(void) {
2599 ret = files_same("/proc/1/root", "/");
2606 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2611 assert(percent <= 100);
2612 assert(new_length >= 3);
2614 if (old_length <= 3 || old_length <= new_length)
2615 return strndup(s, old_length);
2617 r = new0(char, new_length+1);
2621 x = (new_length * percent) / 100;
2623 if (x > new_length - 3)
2631 s + old_length - (new_length - x - 3),
2632 new_length - x - 3);
2637 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2641 unsigned k, len, len2;
2644 assert(percent <= 100);
2645 assert(new_length >= 3);
2647 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2648 if (ascii_is_valid(s))
2649 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2651 if (old_length <= 3 || old_length <= new_length)
2652 return strndup(s, old_length);
2654 x = (new_length * percent) / 100;
2656 if (x > new_length - 3)
2660 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2663 c = utf8_encoded_to_unichar(i);
2666 k += unichar_iswide(c) ? 2 : 1;
2669 if (k > x) /* last character was wide and went over quota */
2672 for (j = s + old_length; k < new_length && j > i; ) {
2675 j = utf8_prev_char(j);
2676 c = utf8_encoded_to_unichar(j);
2679 k += unichar_iswide(c) ? 2 : 1;
2683 /* we don't actually need to ellipsize */
2685 return memdup(s, old_length + 1);
2687 /* make space for ellipsis */
2688 j = utf8_next_char(j);
2691 len2 = s + old_length - j;
2692 e = new(char, len + 3 + len2 + 1);
2697 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2698 old_length, new_length, x, len, len2, k);
2702 e[len] = 0xe2; /* tri-dot ellipsis: … */
2706 memcpy(e + len + 3, j, len2 + 1);
2711 char *ellipsize(const char *s, size_t length, unsigned percent) {
2712 return ellipsize_mem(s, strlen(s), length, percent);
2715 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2716 _cleanup_close_ int fd;
2722 mkdir_parents(path, 0755);
2724 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2729 r = fchmod(fd, mode);
2734 if (uid != UID_INVALID || gid != GID_INVALID) {
2735 r = fchown(fd, uid, gid);
2740 if (stamp != USEC_INFINITY) {
2741 struct timespec ts[2];
2743 timespec_store(&ts[0], stamp);
2745 r = futimens(fd, ts);
2747 r = futimens(fd, NULL);
2754 int touch(const char *path) {
2755 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2758 /// UNNEEDED by elogind
2760 static char *unquote(const char *s, const char* quotes) {
2764 /* This is rather stupid, simply removes the heading and
2765 * trailing quotes if there is one. Doesn't care about
2766 * escaping or anything.
2768 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2774 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2775 return strndup(s+1, l-2);
2781 noreturn void freeze(void) {
2783 /* Make sure nobody waits for us on a socket anymore */
2784 close_all_fds(NULL, 0);
2792 bool null_or_empty(struct stat *st) {
2795 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2798 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2804 int null_or_empty_path(const char *fn) {
2809 if (stat(fn, &st) < 0)
2812 return null_or_empty(&st);
2815 /// UNNEEDED by elogind
2817 int null_or_empty_fd(int fd) {
2822 if (fstat(fd, &st) < 0)
2825 return null_or_empty(&st);
2829 DIR *xopendirat(int fd, const char *name, int flags) {
2833 assert(!(flags & O_CREAT));
2835 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2848 /// UNNEEDED by elogind
2850 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2851 _cleanup_free_ char *t = NULL, *u = NULL;
2854 u = unquote(tagvalue, QUOTES);
2858 enc_len = strlen(u) * 4 + 1;
2859 t = new(char, enc_len);
2863 if (encode_devnode_name(u, t, enc_len) < 0)
2866 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2869 char *fstab_node_to_udev_node(const char *p) {
2872 if (startswith(p, "LABEL="))
2873 return tag_to_udev_node(p+6, "label");
2875 if (startswith(p, "UUID="))
2876 return tag_to_udev_node(p+5, "uuid");
2878 if (startswith(p, "PARTUUID="))
2879 return tag_to_udev_node(p+9, "partuuid");
2881 if (startswith(p, "PARTLABEL="))
2882 return tag_to_udev_node(p+10, "partlabel");
2888 bool dirent_is_file(const struct dirent *de) {
2891 if (hidden_file(de->d_name))
2894 if (de->d_type != DT_REG &&
2895 de->d_type != DT_LNK &&
2896 de->d_type != DT_UNKNOWN)
2902 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2905 if (de->d_type != DT_REG &&
2906 de->d_type != DT_LNK &&
2907 de->d_type != DT_UNKNOWN)
2910 if (hidden_file_allow_backup(de->d_name))
2913 return endswith(de->d_name, suffix);
2916 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2917 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2918 _cleanup_set_free_free_ Set *seen = NULL;
2921 /* We fork this all off from a child process so that we can
2922 * somewhat cleanly make use of SIGALRM to set a time limit */
2924 (void) reset_all_signal_handlers();
2925 (void) reset_signal_mask();
2927 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2929 pids = hashmap_new(NULL);
2933 seen = set_new(&string_hash_ops);
2937 STRV_FOREACH(directory, directories) {
2938 _cleanup_closedir_ DIR *d;
2941 d = opendir(*directory);
2943 if (errno == ENOENT)
2946 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2949 FOREACH_DIRENT(de, d, break) {
2950 _cleanup_free_ char *path = NULL;
2954 if (!dirent_is_file(de))
2957 if (set_contains(seen, de->d_name)) {
2958 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2962 r = set_put_strdup(seen, de->d_name);
2966 path = strjoin(*directory, "/", de->d_name, NULL);
2970 if (null_or_empty_path(path)) {
2971 log_debug("%s is empty (a mask).", path);
2977 log_error_errno(errno, "Failed to fork: %m");
2979 } else if (pid == 0) {
2982 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2992 return log_error_errno(errno, "Failed to execute %s: %m", path);
2995 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2997 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3004 /* Abort execution of this process after the timout. We simply
3005 * rely on SIGALRM as default action terminating the process,
3006 * and turn on alarm(). */
3008 if (timeout != USEC_INFINITY)
3009 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3011 while (!hashmap_isempty(pids)) {
3012 _cleanup_free_ char *path = NULL;
3015 pid = PTR_TO_UINT(hashmap_first_key(pids));
3018 path = hashmap_remove(pids, UINT_TO_PTR(pid));
3021 wait_for_terminate_and_warn(path, pid, true);
3027 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
3031 char **dirs = (char**) directories;
3033 assert(!strv_isempty(dirs));
3035 name = basename(dirs[0]);
3036 assert(!isempty(name));
3038 /* Executes all binaries in the directories in parallel and waits
3039 * for them to finish. Optionally a timeout is applied. If a file
3040 * with the same name exists in more than one directory, the
3041 * earliest one wins. */
3043 executor_pid = fork();
3044 if (executor_pid < 0) {
3045 log_error_errno(errno, "Failed to fork: %m");
3048 } else if (executor_pid == 0) {
3049 r = do_execute(dirs, timeout, argv);
3050 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
3053 wait_for_terminate_and_warn(name, executor_pid, true);
3056 bool nulstr_contains(const char*nulstr, const char *needle) {
3062 NULSTR_FOREACH(i, nulstr)
3063 if (streq(i, needle))
3069 /// UNNEEDED by elogind
3071 bool plymouth_running(void) {
3072 return access("/run/plymouth/pid", F_OK) >= 0;
3076 char* strshorten(char *s, size_t l) {
3085 int pipe_eof(int fd) {
3086 struct pollfd pollfd = {
3088 .events = POLLIN|POLLHUP,
3093 r = poll(&pollfd, 1, 0);
3100 return pollfd.revents & POLLHUP;
3103 int fd_wait_for_event(int fd, int event, usec_t t) {
3105 struct pollfd pollfd = {
3113 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
3120 return pollfd.revents;
3123 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3132 r = tempfn_xxxxxx(path, NULL, &t);
3136 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3142 f = fdopen(fd, "we");
3156 /// UNNEEDED by elogind
3158 int symlink_atomic(const char *from, const char *to) {
3159 _cleanup_free_ char *t = NULL;
3165 r = tempfn_random(to, NULL, &t);
3169 if (symlink(from, t) < 0)
3172 if (rename(t, to) < 0) {
3180 int symlink_idempotent(const char *from, const char *to) {
3181 _cleanup_free_ char *p = NULL;
3187 if (symlink(from, to) < 0) {
3188 if (errno != EEXIST)
3191 r = readlink_malloc(to, &p);
3195 if (!streq(p, from))
3202 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
3203 _cleanup_free_ char *t = NULL;
3208 r = tempfn_random(path, NULL, &t);
3212 if (mknod(t, mode, dev) < 0)
3215 if (rename(t, path) < 0) {
3223 int mkfifo_atomic(const char *path, mode_t mode) {
3224 _cleanup_free_ char *t = NULL;
3229 r = tempfn_random(path, NULL, &t);
3233 if (mkfifo(t, mode) < 0)
3236 if (rename(t, path) < 0) {
3245 bool display_is_local(const char *display) {
3249 display[0] == ':' &&
3250 display[1] >= '0' &&
3254 int socket_from_display(const char *display, char **path) {
3261 if (!display_is_local(display))
3264 k = strspn(display+1, "0123456789");
3266 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
3270 c = stpcpy(f, "/tmp/.X11-unix/X");
3271 memcpy(c, display+1, k);
3280 const char **username,
3281 uid_t *uid, gid_t *gid,
3283 const char **shell) {
3291 /* We enforce some special rules for uid=0: in order to avoid
3292 * NSS lookups for root we hardcode its data. */
3294 if (streq(*username, "root") || streq(*username, "0")) {
3312 if (parse_uid(*username, &u) >= 0) {
3316 /* If there are multiple users with the same id, make
3317 * sure to leave $USER to the configured value instead
3318 * of the first occurrence in the database. However if
3319 * the uid was configured by a numeric uid, then let's
3320 * pick the real username from /etc/passwd. */
3322 *username = p->pw_name;
3325 p = getpwnam(*username);
3329 return errno > 0 ? -errno : -ESRCH;
3341 *shell = p->pw_shell;
3346 char* uid_to_name(uid_t uid) {
3351 return strdup("root");
3355 return strdup(p->pw_name);
3357 if (asprintf(&r, UID_FMT, uid) < 0)
3363 char* gid_to_name(gid_t gid) {
3368 return strdup("root");
3372 return strdup(p->gr_name);
3374 if (asprintf(&r, GID_FMT, gid) < 0)
3380 int get_group_creds(const char **groupname, gid_t *gid) {
3386 /* We enforce some special rules for gid=0: in order to avoid
3387 * NSS lookups for root we hardcode its data. */
3389 if (streq(*groupname, "root") || streq(*groupname, "0")) {
3390 *groupname = "root";
3398 if (parse_gid(*groupname, &id) >= 0) {
3403 *groupname = g->gr_name;
3406 g = getgrnam(*groupname);
3410 return errno > 0 ? -errno : -ESRCH;
3418 int in_gid(gid_t gid) {
3420 int ngroups_max, r, i;
3422 if (getgid() == gid)
3425 if (getegid() == gid)
3428 ngroups_max = sysconf(_SC_NGROUPS_MAX);
3429 assert(ngroups_max > 0);
3431 gids = alloca(sizeof(gid_t) * ngroups_max);
3433 r = getgroups(ngroups_max, gids);
3437 for (i = 0; i < r; i++)