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 POSIX
64 * version which is really broken. We prefer GNU basename(). */
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"
96 #include "signal-util.h"
98 /* Put this test here for a lack of better place */
99 assert_cc(EAGAIN == EWOULDBLOCK);
102 char **saved_argv = NULL;
104 size_t page_size(void) {
105 static thread_local size_t pgsz = 0;
108 if (_likely_(pgsz > 0))
111 r = sysconf(_SC_PAGESIZE);
118 bool streq_ptr(const char *a, const char *b) {
120 /* Like streq(), but tries to make sense of NULL pointers */
131 char* endswith(const char *s, const char *postfix) {
138 pl = strlen(postfix);
141 return (char*) s + sl;
146 if (memcmp(s + sl - pl, postfix, pl) != 0)
149 return (char*) s + sl - pl;
152 char* endswith_no_case(const char *s, const char *postfix) {
159 pl = strlen(postfix);
162 return (char*) s + sl;
167 if (strcasecmp(s + sl - pl, postfix) != 0)
170 return (char*) s + sl - pl;
173 char* first_word(const char *s, const char *word) {
180 /* Checks if the string starts with the specified word, either
181 * followed by NUL or by whitespace. Returns a pointer to the
182 * NUL or the first character after the whitespace. */
193 if (memcmp(s, word, wl) != 0)
200 if (!strchr(WHITESPACE, *p))
203 p += strspn(p, WHITESPACE);
207 size_t cescape_char(char c, char *buf) {
208 char * buf_old = buf;
254 /* For special chars we prefer octal over
255 * hexadecimal encoding, simply because glib's
256 * g_strescape() does the same */
257 if ((c < ' ') || (c >= 127)) {
259 *(buf++) = octchar((unsigned char) c >> 6);
260 *(buf++) = octchar((unsigned char) c >> 3);
261 *(buf++) = octchar((unsigned char) c);
267 return buf - buf_old;
270 int close_nointr(int fd) {
277 * Just ignore EINTR; a retry loop is the wrong thing to do on
280 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
281 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
282 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
283 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
291 int safe_close(int fd) {
294 * Like close_nointr() but cannot fail. Guarantees errno is
295 * unchanged. Is a NOP with negative fds passed, and returns
296 * -1, so that it can be used in this syntax:
298 * fd = safe_close(fd);
304 /* The kernel might return pretty much any error code
305 * via close(), but the fd will be closed anyway. The
306 * only condition we want to check for here is whether
307 * the fd was invalid at all... */
309 assert_se(close_nointr(fd) != -EBADF);
315 void close_many(const int fds[], unsigned n_fd) {
318 assert(fds || n_fd <= 0);
320 for (i = 0; i < n_fd; i++)
324 int unlink_noerrno(const char *path) {
335 int parse_boolean(const char *v) {
338 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
340 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
346 int parse_pid(const char *s, pid_t* ret_pid) {
347 unsigned long ul = 0;
354 r = safe_atolu(s, &ul);
360 if ((unsigned long) pid != ul)
370 int parse_uid(const char *s, uid_t* ret_uid) {
371 unsigned long ul = 0;
377 r = safe_atolu(s, &ul);
383 if ((unsigned long) uid != ul)
386 /* Some libc APIs use UID_INVALID as special placeholder */
387 if (uid == (uid_t) 0xFFFFFFFF)
390 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
391 if (uid == (uid_t) 0xFFFF)
400 int safe_atou(const char *s, unsigned *ret_u) {
408 l = strtoul(s, &x, 0);
410 if (!x || x == s || *x || errno)
411 return errno > 0 ? -errno : -EINVAL;
413 if ((unsigned long) (unsigned) l != l)
416 *ret_u = (unsigned) l;
420 int safe_atoi(const char *s, int *ret_i) {
428 l = strtol(s, &x, 0);
430 if (!x || x == s || *x || errno)
431 return errno > 0 ? -errno : -EINVAL;
433 if ((long) (int) l != l)
440 int safe_atou8(const char *s, uint8_t *ret) {
448 l = strtoul(s, &x, 0);
450 if (!x || x == s || *x || errno)
451 return errno > 0 ? -errno : -EINVAL;
453 if ((unsigned long) (uint8_t) l != l)
460 int safe_atou16(const char *s, uint16_t *ret) {
468 l = strtoul(s, &x, 0);
470 if (!x || x == s || *x || errno)
471 return errno > 0 ? -errno : -EINVAL;
473 if ((unsigned long) (uint16_t) l != l)
480 int safe_atoi16(const char *s, int16_t *ret) {
488 l = strtol(s, &x, 0);
490 if (!x || x == s || *x || errno)
491 return errno > 0 ? -errno : -EINVAL;
493 if ((long) (int16_t) l != l)
500 int safe_atollu(const char *s, long long unsigned *ret_llu) {
502 unsigned long long l;
508 l = strtoull(s, &x, 0);
510 if (!x || x == s || *x || errno)
511 return errno ? -errno : -EINVAL;
517 int safe_atolli(const char *s, long long int *ret_lli) {
525 l = strtoll(s, &x, 0);
527 if (!x || x == s || *x || errno)
528 return errno ? -errno : -EINVAL;
534 int safe_atod(const char *s, double *ret_d) {
542 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
543 if (loc == (locale_t) 0)
547 d = strtod_l(s, &x, loc);
549 if (!x || x == s || *x || errno) {
551 return errno ? -errno : -EINVAL;
559 static size_t strcspn_escaped(const char *s, const char *reject) {
560 bool escaped = false;
563 for (n=0; s[n]; n++) {
566 else if (s[n] == '\\')
568 else if (strchr(reject, s[n]))
572 /* if s ends in \, return index of previous char */
576 /* Split a string into words. */
577 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
583 assert(**state == '\0');
587 current += strspn(current, separator);
593 if (quoted && strchr("\'\"", *current)) {
594 char quotechars[2] = {*current, '\0'};
596 *l = strcspn_escaped(current + 1, quotechars);
597 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
598 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
599 /* right quote missing or garbage at the end */
603 *state = current++ + *l + 2;
605 *l = strcspn_escaped(current, separator);
606 if (current[*l] && !strchr(separator, current[*l])) {
607 /* unfinished escape */
611 *state = current + *l;
613 *l = strcspn(current, separator);
614 *state = current + *l;
620 int fchmod_umask(int fd, mode_t m) {
625 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
631 char *truncate_nl(char *s) {
634 s[strcspn(s, NEWLINE)] = 0;
638 char *strnappend(const char *s, const char *suffix, size_t b) {
646 return strndup(suffix, b);
655 if (b > ((size_t) -1) - a)
658 r = new(char, a+b+1);
663 memcpy(r+a, suffix, b);
669 char *strappend(const char *s, const char *suffix) {
670 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
673 int readlinkat_malloc(int fd, const char *p, char **ret) {
688 n = readlinkat(fd, p, c, l-1);
695 if ((size_t) n < l-1) {
706 int readlink_malloc(const char *p, char **ret) {
707 return readlinkat_malloc(AT_FDCWD, p, ret);
710 int readlink_value(const char *p, char **ret) {
711 _cleanup_free_ char *link = NULL;
715 r = readlink_malloc(p, &link);
719 value = basename(link);
723 value = strdup(value);
732 int readlink_and_make_absolute(const char *p, char **r) {
733 _cleanup_free_ char *target = NULL;
740 j = readlink_malloc(p, &target);
744 k = file_in_same_dir(p, target);
752 int readlink_and_canonicalize(const char *p, char **r) {
759 j = readlink_and_make_absolute(p, &t);
763 s = canonicalize_file_name(t);
770 path_kill_slashes(*r);
775 char *strstrip(char *s) {
778 /* Drops trailing whitespace. Modifies the string in
779 * place. Returns pointer to first non-space character */
781 s += strspn(s, WHITESPACE);
783 for (e = strchr(s, 0); e > s; e --)
784 if (!strchr(WHITESPACE, e[-1]))
792 char *delete_chars(char *s, const char *bad) {
795 /* Drops all whitespace, regardless where in the string */
797 for (f = s, t = s; *f; f++) {
809 char *file_in_same_dir(const char *path, const char *filename) {
816 /* This removes the last component of path and appends
817 * filename, unless the latter is absolute anyway or the
820 if (path_is_absolute(filename))
821 return strdup(filename);
823 e = strrchr(path, '/');
825 return strdup(filename);
827 k = strlen(filename);
828 ret = new(char, (e + 1 - path) + k + 1);
832 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
836 int rmdir_parents(const char *path, const char *stop) {
845 /* Skip trailing slashes */
846 while (l > 0 && path[l-1] == '/')
852 /* Skip last component */
853 while (l > 0 && path[l-1] != '/')
856 /* Skip trailing slashes */
857 while (l > 0 && path[l-1] == '/')
863 if (!(t = strndup(path, l)))
866 if (path_startswith(stop, t)) {
882 char hexchar(int x) {
883 static const char table[16] = "0123456789abcdef";
885 return table[x & 15];
888 int unhexchar(char c) {
890 if (c >= '0' && c <= '9')
893 if (c >= 'a' && c <= 'f')
896 if (c >= 'A' && c <= 'F')
902 char *hexmem(const void *p, size_t l) {
906 z = r = malloc(l * 2 + 1);
910 for (x = p; x < (const uint8_t*) p + l; x++) {
911 *(z++) = hexchar(*x >> 4);
912 *(z++) = hexchar(*x & 15);
919 void *unhexmem(const char *p, size_t l) {
925 z = r = malloc((l + 1) / 2 + 1);
929 for (x = p; x < p + l; x += 2) {
938 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
945 char octchar(int x) {
946 return '0' + (x & 7);
949 int unoctchar(char c) {
951 if (c >= '0' && c <= '7')
957 char decchar(int x) {
958 return '0' + (x % 10);
961 int undecchar(char c) {
963 if (c >= '0' && c <= '9')
969 char *cescape(const char *s) {
975 /* Does C style string escaping. May be reversed with
978 r = new(char, strlen(s)*4 + 1);
982 for (f = s, t = r; *f; f++)
983 t += cescape_char(*f, t);
990 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
997 /* Unescapes C style. Returns the unescaped character in ret,
998 * unless we encountered a \u sequence in which case the full
999 * unicode character is returned in ret_unicode, instead. */
1001 if (length != (size_t) -1 && length < 1)
1038 /* This is an extension of the XDG syntax files */
1043 /* hexadecimal encoding */
1046 if (length != (size_t) -1 && length < 3)
1049 a = unhexchar(p[1]);
1053 b = unhexchar(p[2]);
1057 /* Don't allow NUL bytes */
1058 if (a == 0 && b == 0)
1061 *ret = (char) ((a << 4U) | b);
1067 /* C++11 style 16bit unicode */
1073 if (length != (size_t) -1 && length < 5)
1076 for (i = 0; i < 4; i++) {
1077 a[i] = unhexchar(p[1 + i]);
1082 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1084 /* Don't allow 0 chars */
1103 /* C++11 style 32bit unicode */
1109 if (length != (size_t) -1 && length < 9)
1112 for (i = 0; i < 8; i++) {
1113 a[i] = unhexchar(p[1 + i]);
1118 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1119 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1121 /* Don't allow 0 chars */
1125 /* Don't allow invalid code points */
1126 if (!unichar_is_valid(c))
1151 /* octal encoding */
1155 if (length != (size_t) -1 && length < 3)
1158 a = unoctchar(p[0]);
1162 b = unoctchar(p[1]);
1166 c = unoctchar(p[2]);
1170 /* don't allow NUL bytes */
1171 if (a == 0 && b == 0 && c == 0)
1174 /* Don't allow bytes above 255 */
1175 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1191 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1199 /* Undoes C style string escaping, and optionally prefixes it. */
1201 pl = prefix ? strlen(prefix) : 0;
1203 r = new(char, pl+length+1);
1208 memcpy(r, prefix, pl);
1210 for (f = s, t = r + pl; f < s + length; f++) {
1216 remaining = s + length - f;
1217 assert(remaining > 0);
1220 /* A literal literal, copy verbatim */
1225 if (remaining == 1) {
1226 if (flags & UNESCAPE_RELAX) {
1227 /* A trailing backslash, copy verbatim */
1236 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1238 if (flags & UNESCAPE_RELAX) {
1239 /* Invalid escape code, let's take it literal then */
1249 /* Non-Unicode? Let's encode this directly */
1252 /* Unicode? Then let's encode this in UTF-8 */
1253 t += utf8_encode_unichar(t, u);
1264 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1265 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1268 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1269 return cunescape_length(s, strlen(s), flags, ret);
1272 char *xescape(const char *s, const char *bad) {
1276 /* Escapes all chars in bad, in addition to \ and all special
1277 * chars, in \xFF style escaping. May be reversed with
1280 r = new(char, strlen(s) * 4 + 1);
1284 for (f = s, t = r; *f; f++) {
1286 if ((*f < ' ') || (*f >= 127) ||
1287 (*f == '\\') || strchr(bad, *f)) {
1290 *(t++) = hexchar(*f >> 4);
1291 *(t++) = hexchar(*f);
1301 char *ascii_strlower(char *t) {
1306 for (p = t; *p; p++)
1307 if (*p >= 'A' && *p <= 'Z')
1308 *p = *p - 'A' + 'a';
1313 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1317 filename[0] == '.' ||
1318 streq(filename, "lost+found") ||
1319 streq(filename, "aquota.user") ||
1320 streq(filename, "aquota.group") ||
1321 endswith(filename, ".rpmnew") ||
1322 endswith(filename, ".rpmsave") ||
1323 endswith(filename, ".rpmorig") ||
1324 endswith(filename, ".dpkg-old") ||
1325 endswith(filename, ".dpkg-new") ||
1326 endswith(filename, ".dpkg-tmp") ||
1327 endswith(filename, ".dpkg-dist") ||
1328 endswith(filename, ".dpkg-bak") ||
1329 endswith(filename, ".dpkg-backup") ||
1330 endswith(filename, ".dpkg-remove") ||
1331 endswith(filename, ".swp");
1334 bool hidden_file(const char *filename) {
1337 if (endswith(filename, "~"))
1340 return hidden_file_allow_backup(filename);
1343 int fd_nonblock(int fd, bool nonblock) {
1348 flags = fcntl(fd, F_GETFL, 0);
1353 nflags = flags | O_NONBLOCK;
1355 nflags = flags & ~O_NONBLOCK;
1357 if (nflags == flags)
1360 if (fcntl(fd, F_SETFL, nflags) < 0)
1366 int fd_cloexec(int fd, bool cloexec) {
1371 flags = fcntl(fd, F_GETFD, 0);
1376 nflags = flags | FD_CLOEXEC;
1378 nflags = flags & ~FD_CLOEXEC;
1380 if (nflags == flags)
1383 if (fcntl(fd, F_SETFD, nflags) < 0)
1389 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1392 assert(n_fdset == 0 || fdset);
1394 for (i = 0; i < n_fdset; i++)
1401 int close_all_fds(const int except[], unsigned n_except) {
1402 _cleanup_closedir_ DIR *d = NULL;
1406 assert(n_except == 0 || except);
1408 d = opendir("/proc/self/fd");
1413 /* When /proc isn't available (for example in chroots)
1414 * the fallback is brute forcing through the fd
1417 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1418 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1420 if (fd_in_set(fd, except, n_except))
1423 if (close_nointr(fd) < 0)
1424 if (errno != EBADF && r == 0)
1431 while ((de = readdir(d))) {
1434 if (hidden_file(de->d_name))
1437 if (safe_atoi(de->d_name, &fd) < 0)
1438 /* Let's better ignore this, just in case */
1447 if (fd_in_set(fd, except, n_except))
1450 if (close_nointr(fd) < 0) {
1451 /* Valgrind has its own FD and doesn't want to have it closed */
1452 if (errno != EBADF && r == 0)
1460 bool chars_intersect(const char *a, const char *b) {
1463 /* Returns true if any of the chars in a are in b. */
1464 for (p = a; *p; p++)
1471 bool fstype_is_network(const char *fstype) {
1472 static const char table[] =
1487 x = startswith(fstype, "fuse.");
1491 return nulstr_contains(table, fstype);
1494 int flush_fd(int fd) {
1495 struct pollfd pollfd = {
1505 r = poll(&pollfd, 1, 0);
1515 l = read(fd, buf, sizeof(buf));
1521 if (errno == EAGAIN)
1530 void safe_close_pair(int p[]) {
1534 /* Special case pairs which use the same fd in both
1536 p[0] = p[1] = safe_close(p[0]);
1540 p[0] = safe_close(p[0]);
1541 p[1] = safe_close(p[1]);
1544 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1551 while (nbytes > 0) {
1554 k = read(fd, p, nbytes);
1559 if (errno == EAGAIN && do_poll) {
1561 /* We knowingly ignore any return value here,
1562 * and expect that any error/EOF is reported
1565 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1569 return n > 0 ? n : -errno;
1583 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1586 n = loop_read(fd, buf, nbytes, do_poll);
1589 if ((size_t) n != nbytes)
1594 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1595 const uint8_t *p = buf;
1605 k = write(fd, p, nbytes);
1610 if (errno == EAGAIN && do_poll) {
1611 /* We knowingly ignore any return value here,
1612 * and expect that any error/EOF is reported
1615 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1622 if (nbytes > 0 && k == 0) /* Can't really happen */
1627 } while (nbytes > 0);
1632 int parse_size(const char *t, off_t base, off_t *size) {
1634 /* Soo, sometimes we want to parse IEC binary suffixes, and
1635 * sometimes SI decimal suffixes. This function can parse
1636 * both. Which one is the right way depends on the
1637 * context. Wikipedia suggests that SI is customary for
1638 * hardware metrics and network speeds, while IEC is
1639 * customary for most data sizes used by software and volatile
1640 * (RAM) memory. Hence be careful which one you pick!
1642 * In either case we use just K, M, G as suffix, and not Ki,
1643 * Mi, Gi or so (as IEC would suggest). That's because that's
1644 * frickin' ugly. But this means you really need to make sure
1645 * to document which base you are parsing when you use this
1650 unsigned long long factor;
1653 static const struct table iec[] = {
1654 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1655 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1656 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1657 { "G", 1024ULL*1024ULL*1024ULL },
1658 { "M", 1024ULL*1024ULL },
1664 static const struct table si[] = {
1665 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1666 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1667 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1668 { "G", 1000ULL*1000ULL*1000ULL },
1669 { "M", 1000ULL*1000ULL },
1675 const struct table *table;
1677 unsigned long long r = 0;
1678 unsigned n_entries, start_pos = 0;
1681 assert(base == 1000 || base == 1024);
1686 n_entries = ELEMENTSOF(si);
1689 n_entries = ELEMENTSOF(iec);
1695 unsigned long long l2;
1701 l = strtoll(p, &e, 10);
1714 if (*e >= '0' && *e <= '9') {
1717 /* strotoull itself would accept space/+/- */
1718 l2 = strtoull(e, &e2, 10);
1720 if (errno == ERANGE)
1723 /* Ignore failure. E.g. 10.M is valid */
1730 e += strspn(e, WHITESPACE);
1732 for (i = start_pos; i < n_entries; i++)
1733 if (startswith(e, table[i].suffix)) {
1734 unsigned long long tmp;
1735 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1737 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1738 if (tmp > ULLONG_MAX - r)
1742 if ((unsigned long long) (off_t) r != r)
1745 p = e + strlen(table[i].suffix);
1761 bool is_device_path(const char *path) {
1763 /* Returns true on paths that refer to a device, either in
1764 * sysfs or in /dev */
1767 path_startswith(path, "/dev/") ||
1768 path_startswith(path, "/sys/");
1771 int dir_is_empty(const char *path) {
1772 _cleanup_closedir_ DIR *d;
1783 if (!de && errno != 0)
1789 if (!hidden_file(de->d_name))
1794 char* dirname_malloc(const char *path) {
1795 char *d, *dir, *dir2;
1812 void rename_process(const char name[8]) {
1815 /* This is a like a poor man's setproctitle(). It changes the
1816 * comm field, argv[0], and also the glibc's internally used
1817 * name of the process. For the first one a limit of 16 chars
1818 * applies, to the second one usually one of 10 (i.e. length
1819 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1820 * "systemd"). If you pass a longer string it will be
1823 prctl(PR_SET_NAME, name);
1825 if (program_invocation_name)
1826 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1828 if (saved_argc > 0) {
1832 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1834 for (i = 1; i < saved_argc; i++) {
1838 memzero(saved_argv[i], strlen(saved_argv[i]));
1843 char *lookup_uid(uid_t uid) {
1846 _cleanup_free_ char *buf = NULL;
1847 struct passwd pwbuf, *pw = NULL;
1849 /* Shortcut things to avoid NSS lookups */
1851 return strdup("root");
1853 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1857 buf = malloc(bufsize);
1861 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1862 return strdup(pw->pw_name);
1864 if (asprintf(&name, UID_FMT, uid) < 0)
1870 char* getlogname_malloc(void) {
1874 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1879 return lookup_uid(uid);
1882 char *getusername_malloc(void) {
1889 return lookup_uid(getuid());
1892 bool is_temporary_fs(const struct statfs *s) {
1895 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
1896 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
1899 int fd_is_temporary_fs(int fd) {
1902 if (fstatfs(fd, &s) < 0)
1905 return is_temporary_fs(&s);
1908 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1911 /* Under the assumption that we are running privileged we
1912 * first change the access mode and only then hand out
1913 * ownership to avoid a window where access is too open. */
1915 if (mode != MODE_INVALID)
1916 if (chmod(path, mode) < 0)
1919 if (uid != UID_INVALID || gid != GID_INVALID)
1920 if (chown(path, uid, gid) < 0)
1926 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
1929 /* Under the assumption that we are running privileged we
1930 * first change the access mode and only then hand out
1931 * ownership to avoid a window where access is too open. */
1933 if (mode != MODE_INVALID)
1934 if (fchmod(fd, mode) < 0)
1937 if (uid != UID_INVALID || gid != GID_INVALID)
1938 if (fchown(fd, uid, gid) < 0)
1944 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
1948 /* Allocates the cpuset in the right size */
1951 if (!(r = CPU_ALLOC(n)))
1954 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
1955 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
1965 if (errno != EINVAL)
1972 int files_same(const char *filea, const char *fileb) {
1975 if (stat(filea, &a) < 0)
1978 if (stat(fileb, &b) < 0)
1981 return a.st_dev == b.st_dev &&
1982 a.st_ino == b.st_ino;
1985 int running_in_chroot(void) {
1988 ret = files_same("/proc/1/root", "/");
1995 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2000 assert(percent <= 100);
2001 assert(new_length >= 3);
2003 if (old_length <= 3 || old_length <= new_length)
2004 return strndup(s, old_length);
2006 r = new0(char, new_length+1);
2010 x = (new_length * percent) / 100;
2012 if (x > new_length - 3)
2020 s + old_length - (new_length - x - 3),
2021 new_length - x - 3);
2026 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2030 unsigned k, len, len2;
2033 assert(percent <= 100);
2034 assert(new_length >= 3);
2036 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2037 if (ascii_is_valid(s))
2038 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2040 if (old_length <= 3 || old_length <= new_length)
2041 return strndup(s, old_length);
2043 x = (new_length * percent) / 100;
2045 if (x > new_length - 3)
2049 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2052 c = utf8_encoded_to_unichar(i);
2055 k += unichar_iswide(c) ? 2 : 1;
2058 if (k > x) /* last character was wide and went over quota */
2061 for (j = s + old_length; k < new_length && j > i; ) {
2064 j = utf8_prev_char(j);
2065 c = utf8_encoded_to_unichar(j);
2068 k += unichar_iswide(c) ? 2 : 1;
2072 /* we don't actually need to ellipsize */
2074 return memdup(s, old_length + 1);
2076 /* make space for ellipsis */
2077 j = utf8_next_char(j);
2080 len2 = s + old_length - j;
2081 e = new(char, len + 3 + len2 + 1);
2086 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2087 old_length, new_length, x, len, len2, k);
2091 e[len] = 0xe2; /* tri-dot ellipsis: … */
2095 memcpy(e + len + 3, j, len2 + 1);
2100 char *ellipsize(const char *s, size_t length, unsigned percent) {
2101 return ellipsize_mem(s, strlen(s), length, percent);
2104 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2105 _cleanup_close_ int fd;
2111 mkdir_parents(path, 0755);
2113 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2118 r = fchmod(fd, mode);
2123 if (uid != UID_INVALID || gid != GID_INVALID) {
2124 r = fchown(fd, uid, gid);
2129 if (stamp != USEC_INFINITY) {
2130 struct timespec ts[2];
2132 timespec_store(&ts[0], stamp);
2134 r = futimens(fd, ts);
2136 r = futimens(fd, NULL);
2143 int touch(const char *path) {
2144 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2147 static char *unquote(const char *s, const char* quotes) {
2151 /* This is rather stupid, simply removes the heading and
2152 * trailing quotes if there is one. Doesn't care about
2153 * escaping or anything.
2155 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2161 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2162 return strndup(s+1, l-2);
2167 noreturn void freeze(void) {
2169 /* Make sure nobody waits for us on a socket anymore */
2170 close_all_fds(NULL, 0);
2178 bool null_or_empty(struct stat *st) {
2181 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2184 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2190 int null_or_empty_path(const char *fn) {
2195 if (stat(fn, &st) < 0)
2198 return null_or_empty(&st);
2201 int null_or_empty_fd(int fd) {
2206 if (fstat(fd, &st) < 0)
2209 return null_or_empty(&st);
2212 DIR *xopendirat(int fd, const char *name, int flags) {
2216 assert(!(flags & O_CREAT));
2218 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2231 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2232 _cleanup_free_ char *t = NULL, *u = NULL;
2235 u = unquote(tagvalue, QUOTES);
2239 enc_len = strlen(u) * 4 + 1;
2240 t = new(char, enc_len);
2244 if (encode_devnode_name(u, t, enc_len) < 0)
2247 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2250 char *fstab_node_to_udev_node(const char *p) {
2253 if (startswith(p, "LABEL="))
2254 return tag_to_udev_node(p+6, "label");
2256 if (startswith(p, "UUID="))
2257 return tag_to_udev_node(p+5, "uuid");
2259 if (startswith(p, "PARTUUID="))
2260 return tag_to_udev_node(p+9, "partuuid");
2262 if (startswith(p, "PARTLABEL="))
2263 return tag_to_udev_node(p+10, "partlabel");
2268 bool dirent_is_file(const struct dirent *de) {
2271 if (hidden_file(de->d_name))
2274 if (de->d_type != DT_REG &&
2275 de->d_type != DT_LNK &&
2276 de->d_type != DT_UNKNOWN)
2282 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2285 if (de->d_type != DT_REG &&
2286 de->d_type != DT_LNK &&
2287 de->d_type != DT_UNKNOWN)
2290 if (hidden_file_allow_backup(de->d_name))
2293 return endswith(de->d_name, suffix);
2296 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2297 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2298 _cleanup_set_free_free_ Set *seen = NULL;
2301 /* We fork this all off from a child process so that we can
2302 * somewhat cleanly make use of SIGALRM to set a time limit */
2304 (void) reset_all_signal_handlers();
2305 (void) reset_signal_mask();
2307 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2309 pids = hashmap_new(NULL);
2313 seen = set_new(&string_hash_ops);
2317 STRV_FOREACH(directory, directories) {
2318 _cleanup_closedir_ DIR *d;
2321 d = opendir(*directory);
2323 if (errno == ENOENT)
2326 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2329 FOREACH_DIRENT(de, d, break) {
2330 _cleanup_free_ char *path = NULL;
2334 if (!dirent_is_file(de))
2337 if (set_contains(seen, de->d_name)) {
2338 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2342 r = set_put_strdup(seen, de->d_name);
2346 path = strjoin(*directory, "/", de->d_name, NULL);
2350 if (null_or_empty_path(path)) {
2351 log_debug("%s is empty (a mask).", path);
2357 log_error_errno(errno, "Failed to fork: %m");
2359 } else if (pid == 0) {
2362 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2372 return log_error_errno(errno, "Failed to execute %s: %m", path);
2375 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2377 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2384 /* Abort execution of this process after the timout. We simply
2385 * rely on SIGALRM as default action terminating the process,
2386 * and turn on alarm(). */
2388 if (timeout != USEC_INFINITY)
2389 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2391 while (!hashmap_isempty(pids)) {
2392 _cleanup_free_ char *path = NULL;
2395 pid = PTR_TO_UINT(hashmap_first_key(pids));
2398 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2401 wait_for_terminate_and_warn(path, pid, true);
2407 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2411 char **dirs = (char**) directories;
2413 assert(!strv_isempty(dirs));
2415 name = basename(dirs[0]);
2416 assert(!isempty(name));
2418 /* Executes all binaries in the directories in parallel and waits
2419 * for them to finish. Optionally a timeout is applied. If a file
2420 * with the same name exists in more than one directory, the
2421 * earliest one wins. */
2423 executor_pid = fork();
2424 if (executor_pid < 0) {
2425 log_error_errno(errno, "Failed to fork: %m");
2428 } else if (executor_pid == 0) {
2429 r = do_execute(dirs, timeout, argv);
2430 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2433 wait_for_terminate_and_warn(name, executor_pid, true);
2436 bool nulstr_contains(const char*nulstr, const char *needle) {
2442 NULSTR_FOREACH(i, nulstr)
2443 if (streq(i, needle))
2449 bool plymouth_running(void) {
2450 return access("/run/plymouth/pid", F_OK) >= 0;
2453 char* strshorten(char *s, size_t l) {
2462 bool machine_name_is_valid(const char *s) {
2464 if (!hostname_is_valid(s))
2467 /* Machine names should be useful hostnames, but also be
2468 * useful in unit names, hence we enforce a stricter length
2477 int pipe_eof(int fd) {
2478 struct pollfd pollfd = {
2480 .events = POLLIN|POLLHUP,
2485 r = poll(&pollfd, 1, 0);
2492 return pollfd.revents & POLLHUP;
2495 int fd_wait_for_event(int fd, int event, usec_t t) {
2497 struct pollfd pollfd = {
2505 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2512 return pollfd.revents;
2515 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2524 r = tempfn_xxxxxx(path, NULL, &t);
2528 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2534 f = fdopen(fd, "we");
2547 int symlink_atomic(const char *from, const char *to) {
2548 _cleanup_free_ char *t = NULL;
2554 r = tempfn_random(to, NULL, &t);
2558 if (symlink(from, t) < 0)
2561 if (rename(t, to) < 0) {
2569 int symlink_idempotent(const char *from, const char *to) {
2570 _cleanup_free_ char *p = NULL;
2576 if (symlink(from, to) < 0) {
2577 if (errno != EEXIST)
2580 r = readlink_malloc(to, &p);
2584 if (!streq(p, from))
2591 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2592 _cleanup_free_ char *t = NULL;
2597 r = tempfn_random(path, NULL, &t);
2601 if (mknod(t, mode, dev) < 0)
2604 if (rename(t, path) < 0) {
2612 int mkfifo_atomic(const char *path, mode_t mode) {
2613 _cleanup_free_ char *t = NULL;
2618 r = tempfn_random(path, NULL, &t);
2622 if (mkfifo(t, mode) < 0)
2625 if (rename(t, path) < 0) {
2633 bool display_is_local(const char *display) {
2637 display[0] == ':' &&
2638 display[1] >= '0' &&
2642 int socket_from_display(const char *display, char **path) {
2649 if (!display_is_local(display))
2652 k = strspn(display+1, "0123456789");
2654 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2658 c = stpcpy(f, "/tmp/.X11-unix/X");
2659 memcpy(c, display+1, k);
2668 const char **username,
2669 uid_t *uid, gid_t *gid,
2671 const char **shell) {
2679 /* We enforce some special rules for uid=0: in order to avoid
2680 * NSS lookups for root we hardcode its data. */
2682 if (streq(*username, "root") || streq(*username, "0")) {
2700 if (parse_uid(*username, &u) >= 0) {
2704 /* If there are multiple users with the same id, make
2705 * sure to leave $USER to the configured value instead
2706 * of the first occurrence in the database. However if
2707 * the uid was configured by a numeric uid, then let's
2708 * pick the real username from /etc/passwd. */
2710 *username = p->pw_name;
2713 p = getpwnam(*username);
2717 return errno > 0 ? -errno : -ESRCH;
2729 *shell = p->pw_shell;
2734 char* uid_to_name(uid_t uid) {
2739 return strdup("root");
2743 return strdup(p->pw_name);
2745 if (asprintf(&r, UID_FMT, uid) < 0)
2751 char* gid_to_name(gid_t gid) {
2756 return strdup("root");
2760 return strdup(p->gr_name);
2762 if (asprintf(&r, GID_FMT, gid) < 0)
2768 int get_group_creds(const char **groupname, gid_t *gid) {
2774 /* We enforce some special rules for gid=0: in order to avoid
2775 * NSS lookups for root we hardcode its data. */
2777 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2778 *groupname = "root";
2786 if (parse_gid(*groupname, &id) >= 0) {
2791 *groupname = g->gr_name;
2794 g = getgrnam(*groupname);
2798 return errno > 0 ? -errno : -ESRCH;
2806 int in_gid(gid_t gid) {
2808 int ngroups_max, r, i;
2810 if (getgid() == gid)
2813 if (getegid() == gid)
2816 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2817 assert(ngroups_max > 0);
2819 gids = alloca(sizeof(gid_t) * ngroups_max);
2821 r = getgroups(ngroups_max, gids);
2825 for (i = 0; i < r; i++)
2832 int in_group(const char *name) {
2836 r = get_group_creds(&name, &gid);
2843 int glob_exists(const char *path) {
2844 _cleanup_globfree_ glob_t g = {};
2850 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2852 if (k == GLOB_NOMATCH)
2854 else if (k == GLOB_NOSPACE)
2857 return !strv_isempty(g.gl_pathv);
2859 return errno ? -errno : -EIO;
2862 int glob_extend(char ***strv, const char *path) {
2863 _cleanup_globfree_ glob_t g = {};
2868 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2870 if (k == GLOB_NOMATCH)
2872 else if (k == GLOB_NOSPACE)
2874 else if (k != 0 || strv_isempty(g.gl_pathv))
2875 return errno ? -errno : -EIO;
2877 STRV_FOREACH(p, g.gl_pathv) {
2878 k = strv_extend(strv, *p);
2886 int dirent_ensure_type(DIR *d, struct dirent *de) {
2892 if (de->d_type != DT_UNKNOWN)
2895 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
2899 S_ISREG(st.st_mode) ? DT_REG :
2900 S_ISDIR(st.st_mode) ? DT_DIR :
2901 S_ISLNK(st.st_mode) ? DT_LNK :
2902 S_ISFIFO(st.st_mode) ? DT_FIFO :
2903 S_ISSOCK(st.st_mode) ? DT_SOCK :
2904 S_ISCHR(st.st_mode) ? DT_CHR :
2905 S_ISBLK(st.st_mode) ? DT_BLK :
2911 int get_files_in_directory(const char *path, char ***list) {
2912 _cleanup_closedir_ DIR *d = NULL;
2913 size_t bufsize = 0, n = 0;
2914 _cleanup_strv_free_ char **l = NULL;
2918 /* Returns all files in a directory in *list, and the number
2919 * of files as return value. If list is NULL returns only the
2931 if (!de && errno != 0)
2936 dirent_ensure_type(d, de);
2938 if (!dirent_is_file(de))
2942 /* one extra slot is needed for the terminating NULL */
2943 if (!GREEDY_REALLOC(l, bufsize, n + 2))
2946 l[n] = strdup(de->d_name);
2957 l = NULL; /* avoid freeing */
2963 char *strjoin(const char *x, ...) {
2977 t = va_arg(ap, const char *);
2982 if (n > ((size_t) -1) - l) {
3006 t = va_arg(ap, const char *);
3020 bool is_main_thread(void) {
3021 static thread_local int cached = 0;
3023 if (_unlikely_(cached == 0))
3024 cached = getpid() == gettid() ? 1 : -1;
3029 int block_get_whole_disk(dev_t d, dev_t *ret) {
3036 /* If it has a queue this is good enough for us */
3037 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3040 r = access(p, F_OK);
3048 /* If it is a partition find the originating device */
3049 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3052 r = access(p, F_OK);
3058 /* Get parent dev_t */
3059 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3062 r = read_one_line_file(p, &s);
3068 r = sscanf(s, "%u:%u", &m, &n);
3074 /* Only return this if it is really good enough for us. */
3075 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3078 r = access(p, F_OK);
3082 *ret = makedev(m, n);
3089 static const char *const ioprio_class_table[] = {
3090 [IOPRIO_CLASS_NONE] = "none",
3091 [IOPRIO_CLASS_RT] = "realtime",
3092 [IOPRIO_CLASS_BE] = "best-effort",
3093 [IOPRIO_CLASS_IDLE] = "idle"
3096 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3098 static const char *const sigchld_code_table[] = {
3099 [CLD_EXITED] = "exited",
3100 [CLD_KILLED] = "killed",
3101 [CLD_DUMPED] = "dumped",
3102 [CLD_TRAPPED] = "trapped",
3103 [CLD_STOPPED] = "stopped",
3104 [CLD_CONTINUED] = "continued",
3107 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3109 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3110 [LOG_FAC(LOG_KERN)] = "kern",
3111 [LOG_FAC(LOG_USER)] = "user",
3112 [LOG_FAC(LOG_MAIL)] = "mail",
3113 [LOG_FAC(LOG_DAEMON)] = "daemon",
3114 [LOG_FAC(LOG_AUTH)] = "auth",
3115 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3116 [LOG_FAC(LOG_LPR)] = "lpr",
3117 [LOG_FAC(LOG_NEWS)] = "news",
3118 [LOG_FAC(LOG_UUCP)] = "uucp",
3119 [LOG_FAC(LOG_CRON)] = "cron",
3120 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3121 [LOG_FAC(LOG_FTP)] = "ftp",
3122 [LOG_FAC(LOG_LOCAL0)] = "local0",
3123 [LOG_FAC(LOG_LOCAL1)] = "local1",
3124 [LOG_FAC(LOG_LOCAL2)] = "local2",
3125 [LOG_FAC(LOG_LOCAL3)] = "local3",
3126 [LOG_FAC(LOG_LOCAL4)] = "local4",
3127 [LOG_FAC(LOG_LOCAL5)] = "local5",
3128 [LOG_FAC(LOG_LOCAL6)] = "local6",
3129 [LOG_FAC(LOG_LOCAL7)] = "local7"
3132 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3134 static const char *const log_level_table[] = {
3135 [LOG_EMERG] = "emerg",
3136 [LOG_ALERT] = "alert",
3137 [LOG_CRIT] = "crit",
3139 [LOG_WARNING] = "warning",
3140 [LOG_NOTICE] = "notice",
3141 [LOG_INFO] = "info",
3142 [LOG_DEBUG] = "debug"
3145 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3147 static const char* const sched_policy_table[] = {
3148 [SCHED_OTHER] = "other",
3149 [SCHED_BATCH] = "batch",
3150 [SCHED_IDLE] = "idle",
3151 [SCHED_FIFO] = "fifo",
3155 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3157 static const char* const rlimit_table[_RLIMIT_MAX] = {
3158 [RLIMIT_CPU] = "LimitCPU",
3159 [RLIMIT_FSIZE] = "LimitFSIZE",
3160 [RLIMIT_DATA] = "LimitDATA",
3161 [RLIMIT_STACK] = "LimitSTACK",
3162 [RLIMIT_CORE] = "LimitCORE",
3163 [RLIMIT_RSS] = "LimitRSS",
3164 [RLIMIT_NOFILE] = "LimitNOFILE",
3165 [RLIMIT_AS] = "LimitAS",
3166 [RLIMIT_NPROC] = "LimitNPROC",
3167 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3168 [RLIMIT_LOCKS] = "LimitLOCKS",
3169 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3170 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3171 [RLIMIT_NICE] = "LimitNICE",
3172 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3173 [RLIMIT_RTTIME] = "LimitRTTIME"
3176 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3178 static const char* const ip_tos_table[] = {
3179 [IPTOS_LOWDELAY] = "low-delay",
3180 [IPTOS_THROUGHPUT] = "throughput",
3181 [IPTOS_RELIABILITY] = "reliability",
3182 [IPTOS_LOWCOST] = "low-cost",
3185 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3187 bool kexec_loaded(void) {
3188 bool loaded = false;
3191 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3199 int prot_from_flags(int flags) {
3201 switch (flags & O_ACCMODE) {
3210 return PROT_READ|PROT_WRITE;
3217 char *format_bytes(char *buf, size_t l, off_t t) {
3220 static const struct {
3224 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3225 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3226 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3227 { "G", 1024ULL*1024ULL*1024ULL },
3228 { "M", 1024ULL*1024ULL },
3232 if (t == (off_t) -1)
3235 for (i = 0; i < ELEMENTSOF(table); i++) {
3237 if (t >= table[i].factor) {
3240 (unsigned long long) (t / table[i].factor),
3241 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3248 snprintf(buf, l, "%lluB", (unsigned long long) t);
3256 void* memdup(const void *p, size_t l) {
3269 int fd_inc_sndbuf(int fd, size_t n) {
3271 socklen_t l = sizeof(value);
3273 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3274 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3277 /* If we have the privileges we will ignore the kernel limit. */
3280 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3281 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3287 int fd_inc_rcvbuf(int fd, size_t n) {
3289 socklen_t l = sizeof(value);
3291 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3292 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3295 /* If we have the privileges we will ignore the kernel limit. */
3298 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3299 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3304 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3305 bool stdout_is_tty, stderr_is_tty;
3306 pid_t parent_pid, agent_pid;
3307 sigset_t ss, saved_ss;
3315 /* Spawns a temporary TTY agent, making sure it goes away when
3318 parent_pid = getpid();
3320 /* First we temporarily block all signals, so that the new
3321 * child has them blocked initially. This way, we can be sure
3322 * that SIGTERMs are not lost we might send to the agent. */
3323 assert_se(sigfillset(&ss) >= 0);
3324 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3327 if (agent_pid < 0) {
3328 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3332 if (agent_pid != 0) {
3333 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3340 * Make sure the agent goes away when the parent dies */
3341 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3342 _exit(EXIT_FAILURE);
3344 /* Make sure we actually can kill the agent, if we need to, in
3345 * case somebody invoked us from a shell script that trapped
3346 * SIGTERM or so... */
3347 (void) reset_all_signal_handlers();
3348 (void) reset_signal_mask();
3350 /* Check whether our parent died before we were able
3351 * to set the death signal and unblock the signals */
3352 if (getppid() != parent_pid)
3353 _exit(EXIT_SUCCESS);
3355 /* Don't leak fds to the agent */
3356 close_all_fds(except, n_except);
3358 stdout_is_tty = isatty(STDOUT_FILENO);
3359 stderr_is_tty = isatty(STDERR_FILENO);
3361 if (!stdout_is_tty || !stderr_is_tty) {
3364 /* Detach from stdout/stderr. and reopen
3365 * /dev/tty for them. This is important to
3366 * ensure that when systemctl is started via
3367 * popen() or a similar call that expects to
3368 * read EOF we actually do generate EOF and
3369 * not delay this indefinitely by because we
3370 * keep an unused copy of stdin around. */
3371 fd = open("/dev/tty", O_WRONLY);
3373 log_error_errno(errno, "Failed to open /dev/tty: %m");
3374 _exit(EXIT_FAILURE);
3378 dup2(fd, STDOUT_FILENO);
3381 dup2(fd, STDERR_FILENO);
3387 /* Count arguments */
3389 for (n = 0; va_arg(ap, char*); n++)
3394 l = alloca(sizeof(char *) * (n + 1));
3396 /* Fill in arguments */
3398 for (i = 0; i <= n; i++)
3399 l[i] = va_arg(ap, char*);
3403 _exit(EXIT_FAILURE);
3406 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3407 struct rlimit highest, fixed;
3411 if (setrlimit(resource, rlim) >= 0)
3417 /* So we failed to set the desired setrlimit, then let's try
3418 * to get as close as we can */
3419 assert_se(getrlimit(resource, &highest) == 0);
3421 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3422 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3424 if (setrlimit(resource, &fixed) < 0)
3430 bool http_etag_is_valid(const char *etag) {
3434 if (!endswith(etag, "\""))
3437 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3443 bool http_url_is_valid(const char *url) {
3449 p = startswith(url, "http://");
3451 p = startswith(url, "https://");
3458 return ascii_is_valid(p);
3461 bool documentation_url_is_valid(const char *url) {
3467 if (http_url_is_valid(url))
3470 p = startswith(url, "file:/");
3472 p = startswith(url, "info:");
3474 p = startswith(url, "man:");
3479 return ascii_is_valid(p);
3482 bool in_initrd(void) {
3483 static int saved = -1;
3489 /* We make two checks here:
3491 * 1. the flag file /etc/initrd-release must exist
3492 * 2. the root file system must be a memory file system
3494 * The second check is extra paranoia, since misdetecting an
3495 * initrd can have bad bad consequences due the initrd
3496 * emptying when transititioning to the main systemd.
3499 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3500 statfs("/", &s) >= 0 &&
3501 is_temporary_fs(&s);
3506 int get_home_dir(char **_h) {
3514 /* Take the user specified one */
3515 e = secure_getenv("HOME");
3516 if (e && path_is_absolute(e)) {
3525 /* Hardcode home directory for root to avoid NSS */
3528 h = strdup("/root");
3536 /* Check the database... */
3540 return errno > 0 ? -errno : -ESRCH;
3542 if (!path_is_absolute(p->pw_dir))
3545 h = strdup(p->pw_dir);
3553 int get_shell(char **_s) {
3561 /* Take the user specified one */
3562 e = getenv("SHELL");
3572 /* Hardcode home directory for root to avoid NSS */
3575 s = strdup("/bin/sh");
3583 /* Check the database... */
3587 return errno > 0 ? -errno : -ESRCH;
3589 if (!path_is_absolute(p->pw_shell))
3592 s = strdup(p->pw_shell);
3600 bool filename_is_valid(const char *p) {
3614 if (strlen(p) > FILENAME_MAX)
3620 bool string_is_safe(const char *p) {
3626 for (t = p; *t; t++) {
3627 if (*t > 0 && *t < ' ')
3630 if (strchr("\\\"\'\0x7f", *t))
3638 * Check if a string contains control characters. If 'ok' is non-NULL
3639 * it may be a string containing additional CCs to be considered OK.
3641 bool string_has_cc(const char *p, const char *ok) {
3646 for (t = p; *t; t++) {
3647 if (ok && strchr(ok, *t))
3650 if (*t > 0 && *t < ' ')
3660 bool path_is_safe(const char *p) {
3665 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3668 if (strlen(p)+1 > PATH_MAX)
3671 /* The following two checks are not really dangerous, but hey, they still are confusing */
3672 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3675 if (strstr(p, "//"))
3681 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3682 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3683 int (*compar) (const void *, const void *, void *), void *arg) {
3692 p = (void *)(((const char *) base) + (idx * size));
3693 comparison = compar(key, p, arg);
3696 else if (comparison > 0)
3704 void init_gettext(void) {
3705 setlocale(LC_ALL, "");
3706 textdomain(GETTEXT_PACKAGE);
3709 bool is_locale_utf8(void) {
3711 static int cached_answer = -1;
3713 if (cached_answer >= 0)
3716 if (!setlocale(LC_ALL, "")) {
3717 cached_answer = true;
3721 set = nl_langinfo(CODESET);
3723 cached_answer = true;
3727 if (streq(set, "UTF-8")) {
3728 cached_answer = true;
3732 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3733 * unset and everything can do to UTF-8 nowadays. */
3734 set = setlocale(LC_CTYPE, NULL);
3736 cached_answer = true;
3740 /* Check result, but ignore the result if C was set
3744 !getenv("LC_ALL") &&
3745 !getenv("LC_CTYPE") &&
3749 return (bool) cached_answer;
3752 const char *draw_special_char(DrawSpecialChar ch) {
3753 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
3756 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
3757 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
3758 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
3759 [DRAW_TREE_SPACE] = " ", /* */
3760 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
3761 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
3762 [DRAW_ARROW] = "\342\206\222", /* → */
3763 [DRAW_DASH] = "\342\200\223", /* – */
3766 /* ASCII fallback */ {
3767 [DRAW_TREE_VERTICAL] = "| ",
3768 [DRAW_TREE_BRANCH] = "|-",
3769 [DRAW_TREE_RIGHT] = "`-",
3770 [DRAW_TREE_SPACE] = " ",
3771 [DRAW_TRIANGULAR_BULLET] = ">",
3772 [DRAW_BLACK_CIRCLE] = "*",
3773 [DRAW_ARROW] = "->",
3778 return draw_table[!is_locale_utf8()][ch];
3781 char *strreplace(const char *text, const char *old_string, const char *new_string) {
3784 size_t l, old_len, new_len;
3790 old_len = strlen(old_string);
3791 new_len = strlen(new_string);
3804 if (!startswith(f, old_string)) {
3810 nl = l - old_len + new_len;
3811 a = realloc(r, nl + 1);
3819 t = stpcpy(t, new_string);
3831 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
3832 const char *i, *begin = NULL;
3837 } state = STATE_OTHER;
3839 size_t osz = 0, isz;
3845 /* Strips ANSI color and replaces TABs by 8 spaces */
3847 isz = _isz ? *_isz : strlen(*ibuf);
3849 f = open_memstream(&obuf, &osz);
3853 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
3858 if (i >= *ibuf + isz) /* EOT */
3860 else if (*i == '\x1B')
3861 state = STATE_ESCAPE;
3862 else if (*i == '\t')
3869 if (i >= *ibuf + isz) { /* EOT */
3872 } else if (*i == '[') {
3873 state = STATE_BRACKET;
3878 state = STATE_OTHER;
3885 if (i >= *ibuf + isz || /* EOT */
3886 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
3889 state = STATE_OTHER;
3891 } else if (*i == 'm')
3892 state = STATE_OTHER;
3914 int on_ac_power(void) {
3915 bool found_offline = false, found_online = false;
3916 _cleanup_closedir_ DIR *d = NULL;
3918 d = opendir("/sys/class/power_supply");
3920 return errno == ENOENT ? true : -errno;
3924 _cleanup_close_ int fd = -1, device = -1;
3930 if (!de && errno != 0)
3936 if (hidden_file(de->d_name))
3939 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
3941 if (errno == ENOENT || errno == ENOTDIR)
3947 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3949 if (errno == ENOENT)
3955 n = read(fd, contents, sizeof(contents));
3959 if (n != 6 || memcmp(contents, "Mains\n", 6))
3963 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3965 if (errno == ENOENT)
3971 n = read(fd, contents, sizeof(contents));
3975 if (n != 2 || contents[1] != '\n')
3978 if (contents[0] == '1') {
3979 found_online = true;
3981 } else if (contents[0] == '0')
3982 found_offline = true;
3987 return found_online || !found_offline;
3990 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
3997 if (!path_strv_resolve_uniq(search, root))
4000 STRV_FOREACH(i, search) {
4001 _cleanup_free_ char *p = NULL;
4005 p = strjoin(root, *i, "/", path, NULL);
4007 p = strjoin(*i, "/", path, NULL);
4017 if (errno != ENOENT)
4024 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4025 _cleanup_strv_free_ char **copy = NULL;
4031 if (path_is_absolute(path)) {
4034 f = fopen(path, mode);
4043 copy = strv_copy((char**) search);
4047 return search_and_fopen_internal(path, mode, root, copy, _f);
4050 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4051 _cleanup_strv_free_ char **s = NULL;
4053 if (path_is_absolute(path)) {
4056 f = fopen(path, mode);
4065 s = strv_split_nulstr(search);
4069 return search_and_fopen_internal(path, mode, root, s, _f);
4072 char *strextend(char **x, ...) {
4079 l = f = *x ? strlen(*x) : 0;
4086 t = va_arg(ap, const char *);
4091 if (n > ((size_t) -1) - l) {
4100 r = realloc(*x, l+1);
4110 t = va_arg(ap, const char *);
4124 char *strrep(const char *s, unsigned n) {
4132 p = r = malloc(l * n + 1);
4136 for (i = 0; i < n; i++)
4143 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4150 if (*allocated >= need)
4153 newalloc = MAX(need * 2, 64u / size);
4154 a = newalloc * size;
4156 /* check for overflows */
4157 if (a < size * need)
4165 *allocated = newalloc;
4169 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4178 q = greedy_realloc(p, allocated, need, size);
4182 if (*allocated > prev)
4183 memzero(q + prev * size, (*allocated - prev) * size);
4188 bool id128_is_valid(const char *s) {
4194 /* Simple formatted 128bit hex string */
4196 for (i = 0; i < l; i++) {
4199 if (!(c >= '0' && c <= '9') &&
4200 !(c >= 'a' && c <= 'z') &&
4201 !(c >= 'A' && c <= 'Z'))
4205 } else if (l == 36) {
4207 /* Formatted UUID */
4209 for (i = 0; i < l; i++) {
4212 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4216 if (!(c >= '0' && c <= '9') &&
4217 !(c >= 'a' && c <= 'z') &&
4218 !(c >= 'A' && c <= 'Z'))
4229 int split_pair(const char *s, const char *sep, char **l, char **r) {
4244 a = strndup(s, x - s);
4248 b = strdup(x + strlen(sep));
4260 int shall_restore_state(void) {
4261 _cleanup_free_ char *value = NULL;
4264 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4270 return parse_boolean(value) != 0;
4273 int proc_cmdline(char **ret) {
4276 if (detect_container(NULL) > 0)
4277 return get_process_cmdline(1, 0, false, ret);
4279 return read_one_line_file("/proc/cmdline", ret);
4282 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4283 _cleanup_free_ char *line = NULL;
4289 r = proc_cmdline(&line);
4295 _cleanup_free_ char *word = NULL;
4298 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4304 /* Filter out arguments that are intended only for the
4306 if (!in_initrd() && startswith(word, "rd."))
4309 value = strchr(word, '=');
4313 r = parse_item(word, value);
4321 int get_proc_cmdline_key(const char *key, char **value) {
4322 _cleanup_free_ char *line = NULL, *ret = NULL;
4329 r = proc_cmdline(&line);
4335 _cleanup_free_ char *word = NULL;
4338 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4344 /* Filter out arguments that are intended only for the
4346 if (!in_initrd() && startswith(word, "rd."))
4350 e = startswith(word, key);
4354 r = free_and_strdup(&ret, e);
4360 if (streq(word, key))
4374 int container_get_leader(const char *machine, pid_t *pid) {
4375 _cleanup_free_ char *s = NULL, *class = NULL;
4383 p = strjoina("/run/systemd/machines/", machine);
4384 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4392 if (!streq_ptr(class, "container"))
4395 r = parse_pid(s, &leader);
4405 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4406 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4414 mntns = procfs_file_alloca(pid, "ns/mnt");
4415 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4423 pidns = procfs_file_alloca(pid, "ns/pid");
4424 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4432 netns = procfs_file_alloca(pid, "ns/net");
4433 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4441 root = procfs_file_alloca(pid, "root");
4442 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4448 *pidns_fd = pidnsfd;
4451 *mntns_fd = mntnsfd;
4454 *netns_fd = netnsfd;
4459 pidnsfd = mntnsfd = netnsfd = -1;
4464 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4467 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4471 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4475 if (setns(netns_fd, CLONE_NEWNET) < 0)
4479 if (fchdir(root_fd) < 0)
4482 if (chroot(".") < 0)
4486 return reset_uid_gid();
4489 int getpeercred(int fd, struct ucred *ucred) {
4490 socklen_t n = sizeof(struct ucred);
4497 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4501 if (n != sizeof(struct ucred))
4504 /* Check if the data is actually useful and not suppressed due
4505 * to namespacing issues */
4508 if (u.uid == UID_INVALID)
4510 if (u.gid == GID_INVALID)
4517 int getpeersec(int fd, char **ret) {
4529 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4533 if (errno != ERANGE)
4540 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4556 /* This is much like like mkostemp() but is subject to umask(). */
4557 int mkostemp_safe(char *pattern, int flags) {
4558 _cleanup_umask_ mode_t u;
4565 fd = mkostemp(pattern, flags);
4572 int open_tmpfile(const char *path, int flags) {
4579 /* Try O_TMPFILE first, if it is supported */
4580 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4585 /* Fall back to unguessable name + unlinking */
4586 p = strjoina(path, "/systemd-tmp-XXXXXX");
4588 fd = mkostemp_safe(p, flags);
4596 int fd_warn_permissions(const char *path, int fd) {
4599 if (fstat(fd, &st) < 0)
4602 if (st.st_mode & 0111)
4603 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4605 if (st.st_mode & 0002)
4606 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4608 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4609 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);
4614 unsigned long personality_from_string(const char *p) {
4616 /* Parse a personality specifier. We introduce our own
4617 * identifiers that indicate specific ABIs, rather than just
4618 * hints regarding the register size, since we want to keep
4619 * things open for multiple locally supported ABIs for the
4620 * same register size. We try to reuse the ABI identifiers
4621 * used by libseccomp. */
4623 #if defined(__x86_64__)
4625 if (streq(p, "x86"))
4628 if (streq(p, "x86-64"))
4631 #elif defined(__i386__)
4633 if (streq(p, "x86"))
4637 return PERSONALITY_INVALID;
4640 const char* personality_to_string(unsigned long p) {
4642 #if defined(__x86_64__)
4644 if (p == PER_LINUX32)
4650 #elif defined(__i386__)
4659 uint64_t physical_memory(void) {
4662 /* We return this as uint64_t in case we are running as 32bit
4663 * process on a 64bit kernel with huge amounts of memory */
4665 mem = sysconf(_SC_PHYS_PAGES);
4668 return (uint64_t) mem * (uint64_t) page_size();
4671 void hexdump(FILE *f, const void *p, size_t s) {
4672 const uint8_t *b = p;
4675 assert(s == 0 || b);
4680 fprintf(f, "%04x ", n);
4682 for (i = 0; i < 16; i++) {
4687 fprintf(f, "%02x ", b[i]);
4695 for (i = 0; i < 16; i++) {
4700 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4714 int update_reboot_param_file(const char *param) {
4719 r = write_string_file(REBOOT_PARAM_FILE, param, WRITE_STRING_FILE_CREATE);
4721 log_error("Failed to write reboot param to "
4722 REBOOT_PARAM_FILE": %s", strerror(-r));
4724 unlink(REBOOT_PARAM_FILE);
4729 int umount_recursive(const char *prefix, int flags) {
4733 /* Try to umount everything recursively below a
4734 * directory. Also, take care of stacked mounts, and keep
4735 * unmounting them until they are gone. */
4738 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4743 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4744 if (!proc_self_mountinfo)
4748 _cleanup_free_ char *path = NULL, *p = NULL;
4751 k = fscanf(proc_self_mountinfo,
4752 "%*s " /* (1) mount id */
4753 "%*s " /* (2) parent id */
4754 "%*s " /* (3) major:minor */
4755 "%*s " /* (4) root */
4756 "%ms " /* (5) mount point */
4757 "%*s" /* (6) mount options */
4758 "%*[^-]" /* (7) optional fields */
4759 "- " /* (8) separator */
4760 "%*s " /* (9) file system type */
4761 "%*s" /* (10) mount source */
4762 "%*s" /* (11) mount options 2 */
4763 "%*[^\n]", /* some rubbish at the end */
4772 r = cunescape(path, UNESCAPE_RELAX, &p);
4776 if (!path_startswith(p, prefix))
4779 if (umount2(p, flags) < 0) {
4795 static int get_mount_flags(const char *path, unsigned long *flags) {
4798 if (statvfs(path, &buf) < 0)
4800 *flags = buf.f_flag;
4804 int bind_remount_recursive(const char *prefix, bool ro) {
4805 _cleanup_set_free_free_ Set *done = NULL;
4806 _cleanup_free_ char *cleaned = NULL;
4809 /* Recursively remount a directory (and all its submounts)
4810 * read-only or read-write. If the directory is already
4811 * mounted, we reuse the mount and simply mark it
4812 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4813 * operation). If it isn't we first make it one. Afterwards we
4814 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4815 * submounts we can access, too. When mounts are stacked on
4816 * the same mount point we only care for each individual
4817 * "top-level" mount on each point, as we cannot
4818 * influence/access the underlying mounts anyway. We do not
4819 * have any effect on future submounts that might get
4820 * propagated, they migt be writable. This includes future
4821 * submounts that have been triggered via autofs. */
4823 cleaned = strdup(prefix);
4827 path_kill_slashes(cleaned);
4829 done = set_new(&string_hash_ops);
4834 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4835 _cleanup_set_free_free_ Set *todo = NULL;
4836 bool top_autofs = false;
4838 unsigned long orig_flags;
4840 todo = set_new(&string_hash_ops);
4844 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4845 if (!proc_self_mountinfo)
4849 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
4852 k = fscanf(proc_self_mountinfo,
4853 "%*s " /* (1) mount id */
4854 "%*s " /* (2) parent id */
4855 "%*s " /* (3) major:minor */
4856 "%*s " /* (4) root */
4857 "%ms " /* (5) mount point */
4858 "%*s" /* (6) mount options (superblock) */
4859 "%*[^-]" /* (7) optional fields */
4860 "- " /* (8) separator */
4861 "%ms " /* (9) file system type */
4862 "%*s" /* (10) mount source */
4863 "%*s" /* (11) mount options (bind mount) */
4864 "%*[^\n]", /* some rubbish at the end */
4874 r = cunescape(path, UNESCAPE_RELAX, &p);
4878 /* Let's ignore autofs mounts. If they aren't
4879 * triggered yet, we want to avoid triggering
4880 * them, as we don't make any guarantees for
4881 * future submounts anyway. If they are
4882 * already triggered, then we will find
4883 * another entry for this. */
4884 if (streq(type, "autofs")) {
4885 top_autofs = top_autofs || path_equal(cleaned, p);
4889 if (path_startswith(p, cleaned) &&
4890 !set_contains(done, p)) {
4892 r = set_consume(todo, p);
4902 /* If we have no submounts to process anymore and if
4903 * the root is either already done, or an autofs, we
4905 if (set_isempty(todo) &&
4906 (top_autofs || set_contains(done, cleaned)))
4909 if (!set_contains(done, cleaned) &&
4910 !set_contains(todo, cleaned)) {
4911 /* The prefix directory itself is not yet a
4912 * mount, make it one. */
4913 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
4917 (void) get_mount_flags(cleaned, &orig_flags);
4918 orig_flags &= ~MS_RDONLY;
4920 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
4923 x = strdup(cleaned);
4927 r = set_consume(done, x);
4932 while ((x = set_steal_first(todo))) {
4934 r = set_consume(done, x);
4935 if (r == -EEXIST || r == 0)
4940 /* Try to reuse the original flag set, but
4941 * don't care for errors, in case of
4942 * obstructed mounts */
4944 (void) get_mount_flags(x, &orig_flags);
4945 orig_flags &= ~MS_RDONLY;
4947 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
4949 /* Deal with mount points that are
4950 * obstructed by a later mount */
4952 if (errno != ENOENT)
4960 int fflush_and_check(FILE *f) {
4967 return errno ? -errno : -EIO;
4972 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
4984 * /foo/bar/.#<extra>waldoXXXXXX
4988 if (!filename_is_valid(fn))
4994 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
4998 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
5000 *ret = path_kill_slashes(t);
5004 int tempfn_random(const char *p, const char *extra, char **ret) {
5018 * /foo/bar/.#<extra>waldobaa2a261115984a9
5022 if (!filename_is_valid(fn))
5028 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
5032 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
5035 for (i = 0; i < 16; i++) {
5036 *(x++) = hexchar(u & 0xF);
5042 *ret = path_kill_slashes(t);
5046 int tempfn_random_child(const char *p, const char *extra, char **ret) {
5057 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5063 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
5067 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
5070 for (i = 0; i < 16; i++) {
5071 *(x++) = hexchar(u & 0xF);
5077 *ret = path_kill_slashes(t);
5081 int take_password_lock(const char *root) {
5083 struct flock flock = {
5085 .l_whence = SEEK_SET,
5093 /* This is roughly the same as lckpwdf(), but not as awful. We
5094 * don't want to use alarm() and signals, hence we implement
5095 * our own trivial version of this.
5097 * Note that shadow-utils also takes per-database locks in
5098 * addition to lckpwdf(). However, we don't given that they
5099 * are redundant as they they invoke lckpwdf() first and keep
5100 * it during everything they do. The per-database locks are
5101 * awfully racy, and thus we just won't do them. */
5104 path = strjoina(root, "/etc/.pwd.lock");
5106 path = "/etc/.pwd.lock";
5108 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5112 r = fcntl(fd, F_SETLKW, &flock);
5121 int is_symlink(const char *path) {
5124 if (lstat(path, &info) < 0)
5127 return !!S_ISLNK(info.st_mode);
5130 int is_dir(const char* path, bool follow) {
5135 r = stat(path, &st);
5137 r = lstat(path, &st);
5141 return !!S_ISDIR(st.st_mode);
5144 int is_device_node(const char *path) {
5147 if (lstat(path, &info) < 0)
5150 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5153 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5154 _cleanup_free_ char *s = NULL;
5155 size_t allocated = 0, sz = 0;
5163 SINGLE_QUOTE_ESCAPE,
5165 DOUBLE_QUOTE_ESCAPE,
5173 /* Parses the first word of a string, and returns it in
5174 * *ret. Removes all quotes in the process. When parsing fails
5175 * (because of an uneven number of quotes or similar), leaves
5176 * the pointer *p at the first invalid character. */
5186 else if (strchr(WHITESPACE, c))
5196 state = SINGLE_QUOTE;
5198 state = VALUE_ESCAPE;
5200 state = DOUBLE_QUOTE;
5201 else if (strchr(WHITESPACE, c))
5204 if (!GREEDY_REALLOC(s, allocated, sz+2))
5214 if (flags & UNQUOTE_RELAX)
5217 } else if (c == '\'')
5220 state = SINGLE_QUOTE_ESCAPE;
5222 if (!GREEDY_REALLOC(s, allocated, sz+2))
5236 state = DOUBLE_QUOTE_ESCAPE;
5238 if (!GREEDY_REALLOC(s, allocated, sz+2))
5246 case SINGLE_QUOTE_ESCAPE:
5247 case DOUBLE_QUOTE_ESCAPE:
5249 if (!GREEDY_REALLOC(s, allocated, sz+7))
5253 if ((flags & UNQUOTE_CUNESCAPE_RELAX) &&
5254 (state == VALUE_ESCAPE || flags & UNQUOTE_RELAX)) {
5255 /* If we find an unquoted trailing backslash and we're in
5256 * UNQUOTE_CUNESCAPE_RELAX mode, keep it verbatim in the
5259 * Unbalanced quotes will only be allowed in UNQUOTE_RELAX
5260 * mode, UNQUOTE_CUNESCAP_RELAX mode does not allow them.
5265 if (flags & UNQUOTE_RELAX)
5270 if (flags & UNQUOTE_CUNESCAPE) {
5273 r = cunescape_one(*p, (size_t) -1, &c, &u);
5275 if (flags & UNQUOTE_CUNESCAPE_RELAX) {
5286 s[sz++] = c; /* normal explicit char */
5288 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5293 state = (state == SINGLE_QUOTE_ESCAPE) ? SINGLE_QUOTE :
5294 (state == DOUBLE_QUOTE_ESCAPE) ? DOUBLE_QUOTE :
5301 if (!strchr(WHITESPACE, c))
5323 int unquote_first_word_and_warn(
5328 const char *filename,
5330 const char *rvalue) {
5331 /* Try to unquote it, if it fails, warn about it and try again but this
5332 * time using UNQUOTE_CUNESCAPE_RELAX to keep the backslashes verbatim
5333 * in invalid escape sequences. */
5338 r = unquote_first_word(p, ret, flags);
5339 if (r < 0 && !(flags&UNQUOTE_CUNESCAPE_RELAX)) {
5340 /* Retry it with UNQUOTE_CUNESCAPE_RELAX. */
5342 r = unquote_first_word(p, ret, flags|UNQUOTE_CUNESCAPE_RELAX);
5344 log_syntax(unit, LOG_ERR, filename, line, EINVAL,
5345 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue);
5347 log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
5348 "Invalid escape sequences in command line: \"%s\"", rvalue);
5353 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5358 /* Parses a number of words from a string, stripping any
5359 * quotes if necessary. */
5363 /* Count how many words are expected */
5364 va_start(ap, flags);
5366 if (!va_arg(ap, char **))
5375 /* Read all words into a temporary array */
5376 l = newa0(char*, n);
5377 for (c = 0; c < n; c++) {
5379 r = unquote_first_word(p, &l[c], flags);
5383 for (j = 0; j < c; j++)
5393 /* If we managed to parse all words, return them in the passed
5395 va_start(ap, flags);
5396 for (i = 0; i < n; i++) {
5399 v = va_arg(ap, char **);
5409 int free_and_strdup(char **p, const char *s) {
5414 /* Replaces a string pointer with an strdup()ed new string,
5415 * possibly freeing the old one. */
5417 if (streq_ptr(*p, s))
5433 int ptsname_malloc(int fd, char **ret) {
5446 if (ptsname_r(fd, c, l) == 0) {
5450 if (errno != ERANGE) {
5460 int openpt_in_namespace(pid_t pid, int flags) {
5461 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5462 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5464 struct cmsghdr cmsghdr;
5465 uint8_t buf[CMSG_SPACE(sizeof(int))];
5467 struct msghdr mh = {
5468 .msg_control = &control,
5469 .msg_controllen = sizeof(control),
5471 struct cmsghdr *cmsg;
5478 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5482 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5492 pair[0] = safe_close(pair[0]);
5494 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5496 _exit(EXIT_FAILURE);
5498 master = posix_openpt(flags);
5500 _exit(EXIT_FAILURE);
5502 cmsg = CMSG_FIRSTHDR(&mh);
5503 cmsg->cmsg_level = SOL_SOCKET;
5504 cmsg->cmsg_type = SCM_RIGHTS;
5505 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5506 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5508 mh.msg_controllen = cmsg->cmsg_len;
5510 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5511 _exit(EXIT_FAILURE);
5513 _exit(EXIT_SUCCESS);
5516 pair[1] = safe_close(pair[1]);
5518 r = wait_for_terminate(child, &si);
5521 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5524 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5527 CMSG_FOREACH(cmsg, &mh)
5528 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5532 fds = (int*) CMSG_DATA(cmsg);
5533 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5536 close_many(fds, n_fds);
5546 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5547 _cleanup_close_ int fd = -1;
5550 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5552 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5556 l = fgetxattr(fd, attribute, value, size);
5563 static int parse_crtime(le64_t le, usec_t *usec) {
5569 if (u == 0 || u == (uint64_t) -1)
5576 int fd_getcrtime(int fd, usec_t *usec) {
5583 /* Until Linux gets a real concept of birthtime/creation time,
5584 * let's fake one with xattrs */
5586 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5589 if (n != sizeof(le))
5592 return parse_crtime(le, usec);
5595 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5599 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5602 if (n != sizeof(le))
5605 return parse_crtime(le, usec);
5608 int path_getcrtime(const char *p, usec_t *usec) {
5615 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5618 if (n != sizeof(le))
5621 return parse_crtime(le, usec);
5624 int fd_setcrtime(int fd, usec_t usec) {
5630 usec = now(CLOCK_REALTIME);
5632 le = htole64((uint64_t) usec);
5633 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5639 int same_fd(int a, int b) {
5640 struct stat sta, stb;
5647 /* Compares two file descriptors. Note that semantics are
5648 * quite different depending on whether we have kcmp() or we
5649 * don't. If we have kcmp() this will only return true for
5650 * dup()ed file descriptors, but not otherwise. If we don't
5651 * have kcmp() this will also return true for two fds of the same
5652 * file, created by separate open() calls. Since we use this
5653 * call mostly for filtering out duplicates in the fd store
5654 * this difference hopefully doesn't matter too much. */
5659 /* Try to use kcmp() if we have it. */
5661 r = kcmp(pid, pid, KCMP_FILE, a, b);
5666 if (errno != ENOSYS)
5669 /* We don't have kcmp(), use fstat() instead. */
5670 if (fstat(a, &sta) < 0)
5673 if (fstat(b, &stb) < 0)
5676 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
5679 /* We consider all device fds different, since two device fds
5680 * might refer to quite different device contexts even though
5681 * they share the same inode and backing dev_t. */
5683 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
5686 if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
5689 /* The fds refer to the same inode on disk, let's also check
5690 * if they have the same fd flags. This is useful to
5691 * distinguish the read and write side of a pipe created with
5693 fa = fcntl(a, F_GETFL);
5697 fb = fcntl(b, F_GETFL);
5704 int chattr_fd(int fd, unsigned value, unsigned mask) {
5705 unsigned old_attr, new_attr;
5710 if (fstat(fd, &st) < 0)
5713 /* Explicitly check whether this is a regular file or
5714 * directory. If it is anything else (such as a device node or
5715 * fifo), then the ioctl will not hit the file systems but
5716 * possibly drivers, where the ioctl might have different
5717 * effects. Notably, DRM is using the same ioctl() number. */
5719 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5725 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5728 new_attr = (old_attr & ~mask) | (value & mask);
5729 if (new_attr == old_attr)
5732 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5738 int chattr_path(const char *p, unsigned value, unsigned mask) {
5739 _cleanup_close_ int fd = -1;
5746 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5750 return chattr_fd(fd, value, mask);
5753 int read_attr_fd(int fd, unsigned *ret) {
5758 if (fstat(fd, &st) < 0)
5761 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5764 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5770 int read_attr_path(const char *p, unsigned *ret) {
5771 _cleanup_close_ int fd = -1;
5776 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5780 return read_attr_fd(fd, ret);
5783 static size_t nul_length(const uint8_t *p, size_t sz) {
5798 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
5799 const uint8_t *q, *w, *e;
5807 n = nul_length(q, e - q);
5809 /* If there are more than the specified run length of
5810 * NUL bytes, or if this is the beginning or the end
5811 * of the buffer, then seek instead of write */
5812 if ((n > run_length) ||
5813 (n > 0 && q == p) ||
5814 (n > 0 && q + n >= e)) {
5816 l = write(fd, w, q - w);
5823 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
5835 l = write(fd, w, q - w);
5842 return q - (const uint8_t*) p;
5845 void sigkill_wait(pid_t *pid) {
5851 if (kill(*pid, SIGKILL) > 0)
5852 (void) wait_for_terminate(*pid, NULL);
5855 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
5856 int a = 0, b = 0, c = 0;
5866 if (!strchr(*p, '>'))
5869 if ((*p)[2] == '>') {
5870 c = undecchar((*p)[1]);
5872 } else if ((*p)[3] == '>') {
5873 b = undecchar((*p)[1]);
5874 c = undecchar((*p)[2]);
5876 } else if ((*p)[4] == '>') {
5877 a = undecchar((*p)[1]);
5878 b = undecchar((*p)[2]);
5879 c = undecchar((*p)[3]);
5884 if (a < 0 || b < 0 || c < 0 ||
5885 (!with_facility && (a || b || c > 7)))
5889 *priority = a*100 + b*10 + c;
5891 *priority = (*priority & LOG_FACMASK) | c;
5897 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
5903 for (i = 0; i < len; ++i)
5904 if (streq_ptr(table[i], key))
5910 void cmsg_close_all(struct msghdr *mh) {
5911 struct cmsghdr *cmsg;
5915 CMSG_FOREACH(cmsg, mh)
5916 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
5917 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
5920 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
5924 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
5928 /* Even though renameat2() exists since Linux 3.15, btrfs added
5929 * support for it later. If it is not implemented, fallback to another
5931 if (errno != EINVAL)
5934 /* The link()/unlink() fallback does not work on directories. But
5935 * renameat() without RENAME_NOREPLACE gives the same semantics on
5936 * directories, except when newpath is an *empty* directory. This is
5938 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
5939 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
5940 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
5941 return ret >= 0 ? 0 : -errno;
5944 /* If it is not a directory, use the link()/unlink() fallback. */
5945 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
5949 ret = unlinkat(olddirfd, oldpath, 0);
5951 /* backup errno before the following unlinkat() alters it */
5953 (void) unlinkat(newdirfd, newpath, 0);
5961 char *shell_maybe_quote(const char *s) {
5967 /* Encloses a string in double quotes if necessary to make it
5968 * OK as shell string. */
5970 for (p = s; *p; p++)
5973 strchr(SHELL_NEED_QUOTES, *p))
5979 r = new(char, 1+strlen(s)*2+1+1);
5985 t = mempcpy(t, s, p - s);
5989 if (strchr(SHELL_NEED_ESCAPE, *p))
6001 int parse_mode(const char *s, mode_t *ret) {
6009 l = strtol(s, &x, 8);
6013 if (!x || x == s || *x)
6015 if (l < 0 || l > 07777)
6022 int mount_move_root(const char *path) {
6025 if (chdir(path) < 0)
6028 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
6031 if (chroot(".") < 0)
6040 int reset_uid_gid(void) {
6042 if (setgroups(0, NULL) < 0)
6045 if (setresgid(0, 0, 0) < 0)
6048 if (setresuid(0, 0, 0) < 0)