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/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
41 #include <sys/prctl.h>
42 #include <sys/utsname.h>
44 #include <netinet/ip.h>
51 #include <sys/mount.h>
52 #include <linux/magic.h>
56 #include <sys/personality.h>
57 #include <sys/xattr.h>
58 #include <sys/statvfs.h>
62 /* When we include libgen.h because we need dirname() we immediately
63 * undefine basename() since libgen.h defines it as a macro to the XDG
64 * version which is really broken. */
68 #ifdef HAVE_SYS_AUXV_H
80 #include "path-util.h"
81 #include "exit-status.h"
85 #include "device-nodes.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"
97 /* Put this test here for a lack of better place */
98 assert_cc(EAGAIN == EWOULDBLOCK);
101 char **saved_argv = NULL;
103 size_t page_size(void) {
104 static thread_local size_t pgsz = 0;
107 if (_likely_(pgsz > 0))
110 r = sysconf(_SC_PAGESIZE);
117 bool streq_ptr(const char *a, const char *b) {
119 /* Like streq(), but tries to make sense of NULL pointers */
130 char* endswith(const char *s, const char *postfix) {
137 pl = strlen(postfix);
140 return (char*) s + sl;
145 if (memcmp(s + sl - pl, postfix, pl) != 0)
148 return (char*) s + sl - pl;
151 char* first_word(const char *s, const char *word) {
158 /* Checks if the string starts with the specified word, either
159 * followed by NUL or by whitespace. Returns a pointer to the
160 * NUL or the first character after the whitespace. */
171 if (memcmp(s, word, wl) != 0)
178 if (!strchr(WHITESPACE, *p))
181 p += strspn(p, WHITESPACE);
185 size_t cescape_char(char c, char *buf) {
186 char * buf_old = buf;
232 /* For special chars we prefer octal over
233 * hexadecimal encoding, simply because glib's
234 * g_strescape() does the same */
235 if ((c < ' ') || (c >= 127)) {
237 *(buf++) = octchar((unsigned char) c >> 6);
238 *(buf++) = octchar((unsigned char) c >> 3);
239 *(buf++) = octchar((unsigned char) c);
245 return buf - buf_old;
248 int close_nointr(int fd) {
255 * Just ignore EINTR; a retry loop is the wrong thing to do on
258 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
259 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
260 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
261 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
269 int safe_close(int fd) {
272 * Like close_nointr() but cannot fail. Guarantees errno is
273 * unchanged. Is a NOP with negative fds passed, and returns
274 * -1, so that it can be used in this syntax:
276 * fd = safe_close(fd);
282 /* The kernel might return pretty much any error code
283 * via close(), but the fd will be closed anyway. The
284 * only condition we want to check for here is whether
285 * the fd was invalid at all... */
287 assert_se(close_nointr(fd) != -EBADF);
293 void close_many(const int fds[], unsigned n_fd) {
296 assert(fds || n_fd <= 0);
298 for (i = 0; i < n_fd; i++)
302 int unlink_noerrno(const char *path) {
313 int parse_boolean(const char *v) {
316 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
318 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
324 int parse_pid(const char *s, pid_t* ret_pid) {
325 unsigned long ul = 0;
332 r = safe_atolu(s, &ul);
338 if ((unsigned long) pid != ul)
348 int parse_uid(const char *s, uid_t* ret_uid) {
349 unsigned long ul = 0;
355 r = safe_atolu(s, &ul);
361 if ((unsigned long) uid != ul)
364 /* Some libc APIs use UID_INVALID as special placeholder */
365 if (uid == (uid_t) 0xFFFFFFFF)
368 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
369 if (uid == (uid_t) 0xFFFF)
378 int safe_atou(const char *s, unsigned *ret_u) {
386 l = strtoul(s, &x, 0);
388 if (!x || x == s || *x || errno)
389 return errno > 0 ? -errno : -EINVAL;
391 if ((unsigned long) (unsigned) l != l)
394 *ret_u = (unsigned) l;
398 int safe_atoi(const char *s, int *ret_i) {
406 l = strtol(s, &x, 0);
408 if (!x || x == s || *x || errno)
409 return errno > 0 ? -errno : -EINVAL;
411 if ((long) (int) l != l)
418 int safe_atou8(const char *s, uint8_t *ret) {
426 l = strtoul(s, &x, 0);
428 if (!x || x == s || *x || errno)
429 return errno > 0 ? -errno : -EINVAL;
431 if ((unsigned long) (uint8_t) l != l)
438 int safe_atou16(const char *s, uint16_t *ret) {
446 l = strtoul(s, &x, 0);
448 if (!x || x == s || *x || errno)
449 return errno > 0 ? -errno : -EINVAL;
451 if ((unsigned long) (uint16_t) l != l)
458 int safe_atoi16(const char *s, int16_t *ret) {
466 l = strtol(s, &x, 0);
468 if (!x || x == s || *x || errno)
469 return errno > 0 ? -errno : -EINVAL;
471 if ((long) (int16_t) l != l)
478 int safe_atollu(const char *s, long long unsigned *ret_llu) {
480 unsigned long long l;
486 l = strtoull(s, &x, 0);
488 if (!x || x == s || *x || errno)
489 return errno ? -errno : -EINVAL;
495 int safe_atolli(const char *s, long long int *ret_lli) {
503 l = strtoll(s, &x, 0);
505 if (!x || x == s || *x || errno)
506 return errno ? -errno : -EINVAL;
512 int safe_atod(const char *s, double *ret_d) {
520 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
521 if (loc == (locale_t) 0)
525 d = strtod_l(s, &x, loc);
527 if (!x || x == s || *x || errno) {
529 return errno ? -errno : -EINVAL;
537 static size_t strcspn_escaped(const char *s, const char *reject) {
538 bool escaped = false;
541 for (n=0; s[n]; n++) {
544 else if (s[n] == '\\')
546 else if (strchr(reject, s[n]))
550 /* if s ends in \, return index of previous char */
554 /* Split a string into words. */
555 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
561 assert(**state == '\0');
565 current += strspn(current, separator);
571 if (quoted && strchr("\'\"", *current)) {
572 char quotechars[2] = {*current, '\0'};
574 *l = strcspn_escaped(current + 1, quotechars);
575 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
576 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
577 /* right quote missing or garbage at the end */
581 *state = current++ + *l + 2;
583 *l = strcspn_escaped(current, separator);
584 if (current[*l] && !strchr(separator, current[*l])) {
585 /* unfinished escape */
589 *state = current + *l;
591 *l = strcspn(current, separator);
592 *state = current + *l;
598 int fchmod_umask(int fd, mode_t m) {
603 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
609 char *truncate_nl(char *s) {
612 s[strcspn(s, NEWLINE)] = 0;
616 char *strnappend(const char *s, const char *suffix, size_t b) {
624 return strndup(suffix, b);
633 if (b > ((size_t) -1) - a)
636 r = new(char, a+b+1);
641 memcpy(r+a, suffix, b);
647 char *strappend(const char *s, const char *suffix) {
648 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
651 int readlinkat_malloc(int fd, const char *p, char **ret) {
666 n = readlinkat(fd, p, c, l-1);
673 if ((size_t) n < l-1) {
684 int readlink_malloc(const char *p, char **ret) {
685 return readlinkat_malloc(AT_FDCWD, p, ret);
688 int readlink_value(const char *p, char **ret) {
689 _cleanup_free_ char *link = NULL;
693 r = readlink_malloc(p, &link);
697 value = basename(link);
701 value = strdup(value);
710 int readlink_and_make_absolute(const char *p, char **r) {
711 _cleanup_free_ char *target = NULL;
718 j = readlink_malloc(p, &target);
722 k = file_in_same_dir(p, target);
730 int readlink_and_canonicalize(const char *p, char **r) {
737 j = readlink_and_make_absolute(p, &t);
741 s = canonicalize_file_name(t);
748 path_kill_slashes(*r);
753 int reset_all_signal_handlers(void) {
756 for (sig = 1; sig < _NSIG; sig++) {
757 struct sigaction sa = {
758 .sa_handler = SIG_DFL,
759 .sa_flags = SA_RESTART,
762 /* These two cannot be caught... */
763 if (sig == SIGKILL || sig == SIGSTOP)
766 /* On Linux the first two RT signals are reserved by
767 * glibc, and sigaction() will return EINVAL for them. */
768 if ((sigaction(sig, &sa, NULL) < 0))
769 if (errno != EINVAL && r == 0)
776 int reset_signal_mask(void) {
779 if (sigemptyset(&ss) < 0)
782 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
788 char *strstrip(char *s) {
791 /* Drops trailing whitespace. Modifies the string in
792 * place. Returns pointer to first non-space character */
794 s += strspn(s, WHITESPACE);
796 for (e = strchr(s, 0); e > s; e --)
797 if (!strchr(WHITESPACE, e[-1]))
805 char *delete_chars(char *s, const char *bad) {
808 /* Drops all whitespace, regardless where in the string */
810 for (f = s, t = s; *f; f++) {
822 char *file_in_same_dir(const char *path, const char *filename) {
829 /* This removes the last component of path and appends
830 * filename, unless the latter is absolute anyway or the
833 if (path_is_absolute(filename))
834 return strdup(filename);
836 e = strrchr(path, '/');
838 return strdup(filename);
840 k = strlen(filename);
841 ret = new(char, (e + 1 - path) + k + 1);
845 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
849 int rmdir_parents(const char *path, const char *stop) {
858 /* Skip trailing slashes */
859 while (l > 0 && path[l-1] == '/')
865 /* Skip last component */
866 while (l > 0 && path[l-1] != '/')
869 /* Skip trailing slashes */
870 while (l > 0 && path[l-1] == '/')
876 if (!(t = strndup(path, l)))
879 if (path_startswith(stop, t)) {
895 char hexchar(int x) {
896 static const char table[16] = "0123456789abcdef";
898 return table[x & 15];
901 int unhexchar(char c) {
903 if (c >= '0' && c <= '9')
906 if (c >= 'a' && c <= 'f')
909 if (c >= 'A' && c <= 'F')
915 char *hexmem(const void *p, size_t l) {
919 z = r = malloc(l * 2 + 1);
923 for (x = p; x < (const uint8_t*) p + l; x++) {
924 *(z++) = hexchar(*x >> 4);
925 *(z++) = hexchar(*x & 15);
932 void *unhexmem(const char *p, size_t l) {
938 z = r = malloc((l + 1) / 2 + 1);
942 for (x = p; x < p + l; x += 2) {
951 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
958 char octchar(int x) {
959 return '0' + (x & 7);
962 int unoctchar(char c) {
964 if (c >= '0' && c <= '7')
970 char decchar(int x) {
971 return '0' + (x % 10);
974 int undecchar(char c) {
976 if (c >= '0' && c <= '9')
982 char *cescape(const char *s) {
988 /* Does C style string escaping. May be reversed with
991 r = new(char, strlen(s)*4 + 1);
995 for (f = s, t = r; *f; f++)
996 t += cescape_char(*f, t);
1003 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1010 /* Unescapes C style. Returns the unescaped character in ret,
1011 * unless we encountered a \u sequence in which case the full
1012 * unicode character is returned in ret_unicode, instead. */
1014 if (length != (size_t) -1 && length < 1)
1051 /* This is an extension of the XDG syntax files */
1056 /* hexadecimal encoding */
1059 if (length != (size_t) -1 && length < 3)
1062 a = unhexchar(p[1]);
1066 b = unhexchar(p[2]);
1070 /* Don't allow NUL bytes */
1071 if (a == 0 && b == 0)
1074 *ret = (char) ((a << 4U) | b);
1080 /* C++11 style 16bit unicode */
1086 if (length != (size_t) -1 && length < 5)
1089 for (i = 0; i < 4; i++) {
1090 a[i] = unhexchar(p[1 + i]);
1095 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1097 /* Don't allow 0 chars */
1116 /* C++11 style 32bit unicode */
1122 if (length != (size_t) -1 && length < 9)
1125 for (i = 0; i < 8; i++) {
1126 a[i] = unhexchar(p[1 + i]);
1131 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1132 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1134 /* Don't allow 0 chars */
1138 /* Don't allow invalid code points */
1139 if (!unichar_is_valid(c))
1164 /* octal encoding */
1168 if (length != (size_t) -1 && length < 4)
1171 a = unoctchar(p[0]);
1175 b = unoctchar(p[1]);
1179 c = unoctchar(p[2]);
1183 /* don't allow NUL bytes */
1184 if (a == 0 && b == 0 && c == 0)
1187 /* Don't allow bytes above 255 */
1188 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1204 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1212 /* Undoes C style string escaping, and optionally prefixes it. */
1214 pl = prefix ? strlen(prefix) : 0;
1216 r = new(char, pl+length+1);
1221 memcpy(r, prefix, pl);
1223 for (f = s, t = r + pl; f < s + length; f++) {
1229 remaining = s + length - f;
1230 assert(remaining > 0);
1233 /* A literal literal, copy verbatim */
1238 if (remaining == 1) {
1239 if (flags & UNESCAPE_RELAX) {
1240 /* A trailing backslash, copy verbatim */
1249 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1251 if (flags & UNESCAPE_RELAX) {
1252 /* Invalid escape code, let's take it literal then */
1262 /* Non-Unicode? Let's encode this directly */
1265 /* Unicode? Then let's encode this in UTF-8 */
1266 t += utf8_encode_unichar(t, u);
1277 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1278 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1281 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1282 return cunescape_length(s, strlen(s), flags, ret);
1285 char *xescape(const char *s, const char *bad) {
1289 /* Escapes all chars in bad, in addition to \ and all special
1290 * chars, in \xFF style escaping. May be reversed with
1293 r = new(char, strlen(s) * 4 + 1);
1297 for (f = s, t = r; *f; f++) {
1299 if ((*f < ' ') || (*f >= 127) ||
1300 (*f == '\\') || strchr(bad, *f)) {
1303 *(t++) = hexchar(*f >> 4);
1304 *(t++) = hexchar(*f);
1314 char *ascii_strlower(char *t) {
1319 for (p = t; *p; p++)
1320 if (*p >= 'A' && *p <= 'Z')
1321 *p = *p - 'A' + 'a';
1326 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1330 filename[0] == '.' ||
1331 streq(filename, "lost+found") ||
1332 streq(filename, "aquota.user") ||
1333 streq(filename, "aquota.group") ||
1334 endswith(filename, ".rpmnew") ||
1335 endswith(filename, ".rpmsave") ||
1336 endswith(filename, ".rpmorig") ||
1337 endswith(filename, ".dpkg-old") ||
1338 endswith(filename, ".dpkg-new") ||
1339 endswith(filename, ".dpkg-tmp") ||
1340 endswith(filename, ".dpkg-dist") ||
1341 endswith(filename, ".dpkg-bak") ||
1342 endswith(filename, ".dpkg-backup") ||
1343 endswith(filename, ".dpkg-remove") ||
1344 endswith(filename, ".swp");
1347 bool hidden_file(const char *filename) {
1350 if (endswith(filename, "~"))
1353 return hidden_file_allow_backup(filename);
1356 int fd_nonblock(int fd, bool nonblock) {
1361 flags = fcntl(fd, F_GETFL, 0);
1366 nflags = flags | O_NONBLOCK;
1368 nflags = flags & ~O_NONBLOCK;
1370 if (nflags == flags)
1373 if (fcntl(fd, F_SETFL, nflags) < 0)
1379 int fd_cloexec(int fd, bool cloexec) {
1384 flags = fcntl(fd, F_GETFD, 0);
1389 nflags = flags | FD_CLOEXEC;
1391 nflags = flags & ~FD_CLOEXEC;
1393 if (nflags == flags)
1396 if (fcntl(fd, F_SETFD, nflags) < 0)
1402 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1405 assert(n_fdset == 0 || fdset);
1407 for (i = 0; i < n_fdset; i++)
1414 int close_all_fds(const int except[], unsigned n_except) {
1415 _cleanup_closedir_ DIR *d = NULL;
1419 assert(n_except == 0 || except);
1421 d = opendir("/proc/self/fd");
1426 /* When /proc isn't available (for example in chroots)
1427 * the fallback is brute forcing through the fd
1430 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1431 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1433 if (fd_in_set(fd, except, n_except))
1436 if (close_nointr(fd) < 0)
1437 if (errno != EBADF && r == 0)
1444 while ((de = readdir(d))) {
1447 if (hidden_file(de->d_name))
1450 if (safe_atoi(de->d_name, &fd) < 0)
1451 /* Let's better ignore this, just in case */
1460 if (fd_in_set(fd, except, n_except))
1463 if (close_nointr(fd) < 0) {
1464 /* Valgrind has its own FD and doesn't want to have it closed */
1465 if (errno != EBADF && r == 0)
1473 bool chars_intersect(const char *a, const char *b) {
1476 /* Returns true if any of the chars in a are in b. */
1477 for (p = a; *p; p++)
1484 bool fstype_is_network(const char *fstype) {
1485 static const char table[] =
1500 x = startswith(fstype, "fuse.");
1504 return nulstr_contains(table, fstype);
1507 int flush_fd(int fd) {
1508 struct pollfd pollfd = {
1518 r = poll(&pollfd, 1, 0);
1528 l = read(fd, buf, sizeof(buf));
1534 if (errno == EAGAIN)
1543 int sigaction_many(const struct sigaction *sa, ...) {
1548 while ((sig = va_arg(ap, int)) > 0)
1549 if (sigaction(sig, sa, NULL) < 0)
1556 int ignore_signals(int sig, ...) {
1557 struct sigaction sa = {
1558 .sa_handler = SIG_IGN,
1559 .sa_flags = SA_RESTART,
1564 if (sigaction(sig, &sa, NULL) < 0)
1568 while ((sig = va_arg(ap, int)) > 0)
1569 if (sigaction(sig, &sa, NULL) < 0)
1576 int default_signals(int sig, ...) {
1577 struct sigaction sa = {
1578 .sa_handler = SIG_DFL,
1579 .sa_flags = SA_RESTART,
1584 if (sigaction(sig, &sa, NULL) < 0)
1588 while ((sig = va_arg(ap, int)) > 0)
1589 if (sigaction(sig, &sa, NULL) < 0)
1596 void safe_close_pair(int p[]) {
1600 /* Special case pairs which use the same fd in both
1602 p[0] = p[1] = safe_close(p[0]);
1606 p[0] = safe_close(p[0]);
1607 p[1] = safe_close(p[1]);
1610 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1617 while (nbytes > 0) {
1620 k = read(fd, p, nbytes);
1625 if (errno == EAGAIN && do_poll) {
1627 /* We knowingly ignore any return value here,
1628 * and expect that any error/EOF is reported
1631 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1635 return n > 0 ? n : -errno;
1649 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1652 n = loop_read(fd, buf, nbytes, do_poll);
1655 if ((size_t) n != nbytes)
1660 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1661 const uint8_t *p = buf;
1671 k = write(fd, p, nbytes);
1676 if (errno == EAGAIN && do_poll) {
1677 /* We knowingly ignore any return value here,
1678 * and expect that any error/EOF is reported
1681 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1688 if (nbytes > 0 && k == 0) /* Can't really happen */
1693 } while (nbytes > 0);
1698 int parse_size(const char *t, off_t base, off_t *size) {
1700 /* Soo, sometimes we want to parse IEC binary suffixes, and
1701 * sometimes SI decimal suffixes. This function can parse
1702 * both. Which one is the right way depends on the
1703 * context. Wikipedia suggests that SI is customary for
1704 * hardware metrics and network speeds, while IEC is
1705 * customary for most data sizes used by software and volatile
1706 * (RAM) memory. Hence be careful which one you pick!
1708 * In either case we use just K, M, G as suffix, and not Ki,
1709 * Mi, Gi or so (as IEC would suggest). That's because that's
1710 * frickin' ugly. But this means you really need to make sure
1711 * to document which base you are parsing when you use this
1716 unsigned long long factor;
1719 static const struct table iec[] = {
1720 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1721 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1722 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1723 { "G", 1024ULL*1024ULL*1024ULL },
1724 { "M", 1024ULL*1024ULL },
1730 static const struct table si[] = {
1731 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1732 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1733 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1734 { "G", 1000ULL*1000ULL*1000ULL },
1735 { "M", 1000ULL*1000ULL },
1741 const struct table *table;
1743 unsigned long long r = 0;
1744 unsigned n_entries, start_pos = 0;
1747 assert(base == 1000 || base == 1024);
1752 n_entries = ELEMENTSOF(si);
1755 n_entries = ELEMENTSOF(iec);
1761 unsigned long long l2;
1767 l = strtoll(p, &e, 10);
1780 if (*e >= '0' && *e <= '9') {
1783 /* strotoull itself would accept space/+/- */
1784 l2 = strtoull(e, &e2, 10);
1786 if (errno == ERANGE)
1789 /* Ignore failure. E.g. 10.M is valid */
1796 e += strspn(e, WHITESPACE);
1798 for (i = start_pos; i < n_entries; i++)
1799 if (startswith(e, table[i].suffix)) {
1800 unsigned long long tmp;
1801 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1803 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1804 if (tmp > ULLONG_MAX - r)
1808 if ((unsigned long long) (off_t) r != r)
1811 p = e + strlen(table[i].suffix);
1827 bool is_device_path(const char *path) {
1829 /* Returns true on paths that refer to a device, either in
1830 * sysfs or in /dev */
1833 path_startswith(path, "/dev/") ||
1834 path_startswith(path, "/sys/");
1837 int dir_is_empty(const char *path) {
1838 _cleanup_closedir_ DIR *d;
1849 if (!de && errno != 0)
1855 if (!hidden_file(de->d_name))
1860 char* dirname_malloc(const char *path) {
1861 char *d, *dir, *dir2;
1878 void rename_process(const char name[8]) {
1881 /* This is a like a poor man's setproctitle(). It changes the
1882 * comm field, argv[0], and also the glibc's internally used
1883 * name of the process. For the first one a limit of 16 chars
1884 * applies, to the second one usually one of 10 (i.e. length
1885 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1886 * "systemd"). If you pass a longer string it will be
1889 prctl(PR_SET_NAME, name);
1891 if (program_invocation_name)
1892 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1894 if (saved_argc > 0) {
1898 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1900 for (i = 1; i < saved_argc; i++) {
1904 memzero(saved_argv[i], strlen(saved_argv[i]));
1909 void sigset_add_many(sigset_t *ss, ...) {
1916 while ((sig = va_arg(ap, int)) > 0)
1917 assert_se(sigaddset(ss, sig) == 0);
1921 int sigprocmask_many(int how, ...) {
1926 assert_se(sigemptyset(&ss) == 0);
1929 while ((sig = va_arg(ap, int)) > 0)
1930 assert_se(sigaddset(&ss, sig) == 0);
1933 if (sigprocmask(how, &ss, NULL) < 0)
1938 char *lookup_uid(uid_t uid) {
1941 _cleanup_free_ char *buf = NULL;
1942 struct passwd pwbuf, *pw = NULL;
1944 /* Shortcut things to avoid NSS lookups */
1946 return strdup("root");
1948 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1952 buf = malloc(bufsize);
1956 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1957 return strdup(pw->pw_name);
1959 if (asprintf(&name, UID_FMT, uid) < 0)
1965 char* getlogname_malloc(void) {
1969 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1974 return lookup_uid(uid);
1977 char *getusername_malloc(void) {
1984 return lookup_uid(getuid());
1987 bool is_temporary_fs(const struct statfs *s) {
1990 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
1991 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
1994 int fd_is_temporary_fs(int fd) {
1997 if (fstatfs(fd, &s) < 0)
2000 return is_temporary_fs(&s);
2003 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2006 /* Under the assumption that we are running privileged we
2007 * first change the access mode and only then hand out
2008 * ownership to avoid a window where access is too open. */
2010 if (mode != MODE_INVALID)
2011 if (chmod(path, mode) < 0)
2014 if (uid != UID_INVALID || gid != GID_INVALID)
2015 if (chown(path, uid, gid) < 0)
2021 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2024 /* Under the assumption that we are running privileged we
2025 * first change the access mode and only then hand out
2026 * ownership to avoid a window where access is too open. */
2028 if (mode != MODE_INVALID)
2029 if (fchmod(fd, mode) < 0)
2032 if (uid != UID_INVALID || gid != GID_INVALID)
2033 if (fchown(fd, uid, gid) < 0)
2039 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2043 /* Allocates the cpuset in the right size */
2046 if (!(r = CPU_ALLOC(n)))
2049 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2050 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2060 if (errno != EINVAL)
2067 int files_same(const char *filea, const char *fileb) {
2070 if (stat(filea, &a) < 0)
2073 if (stat(fileb, &b) < 0)
2076 return a.st_dev == b.st_dev &&
2077 a.st_ino == b.st_ino;
2080 int running_in_chroot(void) {
2083 ret = files_same("/proc/1/root", "/");
2090 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2095 assert(percent <= 100);
2096 assert(new_length >= 3);
2098 if (old_length <= 3 || old_length <= new_length)
2099 return strndup(s, old_length);
2101 r = new0(char, new_length+1);
2105 x = (new_length * percent) / 100;
2107 if (x > new_length - 3)
2115 s + old_length - (new_length - x - 3),
2116 new_length - x - 3);
2121 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2125 unsigned k, len, len2;
2128 assert(percent <= 100);
2129 assert(new_length >= 3);
2131 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2132 if (ascii_is_valid(s))
2133 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2135 if (old_length <= 3 || old_length <= new_length)
2136 return strndup(s, old_length);
2138 x = (new_length * percent) / 100;
2140 if (x > new_length - 3)
2144 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2147 c = utf8_encoded_to_unichar(i);
2150 k += unichar_iswide(c) ? 2 : 1;
2153 if (k > x) /* last character was wide and went over quota */
2156 for (j = s + old_length; k < new_length && j > i; ) {
2159 j = utf8_prev_char(j);
2160 c = utf8_encoded_to_unichar(j);
2163 k += unichar_iswide(c) ? 2 : 1;
2167 /* we don't actually need to ellipsize */
2169 return memdup(s, old_length + 1);
2171 /* make space for ellipsis */
2172 j = utf8_next_char(j);
2175 len2 = s + old_length - j;
2176 e = new(char, len + 3 + len2 + 1);
2181 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2182 old_length, new_length, x, len, len2, k);
2186 e[len] = 0xe2; /* tri-dot ellipsis: … */
2190 memcpy(e + len + 3, j, len2 + 1);
2195 char *ellipsize(const char *s, size_t length, unsigned percent) {
2196 return ellipsize_mem(s, strlen(s), length, percent);
2199 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2200 _cleanup_close_ int fd;
2206 mkdir_parents(path, 0755);
2208 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2213 r = fchmod(fd, mode);
2218 if (uid != UID_INVALID || gid != GID_INVALID) {
2219 r = fchown(fd, uid, gid);
2224 if (stamp != USEC_INFINITY) {
2225 struct timespec ts[2];
2227 timespec_store(&ts[0], stamp);
2229 r = futimens(fd, ts);
2231 r = futimens(fd, NULL);
2238 int touch(const char *path) {
2239 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2242 static char *unquote(const char *s, const char* quotes) {
2246 /* This is rather stupid, simply removes the heading and
2247 * trailing quotes if there is one. Doesn't care about
2248 * escaping or anything.
2250 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2256 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2257 return strndup(s+1, l-2);
2262 noreturn void freeze(void) {
2264 /* Make sure nobody waits for us on a socket anymore */
2265 close_all_fds(NULL, 0);
2273 bool null_or_empty(struct stat *st) {
2276 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2279 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2285 int null_or_empty_path(const char *fn) {
2290 if (stat(fn, &st) < 0)
2293 return null_or_empty(&st);
2296 int null_or_empty_fd(int fd) {
2301 if (fstat(fd, &st) < 0)
2304 return null_or_empty(&st);
2307 DIR *xopendirat(int fd, const char *name, int flags) {
2311 assert(!(flags & O_CREAT));
2313 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2326 int signal_from_string_try_harder(const char *s) {
2330 signo = signal_from_string(s);
2332 if (startswith(s, "SIG"))
2333 return signal_from_string(s+3);
2338 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2339 _cleanup_free_ char *t = NULL, *u = NULL;
2342 u = unquote(tagvalue, QUOTES);
2346 enc_len = strlen(u) * 4 + 1;
2347 t = new(char, enc_len);
2351 if (encode_devnode_name(u, t, enc_len) < 0)
2354 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2357 char *fstab_node_to_udev_node(const char *p) {
2360 if (startswith(p, "LABEL="))
2361 return tag_to_udev_node(p+6, "label");
2363 if (startswith(p, "UUID="))
2364 return tag_to_udev_node(p+5, "uuid");
2366 if (startswith(p, "PARTUUID="))
2367 return tag_to_udev_node(p+9, "partuuid");
2369 if (startswith(p, "PARTLABEL="))
2370 return tag_to_udev_node(p+10, "partlabel");
2375 bool dirent_is_file(const struct dirent *de) {
2378 if (hidden_file(de->d_name))
2381 if (de->d_type != DT_REG &&
2382 de->d_type != DT_LNK &&
2383 de->d_type != DT_UNKNOWN)
2389 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2392 if (de->d_type != DT_REG &&
2393 de->d_type != DT_LNK &&
2394 de->d_type != DT_UNKNOWN)
2397 if (hidden_file_allow_backup(de->d_name))
2400 return endswith(de->d_name, suffix);
2403 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2404 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2405 _cleanup_set_free_free_ Set *seen = NULL;
2408 /* We fork this all off from a child process so that we can
2409 * somewhat cleanly make use of SIGALRM to set a time limit */
2411 reset_all_signal_handlers();
2412 reset_signal_mask();
2414 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2416 pids = hashmap_new(NULL);
2420 seen = set_new(&string_hash_ops);
2424 STRV_FOREACH(directory, directories) {
2425 _cleanup_closedir_ DIR *d;
2428 d = opendir(*directory);
2430 if (errno == ENOENT)
2433 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2436 FOREACH_DIRENT(de, d, break) {
2437 _cleanup_free_ char *path = NULL;
2441 if (!dirent_is_file(de))
2444 if (set_contains(seen, de->d_name)) {
2445 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2449 r = set_put_strdup(seen, de->d_name);
2453 path = strjoin(*directory, "/", de->d_name, NULL);
2457 if (null_or_empty_path(path)) {
2458 log_debug("%s is empty (a mask).", path);
2464 log_error_errno(errno, "Failed to fork: %m");
2466 } else if (pid == 0) {
2469 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2479 return log_error_errno(errno, "Failed to execute %s: %m", path);
2482 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2484 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2491 /* Abort execution of this process after the timout. We simply
2492 * rely on SIGALRM as default action terminating the process,
2493 * and turn on alarm(). */
2495 if (timeout != USEC_INFINITY)
2496 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2498 while (!hashmap_isempty(pids)) {
2499 _cleanup_free_ char *path = NULL;
2502 pid = PTR_TO_UINT(hashmap_first_key(pids));
2505 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2508 wait_for_terminate_and_warn(path, pid, true);
2514 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2518 char **dirs = (char**) directories;
2520 assert(!strv_isempty(dirs));
2522 name = basename(dirs[0]);
2523 assert(!isempty(name));
2525 /* Executes all binaries in the directories in parallel and waits
2526 * for them to finish. Optionally a timeout is applied. If a file
2527 * with the same name exists in more than one directory, the
2528 * earliest one wins. */
2530 executor_pid = fork();
2531 if (executor_pid < 0) {
2532 log_error_errno(errno, "Failed to fork: %m");
2535 } else if (executor_pid == 0) {
2536 r = do_execute(dirs, timeout, argv);
2537 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2540 wait_for_terminate_and_warn(name, executor_pid, true);
2543 bool nulstr_contains(const char*nulstr, const char *needle) {
2549 NULSTR_FOREACH(i, nulstr)
2550 if (streq(i, needle))
2556 bool plymouth_running(void) {
2557 return access("/run/plymouth/pid", F_OK) >= 0;
2560 char* strshorten(char *s, size_t l) {
2569 bool machine_name_is_valid(const char *s) {
2571 if (!hostname_is_valid(s))
2574 /* Machine names should be useful hostnames, but also be
2575 * useful in unit names, hence we enforce a stricter length
2584 int pipe_eof(int fd) {
2585 struct pollfd pollfd = {
2587 .events = POLLIN|POLLHUP,
2592 r = poll(&pollfd, 1, 0);
2599 return pollfd.revents & POLLHUP;
2602 int fd_wait_for_event(int fd, int event, usec_t t) {
2604 struct pollfd pollfd = {
2612 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2619 return pollfd.revents;
2622 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2631 r = tempfn_xxxxxx(path, &t);
2635 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2641 f = fdopen(fd, "we");
2654 int symlink_atomic(const char *from, const char *to) {
2655 _cleanup_free_ char *t = NULL;
2661 r = tempfn_random(to, &t);
2665 if (symlink(from, t) < 0)
2668 if (rename(t, to) < 0) {
2676 int symlink_idempotent(const char *from, const char *to) {
2677 _cleanup_free_ char *p = NULL;
2683 if (symlink(from, to) < 0) {
2684 if (errno != EEXIST)
2687 r = readlink_malloc(to, &p);
2691 if (!streq(p, from))
2698 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2699 _cleanup_free_ char *t = NULL;
2704 r = tempfn_random(path, &t);
2708 if (mknod(t, mode, dev) < 0)
2711 if (rename(t, path) < 0) {
2719 int mkfifo_atomic(const char *path, mode_t mode) {
2720 _cleanup_free_ char *t = NULL;
2725 r = tempfn_random(path, &t);
2729 if (mkfifo(t, mode) < 0)
2732 if (rename(t, path) < 0) {
2740 bool display_is_local(const char *display) {
2744 display[0] == ':' &&
2745 display[1] >= '0' &&
2749 int socket_from_display(const char *display, char **path) {
2756 if (!display_is_local(display))
2759 k = strspn(display+1, "0123456789");
2761 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2765 c = stpcpy(f, "/tmp/.X11-unix/X");
2766 memcpy(c, display+1, k);
2775 const char **username,
2776 uid_t *uid, gid_t *gid,
2778 const char **shell) {
2786 /* We enforce some special rules for uid=0: in order to avoid
2787 * NSS lookups for root we hardcode its data. */
2789 if (streq(*username, "root") || streq(*username, "0")) {
2807 if (parse_uid(*username, &u) >= 0) {
2811 /* If there are multiple users with the same id, make
2812 * sure to leave $USER to the configured value instead
2813 * of the first occurrence in the database. However if
2814 * the uid was configured by a numeric uid, then let's
2815 * pick the real username from /etc/passwd. */
2817 *username = p->pw_name;
2820 p = getpwnam(*username);
2824 return errno > 0 ? -errno : -ESRCH;
2836 *shell = p->pw_shell;
2841 char* uid_to_name(uid_t uid) {
2846 return strdup("root");
2850 return strdup(p->pw_name);
2852 if (asprintf(&r, UID_FMT, uid) < 0)
2858 char* gid_to_name(gid_t gid) {
2863 return strdup("root");
2867 return strdup(p->gr_name);
2869 if (asprintf(&r, GID_FMT, gid) < 0)
2875 int get_group_creds(const char **groupname, gid_t *gid) {
2881 /* We enforce some special rules for gid=0: in order to avoid
2882 * NSS lookups for root we hardcode its data. */
2884 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2885 *groupname = "root";
2893 if (parse_gid(*groupname, &id) >= 0) {
2898 *groupname = g->gr_name;
2901 g = getgrnam(*groupname);
2905 return errno > 0 ? -errno : -ESRCH;
2913 int in_gid(gid_t gid) {
2915 int ngroups_max, r, i;
2917 if (getgid() == gid)
2920 if (getegid() == gid)
2923 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2924 assert(ngroups_max > 0);
2926 gids = alloca(sizeof(gid_t) * ngroups_max);
2928 r = getgroups(ngroups_max, gids);
2932 for (i = 0; i < r; i++)
2939 int in_group(const char *name) {
2943 r = get_group_creds(&name, &gid);
2950 int glob_exists(const char *path) {
2951 _cleanup_globfree_ glob_t g = {};
2957 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2959 if (k == GLOB_NOMATCH)
2961 else if (k == GLOB_NOSPACE)
2964 return !strv_isempty(g.gl_pathv);
2966 return errno ? -errno : -EIO;
2969 int glob_extend(char ***strv, const char *path) {
2970 _cleanup_globfree_ glob_t g = {};
2975 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2977 if (k == GLOB_NOMATCH)
2979 else if (k == GLOB_NOSPACE)
2981 else if (k != 0 || strv_isempty(g.gl_pathv))
2982 return errno ? -errno : -EIO;
2984 STRV_FOREACH(p, g.gl_pathv) {
2985 k = strv_extend(strv, *p);
2993 int dirent_ensure_type(DIR *d, struct dirent *de) {
2999 if (de->d_type != DT_UNKNOWN)
3002 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3006 S_ISREG(st.st_mode) ? DT_REG :
3007 S_ISDIR(st.st_mode) ? DT_DIR :
3008 S_ISLNK(st.st_mode) ? DT_LNK :
3009 S_ISFIFO(st.st_mode) ? DT_FIFO :
3010 S_ISSOCK(st.st_mode) ? DT_SOCK :
3011 S_ISCHR(st.st_mode) ? DT_CHR :
3012 S_ISBLK(st.st_mode) ? DT_BLK :
3018 int get_files_in_directory(const char *path, char ***list) {
3019 _cleanup_closedir_ DIR *d = NULL;
3020 size_t bufsize = 0, n = 0;
3021 _cleanup_strv_free_ char **l = NULL;
3025 /* Returns all files in a directory in *list, and the number
3026 * of files as return value. If list is NULL returns only the
3038 if (!de && errno != 0)
3043 dirent_ensure_type(d, de);
3045 if (!dirent_is_file(de))
3049 /* one extra slot is needed for the terminating NULL */
3050 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3053 l[n] = strdup(de->d_name);
3064 l = NULL; /* avoid freeing */
3070 char *strjoin(const char *x, ...) {
3084 t = va_arg(ap, const char *);
3089 if (n > ((size_t) -1) - l) {
3113 t = va_arg(ap, const char *);
3127 bool is_main_thread(void) {
3128 static thread_local int cached = 0;
3130 if (_unlikely_(cached == 0))
3131 cached = getpid() == gettid() ? 1 : -1;
3136 int block_get_whole_disk(dev_t d, dev_t *ret) {
3143 /* If it has a queue this is good enough for us */
3144 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3147 r = access(p, F_OK);
3155 /* If it is a partition find the originating device */
3156 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3159 r = access(p, F_OK);
3165 /* Get parent dev_t */
3166 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3169 r = read_one_line_file(p, &s);
3175 r = sscanf(s, "%u:%u", &m, &n);
3181 /* Only return this if it is really good enough for us. */
3182 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3185 r = access(p, F_OK);
3189 *ret = makedev(m, n);
3196 static const char *const ioprio_class_table[] = {
3197 [IOPRIO_CLASS_NONE] = "none",
3198 [IOPRIO_CLASS_RT] = "realtime",
3199 [IOPRIO_CLASS_BE] = "best-effort",
3200 [IOPRIO_CLASS_IDLE] = "idle"
3203 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3205 static const char *const sigchld_code_table[] = {
3206 [CLD_EXITED] = "exited",
3207 [CLD_KILLED] = "killed",
3208 [CLD_DUMPED] = "dumped",
3209 [CLD_TRAPPED] = "trapped",
3210 [CLD_STOPPED] = "stopped",
3211 [CLD_CONTINUED] = "continued",
3214 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3216 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3217 [LOG_FAC(LOG_KERN)] = "kern",
3218 [LOG_FAC(LOG_USER)] = "user",
3219 [LOG_FAC(LOG_MAIL)] = "mail",
3220 [LOG_FAC(LOG_DAEMON)] = "daemon",
3221 [LOG_FAC(LOG_AUTH)] = "auth",
3222 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3223 [LOG_FAC(LOG_LPR)] = "lpr",
3224 [LOG_FAC(LOG_NEWS)] = "news",
3225 [LOG_FAC(LOG_UUCP)] = "uucp",
3226 [LOG_FAC(LOG_CRON)] = "cron",
3227 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3228 [LOG_FAC(LOG_FTP)] = "ftp",
3229 [LOG_FAC(LOG_LOCAL0)] = "local0",
3230 [LOG_FAC(LOG_LOCAL1)] = "local1",
3231 [LOG_FAC(LOG_LOCAL2)] = "local2",
3232 [LOG_FAC(LOG_LOCAL3)] = "local3",
3233 [LOG_FAC(LOG_LOCAL4)] = "local4",
3234 [LOG_FAC(LOG_LOCAL5)] = "local5",
3235 [LOG_FAC(LOG_LOCAL6)] = "local6",
3236 [LOG_FAC(LOG_LOCAL7)] = "local7"
3239 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3241 static const char *const log_level_table[] = {
3242 [LOG_EMERG] = "emerg",
3243 [LOG_ALERT] = "alert",
3244 [LOG_CRIT] = "crit",
3246 [LOG_WARNING] = "warning",
3247 [LOG_NOTICE] = "notice",
3248 [LOG_INFO] = "info",
3249 [LOG_DEBUG] = "debug"
3252 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3254 static const char* const sched_policy_table[] = {
3255 [SCHED_OTHER] = "other",
3256 [SCHED_BATCH] = "batch",
3257 [SCHED_IDLE] = "idle",
3258 [SCHED_FIFO] = "fifo",
3262 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3264 static const char* const rlimit_table[_RLIMIT_MAX] = {
3265 [RLIMIT_CPU] = "LimitCPU",
3266 [RLIMIT_FSIZE] = "LimitFSIZE",
3267 [RLIMIT_DATA] = "LimitDATA",
3268 [RLIMIT_STACK] = "LimitSTACK",
3269 [RLIMIT_CORE] = "LimitCORE",
3270 [RLIMIT_RSS] = "LimitRSS",
3271 [RLIMIT_NOFILE] = "LimitNOFILE",
3272 [RLIMIT_AS] = "LimitAS",
3273 [RLIMIT_NPROC] = "LimitNPROC",
3274 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3275 [RLIMIT_LOCKS] = "LimitLOCKS",
3276 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3277 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3278 [RLIMIT_NICE] = "LimitNICE",
3279 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3280 [RLIMIT_RTTIME] = "LimitRTTIME"
3283 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3285 static const char* const ip_tos_table[] = {
3286 [IPTOS_LOWDELAY] = "low-delay",
3287 [IPTOS_THROUGHPUT] = "throughput",
3288 [IPTOS_RELIABILITY] = "reliability",
3289 [IPTOS_LOWCOST] = "low-cost",
3292 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3294 static const char *const __signal_table[] = {
3311 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3322 [SIGVTALRM] = "VTALRM",
3324 [SIGWINCH] = "WINCH",
3330 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3332 const char *signal_to_string(int signo) {
3333 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3336 name = __signal_to_string(signo);
3340 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3341 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3343 snprintf(buf, sizeof(buf), "%d", signo);
3348 int signal_from_string(const char *s) {
3353 signo = __signal_from_string(s);
3357 if (startswith(s, "RTMIN+")) {
3361 if (safe_atou(s, &u) >= 0) {
3362 signo = (int) u + offset;
3363 if (signo > 0 && signo < _NSIG)
3369 bool kexec_loaded(void) {
3370 bool loaded = false;
3373 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3381 int prot_from_flags(int flags) {
3383 switch (flags & O_ACCMODE) {
3392 return PROT_READ|PROT_WRITE;
3399 char *format_bytes(char *buf, size_t l, off_t t) {
3402 static const struct {
3406 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3407 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3408 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3409 { "G", 1024ULL*1024ULL*1024ULL },
3410 { "M", 1024ULL*1024ULL },
3414 if (t == (off_t) -1)
3417 for (i = 0; i < ELEMENTSOF(table); i++) {
3419 if (t >= table[i].factor) {
3422 (unsigned long long) (t / table[i].factor),
3423 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3430 snprintf(buf, l, "%lluB", (unsigned long long) t);
3438 void* memdup(const void *p, size_t l) {
3451 int fd_inc_sndbuf(int fd, size_t n) {
3453 socklen_t l = sizeof(value);
3455 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3456 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3459 /* If we have the privileges we will ignore the kernel limit. */
3462 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3463 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3469 int fd_inc_rcvbuf(int fd, size_t n) {
3471 socklen_t l = sizeof(value);
3473 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3474 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3477 /* If we have the privileges we will ignore the kernel limit. */
3480 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3481 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3486 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3487 bool stdout_is_tty, stderr_is_tty;
3488 pid_t parent_pid, agent_pid;
3489 sigset_t ss, saved_ss;
3497 /* Spawns a temporary TTY agent, making sure it goes away when
3500 parent_pid = getpid();
3502 /* First we temporarily block all signals, so that the new
3503 * child has them blocked initially. This way, we can be sure
3504 * that SIGTERMs are not lost we might send to the agent. */
3505 assert_se(sigfillset(&ss) >= 0);
3506 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3509 if (agent_pid < 0) {
3510 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3514 if (agent_pid != 0) {
3515 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3522 * Make sure the agent goes away when the parent dies */
3523 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3524 _exit(EXIT_FAILURE);
3526 /* Make sure we actually can kill the agent, if we need to, in
3527 * case somebody invoked us from a shell script that trapped
3528 * SIGTERM or so... */
3529 reset_all_signal_handlers();
3530 reset_signal_mask();
3532 /* Check whether our parent died before we were able
3533 * to set the death signal and unblock the signals */
3534 if (getppid() != parent_pid)
3535 _exit(EXIT_SUCCESS);
3537 /* Don't leak fds to the agent */
3538 close_all_fds(except, n_except);
3540 stdout_is_tty = isatty(STDOUT_FILENO);
3541 stderr_is_tty = isatty(STDERR_FILENO);
3543 if (!stdout_is_tty || !stderr_is_tty) {
3546 /* Detach from stdout/stderr. and reopen
3547 * /dev/tty for them. This is important to
3548 * ensure that when systemctl is started via
3549 * popen() or a similar call that expects to
3550 * read EOF we actually do generate EOF and
3551 * not delay this indefinitely by because we
3552 * keep an unused copy of stdin around. */
3553 fd = open("/dev/tty", O_WRONLY);
3555 log_error_errno(errno, "Failed to open /dev/tty: %m");
3556 _exit(EXIT_FAILURE);
3560 dup2(fd, STDOUT_FILENO);
3563 dup2(fd, STDERR_FILENO);
3569 /* Count arguments */
3571 for (n = 0; va_arg(ap, char*); n++)
3576 l = alloca(sizeof(char *) * (n + 1));
3578 /* Fill in arguments */
3580 for (i = 0; i <= n; i++)
3581 l[i] = va_arg(ap, char*);
3585 _exit(EXIT_FAILURE);
3588 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3589 struct rlimit highest, fixed;
3593 if (setrlimit(resource, rlim) >= 0)
3599 /* So we failed to set the desired setrlimit, then let's try
3600 * to get as close as we can */
3601 assert_se(getrlimit(resource, &highest) == 0);
3603 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3604 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3606 if (setrlimit(resource, &fixed) < 0)
3612 bool http_etag_is_valid(const char *etag) {
3616 if (!endswith(etag, "\""))
3619 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3625 bool http_url_is_valid(const char *url) {
3631 p = startswith(url, "http://");
3633 p = startswith(url, "https://");
3640 return ascii_is_valid(p);
3643 bool documentation_url_is_valid(const char *url) {
3649 if (http_url_is_valid(url))
3652 p = startswith(url, "file:/");
3654 p = startswith(url, "info:");
3656 p = startswith(url, "man:");
3661 return ascii_is_valid(p);
3664 bool in_initrd(void) {
3665 static int saved = -1;
3671 /* We make two checks here:
3673 * 1. the flag file /etc/initrd-release must exist
3674 * 2. the root file system must be a memory file system
3676 * The second check is extra paranoia, since misdetecting an
3677 * initrd can have bad bad consequences due the initrd
3678 * emptying when transititioning to the main systemd.
3681 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3682 statfs("/", &s) >= 0 &&
3683 is_temporary_fs(&s);
3688 int get_home_dir(char **_h) {
3696 /* Take the user specified one */
3697 e = secure_getenv("HOME");
3698 if (e && path_is_absolute(e)) {
3707 /* Hardcode home directory for root to avoid NSS */
3710 h = strdup("/root");
3718 /* Check the database... */
3722 return errno > 0 ? -errno : -ESRCH;
3724 if (!path_is_absolute(p->pw_dir))
3727 h = strdup(p->pw_dir);
3735 int get_shell(char **_s) {
3743 /* Take the user specified one */
3744 e = getenv("SHELL");
3754 /* Hardcode home directory for root to avoid NSS */
3757 s = strdup("/bin/sh");
3765 /* Check the database... */
3769 return errno > 0 ? -errno : -ESRCH;
3771 if (!path_is_absolute(p->pw_shell))
3774 s = strdup(p->pw_shell);
3782 bool filename_is_valid(const char *p) {
3796 if (strlen(p) > FILENAME_MAX)
3802 bool string_is_safe(const char *p) {
3808 for (t = p; *t; t++) {
3809 if (*t > 0 && *t < ' ')
3812 if (strchr("\\\"\'\0x7f", *t))
3820 * Check if a string contains control characters. If 'ok' is non-NULL
3821 * it may be a string containing additional CCs to be considered OK.
3823 bool string_has_cc(const char *p, const char *ok) {
3828 for (t = p; *t; t++) {
3829 if (ok && strchr(ok, *t))
3832 if (*t > 0 && *t < ' ')
3842 bool path_is_safe(const char *p) {
3847 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3850 if (strlen(p)+1 > PATH_MAX)
3853 /* The following two checks are not really dangerous, but hey, they still are confusing */
3854 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3857 if (strstr(p, "//"))
3863 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3864 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3865 int (*compar) (const void *, const void *, void *), void *arg) {
3874 p = (void *)(((const char *) base) + (idx * size));
3875 comparison = compar(key, p, arg);
3878 else if (comparison > 0)
3886 void init_gettext(void) {
3887 setlocale(LC_ALL, "");
3888 textdomain(GETTEXT_PACKAGE);
3891 bool is_locale_utf8(void) {
3893 static int cached_answer = -1;
3895 if (cached_answer >= 0)
3898 if (!setlocale(LC_ALL, "")) {
3899 cached_answer = true;
3903 set = nl_langinfo(CODESET);
3905 cached_answer = true;
3909 if (streq(set, "UTF-8")) {
3910 cached_answer = true;
3914 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3915 * unset and everything can do to UTF-8 nowadays. */
3916 set = setlocale(LC_CTYPE, NULL);
3918 cached_answer = true;
3922 /* Check result, but ignore the result if C was set
3926 !getenv("LC_ALL") &&
3927 !getenv("LC_CTYPE") &&
3931 return (bool) cached_answer;
3934 const char *draw_special_char(DrawSpecialChar ch) {
3935 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
3938 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
3939 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
3940 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
3941 [DRAW_TREE_SPACE] = " ", /* */
3942 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
3943 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
3944 [DRAW_ARROW] = "\342\206\222", /* → */
3945 [DRAW_DASH] = "\342\200\223", /* – */
3948 /* ASCII fallback */ {
3949 [DRAW_TREE_VERTICAL] = "| ",
3950 [DRAW_TREE_BRANCH] = "|-",
3951 [DRAW_TREE_RIGHT] = "`-",
3952 [DRAW_TREE_SPACE] = " ",
3953 [DRAW_TRIANGULAR_BULLET] = ">",
3954 [DRAW_BLACK_CIRCLE] = "*",
3955 [DRAW_ARROW] = "->",
3960 return draw_table[!is_locale_utf8()][ch];
3963 char *strreplace(const char *text, const char *old_string, const char *new_string) {
3966 size_t l, old_len, new_len;
3972 old_len = strlen(old_string);
3973 new_len = strlen(new_string);
3986 if (!startswith(f, old_string)) {
3992 nl = l - old_len + new_len;
3993 a = realloc(r, nl + 1);
4001 t = stpcpy(t, new_string);
4013 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4014 const char *i, *begin = NULL;
4019 } state = STATE_OTHER;
4021 size_t osz = 0, isz;
4027 /* Strips ANSI color and replaces TABs by 8 spaces */
4029 isz = _isz ? *_isz : strlen(*ibuf);
4031 f = open_memstream(&obuf, &osz);
4035 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4040 if (i >= *ibuf + isz) /* EOT */
4042 else if (*i == '\x1B')
4043 state = STATE_ESCAPE;
4044 else if (*i == '\t')
4051 if (i >= *ibuf + isz) { /* EOT */
4054 } else if (*i == '[') {
4055 state = STATE_BRACKET;
4060 state = STATE_OTHER;
4067 if (i >= *ibuf + isz || /* EOT */
4068 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4071 state = STATE_OTHER;
4073 } else if (*i == 'm')
4074 state = STATE_OTHER;
4096 int on_ac_power(void) {
4097 bool found_offline = false, found_online = false;
4098 _cleanup_closedir_ DIR *d = NULL;
4100 d = opendir("/sys/class/power_supply");
4102 return errno == ENOENT ? true : -errno;
4106 _cleanup_close_ int fd = -1, device = -1;
4112 if (!de && errno != 0)
4118 if (hidden_file(de->d_name))
4121 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4123 if (errno == ENOENT || errno == ENOTDIR)
4129 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4131 if (errno == ENOENT)
4137 n = read(fd, contents, sizeof(contents));
4141 if (n != 6 || memcmp(contents, "Mains\n", 6))
4145 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4147 if (errno == ENOENT)
4153 n = read(fd, contents, sizeof(contents));
4157 if (n != 2 || contents[1] != '\n')
4160 if (contents[0] == '1') {
4161 found_online = true;
4163 } else if (contents[0] == '0')
4164 found_offline = true;
4169 return found_online || !found_offline;
4172 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4179 if (!path_strv_resolve_uniq(search, root))
4182 STRV_FOREACH(i, search) {
4183 _cleanup_free_ char *p = NULL;
4187 p = strjoin(root, *i, "/", path, NULL);
4189 p = strjoin(*i, "/", path, NULL);
4199 if (errno != ENOENT)
4206 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4207 _cleanup_strv_free_ char **copy = NULL;
4213 if (path_is_absolute(path)) {
4216 f = fopen(path, mode);
4225 copy = strv_copy((char**) search);
4229 return search_and_fopen_internal(path, mode, root, copy, _f);
4232 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4233 _cleanup_strv_free_ char **s = NULL;
4235 if (path_is_absolute(path)) {
4238 f = fopen(path, mode);
4247 s = strv_split_nulstr(search);
4251 return search_and_fopen_internal(path, mode, root, s, _f);
4254 char *strextend(char **x, ...) {
4261 l = f = *x ? strlen(*x) : 0;
4268 t = va_arg(ap, const char *);
4273 if (n > ((size_t) -1) - l) {
4282 r = realloc(*x, l+1);
4292 t = va_arg(ap, const char *);
4306 char *strrep(const char *s, unsigned n) {
4314 p = r = malloc(l * n + 1);
4318 for (i = 0; i < n; i++)
4325 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4332 if (*allocated >= need)
4335 newalloc = MAX(need * 2, 64u / size);
4336 a = newalloc * size;
4338 /* check for overflows */
4339 if (a < size * need)
4347 *allocated = newalloc;
4351 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4360 q = greedy_realloc(p, allocated, need, size);
4364 if (*allocated > prev)
4365 memzero(q + prev * size, (*allocated - prev) * size);
4370 bool id128_is_valid(const char *s) {
4376 /* Simple formatted 128bit hex string */
4378 for (i = 0; i < l; i++) {
4381 if (!(c >= '0' && c <= '9') &&
4382 !(c >= 'a' && c <= 'z') &&
4383 !(c >= 'A' && c <= 'Z'))
4387 } else if (l == 36) {
4389 /* Formatted UUID */
4391 for (i = 0; i < l; i++) {
4394 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4398 if (!(c >= '0' && c <= '9') &&
4399 !(c >= 'a' && c <= 'z') &&
4400 !(c >= 'A' && c <= 'Z'))
4411 int split_pair(const char *s, const char *sep, char **l, char **r) {
4426 a = strndup(s, x - s);
4430 b = strdup(x + strlen(sep));
4442 int shall_restore_state(void) {
4443 _cleanup_free_ char *value = NULL;
4446 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4452 return parse_boolean(value) != 0;
4455 int proc_cmdline(char **ret) {
4458 if (detect_container(NULL) > 0)
4459 return get_process_cmdline(1, 0, false, ret);
4461 return read_one_line_file("/proc/cmdline", ret);
4464 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4465 _cleanup_free_ char *line = NULL;
4471 r = proc_cmdline(&line);
4477 _cleanup_free_ char *word = NULL;
4480 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4486 /* Filter out arguments that are intended only for the
4488 if (!in_initrd() && startswith(word, "rd."))
4491 value = strchr(word, '=');
4495 r = parse_item(word, value);
4503 int get_proc_cmdline_key(const char *key, char **value) {
4504 _cleanup_free_ char *line = NULL, *ret = NULL;
4511 r = proc_cmdline(&line);
4517 _cleanup_free_ char *word = NULL;
4520 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4526 /* Filter out arguments that are intended only for the
4528 if (!in_initrd() && startswith(word, "rd."))
4532 e = startswith(word, key);
4536 r = free_and_strdup(&ret, e);
4542 if (streq(word, key))
4556 int container_get_leader(const char *machine, pid_t *pid) {
4557 _cleanup_free_ char *s = NULL, *class = NULL;
4565 p = strjoina("/run/systemd/machines/", machine);
4566 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4574 if (!streq_ptr(class, "container"))
4577 r = parse_pid(s, &leader);
4587 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4588 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4596 mntns = procfs_file_alloca(pid, "ns/mnt");
4597 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4605 pidns = procfs_file_alloca(pid, "ns/pid");
4606 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4614 netns = procfs_file_alloca(pid, "ns/net");
4615 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4623 root = procfs_file_alloca(pid, "root");
4624 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4630 *pidns_fd = pidnsfd;
4633 *mntns_fd = mntnsfd;
4636 *netns_fd = netnsfd;
4641 pidnsfd = mntnsfd = netnsfd = -1;
4646 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4649 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4653 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4657 if (setns(netns_fd, CLONE_NEWNET) < 0)
4661 if (fchdir(root_fd) < 0)
4664 if (chroot(".") < 0)
4668 return reset_uid_gid();
4671 int getpeercred(int fd, struct ucred *ucred) {
4672 socklen_t n = sizeof(struct ucred);
4679 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4683 if (n != sizeof(struct ucred))
4686 /* Check if the data is actually useful and not suppressed due
4687 * to namespacing issues */
4690 if (u.uid == UID_INVALID)
4692 if (u.gid == GID_INVALID)
4699 int getpeersec(int fd, char **ret) {
4711 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4715 if (errno != ERANGE)
4722 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4738 /* This is much like like mkostemp() but is subject to umask(). */
4739 int mkostemp_safe(char *pattern, int flags) {
4740 _cleanup_umask_ mode_t u;
4747 fd = mkostemp(pattern, flags);
4754 int open_tmpfile(const char *path, int flags) {
4761 /* Try O_TMPFILE first, if it is supported */
4762 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4767 /* Fall back to unguessable name + unlinking */
4768 p = strjoina(path, "/systemd-tmp-XXXXXX");
4770 fd = mkostemp_safe(p, flags);
4778 int fd_warn_permissions(const char *path, int fd) {
4781 if (fstat(fd, &st) < 0)
4784 if (st.st_mode & 0111)
4785 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4787 if (st.st_mode & 0002)
4788 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4790 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4791 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
4796 unsigned long personality_from_string(const char *p) {
4798 /* Parse a personality specifier. We introduce our own
4799 * identifiers that indicate specific ABIs, rather than just
4800 * hints regarding the register size, since we want to keep
4801 * things open for multiple locally supported ABIs for the
4802 * same register size. We try to reuse the ABI identifiers
4803 * used by libseccomp. */
4805 #if defined(__x86_64__)
4807 if (streq(p, "x86"))
4810 if (streq(p, "x86-64"))
4813 #elif defined(__i386__)
4815 if (streq(p, "x86"))
4819 return PERSONALITY_INVALID;
4822 const char* personality_to_string(unsigned long p) {
4824 #if defined(__x86_64__)
4826 if (p == PER_LINUX32)
4832 #elif defined(__i386__)
4841 uint64_t physical_memory(void) {
4844 /* We return this as uint64_t in case we are running as 32bit
4845 * process on a 64bit kernel with huge amounts of memory */
4847 mem = sysconf(_SC_PHYS_PAGES);
4850 return (uint64_t) mem * (uint64_t) page_size();
4853 void hexdump(FILE *f, const void *p, size_t s) {
4854 const uint8_t *b = p;
4857 assert(s == 0 || b);
4862 fprintf(f, "%04x ", n);
4864 for (i = 0; i < 16; i++) {
4869 fprintf(f, "%02x ", b[i]);
4877 for (i = 0; i < 16; i++) {
4882 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4896 int update_reboot_param_file(const char *param) {
4901 r = write_string_file(REBOOT_PARAM_FILE, param);
4903 log_error("Failed to write reboot param to "
4904 REBOOT_PARAM_FILE": %s", strerror(-r));
4906 unlink(REBOOT_PARAM_FILE);
4911 int umount_recursive(const char *prefix, int flags) {
4915 /* Try to umount everything recursively below a
4916 * directory. Also, take care of stacked mounts, and keep
4917 * unmounting them until they are gone. */
4920 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4925 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4926 if (!proc_self_mountinfo)
4930 _cleanup_free_ char *path = NULL, *p = NULL;
4933 k = fscanf(proc_self_mountinfo,
4934 "%*s " /* (1) mount id */
4935 "%*s " /* (2) parent id */
4936 "%*s " /* (3) major:minor */
4937 "%*s " /* (4) root */
4938 "%ms " /* (5) mount point */
4939 "%*s" /* (6) mount options */
4940 "%*[^-]" /* (7) optional fields */
4941 "- " /* (8) separator */
4942 "%*s " /* (9) file system type */
4943 "%*s" /* (10) mount source */
4944 "%*s" /* (11) mount options 2 */
4945 "%*[^\n]", /* some rubbish at the end */
4954 r = cunescape(path, UNESCAPE_RELAX, &p);
4958 if (!path_startswith(p, prefix))
4961 if (umount2(p, flags) < 0) {
4977 static int get_mount_flags(const char *path, unsigned long *flags) {
4980 if (statvfs(path, &buf) < 0)
4982 *flags = buf.f_flag;
4986 int bind_remount_recursive(const char *prefix, bool ro) {
4987 _cleanup_set_free_free_ Set *done = NULL;
4988 _cleanup_free_ char *cleaned = NULL;
4991 /* Recursively remount a directory (and all its submounts)
4992 * read-only or read-write. If the directory is already
4993 * mounted, we reuse the mount and simply mark it
4994 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4995 * operation). If it isn't we first make it one. Afterwards we
4996 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4997 * submounts we can access, too. When mounts are stacked on
4998 * the same mount point we only care for each individual
4999 * "top-level" mount on each point, as we cannot
5000 * influence/access the underlying mounts anyway. We do not
5001 * have any effect on future submounts that might get
5002 * propagated, they migt be writable. This includes future
5003 * submounts that have been triggered via autofs. */
5005 cleaned = strdup(prefix);
5009 path_kill_slashes(cleaned);
5011 done = set_new(&string_hash_ops);
5016 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5017 _cleanup_set_free_free_ Set *todo = NULL;
5018 bool top_autofs = false;
5020 unsigned long orig_flags;
5022 todo = set_new(&string_hash_ops);
5026 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5027 if (!proc_self_mountinfo)
5031 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5034 k = fscanf(proc_self_mountinfo,
5035 "%*s " /* (1) mount id */
5036 "%*s " /* (2) parent id */
5037 "%*s " /* (3) major:minor */
5038 "%*s " /* (4) root */
5039 "%ms " /* (5) mount point */
5040 "%*s" /* (6) mount options (superblock) */
5041 "%*[^-]" /* (7) optional fields */
5042 "- " /* (8) separator */
5043 "%ms " /* (9) file system type */
5044 "%*s" /* (10) mount source */
5045 "%*s" /* (11) mount options (bind mount) */
5046 "%*[^\n]", /* some rubbish at the end */
5056 r = cunescape(path, UNESCAPE_RELAX, &p);
5060 /* Let's ignore autofs mounts. If they aren't
5061 * triggered yet, we want to avoid triggering
5062 * them, as we don't make any guarantees for
5063 * future submounts anyway. If they are
5064 * already triggered, then we will find
5065 * another entry for this. */
5066 if (streq(type, "autofs")) {
5067 top_autofs = top_autofs || path_equal(cleaned, p);
5071 if (path_startswith(p, cleaned) &&
5072 !set_contains(done, p)) {
5074 r = set_consume(todo, p);
5084 /* If we have no submounts to process anymore and if
5085 * the root is either already done, or an autofs, we
5087 if (set_isempty(todo) &&
5088 (top_autofs || set_contains(done, cleaned)))
5091 if (!set_contains(done, cleaned) &&
5092 !set_contains(todo, cleaned)) {
5093 /* The prefix directory itself is not yet a
5094 * mount, make it one. */
5095 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5099 (void) get_mount_flags(cleaned, &orig_flags);
5100 orig_flags &= ~MS_RDONLY;
5102 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5105 x = strdup(cleaned);
5109 r = set_consume(done, x);
5114 while ((x = set_steal_first(todo))) {
5116 r = set_consume(done, x);
5122 /* Try to reuse the original flag set, but
5123 * don't care for errors, in case of
5124 * obstructed mounts */
5126 (void) get_mount_flags(x, &orig_flags);
5127 orig_flags &= ~MS_RDONLY;
5129 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5131 /* Deal with mount points that are
5132 * obstructed by a later mount */
5134 if (errno != ENOENT)
5142 int fflush_and_check(FILE *f) {
5149 return errno ? -errno : -EIO;
5154 int tempfn_xxxxxx(const char *p, char **ret) {
5166 * /foo/bar/.#waldoXXXXXX
5170 if (!filename_is_valid(fn))
5173 t = new(char, strlen(p) + 2 + 6 + 1);
5177 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5179 *ret = path_kill_slashes(t);
5183 int tempfn_random(const char *p, char **ret) {
5197 * /foo/bar/.#waldobaa2a261115984a9
5201 if (!filename_is_valid(fn))
5204 t = new(char, strlen(p) + 2 + 16 + 1);
5208 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5211 for (i = 0; i < 16; i++) {
5212 *(x++) = hexchar(u & 0xF);
5218 *ret = path_kill_slashes(t);
5222 int tempfn_random_child(const char *p, char **ret) {
5233 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5236 t = new(char, strlen(p) + 3 + 16 + 1);
5240 x = stpcpy(stpcpy(t, p), "/.#");
5243 for (i = 0; i < 16; i++) {
5244 *(x++) = hexchar(u & 0xF);
5250 *ret = path_kill_slashes(t);
5254 int take_password_lock(const char *root) {
5256 struct flock flock = {
5258 .l_whence = SEEK_SET,
5266 /* This is roughly the same as lckpwdf(), but not as awful. We
5267 * don't want to use alarm() and signals, hence we implement
5268 * our own trivial version of this.
5270 * Note that shadow-utils also takes per-database locks in
5271 * addition to lckpwdf(). However, we don't given that they
5272 * are redundant as they they invoke lckpwdf() first and keep
5273 * it during everything they do. The per-database locks are
5274 * awfully racy, and thus we just won't do them. */
5277 path = strjoina(root, "/etc/.pwd.lock");
5279 path = "/etc/.pwd.lock";
5281 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5285 r = fcntl(fd, F_SETLKW, &flock);
5294 int is_symlink(const char *path) {
5297 if (lstat(path, &info) < 0)
5300 return !!S_ISLNK(info.st_mode);
5303 int is_dir(const char* path, bool follow) {
5308 r = stat(path, &st);
5310 r = lstat(path, &st);
5314 return !!S_ISDIR(st.st_mode);
5317 int is_device_node(const char *path) {
5320 if (lstat(path, &info) < 0)
5323 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5326 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5327 _cleanup_free_ char *s = NULL;
5328 size_t allocated = 0, sz = 0;
5336 SINGLE_QUOTE_ESCAPE,
5338 DOUBLE_QUOTE_ESCAPE,
5346 /* Parses the first word of a string, and returns it in
5347 * *ret. Removes all quotes in the process. When parsing fails
5348 * (because of an uneven number of quotes or similar), leaves
5349 * the pointer *p at the first invalid character. */
5359 else if (strchr(WHITESPACE, c))
5369 state = SINGLE_QUOTE;
5371 state = VALUE_ESCAPE;
5373 state = DOUBLE_QUOTE;
5374 else if (strchr(WHITESPACE, c))
5377 if (!GREEDY_REALLOC(s, allocated, sz+2))
5387 if (flags & UNQUOTE_RELAX)
5392 if (!GREEDY_REALLOC(s, allocated, sz+7))
5395 if (flags & UNQUOTE_CUNESCAPE) {
5398 r = cunescape_one(*p, (size_t) -1, &c, &u);
5405 s[sz++] = c; /* normal explicit char */
5407 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5416 if (flags & UNQUOTE_RELAX)
5419 } else if (c == '\'')
5422 state = SINGLE_QUOTE_ESCAPE;
5424 if (!GREEDY_REALLOC(s, allocated, sz+2))
5432 case SINGLE_QUOTE_ESCAPE:
5434 if (flags & UNQUOTE_RELAX)
5439 if (!GREEDY_REALLOC(s, allocated, sz+7))
5442 if (flags & UNQUOTE_CUNESCAPE) {
5445 r = cunescape_one(*p, (size_t) -1, &c, &u);
5454 sz += utf8_encode_unichar(s + sz, u);
5458 state = SINGLE_QUOTE;
5467 state = DOUBLE_QUOTE_ESCAPE;
5469 if (!GREEDY_REALLOC(s, allocated, sz+2))
5477 case DOUBLE_QUOTE_ESCAPE:
5479 if (flags & UNQUOTE_RELAX)
5484 if (!GREEDY_REALLOC(s, allocated, sz+7))
5487 if (flags & UNQUOTE_CUNESCAPE) {
5490 r = cunescape_one(*p, (size_t) -1, &c, &u);
5499 sz += utf8_encode_unichar(s + sz, u);
5503 state = DOUBLE_QUOTE;
5509 if (!strchr(WHITESPACE, c))
5531 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5536 /* Parses a number of words from a string, stripping any
5537 * quotes if necessary. */
5541 /* Count how many words are expected */
5542 va_start(ap, flags);
5544 if (!va_arg(ap, char **))
5553 /* Read all words into a temporary array */
5554 l = newa0(char*, n);
5555 for (c = 0; c < n; c++) {
5557 r = unquote_first_word(p, &l[c], flags);
5561 for (j = 0; j < c; j++)
5571 /* If we managed to parse all words, return them in the passed
5573 va_start(ap, flags);
5574 for (i = 0; i < n; i++) {
5577 v = va_arg(ap, char **);
5587 int free_and_strdup(char **p, const char *s) {
5592 /* Replaces a string pointer with an strdup()ed new string,
5593 * possibly freeing the old one. */
5595 if (streq_ptr(*p, s))
5611 int ptsname_malloc(int fd, char **ret) {
5624 if (ptsname_r(fd, c, l) == 0) {
5628 if (errno != ERANGE) {
5638 int openpt_in_namespace(pid_t pid, int flags) {
5639 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5640 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5642 struct cmsghdr cmsghdr;
5643 uint8_t buf[CMSG_SPACE(sizeof(int))];
5645 struct msghdr mh = {
5646 .msg_control = &control,
5647 .msg_controllen = sizeof(control),
5649 struct cmsghdr *cmsg;
5656 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5660 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5670 pair[0] = safe_close(pair[0]);
5672 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5674 _exit(EXIT_FAILURE);
5676 master = posix_openpt(flags);
5678 _exit(EXIT_FAILURE);
5680 cmsg = CMSG_FIRSTHDR(&mh);
5681 cmsg->cmsg_level = SOL_SOCKET;
5682 cmsg->cmsg_type = SCM_RIGHTS;
5683 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5684 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5686 mh.msg_controllen = cmsg->cmsg_len;
5688 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5689 _exit(EXIT_FAILURE);
5691 _exit(EXIT_SUCCESS);
5694 pair[1] = safe_close(pair[1]);
5696 r = wait_for_terminate(child, &si);
5699 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5702 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5705 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5706 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5710 fds = (int*) CMSG_DATA(cmsg);
5711 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5714 close_many(fds, n_fds);
5724 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5725 _cleanup_close_ int fd = -1;
5728 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5730 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5734 l = fgetxattr(fd, attribute, value, size);
5741 static int parse_crtime(le64_t le, usec_t *usec) {
5747 if (u == 0 || u == (uint64_t) -1)
5754 int fd_getcrtime(int fd, usec_t *usec) {
5761 /* Until Linux gets a real concept of birthtime/creation time,
5762 * let's fake one with xattrs */
5764 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5767 if (n != sizeof(le))
5770 return parse_crtime(le, usec);
5773 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5777 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5780 if (n != sizeof(le))
5783 return parse_crtime(le, usec);
5786 int path_getcrtime(const char *p, usec_t *usec) {
5793 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5796 if (n != sizeof(le))
5799 return parse_crtime(le, usec);
5802 int fd_setcrtime(int fd, usec_t usec) {
5808 usec = now(CLOCK_REALTIME);
5810 le = htole64((uint64_t) usec);
5811 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5817 int same_fd(int a, int b) {
5818 struct stat sta, stb;
5825 /* Compares two file descriptors. Note that semantics are
5826 * quite different depending on whether we have kcmp() or we
5827 * don't. If we have kcmp() this will only return true for
5828 * dup()ed file descriptors, but not otherwise. If we don't
5829 * have kcmp() this will also return true for two fds of the same
5830 * file, created by separate open() calls. Since we use this
5831 * call mostly for filtering out duplicates in the fd store
5832 * this difference hopefully doesn't matter too much. */
5837 /* Try to use kcmp() if we have it. */
5839 r = kcmp(pid, pid, KCMP_FILE, a, b);
5844 if (errno != ENOSYS)
5847 /* We don't have kcmp(), use fstat() instead. */
5848 if (fstat(a, &sta) < 0)
5851 if (fstat(b, &stb) < 0)
5854 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
5857 /* We consider all device fds different, since two device fds
5858 * might refer to quite different device contexts even though
5859 * they share the same inode and backing dev_t. */
5861 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
5864 if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
5867 /* The fds refer to the same inode on disk, let's also check
5868 * if they have the same fd flags. This is useful to
5869 * distinguish the read and write side of a pipe created with
5871 fa = fcntl(a, F_GETFL);
5875 fb = fcntl(b, F_GETFL);
5882 int chattr_fd(int fd, unsigned value, unsigned mask) {
5883 unsigned old_attr, new_attr;
5888 if (fstat(fd, &st) < 0)
5891 /* Explicitly check whether this is a regular file or
5892 * directory. If it is anything else (such as a device node or
5893 * fifo), then the ioctl will not hit the file systems but
5894 * possibly drivers, where the ioctl might have different
5895 * effects. Notably, DRM is using the same ioctl() number. */
5897 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5903 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5906 new_attr = (old_attr & ~mask) | (value & mask);
5907 if (new_attr == old_attr)
5910 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5916 int chattr_path(const char *p, unsigned value, unsigned mask) {
5917 _cleanup_close_ int fd = -1;
5924 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5928 return chattr_fd(fd, value, mask);
5931 int read_attr_fd(int fd, unsigned *ret) {
5936 if (fstat(fd, &st) < 0)
5939 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5942 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5948 int read_attr_path(const char *p, unsigned *ret) {
5949 _cleanup_close_ int fd = -1;
5954 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5958 return read_attr_fd(fd, ret);
5961 static size_t nul_length(const uint8_t *p, size_t sz) {
5976 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
5977 const uint8_t *q, *w, *e;
5985 n = nul_length(q, e - q);
5987 /* If there are more than the specified run length of
5988 * NUL bytes, or if this is the beginning or the end
5989 * of the buffer, then seek instead of write */
5990 if ((n > run_length) ||
5991 (n > 0 && q == p) ||
5992 (n > 0 && q + n >= e)) {
5994 l = write(fd, w, q - w);
6001 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6013 l = write(fd, w, q - w);
6020 return q - (const uint8_t*) p;
6023 void sigkill_wait(pid_t *pid) {
6029 if (kill(*pid, SIGKILL) > 0)
6030 (void) wait_for_terminate(*pid, NULL);
6033 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6034 int a = 0, b = 0, c = 0;
6044 if (!strchr(*p, '>'))
6047 if ((*p)[2] == '>') {
6048 c = undecchar((*p)[1]);
6050 } else if ((*p)[3] == '>') {
6051 b = undecchar((*p)[1]);
6052 c = undecchar((*p)[2]);
6054 } else if ((*p)[4] == '>') {
6055 a = undecchar((*p)[1]);
6056 b = undecchar((*p)[2]);
6057 c = undecchar((*p)[3]);
6062 if (a < 0 || b < 0 || c < 0 ||
6063 (!with_facility && (a || b || c > 7)))
6067 *priority = a*100 + b*10 + c;
6069 *priority = (*priority & LOG_FACMASK) | c;
6075 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6081 for (i = 0; i < len; ++i)
6082 if (streq_ptr(table[i], key))
6088 void cmsg_close_all(struct msghdr *mh) {
6089 struct cmsghdr *cmsg;
6093 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6094 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6095 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6098 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6102 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6106 /* Even though renameat2() exists since Linux 3.15, btrfs added
6107 * support for it later. If it is not implemented, fallback to another
6109 if (errno != EINVAL)
6112 /* The link()/unlink() fallback does not work on directories. But
6113 * renameat() without RENAME_NOREPLACE gives the same semantics on
6114 * directories, except when newpath is an *empty* directory. This is
6116 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6117 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6118 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6119 return ret >= 0 ? 0 : -errno;
6122 /* If it is not a directory, use the link()/unlink() fallback. */
6123 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6127 ret = unlinkat(olddirfd, oldpath, 0);
6129 /* backup errno before the following unlinkat() alters it */
6131 (void) unlinkat(newdirfd, newpath, 0);
6139 char *shell_maybe_quote(const char *s) {
6145 /* Encloses a string in double quotes if necessary to make it
6146 * OK as shell string. */
6148 for (p = s; *p; p++)
6151 strchr(SHELL_NEED_QUOTES, *p))
6157 r = new(char, 1+strlen(s)*2+1+1);
6163 t = mempcpy(t, s, p - s);
6167 if (strchr(SHELL_NEED_ESCAPE, *p))
6179 int parse_mode(const char *s, mode_t *ret) {
6187 l = strtol(s, &x, 8);
6191 if (!x || x == s || *x)
6193 if (l < 0 || l > 07777)
6200 int mount_move_root(const char *path) {
6203 if (chdir(path) < 0)
6206 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
6209 if (chroot(".") < 0)
6218 int reset_uid_gid(void) {
6220 if (setgroups(0, NULL) < 0)
6223 if (setresgid(0, 0, 0) < 0)
6226 if (setresuid(0, 0, 0) < 0)