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 /// UNNEEDED by elogind
794 char *delete_chars(char *s, const char *bad) {
797 /* Drops all whitespace, regardless where in the string */
799 for (f = s, t = s; *f; f++) {
812 char *file_in_same_dir(const char *path, const char *filename) {
819 /* This removes the last component of path and appends
820 * filename, unless the latter is absolute anyway or the
823 if (path_is_absolute(filename))
824 return strdup(filename);
826 e = strrchr(path, '/');
828 return strdup(filename);
830 k = strlen(filename);
831 ret = new(char, (e + 1 - path) + k + 1);
835 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
839 int rmdir_parents(const char *path, const char *stop) {
848 /* Skip trailing slashes */
849 while (l > 0 && path[l-1] == '/')
855 /* Skip last component */
856 while (l > 0 && path[l-1] != '/')
859 /* Skip trailing slashes */
860 while (l > 0 && path[l-1] == '/')
866 if (!(t = strndup(path, l)))
869 if (path_startswith(stop, t)) {
885 char hexchar(int x) {
886 static const char table[16] = "0123456789abcdef";
888 return table[x & 15];
891 int unhexchar(char c) {
893 if (c >= '0' && c <= '9')
896 if (c >= 'a' && c <= 'f')
899 if (c >= 'A' && c <= 'F')
905 char *hexmem(const void *p, size_t l) {
909 z = r = malloc(l * 2 + 1);
913 for (x = p; x < (const uint8_t*) p + l; x++) {
914 *(z++) = hexchar(*x >> 4);
915 *(z++) = hexchar(*x & 15);
922 void *unhexmem(const char *p, size_t l) {
928 z = r = malloc((l + 1) / 2 + 1);
932 for (x = p; x < p + l; x += 2) {
941 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
948 char octchar(int x) {
949 return '0' + (x & 7);
952 int unoctchar(char c) {
954 if (c >= '0' && c <= '7')
960 char decchar(int x) {
961 return '0' + (x % 10);
964 int undecchar(char c) {
966 if (c >= '0' && c <= '9')
972 char *cescape(const char *s) {
978 /* Does C style string escaping. May be reversed with
981 r = new(char, strlen(s)*4 + 1);
985 for (f = s, t = r; *f; f++)
986 t += cescape_char(*f, t);
993 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1000 /* Unescapes C style. Returns the unescaped character in ret,
1001 * unless we encountered a \u sequence in which case the full
1002 * unicode character is returned in ret_unicode, instead. */
1004 if (length != (size_t) -1 && length < 1)
1041 /* This is an extension of the XDG syntax files */
1046 /* hexadecimal encoding */
1049 if (length != (size_t) -1 && length < 3)
1052 a = unhexchar(p[1]);
1056 b = unhexchar(p[2]);
1060 /* Don't allow NUL bytes */
1061 if (a == 0 && b == 0)
1064 *ret = (char) ((a << 4U) | b);
1070 /* C++11 style 16bit unicode */
1076 if (length != (size_t) -1 && length < 5)
1079 for (i = 0; i < 4; i++) {
1080 a[i] = unhexchar(p[1 + i]);
1085 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1087 /* Don't allow 0 chars */
1106 /* C++11 style 32bit unicode */
1112 if (length != (size_t) -1 && length < 9)
1115 for (i = 0; i < 8; i++) {
1116 a[i] = unhexchar(p[1 + i]);
1121 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1122 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1124 /* Don't allow 0 chars */
1128 /* Don't allow invalid code points */
1129 if (!unichar_is_valid(c))
1154 /* octal encoding */
1158 if (length != (size_t) -1 && length < 3)
1161 a = unoctchar(p[0]);
1165 b = unoctchar(p[1]);
1169 c = unoctchar(p[2]);
1173 /* don't allow NUL bytes */
1174 if (a == 0 && b == 0 && c == 0)
1177 /* Don't allow bytes above 255 */
1178 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1194 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1202 /* Undoes C style string escaping, and optionally prefixes it. */
1204 pl = prefix ? strlen(prefix) : 0;
1206 r = new(char, pl+length+1);
1211 memcpy(r, prefix, pl);
1213 for (f = s, t = r + pl; f < s + length; f++) {
1219 remaining = s + length - f;
1220 assert(remaining > 0);
1223 /* A literal literal, copy verbatim */
1228 if (remaining == 1) {
1229 if (flags & UNESCAPE_RELAX) {
1230 /* A trailing backslash, copy verbatim */
1239 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1241 if (flags & UNESCAPE_RELAX) {
1242 /* Invalid escape code, let's take it literal then */
1252 /* Non-Unicode? Let's encode this directly */
1255 /* Unicode? Then let's encode this in UTF-8 */
1256 t += utf8_encode_unichar(t, u);
1267 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1268 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1271 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1272 return cunescape_length(s, strlen(s), flags, ret);
1275 char *xescape(const char *s, const char *bad) {
1279 /* Escapes all chars in bad, in addition to \ and all special
1280 * chars, in \xFF style escaping. May be reversed with
1283 r = new(char, strlen(s) * 4 + 1);
1287 for (f = s, t = r; *f; f++) {
1289 if ((*f < ' ') || (*f >= 127) ||
1290 (*f == '\\') || strchr(bad, *f)) {
1293 *(t++) = hexchar(*f >> 4);
1294 *(t++) = hexchar(*f);
1304 char *ascii_strlower(char *t) {
1309 for (p = t; *p; p++)
1310 if (*p >= 'A' && *p <= 'Z')
1311 *p = *p - 'A' + 'a';
1316 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1320 filename[0] == '.' ||
1321 streq(filename, "lost+found") ||
1322 streq(filename, "aquota.user") ||
1323 streq(filename, "aquota.group") ||
1324 endswith(filename, ".rpmnew") ||
1325 endswith(filename, ".rpmsave") ||
1326 endswith(filename, ".rpmorig") ||
1327 endswith(filename, ".dpkg-old") ||
1328 endswith(filename, ".dpkg-new") ||
1329 endswith(filename, ".dpkg-tmp") ||
1330 endswith(filename, ".dpkg-dist") ||
1331 endswith(filename, ".dpkg-bak") ||
1332 endswith(filename, ".dpkg-backup") ||
1333 endswith(filename, ".dpkg-remove") ||
1334 endswith(filename, ".swp");
1337 bool hidden_file(const char *filename) {
1340 if (endswith(filename, "~"))
1343 return hidden_file_allow_backup(filename);
1346 int fd_nonblock(int fd, bool nonblock) {
1351 flags = fcntl(fd, F_GETFL, 0);
1356 nflags = flags | O_NONBLOCK;
1358 nflags = flags & ~O_NONBLOCK;
1360 if (nflags == flags)
1363 if (fcntl(fd, F_SETFL, nflags) < 0)
1369 int fd_cloexec(int fd, bool cloexec) {
1374 flags = fcntl(fd, F_GETFD, 0);
1379 nflags = flags | FD_CLOEXEC;
1381 nflags = flags & ~FD_CLOEXEC;
1383 if (nflags == flags)
1386 if (fcntl(fd, F_SETFD, nflags) < 0)
1392 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1395 assert(n_fdset == 0 || fdset);
1397 for (i = 0; i < n_fdset; i++)
1404 int close_all_fds(const int except[], unsigned n_except) {
1405 _cleanup_closedir_ DIR *d = NULL;
1409 assert(n_except == 0 || except);
1411 d = opendir("/proc/self/fd");
1416 /* When /proc isn't available (for example in chroots)
1417 * the fallback is brute forcing through the fd
1420 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1421 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1423 if (fd_in_set(fd, except, n_except))
1426 if (close_nointr(fd) < 0)
1427 if (errno != EBADF && r == 0)
1434 while ((de = readdir(d))) {
1437 if (hidden_file(de->d_name))
1440 if (safe_atoi(de->d_name, &fd) < 0)
1441 /* Let's better ignore this, just in case */
1450 if (fd_in_set(fd, except, n_except))
1453 if (close_nointr(fd) < 0) {
1454 /* Valgrind has its own FD and doesn't want to have it closed */
1455 if (errno != EBADF && r == 0)
1463 bool chars_intersect(const char *a, const char *b) {
1466 /* Returns true if any of the chars in a are in b. */
1467 for (p = a; *p; p++)
1474 bool fstype_is_network(const char *fstype) {
1475 static const char table[] =
1490 x = startswith(fstype, "fuse.");
1494 return nulstr_contains(table, fstype);
1497 int flush_fd(int fd) {
1498 struct pollfd pollfd = {
1508 r = poll(&pollfd, 1, 0);
1518 l = read(fd, buf, sizeof(buf));
1524 if (errno == EAGAIN)
1533 void safe_close_pair(int p[]) {
1537 /* Special case pairs which use the same fd in both
1539 p[0] = p[1] = safe_close(p[0]);
1543 p[0] = safe_close(p[0]);
1544 p[1] = safe_close(p[1]);
1547 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1554 while (nbytes > 0) {
1557 k = read(fd, p, nbytes);
1562 if (errno == EAGAIN && do_poll) {
1564 /* We knowingly ignore any return value here,
1565 * and expect that any error/EOF is reported
1568 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1572 return n > 0 ? n : -errno;
1586 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1589 n = loop_read(fd, buf, nbytes, do_poll);
1592 if ((size_t) n != nbytes)
1597 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1598 const uint8_t *p = buf;
1608 k = write(fd, p, nbytes);
1613 if (errno == EAGAIN && do_poll) {
1614 /* We knowingly ignore any return value here,
1615 * and expect that any error/EOF is reported
1618 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1625 if (nbytes > 0 && k == 0) /* Can't really happen */
1630 } while (nbytes > 0);
1635 int parse_size(const char *t, off_t base, off_t *size) {
1637 /* Soo, sometimes we want to parse IEC binary suffixes, and
1638 * sometimes SI decimal suffixes. This function can parse
1639 * both. Which one is the right way depends on the
1640 * context. Wikipedia suggests that SI is customary for
1641 * hardware metrics and network speeds, while IEC is
1642 * customary for most data sizes used by software and volatile
1643 * (RAM) memory. Hence be careful which one you pick!
1645 * In either case we use just K, M, G as suffix, and not Ki,
1646 * Mi, Gi or so (as IEC would suggest). That's because that's
1647 * frickin' ugly. But this means you really need to make sure
1648 * to document which base you are parsing when you use this
1653 unsigned long long factor;
1656 static const struct table iec[] = {
1657 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1658 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1659 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1660 { "G", 1024ULL*1024ULL*1024ULL },
1661 { "M", 1024ULL*1024ULL },
1667 static const struct table si[] = {
1668 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1669 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1670 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1671 { "G", 1000ULL*1000ULL*1000ULL },
1672 { "M", 1000ULL*1000ULL },
1678 const struct table *table;
1680 unsigned long long r = 0;
1681 unsigned n_entries, start_pos = 0;
1684 assert(base == 1000 || base == 1024);
1689 n_entries = ELEMENTSOF(si);
1692 n_entries = ELEMENTSOF(iec);
1698 unsigned long long l2;
1704 l = strtoll(p, &e, 10);
1717 if (*e >= '0' && *e <= '9') {
1720 /* strotoull itself would accept space/+/- */
1721 l2 = strtoull(e, &e2, 10);
1723 if (errno == ERANGE)
1726 /* Ignore failure. E.g. 10.M is valid */
1733 e += strspn(e, WHITESPACE);
1735 for (i = start_pos; i < n_entries; i++)
1736 if (startswith(e, table[i].suffix)) {
1737 unsigned long long tmp;
1738 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1740 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1741 if (tmp > ULLONG_MAX - r)
1745 if ((unsigned long long) (off_t) r != r)
1748 p = e + strlen(table[i].suffix);
1764 bool is_device_path(const char *path) {
1766 /* Returns true on paths that refer to a device, either in
1767 * sysfs or in /dev */
1770 path_startswith(path, "/dev/") ||
1771 path_startswith(path, "/sys/");
1774 int dir_is_empty(const char *path) {
1775 _cleanup_closedir_ DIR *d;
1786 if (!de && errno != 0)
1792 if (!hidden_file(de->d_name))
1797 char* dirname_malloc(const char *path) {
1798 char *d, *dir, *dir2;
1815 void rename_process(const char name[8]) {
1818 /* This is a like a poor man's setproctitle(). It changes the
1819 * comm field, argv[0], and also the glibc's internally used
1820 * name of the process. For the first one a limit of 16 chars
1821 * applies, to the second one usually one of 10 (i.e. length
1822 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1823 * "systemd"). If you pass a longer string it will be
1826 prctl(PR_SET_NAME, name);
1828 if (program_invocation_name)
1829 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1831 if (saved_argc > 0) {
1835 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1837 for (i = 1; i < saved_argc; i++) {
1841 memzero(saved_argv[i], strlen(saved_argv[i]));
1846 char *lookup_uid(uid_t uid) {
1849 _cleanup_free_ char *buf = NULL;
1850 struct passwd pwbuf, *pw = NULL;
1852 /* Shortcut things to avoid NSS lookups */
1854 return strdup("root");
1856 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1860 buf = malloc(bufsize);
1864 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1865 return strdup(pw->pw_name);
1867 if (asprintf(&name, UID_FMT, uid) < 0)
1873 char* getlogname_malloc(void) {
1877 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1882 return lookup_uid(uid);
1885 char *getusername_malloc(void) {
1892 return lookup_uid(getuid());
1895 bool is_temporary_fs(const struct statfs *s) {
1898 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
1899 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
1902 int fd_is_temporary_fs(int fd) {
1905 if (fstatfs(fd, &s) < 0)
1908 return is_temporary_fs(&s);
1911 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1914 /* Under the assumption that we are running privileged we
1915 * first change the access mode and only then hand out
1916 * ownership to avoid a window where access is too open. */
1918 if (mode != MODE_INVALID)
1919 if (chmod(path, mode) < 0)
1922 if (uid != UID_INVALID || gid != GID_INVALID)
1923 if (chown(path, uid, gid) < 0)
1929 /// UNNEEDED by elogind
1931 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
1934 /* Under the assumption that we are running privileged we
1935 * first change the access mode and only then hand out
1936 * ownership to avoid a window where access is too open. */
1938 if (mode != MODE_INVALID)
1939 if (fchmod(fd, mode) < 0)
1942 if (uid != UID_INVALID || gid != GID_INVALID)
1943 if (fchown(fd, uid, gid) < 0)
1950 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
1954 /* Allocates the cpuset in the right size */
1957 if (!(r = CPU_ALLOC(n)))
1960 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
1961 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
1971 if (errno != EINVAL)
1978 int files_same(const char *filea, const char *fileb) {
1981 if (stat(filea, &a) < 0)
1984 if (stat(fileb, &b) < 0)
1987 return a.st_dev == b.st_dev &&
1988 a.st_ino == b.st_ino;
1991 int running_in_chroot(void) {
1994 ret = files_same("/proc/1/root", "/");
2001 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2006 assert(percent <= 100);
2007 assert(new_length >= 3);
2009 if (old_length <= 3 || old_length <= new_length)
2010 return strndup(s, old_length);
2012 r = new0(char, new_length+1);
2016 x = (new_length * percent) / 100;
2018 if (x > new_length - 3)
2026 s + old_length - (new_length - x - 3),
2027 new_length - x - 3);
2032 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2036 unsigned k, len, len2;
2039 assert(percent <= 100);
2040 assert(new_length >= 3);
2042 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2043 if (ascii_is_valid(s))
2044 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2046 if (old_length <= 3 || old_length <= new_length)
2047 return strndup(s, old_length);
2049 x = (new_length * percent) / 100;
2051 if (x > new_length - 3)
2055 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2058 c = utf8_encoded_to_unichar(i);
2061 k += unichar_iswide(c) ? 2 : 1;
2064 if (k > x) /* last character was wide and went over quota */
2067 for (j = s + old_length; k < new_length && j > i; ) {
2070 j = utf8_prev_char(j);
2071 c = utf8_encoded_to_unichar(j);
2074 k += unichar_iswide(c) ? 2 : 1;
2078 /* we don't actually need to ellipsize */
2080 return memdup(s, old_length + 1);
2082 /* make space for ellipsis */
2083 j = utf8_next_char(j);
2086 len2 = s + old_length - j;
2087 e = new(char, len + 3 + len2 + 1);
2092 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2093 old_length, new_length, x, len, len2, k);
2097 e[len] = 0xe2; /* tri-dot ellipsis: … */
2101 memcpy(e + len + 3, j, len2 + 1);
2106 char *ellipsize(const char *s, size_t length, unsigned percent) {
2107 return ellipsize_mem(s, strlen(s), length, percent);
2110 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2111 _cleanup_close_ int fd;
2117 mkdir_parents(path, 0755);
2119 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2124 r = fchmod(fd, mode);
2129 if (uid != UID_INVALID || gid != GID_INVALID) {
2130 r = fchown(fd, uid, gid);
2135 if (stamp != USEC_INFINITY) {
2136 struct timespec ts[2];
2138 timespec_store(&ts[0], stamp);
2140 r = futimens(fd, ts);
2142 r = futimens(fd, NULL);
2149 int touch(const char *path) {
2150 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2153 /// UNNEEDED by elogind
2155 static char *unquote(const char *s, const char* quotes) {
2159 /* This is rather stupid, simply removes the heading and
2160 * trailing quotes if there is one. Doesn't care about
2161 * escaping or anything.
2163 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2169 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2170 return strndup(s+1, l-2);
2176 noreturn void freeze(void) {
2178 /* Make sure nobody waits for us on a socket anymore */
2179 close_all_fds(NULL, 0);
2187 bool null_or_empty(struct stat *st) {
2190 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2193 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2199 int null_or_empty_path(const char *fn) {
2204 if (stat(fn, &st) < 0)
2207 return null_or_empty(&st);
2210 /// UNNEEDED by elogind
2212 int null_or_empty_fd(int fd) {
2217 if (fstat(fd, &st) < 0)
2220 return null_or_empty(&st);
2224 DIR *xopendirat(int fd, const char *name, int flags) {
2228 assert(!(flags & O_CREAT));
2230 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2243 /// UNNEEDED by elogind
2245 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2246 _cleanup_free_ char *t = NULL, *u = NULL;
2249 u = unquote(tagvalue, QUOTES);
2253 enc_len = strlen(u) * 4 + 1;
2254 t = new(char, enc_len);
2258 if (encode_devnode_name(u, t, enc_len) < 0)
2261 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2264 char *fstab_node_to_udev_node(const char *p) {
2267 if (startswith(p, "LABEL="))
2268 return tag_to_udev_node(p+6, "label");
2270 if (startswith(p, "UUID="))
2271 return tag_to_udev_node(p+5, "uuid");
2273 if (startswith(p, "PARTUUID="))
2274 return tag_to_udev_node(p+9, "partuuid");
2276 if (startswith(p, "PARTLABEL="))
2277 return tag_to_udev_node(p+10, "partlabel");
2283 bool dirent_is_file(const struct dirent *de) {
2286 if (hidden_file(de->d_name))
2289 if (de->d_type != DT_REG &&
2290 de->d_type != DT_LNK &&
2291 de->d_type != DT_UNKNOWN)
2297 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2300 if (de->d_type != DT_REG &&
2301 de->d_type != DT_LNK &&
2302 de->d_type != DT_UNKNOWN)
2305 if (hidden_file_allow_backup(de->d_name))
2308 return endswith(de->d_name, suffix);
2311 /// UNNEEDED by elogind
2313 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2314 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2315 _cleanup_set_free_free_ Set *seen = NULL;
2318 /* We fork this all off from a child process so that we can
2319 * somewhat cleanly make use of SIGALRM to set a time limit */
2321 (void) reset_all_signal_handlers();
2322 (void) reset_signal_mask();
2324 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2326 pids = hashmap_new(NULL);
2330 seen = set_new(&string_hash_ops);
2334 STRV_FOREACH(directory, directories) {
2335 _cleanup_closedir_ DIR *d;
2338 d = opendir(*directory);
2340 if (errno == ENOENT)
2343 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2346 FOREACH_DIRENT(de, d, break) {
2347 _cleanup_free_ char *path = NULL;
2351 if (!dirent_is_file(de))
2354 if (set_contains(seen, de->d_name)) {
2355 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2359 r = set_put_strdup(seen, de->d_name);
2363 path = strjoin(*directory, "/", de->d_name, NULL);
2367 if (null_or_empty_path(path)) {
2368 log_debug("%s is empty (a mask).", path);
2374 log_error_errno(errno, "Failed to fork: %m");
2376 } else if (pid == 0) {
2379 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2389 return log_error_errno(errno, "Failed to execute %s: %m", path);
2392 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2394 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2401 /* Abort execution of this process after the timout. We simply
2402 * rely on SIGALRM as default action terminating the process,
2403 * and turn on alarm(). */
2405 if (timeout != USEC_INFINITY)
2406 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2408 while (!hashmap_isempty(pids)) {
2409 _cleanup_free_ char *path = NULL;
2412 pid = PTR_TO_UINT(hashmap_first_key(pids));
2415 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2418 wait_for_terminate_and_warn(path, pid, true);
2424 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2428 char **dirs = (char**) directories;
2430 assert(!strv_isempty(dirs));
2432 name = basename(dirs[0]);
2433 assert(!isempty(name));
2435 /* Executes all binaries in the directories in parallel and waits
2436 * for them to finish. Optionally a timeout is applied. If a file
2437 * with the same name exists in more than one directory, the
2438 * earliest one wins. */
2440 executor_pid = fork();
2441 if (executor_pid < 0) {
2442 log_error_errno(errno, "Failed to fork: %m");
2445 } else if (executor_pid == 0) {
2446 r = do_execute(dirs, timeout, argv);
2447 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2450 wait_for_terminate_and_warn(name, executor_pid, true);
2454 bool nulstr_contains(const char*nulstr, const char *needle) {
2460 NULSTR_FOREACH(i, nulstr)
2461 if (streq(i, needle))
2467 /// UNNEEDED by elogind
2469 bool plymouth_running(void) {
2470 return access("/run/plymouth/pid", F_OK) >= 0;
2474 char* strshorten(char *s, size_t l) {
2483 bool machine_name_is_valid(const char *s) {
2485 if (!hostname_is_valid(s))
2488 /* Machine names should be useful hostnames, but also be
2489 * useful in unit names, hence we enforce a stricter length
2498 int pipe_eof(int fd) {
2499 struct pollfd pollfd = {
2501 .events = POLLIN|POLLHUP,
2506 r = poll(&pollfd, 1, 0);
2513 return pollfd.revents & POLLHUP;
2516 int fd_wait_for_event(int fd, int event, usec_t t) {
2518 struct pollfd pollfd = {
2526 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2533 return pollfd.revents;
2536 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2545 r = tempfn_xxxxxx(path, NULL, &t);
2549 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2555 f = fdopen(fd, "we");
2568 int symlink_atomic(const char *from, const char *to) {
2569 _cleanup_free_ char *t = NULL;
2575 r = tempfn_random(to, NULL, &t);
2579 if (symlink(from, t) < 0)
2582 if (rename(t, to) < 0) {
2590 /// UNNEEDED by elogind
2592 int symlink_idempotent(const char *from, const char *to) {
2593 _cleanup_free_ char *p = NULL;
2599 if (symlink(from, to) < 0) {
2600 if (errno != EEXIST)
2603 r = readlink_malloc(to, &p);
2607 if (!streq(p, from))
2614 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2615 _cleanup_free_ char *t = NULL;
2620 r = tempfn_random(path, NULL, &t);
2624 if (mknod(t, mode, dev) < 0)
2627 if (rename(t, path) < 0) {
2635 int mkfifo_atomic(const char *path, mode_t mode) {
2636 _cleanup_free_ char *t = NULL;
2641 r = tempfn_random(path, NULL, &t);
2645 if (mkfifo(t, mode) < 0)
2648 if (rename(t, path) < 0) {
2657 bool display_is_local(const char *display) {
2661 display[0] == ':' &&
2662 display[1] >= '0' &&
2666 int socket_from_display(const char *display, char **path) {
2673 if (!display_is_local(display))
2676 k = strspn(display+1, "0123456789");
2678 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2682 c = stpcpy(f, "/tmp/.X11-unix/X");
2683 memcpy(c, display+1, k);
2692 const char **username,
2693 uid_t *uid, gid_t *gid,
2695 const char **shell) {
2703 /* We enforce some special rules for uid=0: in order to avoid
2704 * NSS lookups for root we hardcode its data. */
2706 if (streq(*username, "root") || streq(*username, "0")) {
2724 if (parse_uid(*username, &u) >= 0) {
2728 /* If there are multiple users with the same id, make
2729 * sure to leave $USER to the configured value instead
2730 * of the first occurrence in the database. However if
2731 * the uid was configured by a numeric uid, then let's
2732 * pick the real username from /etc/passwd. */
2734 *username = p->pw_name;
2737 p = getpwnam(*username);
2741 return errno > 0 ? -errno : -ESRCH;
2753 *shell = p->pw_shell;
2758 char* uid_to_name(uid_t uid) {
2763 return strdup("root");
2767 return strdup(p->pw_name);
2769 if (asprintf(&r, UID_FMT, uid) < 0)
2775 char* gid_to_name(gid_t gid) {
2780 return strdup("root");
2784 return strdup(p->gr_name);
2786 if (asprintf(&r, GID_FMT, gid) < 0)
2792 int get_group_creds(const char **groupname, gid_t *gid) {
2798 /* We enforce some special rules for gid=0: in order to avoid
2799 * NSS lookups for root we hardcode its data. */
2801 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2802 *groupname = "root";
2810 if (parse_gid(*groupname, &id) >= 0) {
2815 *groupname = g->gr_name;
2818 g = getgrnam(*groupname);
2822 return errno > 0 ? -errno : -ESRCH;
2830 int in_gid(gid_t gid) {
2832 int ngroups_max, r, i;
2834 if (getgid() == gid)
2837 if (getegid() == gid)
2840 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2841 assert(ngroups_max > 0);
2843 gids = alloca(sizeof(gid_t) * ngroups_max);
2845 r = getgroups(ngroups_max, gids);
2849 for (i = 0; i < r; i++)
2856 /// UNNEEDED by elogind
2858 int in_group(const char *name) {
2862 r = get_group_creds(&name, &gid);
2870 int glob_exists(const char *path) {
2871 _cleanup_globfree_ glob_t g = {};
2877 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2879 if (k == GLOB_NOMATCH)
2881 else if (k == GLOB_NOSPACE)
2884 return !strv_isempty(g.gl_pathv);
2886 return errno ? -errno : -EIO;
2889 /// UNNEEDED by elogind
2891 int glob_extend(char ***strv, const char *path) {
2892 _cleanup_globfree_ glob_t g = {};
2897 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2899 if (k == GLOB_NOMATCH)
2901 else if (k == GLOB_NOSPACE)
2903 else if (k != 0 || strv_isempty(g.gl_pathv))
2904 return errno ? -errno : -EIO;
2906 STRV_FOREACH(p, g.gl_pathv) {
2907 k = strv_extend(strv, *p);
2916 int dirent_ensure_type(DIR *d, struct dirent *de) {
2922 if (de->d_type != DT_UNKNOWN)
2925 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
2929 S_ISREG(st.st_mode) ? DT_REG :
2930 S_ISDIR(st.st_mode) ? DT_DIR :
2931 S_ISLNK(st.st_mode) ? DT_LNK :
2932 S_ISFIFO(st.st_mode) ? DT_FIFO :
2933 S_ISSOCK(st.st_mode) ? DT_SOCK :
2934 S_ISCHR(st.st_mode) ? DT_CHR :
2935 S_ISBLK(st.st_mode) ? DT_BLK :
2941 int get_files_in_directory(const char *path, char ***list) {
2942 _cleanup_closedir_ DIR *d = NULL;
2943 size_t bufsize = 0, n = 0;
2944 _cleanup_strv_free_ char **l = NULL;
2948 /* Returns all files in a directory in *list, and the number
2949 * of files as return value. If list is NULL returns only the
2961 if (!de && errno != 0)
2966 dirent_ensure_type(d, de);
2968 if (!dirent_is_file(de))
2972 /* one extra slot is needed for the terminating NULL */
2973 if (!GREEDY_REALLOC(l, bufsize, n + 2))
2976 l[n] = strdup(de->d_name);
2987 l = NULL; /* avoid freeing */
2993 char *strjoin(const char *x, ...) {
3007 t = va_arg(ap, const char *);
3012 if (n > ((size_t) -1) - l) {
3036 t = va_arg(ap, const char *);
3050 bool is_main_thread(void) {
3051 static thread_local int cached = 0;
3053 if (_unlikely_(cached == 0))
3054 cached = getpid() == gettid() ? 1 : -1;
3059 int block_get_whole_disk(dev_t d, dev_t *ret) {
3066 /* If it has a queue this is good enough for us */
3067 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3070 r = access(p, F_OK);
3078 /* If it is a partition find the originating device */
3079 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3082 r = access(p, F_OK);
3088 /* Get parent dev_t */
3089 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3092 r = read_one_line_file(p, &s);
3098 r = sscanf(s, "%u:%u", &m, &n);
3104 /* Only return this if it is really good enough for us. */
3105 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3108 r = access(p, F_OK);
3112 *ret = makedev(m, n);
3119 static const char *const ioprio_class_table[] = {
3120 [IOPRIO_CLASS_NONE] = "none",
3121 [IOPRIO_CLASS_RT] = "realtime",
3122 [IOPRIO_CLASS_BE] = "best-effort",
3123 [IOPRIO_CLASS_IDLE] = "idle"
3126 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3128 static const char *const sigchld_code_table[] = {
3129 [CLD_EXITED] = "exited",
3130 [CLD_KILLED] = "killed",
3131 [CLD_DUMPED] = "dumped",
3132 [CLD_TRAPPED] = "trapped",
3133 [CLD_STOPPED] = "stopped",
3134 [CLD_CONTINUED] = "continued",
3137 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3139 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3140 [LOG_FAC(LOG_KERN)] = "kern",
3141 [LOG_FAC(LOG_USER)] = "user",
3142 [LOG_FAC(LOG_MAIL)] = "mail",
3143 [LOG_FAC(LOG_DAEMON)] = "daemon",
3144 [LOG_FAC(LOG_AUTH)] = "auth",
3145 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3146 [LOG_FAC(LOG_LPR)] = "lpr",
3147 [LOG_FAC(LOG_NEWS)] = "news",
3148 [LOG_FAC(LOG_UUCP)] = "uucp",
3149 [LOG_FAC(LOG_CRON)] = "cron",
3150 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3151 [LOG_FAC(LOG_FTP)] = "ftp",
3152 [LOG_FAC(LOG_LOCAL0)] = "local0",
3153 [LOG_FAC(LOG_LOCAL1)] = "local1",
3154 [LOG_FAC(LOG_LOCAL2)] = "local2",
3155 [LOG_FAC(LOG_LOCAL3)] = "local3",
3156 [LOG_FAC(LOG_LOCAL4)] = "local4",
3157 [LOG_FAC(LOG_LOCAL5)] = "local5",
3158 [LOG_FAC(LOG_LOCAL6)] = "local6",
3159 [LOG_FAC(LOG_LOCAL7)] = "local7"
3162 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3164 static const char *const log_level_table[] = {
3165 [LOG_EMERG] = "emerg",
3166 [LOG_ALERT] = "alert",
3167 [LOG_CRIT] = "crit",
3169 [LOG_WARNING] = "warning",
3170 [LOG_NOTICE] = "notice",
3171 [LOG_INFO] = "info",
3172 [LOG_DEBUG] = "debug"
3175 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3177 static const char* const sched_policy_table[] = {
3178 [SCHED_OTHER] = "other",
3179 [SCHED_BATCH] = "batch",
3180 [SCHED_IDLE] = "idle",
3181 [SCHED_FIFO] = "fifo",
3185 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3187 static const char* const rlimit_table[_RLIMIT_MAX] = {
3188 [RLIMIT_CPU] = "LimitCPU",
3189 [RLIMIT_FSIZE] = "LimitFSIZE",
3190 [RLIMIT_DATA] = "LimitDATA",
3191 [RLIMIT_STACK] = "LimitSTACK",
3192 [RLIMIT_CORE] = "LimitCORE",
3193 [RLIMIT_RSS] = "LimitRSS",
3194 [RLIMIT_NOFILE] = "LimitNOFILE",
3195 [RLIMIT_AS] = "LimitAS",
3196 [RLIMIT_NPROC] = "LimitNPROC",
3197 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3198 [RLIMIT_LOCKS] = "LimitLOCKS",
3199 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3200 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3201 [RLIMIT_NICE] = "LimitNICE",
3202 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3203 [RLIMIT_RTTIME] = "LimitRTTIME"
3206 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3208 static const char* const ip_tos_table[] = {
3209 [IPTOS_LOWDELAY] = "low-delay",
3210 [IPTOS_THROUGHPUT] = "throughput",
3211 [IPTOS_RELIABILITY] = "reliability",
3212 [IPTOS_LOWCOST] = "low-cost",
3215 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3217 bool kexec_loaded(void) {
3218 bool loaded = false;
3221 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3229 /// UNNEEDED by elogind
3231 int prot_from_flags(int flags) {
3233 switch (flags & O_ACCMODE) {
3242 return PROT_READ|PROT_WRITE;
3249 char *format_bytes(char *buf, size_t l, off_t t) {
3252 static const struct {
3256 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3257 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3258 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3259 { "G", 1024ULL*1024ULL*1024ULL },
3260 { "M", 1024ULL*1024ULL },
3264 if (t == (off_t) -1)
3267 for (i = 0; i < ELEMENTSOF(table); i++) {
3269 if (t >= table[i].factor) {
3272 (unsigned long long) (t / table[i].factor),
3273 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3280 snprintf(buf, l, "%lluB", (unsigned long long) t);
3288 void* memdup(const void *p, size_t l) {
3301 int fd_inc_sndbuf(int fd, size_t n) {
3303 socklen_t l = sizeof(value);
3305 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3306 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3309 /* If we have the privileges we will ignore the kernel limit. */
3312 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3313 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3319 int fd_inc_rcvbuf(int fd, size_t n) {
3321 socklen_t l = sizeof(value);
3323 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3324 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3327 /* If we have the privileges we will ignore the kernel limit. */
3330 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3331 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3336 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3337 bool stdout_is_tty, stderr_is_tty;
3338 pid_t parent_pid, agent_pid;
3339 sigset_t ss, saved_ss;
3347 /* Spawns a temporary TTY agent, making sure it goes away when
3350 parent_pid = getpid();
3352 /* First we temporarily block all signals, so that the new
3353 * child has them blocked initially. This way, we can be sure
3354 * that SIGTERMs are not lost we might send to the agent. */
3355 assert_se(sigfillset(&ss) >= 0);
3356 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3359 if (agent_pid < 0) {
3360 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3364 if (agent_pid != 0) {
3365 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3372 * Make sure the agent goes away when the parent dies */
3373 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3374 _exit(EXIT_FAILURE);
3376 /* Make sure we actually can kill the agent, if we need to, in
3377 * case somebody invoked us from a shell script that trapped
3378 * SIGTERM or so... */
3379 (void) reset_all_signal_handlers();
3380 (void) reset_signal_mask();
3382 /* Check whether our parent died before we were able
3383 * to set the death signal and unblock the signals */
3384 if (getppid() != parent_pid)
3385 _exit(EXIT_SUCCESS);
3387 /* Don't leak fds to the agent */
3388 close_all_fds(except, n_except);
3390 stdout_is_tty = isatty(STDOUT_FILENO);
3391 stderr_is_tty = isatty(STDERR_FILENO);
3393 if (!stdout_is_tty || !stderr_is_tty) {
3396 /* Detach from stdout/stderr. and reopen
3397 * /dev/tty for them. This is important to
3398 * ensure that when systemctl is started via
3399 * popen() or a similar call that expects to
3400 * read EOF we actually do generate EOF and
3401 * not delay this indefinitely by because we
3402 * keep an unused copy of stdin around. */
3403 fd = open("/dev/tty", O_WRONLY);
3405 log_error_errno(errno, "Failed to open /dev/tty: %m");
3406 _exit(EXIT_FAILURE);
3410 dup2(fd, STDOUT_FILENO);
3413 dup2(fd, STDERR_FILENO);
3419 /* Count arguments */
3421 for (n = 0; va_arg(ap, char*); n++)
3426 l = alloca(sizeof(char *) * (n + 1));
3428 /* Fill in arguments */
3430 for (i = 0; i <= n; i++)
3431 l[i] = va_arg(ap, char*);
3435 _exit(EXIT_FAILURE);
3438 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3439 struct rlimit highest, fixed;
3443 if (setrlimit(resource, rlim) >= 0)
3449 /* So we failed to set the desired setrlimit, then let's try
3450 * to get as close as we can */
3451 assert_se(getrlimit(resource, &highest) == 0);
3453 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3454 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3456 if (setrlimit(resource, &fixed) < 0)
3462 /// UNNEEDED by elogind
3464 bool http_etag_is_valid(const char *etag) {
3468 if (!endswith(etag, "\""))
3471 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3478 bool http_url_is_valid(const char *url) {
3484 p = startswith(url, "http://");
3486 p = startswith(url, "https://");
3493 return ascii_is_valid(p);
3496 bool documentation_url_is_valid(const char *url) {
3502 if (http_url_is_valid(url))
3505 p = startswith(url, "file:/");
3507 p = startswith(url, "info:");
3509 p = startswith(url, "man:");
3514 return ascii_is_valid(p);
3517 bool in_initrd(void) {
3518 static int saved = -1;
3524 /* We make two checks here:
3526 * 1. the flag file /etc/initrd-release must exist
3527 * 2. the root file system must be a memory file system
3529 * The second check is extra paranoia, since misdetecting an
3530 * initrd can have bad bad consequences due the initrd
3531 * emptying when transititioning to the main systemd.
3534 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3535 statfs("/", &s) >= 0 &&
3536 is_temporary_fs(&s);
3541 int get_home_dir(char **_h) {
3549 /* Take the user specified one */
3550 e = secure_getenv("HOME");
3551 if (e && path_is_absolute(e)) {
3560 /* Hardcode home directory for root to avoid NSS */
3563 h = strdup("/root");
3571 /* Check the database... */
3575 return errno > 0 ? -errno : -ESRCH;
3577 if (!path_is_absolute(p->pw_dir))
3580 h = strdup(p->pw_dir);
3588 int get_shell(char **_s) {
3596 /* Take the user specified one */
3597 e = getenv("SHELL");
3607 /* Hardcode home directory for root to avoid NSS */
3610 s = strdup("/bin/sh");
3618 /* Check the database... */
3622 return errno > 0 ? -errno : -ESRCH;
3624 if (!path_is_absolute(p->pw_shell))
3627 s = strdup(p->pw_shell);
3635 bool filename_is_valid(const char *p) {
3649 if (strlen(p) > FILENAME_MAX)
3655 bool string_is_safe(const char *p) {
3661 for (t = p; *t; t++) {
3662 if (*t > 0 && *t < ' ')
3665 if (strchr("\\\"\'\0x7f", *t))
3673 * Check if a string contains control characters. If 'ok' is non-NULL
3674 * it may be a string containing additional CCs to be considered OK.
3676 bool string_has_cc(const char *p, const char *ok) {
3681 for (t = p; *t; t++) {
3682 if (ok && strchr(ok, *t))
3685 if (*t > 0 && *t < ' ')
3695 bool path_is_safe(const char *p) {
3700 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3703 if (strlen(p)+1 > PATH_MAX)
3706 /* The following two checks are not really dangerous, but hey, they still are confusing */
3707 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3710 if (strstr(p, "//"))
3716 /// UNNEEDED by elogind
3718 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3719 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3720 int (*compar) (const void *, const void *, void *), void *arg) {
3729 p = (void *)(((const char *) base) + (idx * size));
3730 comparison = compar(key, p, arg);
3733 else if (comparison > 0)
3741 void init_gettext(void) {
3742 setlocale(LC_ALL, "");
3743 textdomain(GETTEXT_PACKAGE);
3747 bool is_locale_utf8(void) {
3749 static int cached_answer = -1;
3751 if (cached_answer >= 0)
3754 if (!setlocale(LC_ALL, "")) {
3755 cached_answer = true;
3759 set = nl_langinfo(CODESET);
3761 cached_answer = true;
3765 if (streq(set, "UTF-8")) {
3766 cached_answer = true;
3770 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3771 * unset and everything can do to UTF-8 nowadays. */
3772 set = setlocale(LC_CTYPE, NULL);
3774 cached_answer = true;
3778 /* Check result, but ignore the result if C was set
3782 !getenv("LC_ALL") &&
3783 !getenv("LC_CTYPE") &&
3787 return (bool) cached_answer;
3790 const char *draw_special_char(DrawSpecialChar ch) {
3791 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
3794 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
3795 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
3796 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
3797 [DRAW_TREE_SPACE] = " ", /* */
3798 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
3799 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
3800 [DRAW_ARROW] = "\342\206\222", /* → */
3801 [DRAW_DASH] = "\342\200\223", /* – */
3804 /* ASCII fallback */ {
3805 [DRAW_TREE_VERTICAL] = "| ",
3806 [DRAW_TREE_BRANCH] = "|-",
3807 [DRAW_TREE_RIGHT] = "`-",
3808 [DRAW_TREE_SPACE] = " ",
3809 [DRAW_TRIANGULAR_BULLET] = ">",
3810 [DRAW_BLACK_CIRCLE] = "*",
3811 [DRAW_ARROW] = "->",
3816 return draw_table[!is_locale_utf8()][ch];
3819 char *strreplace(const char *text, const char *old_string, const char *new_string) {
3822 size_t l, old_len, new_len;
3828 old_len = strlen(old_string);
3829 new_len = strlen(new_string);
3842 if (!startswith(f, old_string)) {
3848 nl = l - old_len + new_len;
3849 a = realloc(r, nl + 1);
3857 t = stpcpy(t, new_string);
3869 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
3870 const char *i, *begin = NULL;
3875 } state = STATE_OTHER;
3877 size_t osz = 0, isz;
3883 /* Strips ANSI color and replaces TABs by 8 spaces */
3885 isz = _isz ? *_isz : strlen(*ibuf);
3887 f = open_memstream(&obuf, &osz);
3891 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
3896 if (i >= *ibuf + isz) /* EOT */
3898 else if (*i == '\x1B')
3899 state = STATE_ESCAPE;
3900 else if (*i == '\t')
3907 if (i >= *ibuf + isz) { /* EOT */
3910 } else if (*i == '[') {
3911 state = STATE_BRACKET;
3916 state = STATE_OTHER;
3923 if (i >= *ibuf + isz || /* EOT */
3924 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
3927 state = STATE_OTHER;
3929 } else if (*i == 'm')
3930 state = STATE_OTHER;
3952 int on_ac_power(void) {
3953 bool found_offline = false, found_online = false;
3954 _cleanup_closedir_ DIR *d = NULL;
3956 d = opendir("/sys/class/power_supply");
3958 return errno == ENOENT ? true : -errno;
3962 _cleanup_close_ int fd = -1, device = -1;
3968 if (!de && errno != 0)
3974 if (hidden_file(de->d_name))
3977 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
3979 if (errno == ENOENT || errno == ENOTDIR)
3985 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3987 if (errno == ENOENT)
3993 n = read(fd, contents, sizeof(contents));
3997 if (n != 6 || memcmp(contents, "Mains\n", 6))
4001 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4003 if (errno == ENOENT)
4009 n = read(fd, contents, sizeof(contents));
4013 if (n != 2 || contents[1] != '\n')
4016 if (contents[0] == '1') {
4017 found_online = true;
4019 } else if (contents[0] == '0')
4020 found_offline = true;
4025 return found_online || !found_offline;
4028 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4035 if (!path_strv_resolve_uniq(search, root))
4038 STRV_FOREACH(i, search) {
4039 _cleanup_free_ char *p = NULL;
4043 p = strjoin(root, *i, "/", path, NULL);
4045 p = strjoin(*i, "/", path, NULL);
4055 if (errno != ENOENT)
4062 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4063 _cleanup_strv_free_ char **copy = NULL;
4069 if (path_is_absolute(path)) {
4072 f = fopen(path, mode);
4081 copy = strv_copy((char**) search);
4085 return search_and_fopen_internal(path, mode, root, copy, _f);
4088 /// UNNEEDED by elogind
4090 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4091 _cleanup_strv_free_ char **s = NULL;
4093 if (path_is_absolute(path)) {
4096 f = fopen(path, mode);
4105 s = strv_split_nulstr(search);
4109 return search_and_fopen_internal(path, mode, root, s, _f);
4113 char *strextend(char **x, ...) {
4120 l = f = *x ? strlen(*x) : 0;
4127 t = va_arg(ap, const char *);
4132 if (n > ((size_t) -1) - l) {
4141 r = realloc(*x, l+1);
4151 t = va_arg(ap, const char *);
4165 char *strrep(const char *s, unsigned n) {
4173 p = r = malloc(l * n + 1);
4177 for (i = 0; i < n; i++)
4184 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4191 if (*allocated >= need)
4194 newalloc = MAX(need * 2, 64u / size);
4195 a = newalloc * size;
4197 /* check for overflows */
4198 if (a < size * need)
4206 *allocated = newalloc;
4210 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4219 q = greedy_realloc(p, allocated, need, size);
4223 if (*allocated > prev)
4224 memzero(q + prev * size, (*allocated - prev) * size);
4229 bool id128_is_valid(const char *s) {
4235 /* Simple formatted 128bit hex string */
4237 for (i = 0; i < l; i++) {
4240 if (!(c >= '0' && c <= '9') &&
4241 !(c >= 'a' && c <= 'z') &&
4242 !(c >= 'A' && c <= 'Z'))
4246 } else if (l == 36) {
4248 /* Formatted UUID */
4250 for (i = 0; i < l; i++) {
4253 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4257 if (!(c >= '0' && c <= '9') &&
4258 !(c >= 'a' && c <= 'z') &&
4259 !(c >= 'A' && c <= 'Z'))
4270 /// UNNEEDED by elogind
4272 int split_pair(const char *s, const char *sep, char **l, char **r) {
4287 a = strndup(s, x - s);
4291 b = strdup(x + strlen(sep));
4303 int shall_restore_state(void) {
4304 _cleanup_free_ char *value = NULL;
4307 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4313 return parse_boolean(value) != 0;
4317 int proc_cmdline(char **ret) {
4320 if (detect_container(NULL) > 0)
4321 return get_process_cmdline(1, 0, false, ret);
4323 return read_one_line_file("/proc/cmdline", ret);
4326 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4327 _cleanup_free_ char *line = NULL;
4333 r = proc_cmdline(&line);
4339 _cleanup_free_ char *word = NULL;
4342 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4348 /* Filter out arguments that are intended only for the
4350 if (!in_initrd() && startswith(word, "rd."))
4353 value = strchr(word, '=');
4357 r = parse_item(word, value);
4365 int get_proc_cmdline_key(const char *key, char **value) {
4366 _cleanup_free_ char *line = NULL, *ret = NULL;
4373 r = proc_cmdline(&line);
4379 _cleanup_free_ char *word = NULL;
4382 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4388 /* Filter out arguments that are intended only for the
4390 if (!in_initrd() && startswith(word, "rd."))
4394 e = startswith(word, key);
4398 r = free_and_strdup(&ret, e);
4404 if (streq(word, key))
4418 int container_get_leader(const char *machine, pid_t *pid) {
4419 _cleanup_free_ char *s = NULL, *class = NULL;
4427 p = strjoina("/run/systemd/machines/", machine);
4428 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4436 if (!streq_ptr(class, "container"))
4439 r = parse_pid(s, &leader);
4449 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4450 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4458 mntns = procfs_file_alloca(pid, "ns/mnt");
4459 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4467 pidns = procfs_file_alloca(pid, "ns/pid");
4468 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4476 netns = procfs_file_alloca(pid, "ns/net");
4477 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4485 root = procfs_file_alloca(pid, "root");
4486 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4492 *pidns_fd = pidnsfd;
4495 *mntns_fd = mntnsfd;
4498 *netns_fd = netnsfd;
4503 pidnsfd = mntnsfd = netnsfd = -1;
4508 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4511 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4515 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4519 if (setns(netns_fd, CLONE_NEWNET) < 0)
4523 if (fchdir(root_fd) < 0)
4526 if (chroot(".") < 0)
4530 return reset_uid_gid();
4533 int getpeercred(int fd, struct ucred *ucred) {
4534 socklen_t n = sizeof(struct ucred);
4541 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4545 if (n != sizeof(struct ucred))
4548 /* Check if the data is actually useful and not suppressed due
4549 * to namespacing issues */
4552 if (u.uid == UID_INVALID)
4554 if (u.gid == GID_INVALID)
4561 int getpeersec(int fd, char **ret) {
4573 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4577 if (errno != ERANGE)
4584 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4600 /* This is much like like mkostemp() but is subject to umask(). */
4601 int mkostemp_safe(char *pattern, int flags) {
4602 _cleanup_umask_ mode_t u;
4609 fd = mkostemp(pattern, flags);
4616 int open_tmpfile(const char *path, int flags) {
4623 /* Try O_TMPFILE first, if it is supported */
4624 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4629 /* Fall back to unguessable name + unlinking */
4630 p = strjoina(path, "/systemd-tmp-XXXXXX");
4632 fd = mkostemp_safe(p, flags);
4640 int fd_warn_permissions(const char *path, int fd) {
4643 if (fstat(fd, &st) < 0)
4646 if (st.st_mode & 0111)
4647 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4649 if (st.st_mode & 0002)
4650 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4652 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4653 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);
4658 /// UNNEEDED by elogind
4660 unsigned long personality_from_string(const char *p) {
4662 /* Parse a personality specifier. We introduce our own
4663 * identifiers that indicate specific ABIs, rather than just
4664 * hints regarding the register size, since we want to keep
4665 * things open for multiple locally supported ABIs for the
4666 * same register size. We try to reuse the ABI identifiers
4667 * used by libseccomp. */
4669 #if defined(__x86_64__)
4671 if (streq(p, "x86"))
4674 if (streq(p, "x86-64"))
4677 #elif defined(__i386__)
4679 if (streq(p, "x86"))
4683 return PERSONALITY_INVALID;
4687 const char* personality_to_string(unsigned long p) {
4689 #if defined(__x86_64__)
4691 if (p == PER_LINUX32)
4697 #elif defined(__i386__)
4706 uint64_t physical_memory(void) {
4709 /* We return this as uint64_t in case we are running as 32bit
4710 * process on a 64bit kernel with huge amounts of memory */
4712 mem = sysconf(_SC_PHYS_PAGES);
4715 return (uint64_t) mem * (uint64_t) page_size();
4718 /// UNNEEDED by elogind
4720 void hexdump(FILE *f, const void *p, size_t s) {
4721 const uint8_t *b = p;
4724 assert(s == 0 || b);
4729 fprintf(f, "%04x ", n);
4731 for (i = 0; i < 16; i++) {
4736 fprintf(f, "%02x ", b[i]);
4744 for (i = 0; i < 16; i++) {
4749 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4764 int update_reboot_param_file(const char *param) {
4769 r = write_string_file(REBOOT_PARAM_FILE, param, WRITE_STRING_FILE_CREATE);
4771 log_error("Failed to write reboot param to "
4772 REBOOT_PARAM_FILE": %s", strerror(-r));
4774 unlink(REBOOT_PARAM_FILE);
4779 int umount_recursive(const char *prefix, int flags) {
4783 /* Try to umount everything recursively below a
4784 * directory. Also, take care of stacked mounts, and keep
4785 * unmounting them until they are gone. */
4788 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4793 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4794 if (!proc_self_mountinfo)
4798 _cleanup_free_ char *path = NULL, *p = NULL;
4801 k = fscanf(proc_self_mountinfo,
4802 "%*s " /* (1) mount id */
4803 "%*s " /* (2) parent id */
4804 "%*s " /* (3) major:minor */
4805 "%*s " /* (4) root */
4806 "%ms " /* (5) mount point */
4807 "%*s" /* (6) mount options */
4808 "%*[^-]" /* (7) optional fields */
4809 "- " /* (8) separator */
4810 "%*s " /* (9) file system type */
4811 "%*s" /* (10) mount source */
4812 "%*s" /* (11) mount options 2 */
4813 "%*[^\n]", /* some rubbish at the end */
4822 r = cunescape(path, UNESCAPE_RELAX, &p);
4826 if (!path_startswith(p, prefix))
4829 if (umount2(p, flags) < 0) {
4845 static int get_mount_flags(const char *path, unsigned long *flags) {
4848 if (statvfs(path, &buf) < 0)
4850 *flags = buf.f_flag;
4854 int bind_remount_recursive(const char *prefix, bool ro) {
4855 _cleanup_set_free_free_ Set *done = NULL;
4856 _cleanup_free_ char *cleaned = NULL;
4859 /* Recursively remount a directory (and all its submounts)
4860 * read-only or read-write. If the directory is already
4861 * mounted, we reuse the mount and simply mark it
4862 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4863 * operation). If it isn't we first make it one. Afterwards we
4864 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4865 * submounts we can access, too. When mounts are stacked on
4866 * the same mount point we only care for each individual
4867 * "top-level" mount on each point, as we cannot
4868 * influence/access the underlying mounts anyway. We do not
4869 * have any effect on future submounts that might get
4870 * propagated, they migt be writable. This includes future
4871 * submounts that have been triggered via autofs. */
4873 cleaned = strdup(prefix);
4877 path_kill_slashes(cleaned);
4879 done = set_new(&string_hash_ops);
4884 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4885 _cleanup_set_free_free_ Set *todo = NULL;
4886 bool top_autofs = false;
4888 unsigned long orig_flags;
4890 todo = set_new(&string_hash_ops);
4894 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4895 if (!proc_self_mountinfo)
4899 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
4902 k = fscanf(proc_self_mountinfo,
4903 "%*s " /* (1) mount id */
4904 "%*s " /* (2) parent id */
4905 "%*s " /* (3) major:minor */
4906 "%*s " /* (4) root */
4907 "%ms " /* (5) mount point */
4908 "%*s" /* (6) mount options (superblock) */
4909 "%*[^-]" /* (7) optional fields */
4910 "- " /* (8) separator */
4911 "%ms " /* (9) file system type */
4912 "%*s" /* (10) mount source */
4913 "%*s" /* (11) mount options (bind mount) */
4914 "%*[^\n]", /* some rubbish at the end */
4924 r = cunescape(path, UNESCAPE_RELAX, &p);
4928 /* Let's ignore autofs mounts. If they aren't
4929 * triggered yet, we want to avoid triggering
4930 * them, as we don't make any guarantees for
4931 * future submounts anyway. If they are
4932 * already triggered, then we will find
4933 * another entry for this. */
4934 if (streq(type, "autofs")) {
4935 top_autofs = top_autofs || path_equal(cleaned, p);
4939 if (path_startswith(p, cleaned) &&
4940 !set_contains(done, p)) {
4942 r = set_consume(todo, p);
4952 /* If we have no submounts to process anymore and if
4953 * the root is either already done, or an autofs, we
4955 if (set_isempty(todo) &&
4956 (top_autofs || set_contains(done, cleaned)))
4959 if (!set_contains(done, cleaned) &&
4960 !set_contains(todo, cleaned)) {
4961 /* The prefix directory itself is not yet a
4962 * mount, make it one. */
4963 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
4967 (void) get_mount_flags(cleaned, &orig_flags);
4968 orig_flags &= ~MS_RDONLY;
4970 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
4973 x = strdup(cleaned);
4977 r = set_consume(done, x);
4982 while ((x = set_steal_first(todo))) {
4984 r = set_consume(done, x);
4985 if (r == -EEXIST || r == 0)
4990 /* Try to reuse the original flag set, but
4991 * don't care for errors, in case of
4992 * obstructed mounts */
4994 (void) get_mount_flags(x, &orig_flags);
4995 orig_flags &= ~MS_RDONLY;
4997 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
4999 /* Deal with mount points that are
5000 * obstructed by a later mount */
5002 if (errno != ENOENT)
5010 int fflush_and_check(FILE *f) {
5017 return errno ? -errno : -EIO;
5022 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
5034 * /foo/bar/.#<extra>waldoXXXXXX
5038 if (!filename_is_valid(fn))
5044 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
5048 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
5050 *ret = path_kill_slashes(t);
5054 int tempfn_random(const char *p, const char *extra, char **ret) {
5068 * /foo/bar/.#<extra>waldobaa2a261115984a9
5072 if (!filename_is_valid(fn))
5078 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
5082 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
5085 for (i = 0; i < 16; i++) {
5086 *(x++) = hexchar(u & 0xF);
5092 *ret = path_kill_slashes(t);
5096 /// UNNEEDED by elogind
5098 int tempfn_random_child(const char *p, const char *extra, char **ret) {
5109 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5115 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
5119 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
5122 for (i = 0; i < 16; i++) {
5123 *(x++) = hexchar(u & 0xF);
5129 *ret = path_kill_slashes(t);
5133 int take_password_lock(const char *root) {
5135 struct flock flock = {
5137 .l_whence = SEEK_SET,
5145 /* This is roughly the same as lckpwdf(), but not as awful. We
5146 * don't want to use alarm() and signals, hence we implement
5147 * our own trivial version of this.
5149 * Note that shadow-utils also takes per-database locks in
5150 * addition to lckpwdf(). However, we don't given that they
5151 * are redundant as they they invoke lckpwdf() first and keep
5152 * it during everything they do. The per-database locks are
5153 * awfully racy, and thus we just won't do them. */
5156 path = strjoina(root, "/etc/.pwd.lock");
5158 path = "/etc/.pwd.lock";
5160 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5164 r = fcntl(fd, F_SETLKW, &flock);
5174 int is_symlink(const char *path) {
5177 if (lstat(path, &info) < 0)
5180 return !!S_ISLNK(info.st_mode);
5183 int is_dir(const char* path, bool follow) {
5188 r = stat(path, &st);
5190 r = lstat(path, &st);
5194 return !!S_ISDIR(st.st_mode);
5197 /// UNNEEDED by elogind
5199 int is_device_node(const char *path) {
5202 if (lstat(path, &info) < 0)
5205 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5209 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5210 _cleanup_free_ char *s = NULL;
5211 size_t allocated = 0, sz = 0;
5219 SINGLE_QUOTE_ESCAPE,
5221 DOUBLE_QUOTE_ESCAPE,
5229 /* Parses the first word of a string, and returns it in
5230 * *ret. Removes all quotes in the process. When parsing fails
5231 * (because of an uneven number of quotes or similar), leaves
5232 * the pointer *p at the first invalid character. */
5242 else if (strchr(WHITESPACE, c))
5252 state = SINGLE_QUOTE;
5254 state = VALUE_ESCAPE;
5256 state = DOUBLE_QUOTE;
5257 else if (strchr(WHITESPACE, c))
5260 if (!GREEDY_REALLOC(s, allocated, sz+2))
5270 if (flags & UNQUOTE_RELAX)
5273 } else if (c == '\'')
5276 state = SINGLE_QUOTE_ESCAPE;
5278 if (!GREEDY_REALLOC(s, allocated, sz+2))
5292 state = DOUBLE_QUOTE_ESCAPE;
5294 if (!GREEDY_REALLOC(s, allocated, sz+2))
5302 case SINGLE_QUOTE_ESCAPE:
5303 case DOUBLE_QUOTE_ESCAPE:
5305 if (!GREEDY_REALLOC(s, allocated, sz+7))
5309 if ((flags & UNQUOTE_CUNESCAPE_RELAX) &&
5310 (state == VALUE_ESCAPE || flags & UNQUOTE_RELAX)) {
5311 /* If we find an unquoted trailing backslash and we're in
5312 * UNQUOTE_CUNESCAPE_RELAX mode, keep it verbatim in the
5315 * Unbalanced quotes will only be allowed in UNQUOTE_RELAX
5316 * mode, UNQUOTE_CUNESCAP_RELAX mode does not allow them.
5321 if (flags & UNQUOTE_RELAX)
5326 if (flags & UNQUOTE_CUNESCAPE) {
5329 r = cunescape_one(*p, (size_t) -1, &c, &u);
5331 if (flags & UNQUOTE_CUNESCAPE_RELAX) {
5342 s[sz++] = c; /* normal explicit char */
5344 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5349 state = (state == SINGLE_QUOTE_ESCAPE) ? SINGLE_QUOTE :
5350 (state == DOUBLE_QUOTE_ESCAPE) ? DOUBLE_QUOTE :
5357 if (!strchr(WHITESPACE, c))
5379 int unquote_first_word_and_warn(
5384 const char *filename,
5386 const char *rvalue) {
5387 /* Try to unquote it, if it fails, warn about it and try again but this
5388 * time using UNQUOTE_CUNESCAPE_RELAX to keep the backslashes verbatim
5389 * in invalid escape sequences. */
5394 r = unquote_first_word(p, ret, flags);
5395 if (r < 0 && !(flags&UNQUOTE_CUNESCAPE_RELAX)) {
5396 /* Retry it with UNQUOTE_CUNESCAPE_RELAX. */
5398 r = unquote_first_word(p, ret, flags|UNQUOTE_CUNESCAPE_RELAX);
5400 log_syntax(unit, LOG_ERR, filename, line, EINVAL,
5401 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue);
5403 log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
5404 "Invalid escape sequences in command line: \"%s\"", rvalue);
5409 /// UNNEEDED by elogind
5411 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5416 /* Parses a number of words from a string, stripping any
5417 * quotes if necessary. */
5421 /* Count how many words are expected */
5422 va_start(ap, flags);
5424 if (!va_arg(ap, char **))
5433 /* Read all words into a temporary array */
5434 l = newa0(char*, n);
5435 for (c = 0; c < n; c++) {
5437 r = unquote_first_word(p, &l[c], flags);
5441 for (j = 0; j < c; j++)
5451 /* If we managed to parse all words, return them in the passed
5453 va_start(ap, flags);
5454 for (i = 0; i < n; i++) {
5457 v = va_arg(ap, char **);
5468 int free_and_strdup(char **p, const char *s) {
5473 /* Replaces a string pointer with an strdup()ed new string,
5474 * possibly freeing the old one. */
5476 if (streq_ptr(*p, s))
5492 int ptsname_malloc(int fd, char **ret) {
5505 if (ptsname_r(fd, c, l) == 0) {
5509 if (errno != ERANGE) {
5519 /// UNNEEDED by elogind
5521 int openpt_in_namespace(pid_t pid, int flags) {
5522 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5523 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5525 struct cmsghdr cmsghdr;
5526 uint8_t buf[CMSG_SPACE(sizeof(int))];
5528 struct msghdr mh = {
5529 .msg_control = &control,
5530 .msg_controllen = sizeof(control),
5532 struct cmsghdr *cmsg;
5539 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5543 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5553 pair[0] = safe_close(pair[0]);
5555 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5557 _exit(EXIT_FAILURE);
5559 master = posix_openpt(flags);
5561 _exit(EXIT_FAILURE);
5563 cmsg = CMSG_FIRSTHDR(&mh);
5564 cmsg->cmsg_level = SOL_SOCKET;
5565 cmsg->cmsg_type = SCM_RIGHTS;
5566 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5567 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5569 mh.msg_controllen = cmsg->cmsg_len;
5571 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5572 _exit(EXIT_FAILURE);
5574 _exit(EXIT_SUCCESS);
5577 pair[1] = safe_close(pair[1]);
5579 r = wait_for_terminate(child, &si);
5582 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5585 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5588 CMSG_FOREACH(cmsg, &mh)
5589 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5593 fds = (int*) CMSG_DATA(cmsg);
5594 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5597 close_many(fds, n_fds);
5608 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5609 _cleanup_close_ int fd = -1;
5612 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5614 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5618 l = fgetxattr(fd, attribute, value, size);
5625 static int parse_crtime(le64_t le, usec_t *usec) {
5631 if (u == 0 || u == (uint64_t) -1)
5638 int fd_getcrtime(int fd, usec_t *usec) {
5645 /* Until Linux gets a real concept of birthtime/creation time,
5646 * let's fake one with xattrs */
5648 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5651 if (n != sizeof(le))
5654 return parse_crtime(le, usec);
5657 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5661 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5664 if (n != sizeof(le))
5667 return parse_crtime(le, usec);
5670 /// UNNEEDED by elogind
5672 int path_getcrtime(const char *p, usec_t *usec) {
5679 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5682 if (n != sizeof(le))
5685 return parse_crtime(le, usec);
5689 int fd_setcrtime(int fd, usec_t usec) {
5695 usec = now(CLOCK_REALTIME);
5697 le = htole64((uint64_t) usec);
5698 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5704 int same_fd(int a, int b) {
5705 struct stat sta, stb;
5712 /* Compares two file descriptors. Note that semantics are
5713 * quite different depending on whether we have kcmp() or we
5714 * don't. If we have kcmp() this will only return true for
5715 * dup()ed file descriptors, but not otherwise. If we don't
5716 * have kcmp() this will also return true for two fds of the same
5717 * file, created by separate open() calls. Since we use this
5718 * call mostly for filtering out duplicates in the fd store
5719 * this difference hopefully doesn't matter too much. */
5724 /* Try to use kcmp() if we have it. */
5726 r = kcmp(pid, pid, KCMP_FILE, a, b);
5731 if (errno != ENOSYS)
5734 /* We don't have kcmp(), use fstat() instead. */
5735 if (fstat(a, &sta) < 0)
5738 if (fstat(b, &stb) < 0)
5741 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
5744 /* We consider all device fds different, since two device fds
5745 * might refer to quite different device contexts even though
5746 * they share the same inode and backing dev_t. */
5748 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
5751 if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
5754 /* The fds refer to the same inode on disk, let's also check
5755 * if they have the same fd flags. This is useful to
5756 * distinguish the read and write side of a pipe created with
5758 fa = fcntl(a, F_GETFL);
5762 fb = fcntl(b, F_GETFL);
5769 int chattr_fd(int fd, unsigned value, unsigned mask) {
5770 unsigned old_attr, new_attr;
5775 if (fstat(fd, &st) < 0)
5778 /* Explicitly check whether this is a regular file or
5779 * directory. If it is anything else (such as a device node or
5780 * fifo), then the ioctl will not hit the file systems but
5781 * possibly drivers, where the ioctl might have different
5782 * effects. Notably, DRM is using the same ioctl() number. */
5784 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5790 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5793 new_attr = (old_attr & ~mask) | (value & mask);
5794 if (new_attr == old_attr)
5797 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5803 int chattr_path(const char *p, unsigned value, unsigned mask) {
5804 _cleanup_close_ int fd = -1;
5811 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5815 return chattr_fd(fd, value, mask);
5818 int read_attr_fd(int fd, unsigned *ret) {
5823 if (fstat(fd, &st) < 0)
5826 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5829 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5835 int read_attr_path(const char *p, unsigned *ret) {
5836 _cleanup_close_ int fd = -1;
5841 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5845 return read_attr_fd(fd, ret);
5848 /// UNNEEDED by elogind
5850 static size_t nul_length(const uint8_t *p, size_t sz) {
5865 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
5866 const uint8_t *q, *w, *e;
5874 n = nul_length(q, e - q);
5876 /* If there are more than the specified run length of
5877 * NUL bytes, or if this is the beginning or the end
5878 * of the buffer, then seek instead of write */
5879 if ((n > run_length) ||
5880 (n > 0 && q == p) ||
5881 (n > 0 && q + n >= e)) {
5883 l = write(fd, w, q - w);
5890 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
5902 l = write(fd, w, q - w);
5909 return q - (const uint8_t*) p;
5913 void sigkill_wait(pid_t *pid) {
5919 if (kill(*pid, SIGKILL) > 0)
5920 (void) wait_for_terminate(*pid, NULL);
5923 /// UNNEEDED by elogind
5925 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
5926 int a = 0, b = 0, c = 0;
5936 if (!strchr(*p, '>'))
5939 if ((*p)[2] == '>') {
5940 c = undecchar((*p)[1]);
5942 } else if ((*p)[3] == '>') {
5943 b = undecchar((*p)[1]);
5944 c = undecchar((*p)[2]);
5946 } else if ((*p)[4] == '>') {
5947 a = undecchar((*p)[1]);
5948 b = undecchar((*p)[2]);
5949 c = undecchar((*p)[3]);
5954 if (a < 0 || b < 0 || c < 0 ||
5955 (!with_facility && (a || b || c > 7)))
5959 *priority = a*100 + b*10 + c;
5961 *priority = (*priority & LOG_FACMASK) | c;
5968 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
5974 for (i = 0; i < len; ++i)
5975 if (streq_ptr(table[i], key))
5981 void cmsg_close_all(struct msghdr *mh) {
5982 struct cmsghdr *cmsg;
5986 CMSG_FOREACH(cmsg, mh)
5987 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
5988 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
5991 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
5995 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
5999 /* Even though renameat2() exists since Linux 3.15, btrfs added
6000 * support for it later. If it is not implemented, fallback to another
6002 if (errno != EINVAL)
6005 /* The link()/unlink() fallback does not work on directories. But
6006 * renameat() without RENAME_NOREPLACE gives the same semantics on
6007 * directories, except when newpath is an *empty* directory. This is
6009 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6010 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6011 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6012 return ret >= 0 ? 0 : -errno;
6015 /* If it is not a directory, use the link()/unlink() fallback. */
6016 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6020 ret = unlinkat(olddirfd, oldpath, 0);
6022 /* backup errno before the following unlinkat() alters it */
6024 (void) unlinkat(newdirfd, newpath, 0);
6032 char *shell_maybe_quote(const char *s) {
6038 /* Encloses a string in double quotes if necessary to make it
6039 * OK as shell string. */
6041 for (p = s; *p; p++)
6044 strchr(SHELL_NEED_QUOTES, *p))
6050 r = new(char, 1+strlen(s)*2+1+1);
6056 t = mempcpy(t, s, p - s);
6060 if (strchr(SHELL_NEED_ESCAPE, *p))
6072 int parse_mode(const char *s, mode_t *ret) {
6080 l = strtol(s, &x, 8);
6084 if (!x || x == s || *x)
6086 if (l < 0 || l > 07777)
6093 int mount_move_root(const char *path) {
6096 if (chdir(path) < 0)
6099 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
6102 if (chroot(".") < 0)
6111 int reset_uid_gid(void) {
6113 if (setgroups(0, NULL) < 0)
6116 if (setresgid(0, 0, 0) < 0)
6119 if (setresuid(0, 0, 0) < 0)