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' ||
576 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
577 /* right quote missing or garbage at the end */
581 assert(current[*l + 1] == quotechars[0]);
582 *state = current++ + *l + 2;
584 *l = strcspn_escaped(current, separator);
585 if (current[*l] && !strchr(separator, current[*l])) {
586 /* unfinished escape */
590 *state = current + *l;
592 *l = strcspn(current, separator);
593 *state = current + *l;
599 int fchmod_umask(int fd, mode_t m) {
604 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
610 char *truncate_nl(char *s) {
613 s[strcspn(s, NEWLINE)] = 0;
617 char *strnappend(const char *s, const char *suffix, size_t b) {
625 return strndup(suffix, b);
634 if (b > ((size_t) -1) - a)
637 r = new(char, a+b+1);
642 memcpy(r+a, suffix, b);
648 char *strappend(const char *s, const char *suffix) {
649 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
652 int readlinkat_malloc(int fd, const char *p, char **ret) {
667 n = readlinkat(fd, p, c, l-1);
674 if ((size_t) n < l-1) {
685 int readlink_malloc(const char *p, char **ret) {
686 return readlinkat_malloc(AT_FDCWD, p, ret);
689 int readlink_value(const char *p, char **ret) {
690 _cleanup_free_ char *link = NULL;
694 r = readlink_malloc(p, &link);
698 value = basename(link);
702 value = strdup(value);
711 int readlink_and_make_absolute(const char *p, char **r) {
712 _cleanup_free_ char *target = NULL;
719 j = readlink_malloc(p, &target);
723 k = file_in_same_dir(p, target);
731 int readlink_and_canonicalize(const char *p, char **r) {
738 j = readlink_and_make_absolute(p, &t);
742 s = canonicalize_file_name(t);
749 path_kill_slashes(*r);
754 int reset_all_signal_handlers(void) {
757 for (sig = 1; sig < _NSIG; sig++) {
758 struct sigaction sa = {
759 .sa_handler = SIG_DFL,
760 .sa_flags = SA_RESTART,
763 /* These two cannot be caught... */
764 if (sig == SIGKILL || sig == SIGSTOP)
767 /* On Linux the first two RT signals are reserved by
768 * glibc, and sigaction() will return EINVAL for them. */
769 if ((sigaction(sig, &sa, NULL) < 0))
770 if (errno != EINVAL && r == 0)
777 int reset_signal_mask(void) {
780 if (sigemptyset(&ss) < 0)
783 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
789 char *strstrip(char *s) {
792 /* Drops trailing whitespace. Modifies the string in
793 * place. Returns pointer to first non-space character */
795 s += strspn(s, WHITESPACE);
797 for (e = strchr(s, 0); e > s; e --)
798 if (!strchr(WHITESPACE, e[-1]))
806 char *delete_chars(char *s, const char *bad) {
809 /* Drops all whitespace, regardless where in the string */
811 for (f = s, t = s; *f; f++) {
823 char *file_in_same_dir(const char *path, const char *filename) {
830 /* This removes the last component of path and appends
831 * filename, unless the latter is absolute anyway or the
834 if (path_is_absolute(filename))
835 return strdup(filename);
837 e = strrchr(path, '/');
839 return strdup(filename);
841 k = strlen(filename);
842 ret = new(char, (e + 1 - path) + k + 1);
846 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
850 int rmdir_parents(const char *path, const char *stop) {
859 /* Skip trailing slashes */
860 while (l > 0 && path[l-1] == '/')
866 /* Skip last component */
867 while (l > 0 && path[l-1] != '/')
870 /* Skip trailing slashes */
871 while (l > 0 && path[l-1] == '/')
877 if (!(t = strndup(path, l)))
880 if (path_startswith(stop, t)) {
896 char hexchar(int x) {
897 static const char table[16] = "0123456789abcdef";
899 return table[x & 15];
902 int unhexchar(char c) {
904 if (c >= '0' && c <= '9')
907 if (c >= 'a' && c <= 'f')
910 if (c >= 'A' && c <= 'F')
916 char *hexmem(const void *p, size_t l) {
920 z = r = malloc(l * 2 + 1);
924 for (x = p; x < (const uint8_t*) p + l; x++) {
925 *(z++) = hexchar(*x >> 4);
926 *(z++) = hexchar(*x & 15);
933 void *unhexmem(const char *p, size_t l) {
939 z = r = malloc((l + 1) / 2 + 1);
943 for (x = p; x < p + l; x += 2) {
952 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
959 char octchar(int x) {
960 return '0' + (x & 7);
963 int unoctchar(char c) {
965 if (c >= '0' && c <= '7')
971 char decchar(int x) {
972 return '0' + (x % 10);
975 int undecchar(char c) {
977 if (c >= '0' && c <= '9')
983 char *cescape(const char *s) {
989 /* Does C style string escaping. May be reversed with
992 r = new(char, strlen(s)*4 + 1);
996 for (f = s, t = r; *f; f++)
997 t += cescape_char(*f, t);
1004 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1011 /* Unescapes C style. Returns the unescaped character in ret,
1012 * unless we encountered a \u sequence in which case the full
1013 * unicode character is returned in ret_unicode, instead. */
1015 if (length != (size_t) -1 && length < 1)
1052 /* This is an extension of the XDG syntax files */
1057 /* hexadecimal encoding */
1060 if (length != (size_t) -1 && length < 3)
1063 a = unhexchar(p[1]);
1067 b = unhexchar(p[2]);
1071 /* Don't allow NUL bytes */
1072 if (a == 0 && b == 0)
1075 *ret = (char) ((a << 4U) | b);
1081 /* C++11 style 16bit unicode */
1087 if (length != (size_t) -1 && length < 5)
1090 for (i = 0; i < 4; i++) {
1091 a[i] = unhexchar(p[1 + i]);
1096 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1098 /* Don't allow 0 chars */
1117 /* C++11 style 32bit unicode */
1123 if (length != (size_t) -1 && length < 9)
1126 for (i = 0; i < 8; i++) {
1127 a[i] = unhexchar(p[1 + i]);
1132 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1133 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1135 /* Don't allow 0 chars */
1139 /* Don't allow invalid code points */
1140 if (!unichar_is_valid(c))
1165 /* octal encoding */
1169 if (length != (size_t) -1 && length < 4)
1172 a = unoctchar(p[0]);
1176 b = unoctchar(p[1]);
1180 c = unoctchar(p[2]);
1184 /* don't allow NUL bytes */
1185 if (a == 0 && b == 0 && c == 0)
1188 /* Don't allow bytes above 255 */
1189 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1205 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1213 /* Undoes C style string escaping, and optionally prefixes it. */
1215 pl = prefix ? strlen(prefix) : 0;
1217 r = new(char, pl+length+1);
1222 memcpy(r, prefix, pl);
1224 for (f = s, t = r + pl; f < s + length; f++) {
1230 remaining = s + length - f;
1231 assert(remaining > 0);
1234 /* A literal literal, copy verbatim */
1239 if (remaining == 1) {
1240 if (flags & UNESCAPE_RELAX) {
1241 /* A trailing backslash, copy verbatim */
1250 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1252 if (flags & UNESCAPE_RELAX) {
1253 /* Invalid escape code, let's take it literal then */
1263 /* Non-Unicode? Let's encode this directly */
1266 /* Unicode? Then let's encode this in UTF-8 */
1267 t += utf8_encode_unichar(t, u);
1278 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1279 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1282 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1283 return cunescape_length(s, strlen(s), flags, ret);
1286 char *xescape(const char *s, const char *bad) {
1290 /* Escapes all chars in bad, in addition to \ and all special
1291 * chars, in \xFF style escaping. May be reversed with
1294 r = new(char, strlen(s) * 4 + 1);
1298 for (f = s, t = r; *f; f++) {
1300 if ((*f < ' ') || (*f >= 127) ||
1301 (*f == '\\') || strchr(bad, *f)) {
1304 *(t++) = hexchar(*f >> 4);
1305 *(t++) = hexchar(*f);
1315 char *ascii_strlower(char *t) {
1320 for (p = t; *p; p++)
1321 if (*p >= 'A' && *p <= 'Z')
1322 *p = *p - 'A' + 'a';
1327 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1331 filename[0] == '.' ||
1332 streq(filename, "lost+found") ||
1333 streq(filename, "aquota.user") ||
1334 streq(filename, "aquota.group") ||
1335 endswith(filename, ".rpmnew") ||
1336 endswith(filename, ".rpmsave") ||
1337 endswith(filename, ".rpmorig") ||
1338 endswith(filename, ".dpkg-old") ||
1339 endswith(filename, ".dpkg-new") ||
1340 endswith(filename, ".dpkg-tmp") ||
1341 endswith(filename, ".dpkg-dist") ||
1342 endswith(filename, ".dpkg-bak") ||
1343 endswith(filename, ".dpkg-backup") ||
1344 endswith(filename, ".dpkg-remove") ||
1345 endswith(filename, ".swp");
1348 bool hidden_file(const char *filename) {
1351 if (endswith(filename, "~"))
1354 return hidden_file_allow_backup(filename);
1357 int fd_nonblock(int fd, bool nonblock) {
1362 flags = fcntl(fd, F_GETFL, 0);
1367 nflags = flags | O_NONBLOCK;
1369 nflags = flags & ~O_NONBLOCK;
1371 if (nflags == flags)
1374 if (fcntl(fd, F_SETFL, nflags) < 0)
1380 int fd_cloexec(int fd, bool cloexec) {
1385 flags = fcntl(fd, F_GETFD, 0);
1390 nflags = flags | FD_CLOEXEC;
1392 nflags = flags & ~FD_CLOEXEC;
1394 if (nflags == flags)
1397 if (fcntl(fd, F_SETFD, nflags) < 0)
1403 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1406 assert(n_fdset == 0 || fdset);
1408 for (i = 0; i < n_fdset; i++)
1415 int close_all_fds(const int except[], unsigned n_except) {
1416 _cleanup_closedir_ DIR *d = NULL;
1420 assert(n_except == 0 || except);
1422 d = opendir("/proc/self/fd");
1427 /* When /proc isn't available (for example in chroots)
1428 * the fallback is brute forcing through the fd
1431 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1432 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1434 if (fd_in_set(fd, except, n_except))
1437 if (close_nointr(fd) < 0)
1438 if (errno != EBADF && r == 0)
1445 while ((de = readdir(d))) {
1448 if (hidden_file(de->d_name))
1451 if (safe_atoi(de->d_name, &fd) < 0)
1452 /* Let's better ignore this, just in case */
1461 if (fd_in_set(fd, except, n_except))
1464 if (close_nointr(fd) < 0) {
1465 /* Valgrind has its own FD and doesn't want to have it closed */
1466 if (errno != EBADF && r == 0)
1474 bool chars_intersect(const char *a, const char *b) {
1477 /* Returns true if any of the chars in a are in b. */
1478 for (p = a; *p; p++)
1485 bool fstype_is_network(const char *fstype) {
1486 static const char table[] =
1501 x = startswith(fstype, "fuse.");
1505 return nulstr_contains(table, fstype);
1508 int flush_fd(int fd) {
1509 struct pollfd pollfd = {
1519 r = poll(&pollfd, 1, 0);
1529 l = read(fd, buf, sizeof(buf));
1535 if (errno == EAGAIN)
1544 int sigaction_many(const struct sigaction *sa, ...) {
1549 while ((sig = va_arg(ap, int)) > 0)
1550 if (sigaction(sig, sa, NULL) < 0)
1557 int ignore_signals(int sig, ...) {
1558 struct sigaction sa = {
1559 .sa_handler = SIG_IGN,
1560 .sa_flags = SA_RESTART,
1565 if (sigaction(sig, &sa, NULL) < 0)
1569 while ((sig = va_arg(ap, int)) > 0)
1570 if (sigaction(sig, &sa, NULL) < 0)
1577 int default_signals(int sig, ...) {
1578 struct sigaction sa = {
1579 .sa_handler = SIG_DFL,
1580 .sa_flags = SA_RESTART,
1585 if (sigaction(sig, &sa, NULL) < 0)
1589 while ((sig = va_arg(ap, int)) > 0)
1590 if (sigaction(sig, &sa, NULL) < 0)
1597 void safe_close_pair(int p[]) {
1601 /* Special case pairs which use the same fd in both
1603 p[0] = p[1] = safe_close(p[0]);
1607 p[0] = safe_close(p[0]);
1608 p[1] = safe_close(p[1]);
1611 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1618 while (nbytes > 0) {
1621 k = read(fd, p, nbytes);
1626 if (errno == EAGAIN && do_poll) {
1628 /* We knowingly ignore any return value here,
1629 * and expect that any error/EOF is reported
1632 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1636 return n > 0 ? n : -errno;
1650 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1653 n = loop_read(fd, buf, nbytes, do_poll);
1656 if ((size_t) n != nbytes)
1661 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1662 const uint8_t *p = buf;
1672 k = write(fd, p, nbytes);
1677 if (errno == EAGAIN && do_poll) {
1678 /* We knowingly ignore any return value here,
1679 * and expect that any error/EOF is reported
1682 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1689 if (nbytes > 0 && k == 0) /* Can't really happen */
1694 } while (nbytes > 0);
1699 int parse_size(const char *t, off_t base, off_t *size) {
1701 /* Soo, sometimes we want to parse IEC binary suffxies, and
1702 * sometimes SI decimal suffixes. This function can parse
1703 * both. Which one is the right way depends on the
1704 * context. Wikipedia suggests that SI is customary for
1705 * hardware metrics and network speeds, while IEC is
1706 * customary for most data sizes used by software and volatile
1707 * (RAM) memory. Hence be careful which one you pick!
1709 * In either case we use just K, M, G as suffix, and not Ki,
1710 * Mi, Gi or so (as IEC would suggest). That's because that's
1711 * frickin' ugly. But this means you really need to make sure
1712 * to document which base you are parsing when you use this
1717 unsigned long long factor;
1720 static const struct table iec[] = {
1721 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1722 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1723 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1724 { "G", 1024ULL*1024ULL*1024ULL },
1725 { "M", 1024ULL*1024ULL },
1731 static const struct table si[] = {
1732 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1733 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1734 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1735 { "G", 1000ULL*1000ULL*1000ULL },
1736 { "M", 1000ULL*1000ULL },
1742 const struct table *table;
1744 unsigned long long r = 0;
1745 unsigned n_entries, start_pos = 0;
1748 assert(base == 1000 || base == 1024);
1753 n_entries = ELEMENTSOF(si);
1756 n_entries = ELEMENTSOF(iec);
1762 unsigned long long l2;
1768 l = strtoll(p, &e, 10);
1781 if (*e >= '0' && *e <= '9') {
1784 /* strotoull itself would accept space/+/- */
1785 l2 = strtoull(e, &e2, 10);
1787 if (errno == ERANGE)
1790 /* Ignore failure. E.g. 10.M is valid */
1797 e += strspn(e, WHITESPACE);
1799 for (i = start_pos; i < n_entries; i++)
1800 if (startswith(e, table[i].suffix)) {
1801 unsigned long long tmp;
1802 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1804 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1805 if (tmp > ULLONG_MAX - r)
1809 if ((unsigned long long) (off_t) r != r)
1812 p = e + strlen(table[i].suffix);
1828 bool is_device_path(const char *path) {
1830 /* Returns true on paths that refer to a device, either in
1831 * sysfs or in /dev */
1834 path_startswith(path, "/dev/") ||
1835 path_startswith(path, "/sys/");
1838 int dir_is_empty(const char *path) {
1839 _cleanup_closedir_ DIR *d;
1850 if (!de && errno != 0)
1856 if (!hidden_file(de->d_name))
1861 char* dirname_malloc(const char *path) {
1862 char *d, *dir, *dir2;
1879 void rename_process(const char name[8]) {
1882 /* This is a like a poor man's setproctitle(). It changes the
1883 * comm field, argv[0], and also the glibc's internally used
1884 * name of the process. For the first one a limit of 16 chars
1885 * applies, to the second one usually one of 10 (i.e. length
1886 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1887 * "systemd"). If you pass a longer string it will be
1890 prctl(PR_SET_NAME, name);
1892 if (program_invocation_name)
1893 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1895 if (saved_argc > 0) {
1899 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1901 for (i = 1; i < saved_argc; i++) {
1905 memzero(saved_argv[i], strlen(saved_argv[i]));
1910 void sigset_add_many(sigset_t *ss, ...) {
1917 while ((sig = va_arg(ap, int)) > 0)
1918 assert_se(sigaddset(ss, sig) == 0);
1922 int sigprocmask_many(int how, ...) {
1927 assert_se(sigemptyset(&ss) == 0);
1930 while ((sig = va_arg(ap, int)) > 0)
1931 assert_se(sigaddset(&ss, sig) == 0);
1934 if (sigprocmask(how, &ss, NULL) < 0)
1939 char *lookup_uid(uid_t uid) {
1942 _cleanup_free_ char *buf = NULL;
1943 struct passwd pwbuf, *pw = NULL;
1945 /* Shortcut things to avoid NSS lookups */
1947 return strdup("root");
1949 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1953 buf = malloc(bufsize);
1957 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1958 return strdup(pw->pw_name);
1960 if (asprintf(&name, UID_FMT, uid) < 0)
1966 char* getlogname_malloc(void) {
1970 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1975 return lookup_uid(uid);
1978 char *getusername_malloc(void) {
1985 return lookup_uid(getuid());
1988 bool is_temporary_fs(const struct statfs *s) {
1991 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
1992 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
1995 int fd_is_temporary_fs(int fd) {
1998 if (fstatfs(fd, &s) < 0)
2001 return is_temporary_fs(&s);
2004 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2007 /* Under the assumption that we are running privileged we
2008 * first change the access mode and only then hand out
2009 * ownership to avoid a window where access is too open. */
2011 if (mode != MODE_INVALID)
2012 if (chmod(path, mode) < 0)
2015 if (uid != UID_INVALID || gid != GID_INVALID)
2016 if (chown(path, uid, gid) < 0)
2022 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2025 /* Under the assumption that we are running privileged we
2026 * first change the access mode and only then hand out
2027 * ownership to avoid a window where access is too open. */
2029 if (mode != MODE_INVALID)
2030 if (fchmod(fd, mode) < 0)
2033 if (uid != UID_INVALID || gid != GID_INVALID)
2034 if (fchown(fd, uid, gid) < 0)
2040 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2044 /* Allocates the cpuset in the right size */
2047 if (!(r = CPU_ALLOC(n)))
2050 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2051 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2061 if (errno != EINVAL)
2068 int files_same(const char *filea, const char *fileb) {
2071 if (stat(filea, &a) < 0)
2074 if (stat(fileb, &b) < 0)
2077 return a.st_dev == b.st_dev &&
2078 a.st_ino == b.st_ino;
2081 int running_in_chroot(void) {
2084 ret = files_same("/proc/1/root", "/");
2091 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2096 assert(percent <= 100);
2097 assert(new_length >= 3);
2099 if (old_length <= 3 || old_length <= new_length)
2100 return strndup(s, old_length);
2102 r = new0(char, new_length+1);
2106 x = (new_length * percent) / 100;
2108 if (x > new_length - 3)
2116 s + old_length - (new_length - x - 3),
2117 new_length - x - 3);
2122 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2126 unsigned k, len, len2;
2129 assert(percent <= 100);
2130 assert(new_length >= 3);
2132 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2133 if (ascii_is_valid(s))
2134 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2136 if (old_length <= 3 || old_length <= new_length)
2137 return strndup(s, old_length);
2139 x = (new_length * percent) / 100;
2141 if (x > new_length - 3)
2145 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2148 c = utf8_encoded_to_unichar(i);
2151 k += unichar_iswide(c) ? 2 : 1;
2154 if (k > x) /* last character was wide and went over quota */
2157 for (j = s + old_length; k < new_length && j > i; ) {
2160 j = utf8_prev_char(j);
2161 c = utf8_encoded_to_unichar(j);
2164 k += unichar_iswide(c) ? 2 : 1;
2168 /* we don't actually need to ellipsize */
2170 return memdup(s, old_length + 1);
2172 /* make space for ellipsis */
2173 j = utf8_next_char(j);
2176 len2 = s + old_length - j;
2177 e = new(char, len + 3 + len2 + 1);
2182 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2183 old_length, new_length, x, len, len2, k);
2187 e[len] = 0xe2; /* tri-dot ellipsis: … */
2191 memcpy(e + len + 3, j, len2 + 1);
2196 char *ellipsize(const char *s, size_t length, unsigned percent) {
2197 return ellipsize_mem(s, strlen(s), length, percent);
2200 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2201 _cleanup_close_ int fd;
2207 mkdir_parents(path, 0755);
2209 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2214 r = fchmod(fd, mode);
2219 if (uid != UID_INVALID || gid != GID_INVALID) {
2220 r = fchown(fd, uid, gid);
2225 if (stamp != USEC_INFINITY) {
2226 struct timespec ts[2];
2228 timespec_store(&ts[0], stamp);
2230 r = futimens(fd, ts);
2232 r = futimens(fd, NULL);
2239 int touch(const char *path) {
2240 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2243 static char *unquote(const char *s, const char* quotes) {
2247 /* This is rather stupid, simply removes the heading and
2248 * trailing quotes if there is one. Doesn't care about
2249 * escaping or anything.
2251 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2257 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2258 return strndup(s+1, l-2);
2263 noreturn void freeze(void) {
2265 /* Make sure nobody waits for us on a socket anymore */
2266 close_all_fds(NULL, 0);
2274 bool null_or_empty(struct stat *st) {
2277 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2280 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2286 int null_or_empty_path(const char *fn) {
2291 if (stat(fn, &st) < 0)
2294 return null_or_empty(&st);
2297 int null_or_empty_fd(int fd) {
2302 if (fstat(fd, &st) < 0)
2305 return null_or_empty(&st);
2308 DIR *xopendirat(int fd, const char *name, int flags) {
2312 assert(!(flags & O_CREAT));
2314 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2327 int signal_from_string_try_harder(const char *s) {
2331 signo = signal_from_string(s);
2333 if (startswith(s, "SIG"))
2334 return signal_from_string(s+3);
2339 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2340 _cleanup_free_ char *t = NULL, *u = NULL;
2343 u = unquote(tagvalue, QUOTES);
2347 enc_len = strlen(u) * 4 + 1;
2348 t = new(char, enc_len);
2352 if (encode_devnode_name(u, t, enc_len) < 0)
2355 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2358 char *fstab_node_to_udev_node(const char *p) {
2361 if (startswith(p, "LABEL="))
2362 return tag_to_udev_node(p+6, "label");
2364 if (startswith(p, "UUID="))
2365 return tag_to_udev_node(p+5, "uuid");
2367 if (startswith(p, "PARTUUID="))
2368 return tag_to_udev_node(p+9, "partuuid");
2370 if (startswith(p, "PARTLABEL="))
2371 return tag_to_udev_node(p+10, "partlabel");
2376 bool dirent_is_file(const struct dirent *de) {
2379 if (hidden_file(de->d_name))
2382 if (de->d_type != DT_REG &&
2383 de->d_type != DT_LNK &&
2384 de->d_type != DT_UNKNOWN)
2390 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2393 if (de->d_type != DT_REG &&
2394 de->d_type != DT_LNK &&
2395 de->d_type != DT_UNKNOWN)
2398 if (hidden_file_allow_backup(de->d_name))
2401 return endswith(de->d_name, suffix);
2404 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2405 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2406 _cleanup_set_free_free_ Set *seen = NULL;
2409 /* We fork this all off from a child process so that we can
2410 * somewhat cleanly make use of SIGALRM to set a time limit */
2412 reset_all_signal_handlers();
2413 reset_signal_mask();
2415 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2417 pids = hashmap_new(NULL);
2421 seen = set_new(&string_hash_ops);
2425 STRV_FOREACH(directory, directories) {
2426 _cleanup_closedir_ DIR *d;
2429 d = opendir(*directory);
2431 if (errno == ENOENT)
2434 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2437 FOREACH_DIRENT(de, d, break) {
2438 _cleanup_free_ char *path = NULL;
2442 if (!dirent_is_file(de))
2445 if (set_contains(seen, de->d_name)) {
2446 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2450 r = set_put_strdup(seen, de->d_name);
2454 path = strjoin(*directory, "/", de->d_name, NULL);
2458 if (null_or_empty_path(path)) {
2459 log_debug("%s is empty (a mask).", path);
2465 log_error_errno(errno, "Failed to fork: %m");
2467 } else if (pid == 0) {
2470 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2480 return log_error_errno(errno, "Failed to execute %s: %m", path);
2483 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2485 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2492 /* Abort execution of this process after the timout. We simply
2493 * rely on SIGALRM as default action terminating the process,
2494 * and turn on alarm(). */
2496 if (timeout != USEC_INFINITY)
2497 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2499 while (!hashmap_isempty(pids)) {
2500 _cleanup_free_ char *path = NULL;
2503 pid = PTR_TO_UINT(hashmap_first_key(pids));
2506 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2509 wait_for_terminate_and_warn(path, pid, true);
2515 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2519 char **dirs = (char**) directories;
2521 assert(!strv_isempty(dirs));
2523 name = basename(dirs[0]);
2524 assert(!isempty(name));
2526 /* Executes all binaries in the directories in parallel and waits
2527 * for them to finish. Optionally a timeout is applied. If a file
2528 * with the same name exists in more than one directory, the
2529 * earliest one wins. */
2531 executor_pid = fork();
2532 if (executor_pid < 0) {
2533 log_error_errno(errno, "Failed to fork: %m");
2536 } else if (executor_pid == 0) {
2537 r = do_execute(dirs, timeout, argv);
2538 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2541 wait_for_terminate_and_warn(name, executor_pid, true);
2544 bool nulstr_contains(const char*nulstr, const char *needle) {
2550 NULSTR_FOREACH(i, nulstr)
2551 if (streq(i, needle))
2557 bool plymouth_running(void) {
2558 return access("/run/plymouth/pid", F_OK) >= 0;
2561 char* strshorten(char *s, size_t l) {
2570 bool machine_name_is_valid(const char *s) {
2572 if (!hostname_is_valid(s))
2575 /* Machine names should be useful hostnames, but also be
2576 * useful in unit names, hence we enforce a stricter length
2585 int pipe_eof(int fd) {
2586 struct pollfd pollfd = {
2588 .events = POLLIN|POLLHUP,
2593 r = poll(&pollfd, 1, 0);
2600 return pollfd.revents & POLLHUP;
2603 int fd_wait_for_event(int fd, int event, usec_t t) {
2605 struct pollfd pollfd = {
2613 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2620 return pollfd.revents;
2623 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2632 r = tempfn_xxxxxx(path, &t);
2636 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2642 f = fdopen(fd, "we");
2655 int symlink_atomic(const char *from, const char *to) {
2656 _cleanup_free_ char *t = NULL;
2662 r = tempfn_random(to, &t);
2666 if (symlink(from, t) < 0)
2669 if (rename(t, to) < 0) {
2677 int symlink_idempotent(const char *from, const char *to) {
2678 _cleanup_free_ char *p = NULL;
2684 if (symlink(from, to) < 0) {
2685 if (errno != EEXIST)
2688 r = readlink_malloc(to, &p);
2692 if (!streq(p, from))
2699 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2700 _cleanup_free_ char *t = NULL;
2705 r = tempfn_random(path, &t);
2709 if (mknod(t, mode, dev) < 0)
2712 if (rename(t, path) < 0) {
2720 int mkfifo_atomic(const char *path, mode_t mode) {
2721 _cleanup_free_ char *t = NULL;
2726 r = tempfn_random(path, &t);
2730 if (mkfifo(t, mode) < 0)
2733 if (rename(t, path) < 0) {
2741 bool display_is_local(const char *display) {
2745 display[0] == ':' &&
2746 display[1] >= '0' &&
2750 int socket_from_display(const char *display, char **path) {
2757 if (!display_is_local(display))
2760 k = strspn(display+1, "0123456789");
2762 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2766 c = stpcpy(f, "/tmp/.X11-unix/X");
2767 memcpy(c, display+1, k);
2776 const char **username,
2777 uid_t *uid, gid_t *gid,
2779 const char **shell) {
2787 /* We enforce some special rules for uid=0: in order to avoid
2788 * NSS lookups for root we hardcode its data. */
2790 if (streq(*username, "root") || streq(*username, "0")) {
2808 if (parse_uid(*username, &u) >= 0) {
2812 /* If there are multiple users with the same id, make
2813 * sure to leave $USER to the configured value instead
2814 * of the first occurrence in the database. However if
2815 * the uid was configured by a numeric uid, then let's
2816 * pick the real username from /etc/passwd. */
2818 *username = p->pw_name;
2821 p = getpwnam(*username);
2825 return errno > 0 ? -errno : -ESRCH;
2837 *shell = p->pw_shell;
2842 char* uid_to_name(uid_t uid) {
2847 return strdup("root");
2851 return strdup(p->pw_name);
2853 if (asprintf(&r, UID_FMT, uid) < 0)
2859 char* gid_to_name(gid_t gid) {
2864 return strdup("root");
2868 return strdup(p->gr_name);
2870 if (asprintf(&r, GID_FMT, gid) < 0)
2876 int get_group_creds(const char **groupname, gid_t *gid) {
2882 /* We enforce some special rules for gid=0: in order to avoid
2883 * NSS lookups for root we hardcode its data. */
2885 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2886 *groupname = "root";
2894 if (parse_gid(*groupname, &id) >= 0) {
2899 *groupname = g->gr_name;
2902 g = getgrnam(*groupname);
2906 return errno > 0 ? -errno : -ESRCH;
2914 int in_gid(gid_t gid) {
2916 int ngroups_max, r, i;
2918 if (getgid() == gid)
2921 if (getegid() == gid)
2924 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2925 assert(ngroups_max > 0);
2927 gids = alloca(sizeof(gid_t) * ngroups_max);
2929 r = getgroups(ngroups_max, gids);
2933 for (i = 0; i < r; i++)
2940 int in_group(const char *name) {
2944 r = get_group_creds(&name, &gid);
2951 int glob_exists(const char *path) {
2952 _cleanup_globfree_ glob_t g = {};
2958 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2960 if (k == GLOB_NOMATCH)
2962 else if (k == GLOB_NOSPACE)
2965 return !strv_isempty(g.gl_pathv);
2967 return errno ? -errno : -EIO;
2970 int glob_extend(char ***strv, const char *path) {
2971 _cleanup_globfree_ glob_t g = {};
2976 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2978 if (k == GLOB_NOMATCH)
2980 else if (k == GLOB_NOSPACE)
2982 else if (k != 0 || strv_isempty(g.gl_pathv))
2983 return errno ? -errno : -EIO;
2985 STRV_FOREACH(p, g.gl_pathv) {
2986 k = strv_extend(strv, *p);
2994 int dirent_ensure_type(DIR *d, struct dirent *de) {
3000 if (de->d_type != DT_UNKNOWN)
3003 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3007 S_ISREG(st.st_mode) ? DT_REG :
3008 S_ISDIR(st.st_mode) ? DT_DIR :
3009 S_ISLNK(st.st_mode) ? DT_LNK :
3010 S_ISFIFO(st.st_mode) ? DT_FIFO :
3011 S_ISSOCK(st.st_mode) ? DT_SOCK :
3012 S_ISCHR(st.st_mode) ? DT_CHR :
3013 S_ISBLK(st.st_mode) ? DT_BLK :
3019 int get_files_in_directory(const char *path, char ***list) {
3020 _cleanup_closedir_ DIR *d = NULL;
3021 size_t bufsize = 0, n = 0;
3022 _cleanup_strv_free_ char **l = NULL;
3026 /* Returns all files in a directory in *list, and the number
3027 * of files as return value. If list is NULL returns only the
3039 if (!de && errno != 0)
3044 dirent_ensure_type(d, de);
3046 if (!dirent_is_file(de))
3050 /* one extra slot is needed for the terminating NULL */
3051 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3054 l[n] = strdup(de->d_name);
3065 l = NULL; /* avoid freeing */
3071 char *strjoin(const char *x, ...) {
3085 t = va_arg(ap, const char *);
3090 if (n > ((size_t) -1) - l) {
3114 t = va_arg(ap, const char *);
3128 bool is_main_thread(void) {
3129 static thread_local int cached = 0;
3131 if (_unlikely_(cached == 0))
3132 cached = getpid() == gettid() ? 1 : -1;
3137 int block_get_whole_disk(dev_t d, dev_t *ret) {
3144 /* If it has a queue this is good enough for us */
3145 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3148 r = access(p, F_OK);
3156 /* If it is a partition find the originating device */
3157 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3160 r = access(p, F_OK);
3166 /* Get parent dev_t */
3167 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3170 r = read_one_line_file(p, &s);
3176 r = sscanf(s, "%u:%u", &m, &n);
3182 /* Only return this if it is really good enough for us. */
3183 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3186 r = access(p, F_OK);
3190 *ret = makedev(m, n);
3197 static const char *const ioprio_class_table[] = {
3198 [IOPRIO_CLASS_NONE] = "none",
3199 [IOPRIO_CLASS_RT] = "realtime",
3200 [IOPRIO_CLASS_BE] = "best-effort",
3201 [IOPRIO_CLASS_IDLE] = "idle"
3204 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3206 static const char *const sigchld_code_table[] = {
3207 [CLD_EXITED] = "exited",
3208 [CLD_KILLED] = "killed",
3209 [CLD_DUMPED] = "dumped",
3210 [CLD_TRAPPED] = "trapped",
3211 [CLD_STOPPED] = "stopped",
3212 [CLD_CONTINUED] = "continued",
3215 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3217 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3218 [LOG_FAC(LOG_KERN)] = "kern",
3219 [LOG_FAC(LOG_USER)] = "user",
3220 [LOG_FAC(LOG_MAIL)] = "mail",
3221 [LOG_FAC(LOG_DAEMON)] = "daemon",
3222 [LOG_FAC(LOG_AUTH)] = "auth",
3223 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3224 [LOG_FAC(LOG_LPR)] = "lpr",
3225 [LOG_FAC(LOG_NEWS)] = "news",
3226 [LOG_FAC(LOG_UUCP)] = "uucp",
3227 [LOG_FAC(LOG_CRON)] = "cron",
3228 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3229 [LOG_FAC(LOG_FTP)] = "ftp",
3230 [LOG_FAC(LOG_LOCAL0)] = "local0",
3231 [LOG_FAC(LOG_LOCAL1)] = "local1",
3232 [LOG_FAC(LOG_LOCAL2)] = "local2",
3233 [LOG_FAC(LOG_LOCAL3)] = "local3",
3234 [LOG_FAC(LOG_LOCAL4)] = "local4",
3235 [LOG_FAC(LOG_LOCAL5)] = "local5",
3236 [LOG_FAC(LOG_LOCAL6)] = "local6",
3237 [LOG_FAC(LOG_LOCAL7)] = "local7"
3240 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3242 static const char *const log_level_table[] = {
3243 [LOG_EMERG] = "emerg",
3244 [LOG_ALERT] = "alert",
3245 [LOG_CRIT] = "crit",
3247 [LOG_WARNING] = "warning",
3248 [LOG_NOTICE] = "notice",
3249 [LOG_INFO] = "info",
3250 [LOG_DEBUG] = "debug"
3253 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3255 static const char* const sched_policy_table[] = {
3256 [SCHED_OTHER] = "other",
3257 [SCHED_BATCH] = "batch",
3258 [SCHED_IDLE] = "idle",
3259 [SCHED_FIFO] = "fifo",
3263 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3265 static const char* const rlimit_table[_RLIMIT_MAX] = {
3266 [RLIMIT_CPU] = "LimitCPU",
3267 [RLIMIT_FSIZE] = "LimitFSIZE",
3268 [RLIMIT_DATA] = "LimitDATA",
3269 [RLIMIT_STACK] = "LimitSTACK",
3270 [RLIMIT_CORE] = "LimitCORE",
3271 [RLIMIT_RSS] = "LimitRSS",
3272 [RLIMIT_NOFILE] = "LimitNOFILE",
3273 [RLIMIT_AS] = "LimitAS",
3274 [RLIMIT_NPROC] = "LimitNPROC",
3275 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3276 [RLIMIT_LOCKS] = "LimitLOCKS",
3277 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3278 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3279 [RLIMIT_NICE] = "LimitNICE",
3280 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3281 [RLIMIT_RTTIME] = "LimitRTTIME"
3284 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3286 static const char* const ip_tos_table[] = {
3287 [IPTOS_LOWDELAY] = "low-delay",
3288 [IPTOS_THROUGHPUT] = "throughput",
3289 [IPTOS_RELIABILITY] = "reliability",
3290 [IPTOS_LOWCOST] = "low-cost",
3293 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3295 static const char *const __signal_table[] = {
3312 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3323 [SIGVTALRM] = "VTALRM",
3325 [SIGWINCH] = "WINCH",
3331 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3333 const char *signal_to_string(int signo) {
3334 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3337 name = __signal_to_string(signo);
3341 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3342 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3344 snprintf(buf, sizeof(buf), "%d", signo);
3349 int signal_from_string(const char *s) {
3354 signo = __signal_from_string(s);
3358 if (startswith(s, "RTMIN+")) {
3362 if (safe_atou(s, &u) >= 0) {
3363 signo = (int) u + offset;
3364 if (signo > 0 && signo < _NSIG)
3370 bool kexec_loaded(void) {
3371 bool loaded = false;
3374 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3382 int prot_from_flags(int flags) {
3384 switch (flags & O_ACCMODE) {
3393 return PROT_READ|PROT_WRITE;
3400 char *format_bytes(char *buf, size_t l, off_t t) {
3403 static const struct {
3407 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3408 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3409 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3410 { "G", 1024ULL*1024ULL*1024ULL },
3411 { "M", 1024ULL*1024ULL },
3415 if (t == (off_t) -1)
3418 for (i = 0; i < ELEMENTSOF(table); i++) {
3420 if (t >= table[i].factor) {
3423 (unsigned long long) (t / table[i].factor),
3424 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3431 snprintf(buf, l, "%lluB", (unsigned long long) t);
3439 void* memdup(const void *p, size_t l) {
3452 int fd_inc_sndbuf(int fd, size_t n) {
3454 socklen_t l = sizeof(value);
3456 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3457 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3460 /* If we have the privileges we will ignore the kernel limit. */
3463 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3464 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3470 int fd_inc_rcvbuf(int fd, size_t n) {
3472 socklen_t l = sizeof(value);
3474 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3475 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3478 /* If we have the privileges we will ignore the kernel limit. */
3481 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3482 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3487 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3488 bool stdout_is_tty, stderr_is_tty;
3489 pid_t parent_pid, agent_pid;
3490 sigset_t ss, saved_ss;
3498 /* Spawns a temporary TTY agent, making sure it goes away when
3501 parent_pid = getpid();
3503 /* First we temporarily block all signals, so that the new
3504 * child has them blocked initially. This way, we can be sure
3505 * that SIGTERMs are not lost we might send to the agent. */
3506 assert_se(sigfillset(&ss) >= 0);
3507 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3510 if (agent_pid < 0) {
3511 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3515 if (agent_pid != 0) {
3516 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3523 * Make sure the agent goes away when the parent dies */
3524 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3525 _exit(EXIT_FAILURE);
3527 /* Make sure we actually can kill the agent, if we need to, in
3528 * case somebody invoked us from a shell script that trapped
3529 * SIGTERM or so... */
3530 reset_all_signal_handlers();
3531 reset_signal_mask();
3533 /* Check whether our parent died before we were able
3534 * to set the death signal and unblock the signals */
3535 if (getppid() != parent_pid)
3536 _exit(EXIT_SUCCESS);
3538 /* Don't leak fds to the agent */
3539 close_all_fds(except, n_except);
3541 stdout_is_tty = isatty(STDOUT_FILENO);
3542 stderr_is_tty = isatty(STDERR_FILENO);
3544 if (!stdout_is_tty || !stderr_is_tty) {
3547 /* Detach from stdout/stderr. and reopen
3548 * /dev/tty for them. This is important to
3549 * ensure that when systemctl is started via
3550 * popen() or a similar call that expects to
3551 * read EOF we actually do generate EOF and
3552 * not delay this indefinitely by because we
3553 * keep an unused copy of stdin around. */
3554 fd = open("/dev/tty", O_WRONLY);
3556 log_error_errno(errno, "Failed to open /dev/tty: %m");
3557 _exit(EXIT_FAILURE);
3561 dup2(fd, STDOUT_FILENO);
3564 dup2(fd, STDERR_FILENO);
3570 /* Count arguments */
3572 for (n = 0; va_arg(ap, char*); n++)
3577 l = alloca(sizeof(char *) * (n + 1));
3579 /* Fill in arguments */
3581 for (i = 0; i <= n; i++)
3582 l[i] = va_arg(ap, char*);
3586 _exit(EXIT_FAILURE);
3589 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3590 struct rlimit highest, fixed;
3594 if (setrlimit(resource, rlim) >= 0)
3600 /* So we failed to set the desired setrlimit, then let's try
3601 * to get as close as we can */
3602 assert_se(getrlimit(resource, &highest) == 0);
3604 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3605 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3607 if (setrlimit(resource, &fixed) < 0)
3613 bool http_etag_is_valid(const char *etag) {
3617 if (!endswith(etag, "\""))
3620 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3626 bool http_url_is_valid(const char *url) {
3632 p = startswith(url, "http://");
3634 p = startswith(url, "https://");
3641 return ascii_is_valid(p);
3644 bool documentation_url_is_valid(const char *url) {
3650 if (http_url_is_valid(url))
3653 p = startswith(url, "file:/");
3655 p = startswith(url, "info:");
3657 p = startswith(url, "man:");
3662 return ascii_is_valid(p);
3665 bool in_initrd(void) {
3666 static int saved = -1;
3672 /* We make two checks here:
3674 * 1. the flag file /etc/initrd-release must exist
3675 * 2. the root file system must be a memory file system
3677 * The second check is extra paranoia, since misdetecting an
3678 * initrd can have bad bad consequences due the initrd
3679 * emptying when transititioning to the main systemd.
3682 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3683 statfs("/", &s) >= 0 &&
3684 is_temporary_fs(&s);
3689 int get_home_dir(char **_h) {
3697 /* Take the user specified one */
3698 e = secure_getenv("HOME");
3699 if (e && path_is_absolute(e)) {
3708 /* Hardcode home directory for root to avoid NSS */
3711 h = strdup("/root");
3719 /* Check the database... */
3723 return errno > 0 ? -errno : -ESRCH;
3725 if (!path_is_absolute(p->pw_dir))
3728 h = strdup(p->pw_dir);
3736 int get_shell(char **_s) {
3744 /* Take the user specified one */
3745 e = getenv("SHELL");
3755 /* Hardcode home directory for root to avoid NSS */
3758 s = strdup("/bin/sh");
3766 /* Check the database... */
3770 return errno > 0 ? -errno : -ESRCH;
3772 if (!path_is_absolute(p->pw_shell))
3775 s = strdup(p->pw_shell);
3783 bool filename_is_valid(const char *p) {
3797 if (strlen(p) > FILENAME_MAX)
3803 bool string_is_safe(const char *p) {
3809 for (t = p; *t; t++) {
3810 if (*t > 0 && *t < ' ')
3813 if (strchr("\\\"\'\0x7f", *t))
3821 * Check if a string contains control characters. If 'ok' is non-NULL
3822 * it may be a string containing additional CCs to be considered OK.
3824 bool string_has_cc(const char *p, const char *ok) {
3829 for (t = p; *t; t++) {
3830 if (ok && strchr(ok, *t))
3833 if (*t > 0 && *t < ' ')
3843 bool path_is_safe(const char *p) {
3848 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3851 if (strlen(p)+1 > PATH_MAX)
3854 /* The following two checks are not really dangerous, but hey, they still are confusing */
3855 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3858 if (strstr(p, "//"))
3864 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3865 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3866 int (*compar) (const void *, const void *, void *), void *arg) {
3875 p = (void *)(((const char *) base) + (idx * size));
3876 comparison = compar(key, p, arg);
3879 else if (comparison > 0)
3887 void init_gettext(void) {
3888 setlocale(LC_ALL, "");
3889 textdomain(GETTEXT_PACKAGE);
3892 bool is_locale_utf8(void) {
3894 static int cached_answer = -1;
3896 if (cached_answer >= 0)
3899 if (!setlocale(LC_ALL, "")) {
3900 cached_answer = true;
3904 set = nl_langinfo(CODESET);
3906 cached_answer = true;
3910 if (streq(set, "UTF-8")) {
3911 cached_answer = true;
3915 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3916 * unset and everything can do to UTF-8 nowadays. */
3917 set = setlocale(LC_CTYPE, NULL);
3919 cached_answer = true;
3923 /* Check result, but ignore the result if C was set
3927 !getenv("LC_ALL") &&
3928 !getenv("LC_CTYPE") &&
3932 return (bool) cached_answer;
3935 const char *draw_special_char(DrawSpecialChar ch) {
3936 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
3939 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
3940 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
3941 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
3942 [DRAW_TREE_SPACE] = " ", /* */
3943 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
3944 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
3945 [DRAW_ARROW] = "\342\206\222", /* → */
3946 [DRAW_DASH] = "\342\200\223", /* – */
3949 /* ASCII fallback */ {
3950 [DRAW_TREE_VERTICAL] = "| ",
3951 [DRAW_TREE_BRANCH] = "|-",
3952 [DRAW_TREE_RIGHT] = "`-",
3953 [DRAW_TREE_SPACE] = " ",
3954 [DRAW_TRIANGULAR_BULLET] = ">",
3955 [DRAW_BLACK_CIRCLE] = "*",
3956 [DRAW_ARROW] = "->",
3961 return draw_table[!is_locale_utf8()][ch];
3964 char *strreplace(const char *text, const char *old_string, const char *new_string) {
3967 size_t l, old_len, new_len;
3973 old_len = strlen(old_string);
3974 new_len = strlen(new_string);
3987 if (!startswith(f, old_string)) {
3993 nl = l - old_len + new_len;
3994 a = realloc(r, nl + 1);
4002 t = stpcpy(t, new_string);
4014 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4015 const char *i, *begin = NULL;
4020 } state = STATE_OTHER;
4022 size_t osz = 0, isz;
4028 /* Strips ANSI color and replaces TABs by 8 spaces */
4030 isz = _isz ? *_isz : strlen(*ibuf);
4032 f = open_memstream(&obuf, &osz);
4036 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4041 if (i >= *ibuf + isz) /* EOT */
4043 else if (*i == '\x1B')
4044 state = STATE_ESCAPE;
4045 else if (*i == '\t')
4052 if (i >= *ibuf + isz) { /* EOT */
4055 } else if (*i == '[') {
4056 state = STATE_BRACKET;
4061 state = STATE_OTHER;
4068 if (i >= *ibuf + isz || /* EOT */
4069 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4072 state = STATE_OTHER;
4074 } else if (*i == 'm')
4075 state = STATE_OTHER;
4097 int on_ac_power(void) {
4098 bool found_offline = false, found_online = false;
4099 _cleanup_closedir_ DIR *d = NULL;
4101 d = opendir("/sys/class/power_supply");
4103 return errno == ENOENT ? true : -errno;
4107 _cleanup_close_ int fd = -1, device = -1;
4113 if (!de && errno != 0)
4119 if (hidden_file(de->d_name))
4122 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4124 if (errno == ENOENT || errno == ENOTDIR)
4130 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4132 if (errno == ENOENT)
4138 n = read(fd, contents, sizeof(contents));
4142 if (n != 6 || memcmp(contents, "Mains\n", 6))
4146 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4148 if (errno == ENOENT)
4154 n = read(fd, contents, sizeof(contents));
4158 if (n != 2 || contents[1] != '\n')
4161 if (contents[0] == '1') {
4162 found_online = true;
4164 } else if (contents[0] == '0')
4165 found_offline = true;
4170 return found_online || !found_offline;
4173 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4180 if (!path_strv_resolve_uniq(search, root))
4183 STRV_FOREACH(i, search) {
4184 _cleanup_free_ char *p = NULL;
4188 p = strjoin(root, *i, "/", path, NULL);
4190 p = strjoin(*i, "/", path, NULL);
4200 if (errno != ENOENT)
4207 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4208 _cleanup_strv_free_ char **copy = NULL;
4214 if (path_is_absolute(path)) {
4217 f = fopen(path, mode);
4226 copy = strv_copy((char**) search);
4230 return search_and_fopen_internal(path, mode, root, copy, _f);
4233 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4234 _cleanup_strv_free_ char **s = NULL;
4236 if (path_is_absolute(path)) {
4239 f = fopen(path, mode);
4248 s = strv_split_nulstr(search);
4252 return search_and_fopen_internal(path, mode, root, s, _f);
4255 char *strextend(char **x, ...) {
4262 l = f = *x ? strlen(*x) : 0;
4269 t = va_arg(ap, const char *);
4274 if (n > ((size_t) -1) - l) {
4283 r = realloc(*x, l+1);
4293 t = va_arg(ap, const char *);
4307 char *strrep(const char *s, unsigned n) {
4315 p = r = malloc(l * n + 1);
4319 for (i = 0; i < n; i++)
4326 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4333 if (*allocated >= need)
4336 newalloc = MAX(need * 2, 64u / size);
4337 a = newalloc * size;
4339 /* check for overflows */
4340 if (a < size * need)
4348 *allocated = newalloc;
4352 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4361 q = greedy_realloc(p, allocated, need, size);
4365 if (*allocated > prev)
4366 memzero(q + prev * size, (*allocated - prev) * size);
4371 bool id128_is_valid(const char *s) {
4377 /* Simple formatted 128bit hex string */
4379 for (i = 0; i < l; i++) {
4382 if (!(c >= '0' && c <= '9') &&
4383 !(c >= 'a' && c <= 'z') &&
4384 !(c >= 'A' && c <= 'Z'))
4388 } else if (l == 36) {
4390 /* Formatted UUID */
4392 for (i = 0; i < l; i++) {
4395 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4399 if (!(c >= '0' && c <= '9') &&
4400 !(c >= 'a' && c <= 'z') &&
4401 !(c >= 'A' && c <= 'Z'))
4412 int split_pair(const char *s, const char *sep, char **l, char **r) {
4427 a = strndup(s, x - s);
4431 b = strdup(x + strlen(sep));
4443 int shall_restore_state(void) {
4444 _cleanup_free_ char *value = NULL;
4447 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4453 return parse_boolean(value) != 0;
4456 int proc_cmdline(char **ret) {
4459 if (detect_container(NULL) > 0)
4460 return get_process_cmdline(1, 0, false, ret);
4462 return read_one_line_file("/proc/cmdline", ret);
4465 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4466 _cleanup_free_ char *line = NULL;
4472 r = proc_cmdline(&line);
4478 _cleanup_free_ char *word = NULL;
4481 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4487 /* Filter out arguments that are intended only for the
4489 if (!in_initrd() && startswith(word, "rd."))
4492 value = strchr(word, '=');
4496 r = parse_item(word, value);
4504 int get_proc_cmdline_key(const char *key, char **value) {
4505 _cleanup_free_ char *line = NULL, *ret = NULL;
4512 r = proc_cmdline(&line);
4518 _cleanup_free_ char *word = NULL;
4521 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4527 /* Filter out arguments that are intended only for the
4529 if (!in_initrd() && startswith(word, "rd."))
4533 e = startswith(word, key);
4537 r = free_and_strdup(&ret, e);
4543 if (streq(word, key))
4557 int container_get_leader(const char *machine, pid_t *pid) {
4558 _cleanup_free_ char *s = NULL, *class = NULL;
4566 p = strjoina("/run/systemd/machines/", machine);
4567 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4575 if (!streq_ptr(class, "container"))
4578 r = parse_pid(s, &leader);
4588 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4589 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4597 mntns = procfs_file_alloca(pid, "ns/mnt");
4598 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4606 pidns = procfs_file_alloca(pid, "ns/pid");
4607 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4615 netns = procfs_file_alloca(pid, "ns/net");
4616 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4624 root = procfs_file_alloca(pid, "root");
4625 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4631 *pidns_fd = pidnsfd;
4634 *mntns_fd = mntnsfd;
4637 *netns_fd = netnsfd;
4642 pidnsfd = mntnsfd = netnsfd = -1;
4647 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4650 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4654 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4658 if (setns(netns_fd, CLONE_NEWNET) < 0)
4662 if (fchdir(root_fd) < 0)
4665 if (chroot(".") < 0)
4669 if (setresgid(0, 0, 0) < 0)
4672 if (setgroups(0, NULL) < 0)
4675 if (setresuid(0, 0, 0) < 0)
4681 int getpeercred(int fd, struct ucred *ucred) {
4682 socklen_t n = sizeof(struct ucred);
4689 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4693 if (n != sizeof(struct ucred))
4696 /* Check if the data is actually useful and not suppressed due
4697 * to namespacing issues */
4700 if (u.uid == UID_INVALID)
4702 if (u.gid == GID_INVALID)
4709 int getpeersec(int fd, char **ret) {
4721 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4725 if (errno != ERANGE)
4732 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4748 /* This is much like like mkostemp() but is subject to umask(). */
4749 int mkostemp_safe(char *pattern, int flags) {
4750 _cleanup_umask_ mode_t u;
4757 fd = mkostemp(pattern, flags);
4764 int open_tmpfile(const char *path, int flags) {
4771 /* Try O_TMPFILE first, if it is supported */
4772 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4777 /* Fall back to unguessable name + unlinking */
4778 p = strjoina(path, "/systemd-tmp-XXXXXX");
4780 fd = mkostemp_safe(p, flags);
4788 int fd_warn_permissions(const char *path, int fd) {
4791 if (fstat(fd, &st) < 0)
4794 if (st.st_mode & 0111)
4795 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4797 if (st.st_mode & 0002)
4798 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4800 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4801 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);
4806 unsigned long personality_from_string(const char *p) {
4808 /* Parse a personality specifier. We introduce our own
4809 * identifiers that indicate specific ABIs, rather than just
4810 * hints regarding the register size, since we want to keep
4811 * things open for multiple locally supported ABIs for the
4812 * same register size. We try to reuse the ABI identifiers
4813 * used by libseccomp. */
4815 #if defined(__x86_64__)
4817 if (streq(p, "x86"))
4820 if (streq(p, "x86-64"))
4823 #elif defined(__i386__)
4825 if (streq(p, "x86"))
4829 /* personality(7) documents that 0xffffffffUL is used for
4830 * querying the current personality, hence let's use that here
4831 * as error indicator. */
4832 return 0xffffffffUL;
4835 const char* personality_to_string(unsigned long p) {
4837 #if defined(__x86_64__)
4839 if (p == PER_LINUX32)
4845 #elif defined(__i386__)
4854 uint64_t physical_memory(void) {
4857 /* We return this as uint64_t in case we are running as 32bit
4858 * process on a 64bit kernel with huge amounts of memory */
4860 mem = sysconf(_SC_PHYS_PAGES);
4863 return (uint64_t) mem * (uint64_t) page_size();
4866 void hexdump(FILE *f, const void *p, size_t s) {
4867 const uint8_t *b = p;
4870 assert(s == 0 || b);
4875 fprintf(f, "%04x ", n);
4877 for (i = 0; i < 16; i++) {
4882 fprintf(f, "%02x ", b[i]);
4890 for (i = 0; i < 16; i++) {
4895 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4909 int update_reboot_param_file(const char *param) {
4914 r = write_string_file(REBOOT_PARAM_FILE, param);
4916 log_error("Failed to write reboot param to "
4917 REBOOT_PARAM_FILE": %s", strerror(-r));
4919 unlink(REBOOT_PARAM_FILE);
4924 int umount_recursive(const char *prefix, int flags) {
4928 /* Try to umount everything recursively below a
4929 * directory. Also, take care of stacked mounts, and keep
4930 * unmounting them until they are gone. */
4933 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4938 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4939 if (!proc_self_mountinfo)
4943 _cleanup_free_ char *path = NULL, *p = NULL;
4946 k = fscanf(proc_self_mountinfo,
4947 "%*s " /* (1) mount id */
4948 "%*s " /* (2) parent id */
4949 "%*s " /* (3) major:minor */
4950 "%*s " /* (4) root */
4951 "%ms " /* (5) mount point */
4952 "%*s" /* (6) mount options */
4953 "%*[^-]" /* (7) optional fields */
4954 "- " /* (8) separator */
4955 "%*s " /* (9) file system type */
4956 "%*s" /* (10) mount source */
4957 "%*s" /* (11) mount options 2 */
4958 "%*[^\n]", /* some rubbish at the end */
4967 r = cunescape(path, UNESCAPE_RELAX, &p);
4971 if (!path_startswith(p, prefix))
4974 if (umount2(p, flags) < 0) {
4990 static int get_mount_flags(const char *path, unsigned long *flags) {
4993 if (statvfs(path, &buf) < 0)
4995 *flags = buf.f_flag;
4999 int bind_remount_recursive(const char *prefix, bool ro) {
5000 _cleanup_set_free_free_ Set *done = NULL;
5001 _cleanup_free_ char *cleaned = NULL;
5004 /* Recursively remount a directory (and all its submounts)
5005 * read-only or read-write. If the directory is already
5006 * mounted, we reuse the mount and simply mark it
5007 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5008 * operation). If it isn't we first make it one. Afterwards we
5009 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5010 * submounts we can access, too. When mounts are stacked on
5011 * the same mount point we only care for each individual
5012 * "top-level" mount on each point, as we cannot
5013 * influence/access the underlying mounts anyway. We do not
5014 * have any effect on future submounts that might get
5015 * propagated, they migt be writable. This includes future
5016 * submounts that have been triggered via autofs. */
5018 cleaned = strdup(prefix);
5022 path_kill_slashes(cleaned);
5024 done = set_new(&string_hash_ops);
5029 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5030 _cleanup_set_free_free_ Set *todo = NULL;
5031 bool top_autofs = false;
5033 unsigned long orig_flags;
5035 todo = set_new(&string_hash_ops);
5039 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5040 if (!proc_self_mountinfo)
5044 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5047 k = fscanf(proc_self_mountinfo,
5048 "%*s " /* (1) mount id */
5049 "%*s " /* (2) parent id */
5050 "%*s " /* (3) major:minor */
5051 "%*s " /* (4) root */
5052 "%ms " /* (5) mount point */
5053 "%*s" /* (6) mount options (superblock) */
5054 "%*[^-]" /* (7) optional fields */
5055 "- " /* (8) separator */
5056 "%ms " /* (9) file system type */
5057 "%*s" /* (10) mount source */
5058 "%*s" /* (11) mount options (bind mount) */
5059 "%*[^\n]", /* some rubbish at the end */
5069 r = cunescape(path, UNESCAPE_RELAX, &p);
5073 /* Let's ignore autofs mounts. If they aren't
5074 * triggered yet, we want to avoid triggering
5075 * them, as we don't make any guarantees for
5076 * future submounts anyway. If they are
5077 * already triggered, then we will find
5078 * another entry for this. */
5079 if (streq(type, "autofs")) {
5080 top_autofs = top_autofs || path_equal(cleaned, p);
5084 if (path_startswith(p, cleaned) &&
5085 !set_contains(done, p)) {
5087 r = set_consume(todo, p);
5097 /* If we have no submounts to process anymore and if
5098 * the root is either already done, or an autofs, we
5100 if (set_isempty(todo) &&
5101 (top_autofs || set_contains(done, cleaned)))
5104 if (!set_contains(done, cleaned) &&
5105 !set_contains(todo, cleaned)) {
5106 /* The prefix directory itself is not yet a
5107 * mount, make it one. */
5108 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5112 (void) get_mount_flags(cleaned, &orig_flags);
5113 orig_flags &= ~MS_RDONLY;
5115 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5118 x = strdup(cleaned);
5122 r = set_consume(done, x);
5127 while ((x = set_steal_first(todo))) {
5129 r = set_consume(done, x);
5135 /* Try to reuse the original flag set, but
5136 * don't care for errors, in case of
5137 * obstructed mounts */
5139 (void) get_mount_flags(x, &orig_flags);
5140 orig_flags &= ~MS_RDONLY;
5142 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5144 /* Deal with mount points that are
5145 * obstructed by a later mount */
5147 if (errno != ENOENT)
5155 int fflush_and_check(FILE *f) {
5162 return errno ? -errno : -EIO;
5167 int tempfn_xxxxxx(const char *p, char **ret) {
5179 * /foo/bar/.#waldoXXXXXX
5183 if (!filename_is_valid(fn))
5186 t = new(char, strlen(p) + 2 + 6 + 1);
5190 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5192 *ret = path_kill_slashes(t);
5196 int tempfn_random(const char *p, char **ret) {
5210 * /foo/bar/.#waldobaa2a261115984a9
5214 if (!filename_is_valid(fn))
5217 t = new(char, strlen(p) + 2 + 16 + 1);
5221 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5224 for (i = 0; i < 16; i++) {
5225 *(x++) = hexchar(u & 0xF);
5231 *ret = path_kill_slashes(t);
5235 int tempfn_random_child(const char *p, char **ret) {
5246 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5249 t = new(char, strlen(p) + 3 + 16 + 1);
5253 x = stpcpy(stpcpy(t, p), "/.#");
5256 for (i = 0; i < 16; i++) {
5257 *(x++) = hexchar(u & 0xF);
5263 *ret = path_kill_slashes(t);
5267 int take_password_lock(const char *root) {
5269 struct flock flock = {
5271 .l_whence = SEEK_SET,
5279 /* This is roughly the same as lckpwdf(), but not as awful. We
5280 * don't want to use alarm() and signals, hence we implement
5281 * our own trivial version of this.
5283 * Note that shadow-utils also takes per-database locks in
5284 * addition to lckpwdf(). However, we don't given that they
5285 * are redundant as they they invoke lckpwdf() first and keep
5286 * it during everything they do. The per-database locks are
5287 * awfully racy, and thus we just won't do them. */
5290 path = strjoina(root, "/etc/.pwd.lock");
5292 path = "/etc/.pwd.lock";
5294 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5298 r = fcntl(fd, F_SETLKW, &flock);
5307 int is_symlink(const char *path) {
5310 if (lstat(path, &info) < 0)
5313 return !!S_ISLNK(info.st_mode);
5316 int is_dir(const char* path, bool follow) {
5321 r = stat(path, &st);
5323 r = lstat(path, &st);
5327 return !!S_ISDIR(st.st_mode);
5330 int is_device_node(const char *path) {
5333 if (lstat(path, &info) < 0)
5336 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5339 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5340 _cleanup_free_ char *s = NULL;
5341 size_t allocated = 0, sz = 0;
5349 SINGLE_QUOTE_ESCAPE,
5351 DOUBLE_QUOTE_ESCAPE,
5359 /* Parses the first word of a string, and returns it in
5360 * *ret. Removes all quotes in the process. When parsing fails
5361 * (because of an uneven number of quotes or similar), leaves
5362 * the pointer *p at the first invalid character. */
5372 else if (strchr(WHITESPACE, c))
5382 state = SINGLE_QUOTE;
5384 state = VALUE_ESCAPE;
5386 state = DOUBLE_QUOTE;
5387 else if (strchr(WHITESPACE, c))
5390 if (!GREEDY_REALLOC(s, allocated, sz+2))
5400 if (flags & UNQUOTE_RELAX)
5405 if (!GREEDY_REALLOC(s, allocated, sz+7))
5408 if (flags & UNQUOTE_CUNESCAPE) {
5411 r = cunescape_one(*p, (size_t) -1, &c, &u);
5418 s[sz++] = c; /* normal explicit char */
5420 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5429 if (flags & UNQUOTE_RELAX)
5432 } else if (c == '\'')
5435 state = SINGLE_QUOTE_ESCAPE;
5437 if (!GREEDY_REALLOC(s, allocated, sz+2))
5445 case SINGLE_QUOTE_ESCAPE:
5447 if (flags & UNQUOTE_RELAX)
5452 if (!GREEDY_REALLOC(s, allocated, sz+7))
5455 if (flags & UNQUOTE_CUNESCAPE) {
5458 r = cunescape_one(*p, (size_t) -1, &c, &u);
5467 sz += utf8_encode_unichar(s + sz, u);
5471 state = SINGLE_QUOTE;
5480 state = DOUBLE_QUOTE_ESCAPE;
5482 if (!GREEDY_REALLOC(s, allocated, sz+2))
5490 case DOUBLE_QUOTE_ESCAPE:
5492 if (flags & UNQUOTE_RELAX)
5497 if (!GREEDY_REALLOC(s, allocated, sz+7))
5500 if (flags & UNQUOTE_CUNESCAPE) {
5503 r = cunescape_one(*p, (size_t) -1, &c, &u);
5512 sz += utf8_encode_unichar(s + sz, u);
5516 state = DOUBLE_QUOTE;
5522 if (!strchr(WHITESPACE, c))
5544 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5549 /* Parses a number of words from a string, stripping any
5550 * quotes if necessary. */
5554 /* Count how many words are expected */
5555 va_start(ap, flags);
5557 if (!va_arg(ap, char **))
5566 /* Read all words into a temporary array */
5567 l = newa0(char*, n);
5568 for (c = 0; c < n; c++) {
5570 r = unquote_first_word(p, &l[c], flags);
5574 for (j = 0; j < c; j++)
5584 /* If we managed to parse all words, return them in the passed
5586 va_start(ap, flags);
5587 for (i = 0; i < n; i++) {
5590 v = va_arg(ap, char **);
5600 int free_and_strdup(char **p, const char *s) {
5605 /* Replaces a string pointer with an strdup()ed new string,
5606 * possibly freeing the old one. */
5608 if (streq_ptr(*p, s))
5624 int ptsname_malloc(int fd, char **ret) {
5637 if (ptsname_r(fd, c, l) == 0) {
5641 if (errno != ERANGE) {
5651 int openpt_in_namespace(pid_t pid, int flags) {
5652 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5653 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5655 struct cmsghdr cmsghdr;
5656 uint8_t buf[CMSG_SPACE(sizeof(int))];
5658 struct msghdr mh = {
5659 .msg_control = &control,
5660 .msg_controllen = sizeof(control),
5662 struct cmsghdr *cmsg;
5669 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5673 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5683 pair[0] = safe_close(pair[0]);
5685 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5687 _exit(EXIT_FAILURE);
5689 master = posix_openpt(flags);
5691 _exit(EXIT_FAILURE);
5693 cmsg = CMSG_FIRSTHDR(&mh);
5694 cmsg->cmsg_level = SOL_SOCKET;
5695 cmsg->cmsg_type = SCM_RIGHTS;
5696 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5697 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5699 mh.msg_controllen = cmsg->cmsg_len;
5701 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5702 _exit(EXIT_FAILURE);
5704 _exit(EXIT_SUCCESS);
5707 pair[1] = safe_close(pair[1]);
5709 r = wait_for_terminate(child, &si);
5712 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5715 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5718 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5719 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5723 fds = (int*) CMSG_DATA(cmsg);
5724 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5727 close_many(fds, n_fds);
5737 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5738 _cleanup_close_ int fd = -1;
5741 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5743 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5747 l = fgetxattr(fd, attribute, value, size);
5754 static int parse_crtime(le64_t le, usec_t *usec) {
5760 if (u == 0 || u == (uint64_t) -1)
5767 int fd_getcrtime(int fd, usec_t *usec) {
5774 /* Until Linux gets a real concept of birthtime/creation time,
5775 * let's fake one with xattrs */
5777 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5780 if (n != sizeof(le))
5783 return parse_crtime(le, usec);
5786 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5790 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5793 if (n != sizeof(le))
5796 return parse_crtime(le, usec);
5799 int path_getcrtime(const char *p, usec_t *usec) {
5806 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5809 if (n != sizeof(le))
5812 return parse_crtime(le, usec);
5815 int fd_setcrtime(int fd, usec_t usec) {
5821 usec = now(CLOCK_REALTIME);
5823 le = htole64((uint64_t) usec);
5824 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5830 int chattr_fd(int fd, unsigned value, unsigned mask) {
5831 unsigned old_attr, new_attr;
5836 if (fstat(fd, &st) < 0)
5839 /* Explicitly check whether this is a regular file or
5840 * directory. If it is anything else (such as a device node or
5841 * fifo), then the ioctl will not hit the file systems but
5842 * possibly drivers, where the ioctl might have different
5843 * effects. Notably, DRM is using the same ioctl() number. */
5845 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5851 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5854 new_attr = (old_attr & ~mask) | (value & mask);
5855 if (new_attr == old_attr)
5858 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5864 int chattr_path(const char *p, unsigned value, unsigned mask) {
5865 _cleanup_close_ int fd = -1;
5872 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5876 return chattr_fd(fd, value, mask);
5879 int read_attr_fd(int fd, unsigned *ret) {
5884 if (fstat(fd, &st) < 0)
5887 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5890 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5896 int read_attr_path(const char *p, unsigned *ret) {
5897 _cleanup_close_ int fd = -1;
5902 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5906 return read_attr_fd(fd, ret);
5909 static size_t nul_length(const uint8_t *p, size_t sz) {
5924 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
5925 const uint8_t *q, *w, *e;
5933 n = nul_length(q, e - q);
5935 /* If there are more than the specified run length of
5936 * NUL bytes, or if this is the beginning or the end
5937 * of the buffer, then seek instead of write */
5938 if ((n > run_length) ||
5939 (n > 0 && q == p) ||
5940 (n > 0 && q + n >= e)) {
5942 l = write(fd, w, q - w);
5949 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
5961 l = write(fd, w, q - w);
5968 return q - (const uint8_t*) p;
5971 void sigkill_wait(pid_t *pid) {
5977 if (kill(*pid, SIGKILL) > 0)
5978 (void) wait_for_terminate(*pid, NULL);
5981 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
5982 int a = 0, b = 0, c = 0;
5992 if (!strchr(*p, '>'))
5995 if ((*p)[2] == '>') {
5996 c = undecchar((*p)[1]);
5998 } else if ((*p)[3] == '>') {
5999 b = undecchar((*p)[1]);
6000 c = undecchar((*p)[2]);
6002 } else if ((*p)[4] == '>') {
6003 a = undecchar((*p)[1]);
6004 b = undecchar((*p)[2]);
6005 c = undecchar((*p)[3]);
6010 if (a < 0 || b < 0 || c < 0 ||
6011 (!with_facility && (a || b || c > 7)))
6015 *priority = a*100 + b*10 + c;
6017 *priority = (*priority & LOG_FACMASK) | c;
6023 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6029 for (i = 0; i < len; ++i)
6030 if (streq_ptr(table[i], key))
6036 void cmsg_close_all(struct msghdr *mh) {
6037 struct cmsghdr *cmsg;
6041 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6042 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6043 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6046 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6050 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6054 /* Even though renameat2() exists since Linux 3.15, btrfs added
6055 * support for it later. If it is not implemented, fallback to another
6057 if (errno != EINVAL)
6060 /* The link()/unlink() fallback does not work on directories. But
6061 * renameat() without RENAME_NOREPLACE gives the same semantics on
6062 * directories, except when newpath is an *empty* directory. This is
6064 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6065 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6066 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6067 return ret >= 0 ? 0 : -errno;
6070 /* If it is not a directory, use the link()/unlink() fallback. */
6071 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6075 ret = unlinkat(olddirfd, oldpath, 0);
6077 /* backup errno before the following unlinkat() alters it */
6079 (void) unlinkat(newdirfd, newpath, 0);
6087 char *shell_maybe_quote(const char *s) {
6093 /* Encloses a string in double quotes if necessary to make it
6094 * OK as shell string. */
6096 for (p = s; *p; p++)
6099 strchr(SHELL_NEED_QUOTES, *p))
6105 r = new(char, 1+strlen(s)*2+1+1);
6111 t = mempcpy(t, s, p - s);
6115 if (strchr(SHELL_NEED_ESCAPE, *p))
6127 int parse_mode(const char *s, mode_t *ret) {
6135 l = strtol(s, &x, 8);
6139 if (!x || x == s || *x)
6141 if (l < 0 || l > 07777)