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"
96 /* Put this test here for a lack of better place */
97 assert_cc(EAGAIN == EWOULDBLOCK);
100 char **saved_argv = NULL;
102 size_t page_size(void) {
103 static thread_local size_t pgsz = 0;
106 if (_likely_(pgsz > 0))
109 r = sysconf(_SC_PAGESIZE);
116 bool streq_ptr(const char *a, const char *b) {
118 /* Like streq(), but tries to make sense of NULL pointers */
129 char* endswith(const char *s, const char *postfix) {
136 pl = strlen(postfix);
139 return (char*) s + sl;
144 if (memcmp(s + sl - pl, postfix, pl) != 0)
147 return (char*) s + sl - pl;
150 char* first_word(const char *s, const char *word) {
157 /* Checks if the string starts with the specified word, either
158 * followed by NUL or by whitespace. Returns a pointer to the
159 * NUL or the first character after the whitespace. */
170 if (memcmp(s, word, wl) != 0)
177 if (!strchr(WHITESPACE, *p))
180 p += strspn(p, WHITESPACE);
184 size_t cescape_char(char c, char *buf) {
185 char * buf_old = buf;
231 /* For special chars we prefer octal over
232 * hexadecimal encoding, simply because glib's
233 * g_strescape() does the same */
234 if ((c < ' ') || (c >= 127)) {
236 *(buf++) = octchar((unsigned char) c >> 6);
237 *(buf++) = octchar((unsigned char) c >> 3);
238 *(buf++) = octchar((unsigned char) c);
244 return buf - buf_old;
247 int close_nointr(int fd) {
254 * Just ignore EINTR; a retry loop is the wrong thing to do on
257 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
258 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
259 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
260 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
268 int safe_close(int fd) {
271 * Like close_nointr() but cannot fail. Guarantees errno is
272 * unchanged. Is a NOP with negative fds passed, and returns
273 * -1, so that it can be used in this syntax:
275 * fd = safe_close(fd);
281 /* The kernel might return pretty much any error code
282 * via close(), but the fd will be closed anyway. The
283 * only condition we want to check for here is whether
284 * the fd was invalid at all... */
286 assert_se(close_nointr(fd) != -EBADF);
292 void close_many(const int fds[], unsigned n_fd) {
295 assert(fds || n_fd <= 0);
297 for (i = 0; i < n_fd; i++)
301 int unlink_noerrno(const char *path) {
312 int parse_boolean(const char *v) {
315 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
317 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
323 int parse_pid(const char *s, pid_t* ret_pid) {
324 unsigned long ul = 0;
331 r = safe_atolu(s, &ul);
337 if ((unsigned long) pid != ul)
347 int parse_uid(const char *s, uid_t* ret_uid) {
348 unsigned long ul = 0;
354 r = safe_atolu(s, &ul);
360 if ((unsigned long) uid != ul)
363 /* Some libc APIs use UID_INVALID as special placeholder */
364 if (uid == (uid_t) 0xFFFFFFFF)
367 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
368 if (uid == (uid_t) 0xFFFF)
377 int safe_atou(const char *s, unsigned *ret_u) {
385 l = strtoul(s, &x, 0);
387 if (!x || x == s || *x || errno)
388 return errno > 0 ? -errno : -EINVAL;
390 if ((unsigned long) (unsigned) l != l)
393 *ret_u = (unsigned) l;
397 int safe_atoi(const char *s, int *ret_i) {
405 l = strtol(s, &x, 0);
407 if (!x || x == s || *x || errno)
408 return errno > 0 ? -errno : -EINVAL;
410 if ((long) (int) l != l)
417 int safe_atou8(const char *s, uint8_t *ret) {
425 l = strtoul(s, &x, 0);
427 if (!x || x == s || *x || errno)
428 return errno > 0 ? -errno : -EINVAL;
430 if ((unsigned long) (uint8_t) l != l)
437 int safe_atou16(const char *s, uint16_t *ret) {
445 l = strtoul(s, &x, 0);
447 if (!x || x == s || *x || errno)
448 return errno > 0 ? -errno : -EINVAL;
450 if ((unsigned long) (uint16_t) l != l)
457 int safe_atoi16(const char *s, int16_t *ret) {
465 l = strtol(s, &x, 0);
467 if (!x || x == s || *x || errno)
468 return errno > 0 ? -errno : -EINVAL;
470 if ((long) (int16_t) l != l)
477 int safe_atollu(const char *s, long long unsigned *ret_llu) {
479 unsigned long long l;
485 l = strtoull(s, &x, 0);
487 if (!x || x == s || *x || errno)
488 return errno ? -errno : -EINVAL;
494 int safe_atolli(const char *s, long long int *ret_lli) {
502 l = strtoll(s, &x, 0);
504 if (!x || x == s || *x || errno)
505 return errno ? -errno : -EINVAL;
511 int safe_atod(const char *s, double *ret_d) {
519 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
520 if (loc == (locale_t) 0)
524 d = strtod_l(s, &x, loc);
526 if (!x || x == s || *x || errno) {
528 return errno ? -errno : -EINVAL;
536 static size_t strcspn_escaped(const char *s, const char *reject) {
537 bool escaped = false;
540 for (n=0; s[n]; n++) {
543 else if (s[n] == '\\')
545 else if (strchr(reject, s[n]))
549 /* if s ends in \, return index of previous char */
553 /* Split a string into words. */
554 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
560 assert(**state == '\0');
564 current += strspn(current, separator);
570 if (quoted && strchr("\'\"", *current)) {
571 char quotechars[2] = {*current, '\0'};
573 *l = strcspn_escaped(current + 1, quotechars);
574 if (current[*l + 1] == '\0' ||
575 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
576 /* right quote missing or garbage at the end */
580 assert(current[*l + 1] == quotechars[0]);
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;
1668 while (nbytes > 0) {
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 (k == 0) /* Can't really happen */
1698 int parse_size(const char *t, off_t base, off_t *size) {
1700 /* Soo, sometimes we want to parse IEC binary suffxies, 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)
1939 char* gethostname_malloc(void) {
1942 assert_se(uname(&u) >= 0);
1944 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
1945 return strdup(u.nodename);
1947 return strdup(u.sysname);
1950 bool hostname_is_set(void) {
1953 assert_se(uname(&u) >= 0);
1955 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
1958 char *lookup_uid(uid_t uid) {
1961 _cleanup_free_ char *buf = NULL;
1962 struct passwd pwbuf, *pw = NULL;
1964 /* Shortcut things to avoid NSS lookups */
1966 return strdup("root");
1968 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1972 buf = malloc(bufsize);
1976 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1977 return strdup(pw->pw_name);
1979 if (asprintf(&name, UID_FMT, uid) < 0)
1985 char* getlogname_malloc(void) {
1989 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1994 return lookup_uid(uid);
1997 char *getusername_malloc(void) {
2004 return lookup_uid(getuid());
2007 bool is_temporary_fs(const struct statfs *s) {
2010 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2011 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2014 int fd_is_temporary_fs(int fd) {
2017 if (fstatfs(fd, &s) < 0)
2020 return is_temporary_fs(&s);
2023 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2026 /* Under the assumption that we are running privileged we
2027 * first change the access mode and only then hand out
2028 * ownership to avoid a window where access is too open. */
2030 if (mode != MODE_INVALID)
2031 if (chmod(path, mode) < 0)
2034 if (uid != UID_INVALID || gid != GID_INVALID)
2035 if (chown(path, uid, gid) < 0)
2041 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2044 /* Under the assumption that we are running privileged we
2045 * first change the access mode and only then hand out
2046 * ownership to avoid a window where access is too open. */
2048 if (mode != MODE_INVALID)
2049 if (fchmod(fd, mode) < 0)
2052 if (uid != UID_INVALID || gid != GID_INVALID)
2053 if (fchown(fd, uid, gid) < 0)
2059 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2063 /* Allocates the cpuset in the right size */
2066 if (!(r = CPU_ALLOC(n)))
2069 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2070 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2080 if (errno != EINVAL)
2087 int files_same(const char *filea, const char *fileb) {
2090 if (stat(filea, &a) < 0)
2093 if (stat(fileb, &b) < 0)
2096 return a.st_dev == b.st_dev &&
2097 a.st_ino == b.st_ino;
2100 int running_in_chroot(void) {
2103 ret = files_same("/proc/1/root", "/");
2110 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2115 assert(percent <= 100);
2116 assert(new_length >= 3);
2118 if (old_length <= 3 || old_length <= new_length)
2119 return strndup(s, old_length);
2121 r = new0(char, new_length+1);
2125 x = (new_length * percent) / 100;
2127 if (x > new_length - 3)
2135 s + old_length - (new_length - x - 3),
2136 new_length - x - 3);
2141 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2145 unsigned k, len, len2;
2148 assert(percent <= 100);
2149 assert(new_length >= 3);
2151 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2152 if (ascii_is_valid(s))
2153 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2155 if (old_length <= 3 || old_length <= new_length)
2156 return strndup(s, old_length);
2158 x = (new_length * percent) / 100;
2160 if (x > new_length - 3)
2164 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2167 c = utf8_encoded_to_unichar(i);
2170 k += unichar_iswide(c) ? 2 : 1;
2173 if (k > x) /* last character was wide and went over quota */
2176 for (j = s + old_length; k < new_length && j > i; ) {
2179 j = utf8_prev_char(j);
2180 c = utf8_encoded_to_unichar(j);
2183 k += unichar_iswide(c) ? 2 : 1;
2187 /* we don't actually need to ellipsize */
2189 return memdup(s, old_length + 1);
2191 /* make space for ellipsis */
2192 j = utf8_next_char(j);
2195 len2 = s + old_length - j;
2196 e = new(char, len + 3 + len2 + 1);
2201 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2202 old_length, new_length, x, len, len2, k);
2206 e[len] = 0xe2; /* tri-dot ellipsis: … */
2210 memcpy(e + len + 3, j, len2 + 1);
2215 char *ellipsize(const char *s, size_t length, unsigned percent) {
2216 return ellipsize_mem(s, strlen(s), length, percent);
2219 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2220 _cleanup_close_ int fd;
2226 mkdir_parents(path, 0755);
2228 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2233 r = fchmod(fd, mode);
2238 if (uid != UID_INVALID || gid != GID_INVALID) {
2239 r = fchown(fd, uid, gid);
2244 if (stamp != USEC_INFINITY) {
2245 struct timespec ts[2];
2247 timespec_store(&ts[0], stamp);
2249 r = futimens(fd, ts);
2251 r = futimens(fd, NULL);
2258 int touch(const char *path) {
2259 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2262 static char *unquote(const char *s, const char* quotes) {
2266 /* This is rather stupid, simply removes the heading and
2267 * trailing quotes if there is one. Doesn't care about
2268 * escaping or anything.
2270 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2276 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2277 return strndup(s+1, l-2);
2282 noreturn void freeze(void) {
2284 /* Make sure nobody waits for us on a socket anymore */
2285 close_all_fds(NULL, 0);
2293 bool null_or_empty(struct stat *st) {
2296 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2299 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2305 int null_or_empty_path(const char *fn) {
2310 if (stat(fn, &st) < 0)
2313 return null_or_empty(&st);
2316 int null_or_empty_fd(int fd) {
2321 if (fstat(fd, &st) < 0)
2324 return null_or_empty(&st);
2327 DIR *xopendirat(int fd, const char *name, int flags) {
2331 assert(!(flags & O_CREAT));
2333 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2346 int signal_from_string_try_harder(const char *s) {
2350 signo = signal_from_string(s);
2352 if (startswith(s, "SIG"))
2353 return signal_from_string(s+3);
2358 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2359 _cleanup_free_ char *t = NULL, *u = NULL;
2362 u = unquote(tagvalue, QUOTES);
2366 enc_len = strlen(u) * 4 + 1;
2367 t = new(char, enc_len);
2371 if (encode_devnode_name(u, t, enc_len) < 0)
2374 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2377 char *fstab_node_to_udev_node(const char *p) {
2380 if (startswith(p, "LABEL="))
2381 return tag_to_udev_node(p+6, "label");
2383 if (startswith(p, "UUID="))
2384 return tag_to_udev_node(p+5, "uuid");
2386 if (startswith(p, "PARTUUID="))
2387 return tag_to_udev_node(p+9, "partuuid");
2389 if (startswith(p, "PARTLABEL="))
2390 return tag_to_udev_node(p+10, "partlabel");
2395 bool dirent_is_file(const struct dirent *de) {
2398 if (hidden_file(de->d_name))
2401 if (de->d_type != DT_REG &&
2402 de->d_type != DT_LNK &&
2403 de->d_type != DT_UNKNOWN)
2409 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2412 if (de->d_type != DT_REG &&
2413 de->d_type != DT_LNK &&
2414 de->d_type != DT_UNKNOWN)
2417 if (hidden_file_allow_backup(de->d_name))
2420 return endswith(de->d_name, suffix);
2423 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2424 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2425 _cleanup_set_free_free_ Set *seen = NULL;
2428 /* We fork this all off from a child process so that we can
2429 * somewhat cleanly make use of SIGALRM to set a time limit */
2431 reset_all_signal_handlers();
2432 reset_signal_mask();
2434 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2436 pids = hashmap_new(NULL);
2440 seen = set_new(&string_hash_ops);
2444 STRV_FOREACH(directory, directories) {
2445 _cleanup_closedir_ DIR *d;
2448 d = opendir(*directory);
2450 if (errno == ENOENT)
2453 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2456 FOREACH_DIRENT(de, d, break) {
2457 _cleanup_free_ char *path = NULL;
2461 if (!dirent_is_file(de))
2464 if (set_contains(seen, de->d_name)) {
2465 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2469 r = set_put_strdup(seen, de->d_name);
2473 path = strjoin(*directory, "/", de->d_name, NULL);
2477 if (null_or_empty_path(path)) {
2478 log_debug("%s is empty (a mask).", path);
2484 log_error_errno(errno, "Failed to fork: %m");
2486 } else if (pid == 0) {
2489 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2499 return log_error_errno(errno, "Failed to execute %s: %m", path);
2502 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2504 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2511 /* Abort execution of this process after the timout. We simply
2512 * rely on SIGALRM as default action terminating the process,
2513 * and turn on alarm(). */
2515 if (timeout != USEC_INFINITY)
2516 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2518 while (!hashmap_isempty(pids)) {
2519 _cleanup_free_ char *path = NULL;
2522 pid = PTR_TO_UINT(hashmap_first_key(pids));
2525 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2528 wait_for_terminate_and_warn(path, pid, true);
2534 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2538 char **dirs = (char**) directories;
2540 assert(!strv_isempty(dirs));
2542 name = basename(dirs[0]);
2543 assert(!isempty(name));
2545 /* Executes all binaries in the directories in parallel and waits
2546 * for them to finish. Optionally a timeout is applied. If a file
2547 * with the same name exists in more than one directory, the
2548 * earliest one wins. */
2550 executor_pid = fork();
2551 if (executor_pid < 0) {
2552 log_error_errno(errno, "Failed to fork: %m");
2555 } else if (executor_pid == 0) {
2556 r = do_execute(dirs, timeout, argv);
2557 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2560 wait_for_terminate_and_warn(name, executor_pid, true);
2563 bool nulstr_contains(const char*nulstr, const char *needle) {
2569 NULSTR_FOREACH(i, nulstr)
2570 if (streq(i, needle))
2576 bool plymouth_running(void) {
2577 return access("/run/plymouth/pid", F_OK) >= 0;
2580 char* strshorten(char *s, size_t l) {
2589 static bool hostname_valid_char(char c) {
2591 (c >= 'a' && c <= 'z') ||
2592 (c >= 'A' && c <= 'Z') ||
2593 (c >= '0' && c <= '9') ||
2599 bool hostname_is_valid(const char *s) {
2606 /* Doesn't accept empty hostnames, hostnames with trailing or
2607 * leading dots, and hostnames with multiple dots in a
2608 * sequence. Also ensures that the length stays below
2611 for (p = s, dot = true; *p; p++) {
2618 if (!hostname_valid_char(*p))
2628 if (p-s > HOST_NAME_MAX)
2634 char* hostname_cleanup(char *s, bool lowercase) {
2638 for (p = s, d = s, dot = true; *p; p++) {
2645 } else if (hostname_valid_char(*p)) {
2646 *(d++) = lowercase ? tolower(*p) : *p;
2657 strshorten(s, HOST_NAME_MAX);
2662 bool machine_name_is_valid(const char *s) {
2664 if (!hostname_is_valid(s))
2667 /* Machine names should be useful hostnames, but also be
2668 * useful in unit names, hence we enforce a stricter length
2677 int pipe_eof(int fd) {
2678 struct pollfd pollfd = {
2680 .events = POLLIN|POLLHUP,
2685 r = poll(&pollfd, 1, 0);
2692 return pollfd.revents & POLLHUP;
2695 int fd_wait_for_event(int fd, int event, usec_t t) {
2697 struct pollfd pollfd = {
2705 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2712 return pollfd.revents;
2715 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2724 r = tempfn_xxxxxx(path, &t);
2728 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2734 f = fdopen(fd, "we");
2747 int symlink_atomic(const char *from, const char *to) {
2748 _cleanup_free_ char *t = NULL;
2754 r = tempfn_random(to, &t);
2758 if (symlink(from, t) < 0)
2761 if (rename(t, to) < 0) {
2769 int symlink_idempotent(const char *from, const char *to) {
2770 _cleanup_free_ char *p = NULL;
2776 if (symlink(from, to) < 0) {
2777 if (errno != EEXIST)
2780 r = readlink_malloc(to, &p);
2784 if (!streq(p, from))
2791 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2792 _cleanup_free_ char *t = NULL;
2797 r = tempfn_random(path, &t);
2801 if (mknod(t, mode, dev) < 0)
2804 if (rename(t, path) < 0) {
2812 int mkfifo_atomic(const char *path, mode_t mode) {
2813 _cleanup_free_ char *t = NULL;
2818 r = tempfn_random(path, &t);
2822 if (mkfifo(t, mode) < 0)
2825 if (rename(t, path) < 0) {
2833 bool display_is_local(const char *display) {
2837 display[0] == ':' &&
2838 display[1] >= '0' &&
2842 int socket_from_display(const char *display, char **path) {
2849 if (!display_is_local(display))
2852 k = strspn(display+1, "0123456789");
2854 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2858 c = stpcpy(f, "/tmp/.X11-unix/X");
2859 memcpy(c, display+1, k);
2868 const char **username,
2869 uid_t *uid, gid_t *gid,
2871 const char **shell) {
2879 /* We enforce some special rules for uid=0: in order to avoid
2880 * NSS lookups for root we hardcode its data. */
2882 if (streq(*username, "root") || streq(*username, "0")) {
2900 if (parse_uid(*username, &u) >= 0) {
2904 /* If there are multiple users with the same id, make
2905 * sure to leave $USER to the configured value instead
2906 * of the first occurrence in the database. However if
2907 * the uid was configured by a numeric uid, then let's
2908 * pick the real username from /etc/passwd. */
2910 *username = p->pw_name;
2913 p = getpwnam(*username);
2917 return errno > 0 ? -errno : -ESRCH;
2929 *shell = p->pw_shell;
2934 char* uid_to_name(uid_t uid) {
2939 return strdup("root");
2943 return strdup(p->pw_name);
2945 if (asprintf(&r, UID_FMT, uid) < 0)
2951 char* gid_to_name(gid_t gid) {
2956 return strdup("root");
2960 return strdup(p->gr_name);
2962 if (asprintf(&r, GID_FMT, gid) < 0)
2968 int get_group_creds(const char **groupname, gid_t *gid) {
2974 /* We enforce some special rules for gid=0: in order to avoid
2975 * NSS lookups for root we hardcode its data. */
2977 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2978 *groupname = "root";
2986 if (parse_gid(*groupname, &id) >= 0) {
2991 *groupname = g->gr_name;
2994 g = getgrnam(*groupname);
2998 return errno > 0 ? -errno : -ESRCH;
3006 int in_gid(gid_t gid) {
3008 int ngroups_max, r, i;
3010 if (getgid() == gid)
3013 if (getegid() == gid)
3016 ngroups_max = sysconf(_SC_NGROUPS_MAX);
3017 assert(ngroups_max > 0);
3019 gids = alloca(sizeof(gid_t) * ngroups_max);
3021 r = getgroups(ngroups_max, gids);
3025 for (i = 0; i < r; i++)
3032 int in_group(const char *name) {
3036 r = get_group_creds(&name, &gid);
3043 int glob_exists(const char *path) {
3044 _cleanup_globfree_ glob_t g = {};
3050 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3052 if (k == GLOB_NOMATCH)
3054 else if (k == GLOB_NOSPACE)
3057 return !strv_isempty(g.gl_pathv);
3059 return errno ? -errno : -EIO;
3062 int glob_extend(char ***strv, const char *path) {
3063 _cleanup_globfree_ glob_t g = {};
3068 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3070 if (k == GLOB_NOMATCH)
3072 else if (k == GLOB_NOSPACE)
3074 else if (k != 0 || strv_isempty(g.gl_pathv))
3075 return errno ? -errno : -EIO;
3077 STRV_FOREACH(p, g.gl_pathv) {
3078 k = strv_extend(strv, *p);
3086 int dirent_ensure_type(DIR *d, struct dirent *de) {
3092 if (de->d_type != DT_UNKNOWN)
3095 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3099 S_ISREG(st.st_mode) ? DT_REG :
3100 S_ISDIR(st.st_mode) ? DT_DIR :
3101 S_ISLNK(st.st_mode) ? DT_LNK :
3102 S_ISFIFO(st.st_mode) ? DT_FIFO :
3103 S_ISSOCK(st.st_mode) ? DT_SOCK :
3104 S_ISCHR(st.st_mode) ? DT_CHR :
3105 S_ISBLK(st.st_mode) ? DT_BLK :
3111 int get_files_in_directory(const char *path, char ***list) {
3112 _cleanup_closedir_ DIR *d = NULL;
3113 size_t bufsize = 0, n = 0;
3114 _cleanup_strv_free_ char **l = NULL;
3118 /* Returns all files in a directory in *list, and the number
3119 * of files as return value. If list is NULL returns only the
3131 if (!de && errno != 0)
3136 dirent_ensure_type(d, de);
3138 if (!dirent_is_file(de))
3142 /* one extra slot is needed for the terminating NULL */
3143 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3146 l[n] = strdup(de->d_name);
3157 l = NULL; /* avoid freeing */
3163 char *strjoin(const char *x, ...) {
3177 t = va_arg(ap, const char *);
3182 if (n > ((size_t) -1) - l) {
3206 t = va_arg(ap, const char *);
3220 bool is_main_thread(void) {
3221 static thread_local int cached = 0;
3223 if (_unlikely_(cached == 0))
3224 cached = getpid() == gettid() ? 1 : -1;
3229 int block_get_whole_disk(dev_t d, dev_t *ret) {
3236 /* If it has a queue this is good enough for us */
3237 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3240 r = access(p, F_OK);
3248 /* If it is a partition find the originating device */
3249 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3252 r = access(p, F_OK);
3258 /* Get parent dev_t */
3259 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3262 r = read_one_line_file(p, &s);
3268 r = sscanf(s, "%u:%u", &m, &n);
3274 /* Only return this if it is really good enough for us. */
3275 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3278 r = access(p, F_OK);
3282 *ret = makedev(m, n);
3289 static const char *const ioprio_class_table[] = {
3290 [IOPRIO_CLASS_NONE] = "none",
3291 [IOPRIO_CLASS_RT] = "realtime",
3292 [IOPRIO_CLASS_BE] = "best-effort",
3293 [IOPRIO_CLASS_IDLE] = "idle"
3296 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3298 static const char *const sigchld_code_table[] = {
3299 [CLD_EXITED] = "exited",
3300 [CLD_KILLED] = "killed",
3301 [CLD_DUMPED] = "dumped",
3302 [CLD_TRAPPED] = "trapped",
3303 [CLD_STOPPED] = "stopped",
3304 [CLD_CONTINUED] = "continued",
3307 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3309 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3310 [LOG_FAC(LOG_KERN)] = "kern",
3311 [LOG_FAC(LOG_USER)] = "user",
3312 [LOG_FAC(LOG_MAIL)] = "mail",
3313 [LOG_FAC(LOG_DAEMON)] = "daemon",
3314 [LOG_FAC(LOG_AUTH)] = "auth",
3315 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3316 [LOG_FAC(LOG_LPR)] = "lpr",
3317 [LOG_FAC(LOG_NEWS)] = "news",
3318 [LOG_FAC(LOG_UUCP)] = "uucp",
3319 [LOG_FAC(LOG_CRON)] = "cron",
3320 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3321 [LOG_FAC(LOG_FTP)] = "ftp",
3322 [LOG_FAC(LOG_LOCAL0)] = "local0",
3323 [LOG_FAC(LOG_LOCAL1)] = "local1",
3324 [LOG_FAC(LOG_LOCAL2)] = "local2",
3325 [LOG_FAC(LOG_LOCAL3)] = "local3",
3326 [LOG_FAC(LOG_LOCAL4)] = "local4",
3327 [LOG_FAC(LOG_LOCAL5)] = "local5",
3328 [LOG_FAC(LOG_LOCAL6)] = "local6",
3329 [LOG_FAC(LOG_LOCAL7)] = "local7"
3332 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3334 static const char *const log_level_table[] = {
3335 [LOG_EMERG] = "emerg",
3336 [LOG_ALERT] = "alert",
3337 [LOG_CRIT] = "crit",
3339 [LOG_WARNING] = "warning",
3340 [LOG_NOTICE] = "notice",
3341 [LOG_INFO] = "info",
3342 [LOG_DEBUG] = "debug"
3345 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3347 static const char* const sched_policy_table[] = {
3348 [SCHED_OTHER] = "other",
3349 [SCHED_BATCH] = "batch",
3350 [SCHED_IDLE] = "idle",
3351 [SCHED_FIFO] = "fifo",
3355 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3357 static const char* const rlimit_table[_RLIMIT_MAX] = {
3358 [RLIMIT_CPU] = "LimitCPU",
3359 [RLIMIT_FSIZE] = "LimitFSIZE",
3360 [RLIMIT_DATA] = "LimitDATA",
3361 [RLIMIT_STACK] = "LimitSTACK",
3362 [RLIMIT_CORE] = "LimitCORE",
3363 [RLIMIT_RSS] = "LimitRSS",
3364 [RLIMIT_NOFILE] = "LimitNOFILE",
3365 [RLIMIT_AS] = "LimitAS",
3366 [RLIMIT_NPROC] = "LimitNPROC",
3367 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3368 [RLIMIT_LOCKS] = "LimitLOCKS",
3369 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3370 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3371 [RLIMIT_NICE] = "LimitNICE",
3372 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3373 [RLIMIT_RTTIME] = "LimitRTTIME"
3376 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3378 static const char* const ip_tos_table[] = {
3379 [IPTOS_LOWDELAY] = "low-delay",
3380 [IPTOS_THROUGHPUT] = "throughput",
3381 [IPTOS_RELIABILITY] = "reliability",
3382 [IPTOS_LOWCOST] = "low-cost",
3385 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3387 static const char *const __signal_table[] = {
3404 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3415 [SIGVTALRM] = "VTALRM",
3417 [SIGWINCH] = "WINCH",
3423 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3425 const char *signal_to_string(int signo) {
3426 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3429 name = __signal_to_string(signo);
3433 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3434 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3436 snprintf(buf, sizeof(buf), "%d", signo);
3441 int signal_from_string(const char *s) {
3446 signo = __signal_from_string(s);
3450 if (startswith(s, "RTMIN+")) {
3454 if (safe_atou(s, &u) >= 0) {
3455 signo = (int) u + offset;
3456 if (signo > 0 && signo < _NSIG)
3462 bool kexec_loaded(void) {
3463 bool loaded = false;
3466 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3474 int prot_from_flags(int flags) {
3476 switch (flags & O_ACCMODE) {
3485 return PROT_READ|PROT_WRITE;
3492 char *format_bytes(char *buf, size_t l, off_t t) {
3495 static const struct {
3499 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3500 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3501 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3502 { "G", 1024ULL*1024ULL*1024ULL },
3503 { "M", 1024ULL*1024ULL },
3507 if (t == (off_t) -1)
3510 for (i = 0; i < ELEMENTSOF(table); i++) {
3512 if (t >= table[i].factor) {
3515 (unsigned long long) (t / table[i].factor),
3516 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3523 snprintf(buf, l, "%lluB", (unsigned long long) t);
3531 void* memdup(const void *p, size_t l) {
3544 int fd_inc_sndbuf(int fd, size_t n) {
3546 socklen_t l = sizeof(value);
3548 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3549 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3552 /* If we have the privileges we will ignore the kernel limit. */
3555 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3556 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3562 int fd_inc_rcvbuf(int fd, size_t n) {
3564 socklen_t l = sizeof(value);
3566 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3567 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3570 /* If we have the privileges we will ignore the kernel limit. */
3573 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3574 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3579 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3580 bool stdout_is_tty, stderr_is_tty;
3581 pid_t parent_pid, agent_pid;
3582 sigset_t ss, saved_ss;
3590 /* Spawns a temporary TTY agent, making sure it goes away when
3593 parent_pid = getpid();
3595 /* First we temporarily block all signals, so that the new
3596 * child has them blocked initially. This way, we can be sure
3597 * that SIGTERMs are not lost we might send to the agent. */
3598 assert_se(sigfillset(&ss) >= 0);
3599 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3602 if (agent_pid < 0) {
3603 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3607 if (agent_pid != 0) {
3608 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3615 * Make sure the agent goes away when the parent dies */
3616 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3617 _exit(EXIT_FAILURE);
3619 /* Make sure we actually can kill the agent, if we need to, in
3620 * case somebody invoked us from a shell script that trapped
3621 * SIGTERM or so... */
3622 reset_all_signal_handlers();
3623 reset_signal_mask();
3625 /* Check whether our parent died before we were able
3626 * to set the death signal and unblock the signals */
3627 if (getppid() != parent_pid)
3628 _exit(EXIT_SUCCESS);
3630 /* Don't leak fds to the agent */
3631 close_all_fds(except, n_except);
3633 stdout_is_tty = isatty(STDOUT_FILENO);
3634 stderr_is_tty = isatty(STDERR_FILENO);
3636 if (!stdout_is_tty || !stderr_is_tty) {
3639 /* Detach from stdout/stderr. and reopen
3640 * /dev/tty for them. This is important to
3641 * ensure that when systemctl is started via
3642 * popen() or a similar call that expects to
3643 * read EOF we actually do generate EOF and
3644 * not delay this indefinitely by because we
3645 * keep an unused copy of stdin around. */
3646 fd = open("/dev/tty", O_WRONLY);
3648 log_error_errno(errno, "Failed to open /dev/tty: %m");
3649 _exit(EXIT_FAILURE);
3653 dup2(fd, STDOUT_FILENO);
3656 dup2(fd, STDERR_FILENO);
3662 /* Count arguments */
3664 for (n = 0; va_arg(ap, char*); n++)
3669 l = alloca(sizeof(char *) * (n + 1));
3671 /* Fill in arguments */
3673 for (i = 0; i <= n; i++)
3674 l[i] = va_arg(ap, char*);
3678 _exit(EXIT_FAILURE);
3681 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3682 struct rlimit highest, fixed;
3686 if (setrlimit(resource, rlim) >= 0)
3692 /* So we failed to set the desired setrlimit, then let's try
3693 * to get as close as we can */
3694 assert_se(getrlimit(resource, &highest) == 0);
3696 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3697 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3699 if (setrlimit(resource, &fixed) < 0)
3705 bool http_etag_is_valid(const char *etag) {
3709 if (!endswith(etag, "\""))
3712 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3718 bool http_url_is_valid(const char *url) {
3724 p = startswith(url, "http://");
3726 p = startswith(url, "https://");
3733 return ascii_is_valid(p);
3736 bool documentation_url_is_valid(const char *url) {
3742 if (http_url_is_valid(url))
3745 p = startswith(url, "file:/");
3747 p = startswith(url, "info:");
3749 p = startswith(url, "man:");
3754 return ascii_is_valid(p);
3757 bool in_initrd(void) {
3758 static int saved = -1;
3764 /* We make two checks here:
3766 * 1. the flag file /etc/initrd-release must exist
3767 * 2. the root file system must be a memory file system
3769 * The second check is extra paranoia, since misdetecting an
3770 * initrd can have bad bad consequences due the initrd
3771 * emptying when transititioning to the main systemd.
3774 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3775 statfs("/", &s) >= 0 &&
3776 is_temporary_fs(&s);
3781 int get_home_dir(char **_h) {
3789 /* Take the user specified one */
3790 e = secure_getenv("HOME");
3791 if (e && path_is_absolute(e)) {
3800 /* Hardcode home directory for root to avoid NSS */
3803 h = strdup("/root");
3811 /* Check the database... */
3815 return errno > 0 ? -errno : -ESRCH;
3817 if (!path_is_absolute(p->pw_dir))
3820 h = strdup(p->pw_dir);
3828 int get_shell(char **_s) {
3836 /* Take the user specified one */
3837 e = getenv("SHELL");
3847 /* Hardcode home directory for root to avoid NSS */
3850 s = strdup("/bin/sh");
3858 /* Check the database... */
3862 return errno > 0 ? -errno : -ESRCH;
3864 if (!path_is_absolute(p->pw_shell))
3867 s = strdup(p->pw_shell);
3875 bool filename_is_valid(const char *p) {
3889 if (strlen(p) > FILENAME_MAX)
3895 bool string_is_safe(const char *p) {
3901 for (t = p; *t; t++) {
3902 if (*t > 0 && *t < ' ')
3905 if (strchr("\\\"\'\0x7f", *t))
3913 * Check if a string contains control characters. If 'ok' is non-NULL
3914 * it may be a string containing additional CCs to be considered OK.
3916 bool string_has_cc(const char *p, const char *ok) {
3921 for (t = p; *t; t++) {
3922 if (ok && strchr(ok, *t))
3925 if (*t > 0 && *t < ' ')
3935 bool path_is_safe(const char *p) {
3940 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3943 if (strlen(p)+1 > PATH_MAX)
3946 /* The following two checks are not really dangerous, but hey, they still are confusing */
3947 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3950 if (strstr(p, "//"))
3956 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3957 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3958 int (*compar) (const void *, const void *, void *), void *arg) {
3967 p = (void *)(((const char *) base) + (idx * size));
3968 comparison = compar(key, p, arg);
3971 else if (comparison > 0)
3979 void init_gettext(void) {
3980 setlocale(LC_ALL, "");
3981 textdomain(GETTEXT_PACKAGE);
3984 bool is_locale_utf8(void) {
3986 static int cached_answer = -1;
3988 if (cached_answer >= 0)
3991 if (!setlocale(LC_ALL, "")) {
3992 cached_answer = true;
3996 set = nl_langinfo(CODESET);
3998 cached_answer = true;
4002 if (streq(set, "UTF-8")) {
4003 cached_answer = true;
4007 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4008 * unset and everything can do to UTF-8 nowadays. */
4009 set = setlocale(LC_CTYPE, NULL);
4011 cached_answer = true;
4015 /* Check result, but ignore the result if C was set
4019 !getenv("LC_ALL") &&
4020 !getenv("LC_CTYPE") &&
4024 return (bool) cached_answer;
4027 const char *draw_special_char(DrawSpecialChar ch) {
4028 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
4031 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
4032 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
4033 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
4034 [DRAW_TREE_SPACE] = " ", /* */
4035 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
4036 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
4037 [DRAW_ARROW] = "\342\206\222", /* → */
4038 [DRAW_DASH] = "\342\200\223", /* – */
4041 /* ASCII fallback */ {
4042 [DRAW_TREE_VERTICAL] = "| ",
4043 [DRAW_TREE_BRANCH] = "|-",
4044 [DRAW_TREE_RIGHT] = "`-",
4045 [DRAW_TREE_SPACE] = " ",
4046 [DRAW_TRIANGULAR_BULLET] = ">",
4047 [DRAW_BLACK_CIRCLE] = "*",
4048 [DRAW_ARROW] = "->",
4053 return draw_table[!is_locale_utf8()][ch];
4056 char *strreplace(const char *text, const char *old_string, const char *new_string) {
4059 size_t l, old_len, new_len;
4065 old_len = strlen(old_string);
4066 new_len = strlen(new_string);
4079 if (!startswith(f, old_string)) {
4085 nl = l - old_len + new_len;
4086 a = realloc(r, nl + 1);
4094 t = stpcpy(t, new_string);
4106 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4107 const char *i, *begin = NULL;
4112 } state = STATE_OTHER;
4114 size_t osz = 0, isz;
4120 /* Strips ANSI color and replaces TABs by 8 spaces */
4122 isz = _isz ? *_isz : strlen(*ibuf);
4124 f = open_memstream(&obuf, &osz);
4128 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4133 if (i >= *ibuf + isz) /* EOT */
4135 else if (*i == '\x1B')
4136 state = STATE_ESCAPE;
4137 else if (*i == '\t')
4144 if (i >= *ibuf + isz) { /* EOT */
4147 } else if (*i == '[') {
4148 state = STATE_BRACKET;
4153 state = STATE_OTHER;
4160 if (i >= *ibuf + isz || /* EOT */
4161 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4164 state = STATE_OTHER;
4166 } else if (*i == 'm')
4167 state = STATE_OTHER;
4189 int on_ac_power(void) {
4190 bool found_offline = false, found_online = false;
4191 _cleanup_closedir_ DIR *d = NULL;
4193 d = opendir("/sys/class/power_supply");
4195 return errno == ENOENT ? true : -errno;
4199 _cleanup_close_ int fd = -1, device = -1;
4205 if (!de && errno != 0)
4211 if (hidden_file(de->d_name))
4214 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4216 if (errno == ENOENT || errno == ENOTDIR)
4222 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4224 if (errno == ENOENT)
4230 n = read(fd, contents, sizeof(contents));
4234 if (n != 6 || memcmp(contents, "Mains\n", 6))
4238 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4240 if (errno == ENOENT)
4246 n = read(fd, contents, sizeof(contents));
4250 if (n != 2 || contents[1] != '\n')
4253 if (contents[0] == '1') {
4254 found_online = true;
4256 } else if (contents[0] == '0')
4257 found_offline = true;
4262 return found_online || !found_offline;
4265 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4272 if (!path_strv_resolve_uniq(search, root))
4275 STRV_FOREACH(i, search) {
4276 _cleanup_free_ char *p = NULL;
4280 p = strjoin(root, *i, "/", path, NULL);
4282 p = strjoin(*i, "/", path, NULL);
4292 if (errno != ENOENT)
4299 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4300 _cleanup_strv_free_ char **copy = NULL;
4306 if (path_is_absolute(path)) {
4309 f = fopen(path, mode);
4318 copy = strv_copy((char**) search);
4322 return search_and_fopen_internal(path, mode, root, copy, _f);
4325 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4326 _cleanup_strv_free_ char **s = NULL;
4328 if (path_is_absolute(path)) {
4331 f = fopen(path, mode);
4340 s = strv_split_nulstr(search);
4344 return search_and_fopen_internal(path, mode, root, s, _f);
4347 char *strextend(char **x, ...) {
4354 l = f = *x ? strlen(*x) : 0;
4361 t = va_arg(ap, const char *);
4366 if (n > ((size_t) -1) - l) {
4375 r = realloc(*x, l+1);
4385 t = va_arg(ap, const char *);
4399 char *strrep(const char *s, unsigned n) {
4407 p = r = malloc(l * n + 1);
4411 for (i = 0; i < n; i++)
4418 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4425 if (*allocated >= need)
4428 newalloc = MAX(need * 2, 64u / size);
4429 a = newalloc * size;
4431 /* check for overflows */
4432 if (a < size * need)
4440 *allocated = newalloc;
4444 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4453 q = greedy_realloc(p, allocated, need, size);
4457 if (*allocated > prev)
4458 memzero(q + prev * size, (*allocated - prev) * size);
4463 bool id128_is_valid(const char *s) {
4469 /* Simple formatted 128bit hex string */
4471 for (i = 0; i < l; i++) {
4474 if (!(c >= '0' && c <= '9') &&
4475 !(c >= 'a' && c <= 'z') &&
4476 !(c >= 'A' && c <= 'Z'))
4480 } else if (l == 36) {
4482 /* Formatted UUID */
4484 for (i = 0; i < l; i++) {
4487 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4491 if (!(c >= '0' && c <= '9') &&
4492 !(c >= 'a' && c <= 'z') &&
4493 !(c >= 'A' && c <= 'Z'))
4504 int split_pair(const char *s, const char *sep, char **l, char **r) {
4519 a = strndup(s, x - s);
4523 b = strdup(x + strlen(sep));
4535 int shall_restore_state(void) {
4536 _cleanup_free_ char *value = NULL;
4539 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4545 return parse_boolean(value) != 0;
4548 int proc_cmdline(char **ret) {
4551 if (detect_container(NULL) > 0)
4552 return get_process_cmdline(1, 0, false, ret);
4554 return read_one_line_file("/proc/cmdline", ret);
4557 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4558 _cleanup_free_ char *line = NULL;
4564 r = proc_cmdline(&line);
4570 _cleanup_free_ char *word = NULL;
4573 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4579 /* Filter out arguments that are intended only for the
4581 if (!in_initrd() && startswith(word, "rd."))
4584 value = strchr(word, '=');
4588 r = parse_item(word, value);
4596 int get_proc_cmdline_key(const char *key, char **value) {
4597 _cleanup_free_ char *line = NULL, *ret = NULL;
4604 r = proc_cmdline(&line);
4610 _cleanup_free_ char *word = NULL;
4613 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4619 /* Filter out arguments that are intended only for the
4621 if (!in_initrd() && startswith(word, "rd."))
4625 e = startswith(word, key);
4629 r = free_and_strdup(&ret, e);
4635 if (streq(word, key))
4649 int container_get_leader(const char *machine, pid_t *pid) {
4650 _cleanup_free_ char *s = NULL, *class = NULL;
4658 p = strjoina("/run/systemd/machines/", machine);
4659 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4667 if (!streq_ptr(class, "container"))
4670 r = parse_pid(s, &leader);
4680 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4681 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4689 mntns = procfs_file_alloca(pid, "ns/mnt");
4690 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4698 pidns = procfs_file_alloca(pid, "ns/pid");
4699 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4707 netns = procfs_file_alloca(pid, "ns/net");
4708 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4716 root = procfs_file_alloca(pid, "root");
4717 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4723 *pidns_fd = pidnsfd;
4726 *mntns_fd = mntnsfd;
4729 *netns_fd = netnsfd;
4734 pidnsfd = mntnsfd = netnsfd = -1;
4739 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4742 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4746 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4750 if (setns(netns_fd, CLONE_NEWNET) < 0)
4754 if (fchdir(root_fd) < 0)
4757 if (chroot(".") < 0)
4761 if (setresgid(0, 0, 0) < 0)
4764 if (setgroups(0, NULL) < 0)
4767 if (setresuid(0, 0, 0) < 0)
4773 int getpeercred(int fd, struct ucred *ucred) {
4774 socklen_t n = sizeof(struct ucred);
4781 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4785 if (n != sizeof(struct ucred))
4788 /* Check if the data is actually useful and not suppressed due
4789 * to namespacing issues */
4792 if (u.uid == UID_INVALID)
4794 if (u.gid == GID_INVALID)
4801 int getpeersec(int fd, char **ret) {
4813 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4817 if (errno != ERANGE)
4824 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4840 /* This is much like like mkostemp() but is subject to umask(). */
4841 int mkostemp_safe(char *pattern, int flags) {
4842 _cleanup_umask_ mode_t u;
4849 fd = mkostemp(pattern, flags);
4856 int open_tmpfile(const char *path, int flags) {
4863 /* Try O_TMPFILE first, if it is supported */
4864 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4869 /* Fall back to unguessable name + unlinking */
4870 p = strjoina(path, "/systemd-tmp-XXXXXX");
4872 fd = mkostemp_safe(p, flags);
4880 int fd_warn_permissions(const char *path, int fd) {
4883 if (fstat(fd, &st) < 0)
4886 if (st.st_mode & 0111)
4887 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4889 if (st.st_mode & 0002)
4890 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4892 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4893 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);
4898 unsigned long personality_from_string(const char *p) {
4900 /* Parse a personality specifier. We introduce our own
4901 * identifiers that indicate specific ABIs, rather than just
4902 * hints regarding the register size, since we want to keep
4903 * things open for multiple locally supported ABIs for the
4904 * same register size. We try to reuse the ABI identifiers
4905 * used by libseccomp. */
4907 #if defined(__x86_64__)
4909 if (streq(p, "x86"))
4912 if (streq(p, "x86-64"))
4915 #elif defined(__i386__)
4917 if (streq(p, "x86"))
4921 /* personality(7) documents that 0xffffffffUL is used for
4922 * querying the current personality, hence let's use that here
4923 * as error indicator. */
4924 return 0xffffffffUL;
4927 const char* personality_to_string(unsigned long p) {
4929 #if defined(__x86_64__)
4931 if (p == PER_LINUX32)
4937 #elif defined(__i386__)
4946 uint64_t physical_memory(void) {
4949 /* We return this as uint64_t in case we are running as 32bit
4950 * process on a 64bit kernel with huge amounts of memory */
4952 mem = sysconf(_SC_PHYS_PAGES);
4955 return (uint64_t) mem * (uint64_t) page_size();
4958 void hexdump(FILE *f, const void *p, size_t s) {
4959 const uint8_t *b = p;
4962 assert(s == 0 || b);
4967 fprintf(f, "%04x ", n);
4969 for (i = 0; i < 16; i++) {
4974 fprintf(f, "%02x ", b[i]);
4982 for (i = 0; i < 16; i++) {
4987 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
5001 int update_reboot_param_file(const char *param) {
5006 r = write_string_file(REBOOT_PARAM_FILE, param);
5008 log_error("Failed to write reboot param to "
5009 REBOOT_PARAM_FILE": %s", strerror(-r));
5011 unlink(REBOOT_PARAM_FILE);
5016 int umount_recursive(const char *prefix, int flags) {
5020 /* Try to umount everything recursively below a
5021 * directory. Also, take care of stacked mounts, and keep
5022 * unmounting them until they are gone. */
5025 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5030 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5031 if (!proc_self_mountinfo)
5035 _cleanup_free_ char *path = NULL, *p = NULL;
5038 k = fscanf(proc_self_mountinfo,
5039 "%*s " /* (1) mount id */
5040 "%*s " /* (2) parent id */
5041 "%*s " /* (3) major:minor */
5042 "%*s " /* (4) root */
5043 "%ms " /* (5) mount point */
5044 "%*s" /* (6) mount options */
5045 "%*[^-]" /* (7) optional fields */
5046 "- " /* (8) separator */
5047 "%*s " /* (9) file system type */
5048 "%*s" /* (10) mount source */
5049 "%*s" /* (11) mount options 2 */
5050 "%*[^\n]", /* some rubbish at the end */
5059 r = cunescape(path, UNESCAPE_RELAX, &p);
5063 if (!path_startswith(p, prefix))
5066 if (umount2(p, flags) < 0) {
5082 static int get_mount_flags(const char *path, unsigned long *flags) {
5085 if (statvfs(path, &buf) < 0)
5087 *flags = buf.f_flag;
5091 int bind_remount_recursive(const char *prefix, bool ro) {
5092 _cleanup_set_free_free_ Set *done = NULL;
5093 _cleanup_free_ char *cleaned = NULL;
5096 /* Recursively remount a directory (and all its submounts)
5097 * read-only or read-write. If the directory is already
5098 * mounted, we reuse the mount and simply mark it
5099 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5100 * operation). If it isn't we first make it one. Afterwards we
5101 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5102 * submounts we can access, too. When mounts are stacked on
5103 * the same mount point we only care for each individual
5104 * "top-level" mount on each point, as we cannot
5105 * influence/access the underlying mounts anyway. We do not
5106 * have any effect on future submounts that might get
5107 * propagated, they migt be writable. This includes future
5108 * submounts that have been triggered via autofs. */
5110 cleaned = strdup(prefix);
5114 path_kill_slashes(cleaned);
5116 done = set_new(&string_hash_ops);
5121 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5122 _cleanup_set_free_free_ Set *todo = NULL;
5123 bool top_autofs = false;
5125 unsigned long orig_flags;
5127 todo = set_new(&string_hash_ops);
5131 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5132 if (!proc_self_mountinfo)
5136 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5139 k = fscanf(proc_self_mountinfo,
5140 "%*s " /* (1) mount id */
5141 "%*s " /* (2) parent id */
5142 "%*s " /* (3) major:minor */
5143 "%*s " /* (4) root */
5144 "%ms " /* (5) mount point */
5145 "%*s" /* (6) mount options (superblock) */
5146 "%*[^-]" /* (7) optional fields */
5147 "- " /* (8) separator */
5148 "%ms " /* (9) file system type */
5149 "%*s" /* (10) mount source */
5150 "%*s" /* (11) mount options (bind mount) */
5151 "%*[^\n]", /* some rubbish at the end */
5161 r = cunescape(path, UNESCAPE_RELAX, &p);
5165 /* Let's ignore autofs mounts. If they aren't
5166 * triggered yet, we want to avoid triggering
5167 * them, as we don't make any guarantees for
5168 * future submounts anyway. If they are
5169 * already triggered, then we will find
5170 * another entry for this. */
5171 if (streq(type, "autofs")) {
5172 top_autofs = top_autofs || path_equal(cleaned, p);
5176 if (path_startswith(p, cleaned) &&
5177 !set_contains(done, p)) {
5179 r = set_consume(todo, p);
5189 /* If we have no submounts to process anymore and if
5190 * the root is either already done, or an autofs, we
5192 if (set_isempty(todo) &&
5193 (top_autofs || set_contains(done, cleaned)))
5196 if (!set_contains(done, cleaned) &&
5197 !set_contains(todo, cleaned)) {
5198 /* The prefix directory itself is not yet a
5199 * mount, make it one. */
5200 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5204 (void) get_mount_flags(cleaned, &orig_flags);
5205 orig_flags &= ~MS_RDONLY;
5207 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5210 x = strdup(cleaned);
5214 r = set_consume(done, x);
5219 while ((x = set_steal_first(todo))) {
5221 r = set_consume(done, x);
5227 /* Try to reuse the original flag set, but
5228 * don't care for errors, in case of
5229 * obstructed mounts */
5231 (void) get_mount_flags(x, &orig_flags);
5232 orig_flags &= ~MS_RDONLY;
5234 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5236 /* Deal with mount points that are
5237 * obstructed by a later mount */
5239 if (errno != ENOENT)
5247 int fflush_and_check(FILE *f) {
5254 return errno ? -errno : -EIO;
5259 int tempfn_xxxxxx(const char *p, char **ret) {
5271 * /foo/bar/.#waldoXXXXXX
5275 if (!filename_is_valid(fn))
5278 t = new(char, strlen(p) + 2 + 6 + 1);
5282 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5284 *ret = path_kill_slashes(t);
5288 int tempfn_random(const char *p, char **ret) {
5302 * /foo/bar/.#waldobaa2a261115984a9
5306 if (!filename_is_valid(fn))
5309 t = new(char, strlen(p) + 2 + 16 + 1);
5313 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5316 for (i = 0; i < 16; i++) {
5317 *(x++) = hexchar(u & 0xF);
5323 *ret = path_kill_slashes(t);
5327 int tempfn_random_child(const char *p, char **ret) {
5338 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5341 t = new(char, strlen(p) + 3 + 16 + 1);
5345 x = stpcpy(stpcpy(t, p), "/.#");
5348 for (i = 0; i < 16; i++) {
5349 *(x++) = hexchar(u & 0xF);
5355 *ret = path_kill_slashes(t);
5359 /* make sure the hostname is not "localhost" */
5360 bool is_localhost(const char *hostname) {
5363 /* This tries to identify local host and domain names
5364 * described in RFC6761 plus the redhatism of .localdomain */
5366 return streq(hostname, "localhost") ||
5367 streq(hostname, "localhost.") ||
5368 streq(hostname, "localdomain.") ||
5369 streq(hostname, "localdomain") ||
5370 endswith(hostname, ".localhost") ||
5371 endswith(hostname, ".localhost.") ||
5372 endswith(hostname, ".localdomain") ||
5373 endswith(hostname, ".localdomain.");
5376 int take_password_lock(const char *root) {
5378 struct flock flock = {
5380 .l_whence = SEEK_SET,
5388 /* This is roughly the same as lckpwdf(), but not as awful. We
5389 * don't want to use alarm() and signals, hence we implement
5390 * our own trivial version of this.
5392 * Note that shadow-utils also takes per-database locks in
5393 * addition to lckpwdf(). However, we don't given that they
5394 * are redundant as they they invoke lckpwdf() first and keep
5395 * it during everything they do. The per-database locks are
5396 * awfully racy, and thus we just won't do them. */
5399 path = strjoina(root, "/etc/.pwd.lock");
5401 path = "/etc/.pwd.lock";
5403 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5407 r = fcntl(fd, F_SETLKW, &flock);
5416 int is_symlink(const char *path) {
5419 if (lstat(path, &info) < 0)
5422 return !!S_ISLNK(info.st_mode);
5425 int is_dir(const char* path, bool follow) {
5430 r = stat(path, &st);
5432 r = lstat(path, &st);
5436 return !!S_ISDIR(st.st_mode);
5439 int is_device_node(const char *path) {
5442 if (lstat(path, &info) < 0)
5445 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5448 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5449 _cleanup_free_ char *s = NULL;
5450 size_t allocated = 0, sz = 0;
5458 SINGLE_QUOTE_ESCAPE,
5460 DOUBLE_QUOTE_ESCAPE,
5468 /* Parses the first word of a string, and returns it in
5469 * *ret. Removes all quotes in the process. When parsing fails
5470 * (because of an uneven number of quotes or similar), leaves
5471 * the pointer *p at the first invalid character. */
5481 else if (strchr(WHITESPACE, c))
5491 state = SINGLE_QUOTE;
5493 state = VALUE_ESCAPE;
5495 state = DOUBLE_QUOTE;
5496 else if (strchr(WHITESPACE, c))
5499 if (!GREEDY_REALLOC(s, allocated, sz+2))
5509 if (flags & UNQUOTE_RELAX)
5514 if (!GREEDY_REALLOC(s, allocated, sz+7))
5517 if (flags & UNQUOTE_CUNESCAPE) {
5520 r = cunescape_one(*p, (size_t) -1, &c, &u);
5527 s[sz++] = c; /* normal explicit char */
5529 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5538 if (flags & UNQUOTE_RELAX)
5541 } else if (c == '\'')
5544 state = SINGLE_QUOTE_ESCAPE;
5546 if (!GREEDY_REALLOC(s, allocated, sz+2))
5554 case SINGLE_QUOTE_ESCAPE:
5556 if (flags & UNQUOTE_RELAX)
5561 if (!GREEDY_REALLOC(s, allocated, sz+7))
5564 if (flags & UNQUOTE_CUNESCAPE) {
5567 r = cunescape_one(*p, (size_t) -1, &c, &u);
5576 sz += utf8_encode_unichar(s + sz, u);
5580 state = SINGLE_QUOTE;
5589 state = DOUBLE_QUOTE_ESCAPE;
5591 if (!GREEDY_REALLOC(s, allocated, sz+2))
5599 case DOUBLE_QUOTE_ESCAPE:
5601 if (flags & UNQUOTE_RELAX)
5606 if (!GREEDY_REALLOC(s, allocated, sz+7))
5609 if (flags & UNQUOTE_CUNESCAPE) {
5612 r = cunescape_one(*p, (size_t) -1, &c, &u);
5621 sz += utf8_encode_unichar(s + sz, u);
5625 state = DOUBLE_QUOTE;
5631 if (!strchr(WHITESPACE, c))
5653 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5658 /* Parses a number of words from a string, stripping any
5659 * quotes if necessary. */
5663 /* Count how many words are expected */
5664 va_start(ap, flags);
5666 if (!va_arg(ap, char **))
5675 /* Read all words into a temporary array */
5676 l = newa0(char*, n);
5677 for (c = 0; c < n; c++) {
5679 r = unquote_first_word(p, &l[c], flags);
5683 for (j = 0; j < c; j++)
5693 /* If we managed to parse all words, return them in the passed
5695 va_start(ap, flags);
5696 for (i = 0; i < n; i++) {
5699 v = va_arg(ap, char **);
5709 int free_and_strdup(char **p, const char *s) {
5714 /* Replaces a string pointer with an strdup()ed new string,
5715 * possibly freeing the old one. */
5717 if (streq_ptr(*p, s))
5733 int sethostname_idempotent(const char *s) {
5735 char buf[HOST_NAME_MAX + 1] = {};
5739 r = gethostname(buf, sizeof(buf));
5746 r = sethostname(s, strlen(s));
5753 int ptsname_malloc(int fd, char **ret) {
5766 if (ptsname_r(fd, c, l) == 0) {
5770 if (errno != ERANGE) {
5780 int openpt_in_namespace(pid_t pid, int flags) {
5781 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5782 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5784 struct cmsghdr cmsghdr;
5785 uint8_t buf[CMSG_SPACE(sizeof(int))];
5787 struct msghdr mh = {
5788 .msg_control = &control,
5789 .msg_controllen = sizeof(control),
5791 struct cmsghdr *cmsg;
5798 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5802 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5812 pair[0] = safe_close(pair[0]);
5814 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5816 _exit(EXIT_FAILURE);
5818 master = posix_openpt(flags);
5820 _exit(EXIT_FAILURE);
5822 cmsg = CMSG_FIRSTHDR(&mh);
5823 cmsg->cmsg_level = SOL_SOCKET;
5824 cmsg->cmsg_type = SCM_RIGHTS;
5825 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5826 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5828 mh.msg_controllen = cmsg->cmsg_len;
5830 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5831 _exit(EXIT_FAILURE);
5833 _exit(EXIT_SUCCESS);
5836 pair[1] = safe_close(pair[1]);
5838 r = wait_for_terminate(child, &si);
5841 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5844 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5847 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5848 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5852 fds = (int*) CMSG_DATA(cmsg);
5853 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5856 close_many(fds, n_fds);
5866 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5867 _cleanup_close_ int fd = -1;
5870 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5872 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5876 l = fgetxattr(fd, attribute, value, size);
5883 static int parse_crtime(le64_t le, usec_t *usec) {
5889 if (u == 0 || u == (uint64_t) -1)
5896 int fd_getcrtime(int fd, usec_t *usec) {
5903 /* Until Linux gets a real concept of birthtime/creation time,
5904 * let's fake one with xattrs */
5906 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5909 if (n != sizeof(le))
5912 return parse_crtime(le, usec);
5915 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5919 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5922 if (n != sizeof(le))
5925 return parse_crtime(le, usec);
5928 int path_getcrtime(const char *p, usec_t *usec) {
5935 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5938 if (n != sizeof(le))
5941 return parse_crtime(le, usec);
5944 int fd_setcrtime(int fd, usec_t usec) {
5950 usec = now(CLOCK_REALTIME);
5952 le = htole64((uint64_t) usec);
5953 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5959 int chattr_fd(int fd, unsigned value, unsigned mask) {
5960 unsigned old_attr, new_attr;
5965 if (fstat(fd, &st) < 0)
5968 /* Explicitly check whether this is a regular file or
5969 * directory. If it is anything else (such as a device node or
5970 * fifo), then the ioctl will not hit the file systems but
5971 * possibly drivers, where the ioctl might have different
5972 * effects. Notably, DRM is using the same ioctl() number. */
5974 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5980 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5983 new_attr = (old_attr & ~mask) | (value & mask);
5984 if (new_attr == old_attr)
5987 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5993 int chattr_path(const char *p, unsigned value, unsigned mask) {
5994 _cleanup_close_ int fd = -1;
6001 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6005 return chattr_fd(fd, value, mask);
6008 int read_attr_fd(int fd, unsigned *ret) {
6013 if (fstat(fd, &st) < 0)
6016 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
6019 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
6025 int read_attr_path(const char *p, unsigned *ret) {
6026 _cleanup_close_ int fd = -1;
6031 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6035 return read_attr_fd(fd, ret);
6038 static size_t nul_length(const uint8_t *p, size_t sz) {
6053 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
6054 const uint8_t *q, *w, *e;
6062 n = nul_length(q, e - q);
6064 /* If there are more than the specified run length of
6065 * NUL bytes, or if this is the beginning or the end
6066 * of the buffer, then seek instead of write */
6067 if ((n > run_length) ||
6068 (n > 0 && q == p) ||
6069 (n > 0 && q + n >= e)) {
6071 l = write(fd, w, q - w);
6078 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6090 l = write(fd, w, q - w);
6097 return q - (const uint8_t*) p;
6100 void sigkill_wait(pid_t *pid) {
6106 if (kill(*pid, SIGKILL) > 0)
6107 (void) wait_for_terminate(*pid, NULL);
6110 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6111 int a = 0, b = 0, c = 0;
6121 if (!strchr(*p, '>'))
6124 if ((*p)[2] == '>') {
6125 c = undecchar((*p)[1]);
6127 } else if ((*p)[3] == '>') {
6128 b = undecchar((*p)[1]);
6129 c = undecchar((*p)[2]);
6131 } else if ((*p)[4] == '>') {
6132 a = undecchar((*p)[1]);
6133 b = undecchar((*p)[2]);
6134 c = undecchar((*p)[3]);
6139 if (a < 0 || b < 0 || c < 0 ||
6140 (!with_facility && (a || b || c > 7)))
6144 *priority = a*100 + b*10 + c;
6146 *priority = (*priority & LOG_FACMASK) | c;
6152 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6158 for (i = 0; i < len; ++i)
6159 if (streq_ptr(table[i], key))
6165 void cmsg_close_all(struct msghdr *mh) {
6166 struct cmsghdr *cmsg;
6170 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6171 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6172 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6175 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6179 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6183 /* Even though renameat2() exists since Linux 3.15, btrfs added
6184 * support for it later. If it is not implemented, fallback to another
6186 if (errno != EINVAL)
6189 /* The link()/unlink() fallback does not work on directories. But
6190 * renameat() without RENAME_NOREPLACE gives the same semantics on
6191 * directories, except when newpath is an *empty* directory. This is
6193 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6194 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6195 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6196 return ret >= 0 ? 0 : -errno;
6199 /* If it is not a directory, use the link()/unlink() fallback. */
6200 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6204 ret = unlinkat(olddirfd, oldpath, 0);
6206 /* backup errno before the following unlinkat() alters it */
6208 (void) unlinkat(newdirfd, newpath, 0);
6216 char *shell_maybe_quote(const char *s) {
6222 /* Encloses a string in double quotes if necessary to make it
6223 * OK as shell string. */
6225 for (p = s; *p; p++)
6228 strchr(SHELL_NEED_QUOTES, *p))
6234 r = new(char, 1+strlen(s)*2+1+1);
6240 t = mempcpy(t, s, p - s);
6244 if (strchr(SHELL_NEED_ESCAPE, *p))
6256 int parse_mode(const char *s, mode_t *ret) {
6264 l = strtol(s, &x, 8);
6268 if (!x || x == s || *x)
6270 if (l < 0 || l > 07777)