1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
41 #include <sys/prctl.h>
42 #include <sys/utsname.h>
44 #include <netinet/ip.h>
51 #include <sys/mount.h>
52 #include <linux/magic.h>
56 #include <sys/personality.h>
57 #include <sys/xattr.h>
58 #include <sys/statvfs.h>
62 /* When we include libgen.h because we need dirname() we immediately
63 * undefine basename() since libgen.h defines it as a macro to the XDG
64 * version which is really broken. */
68 #ifdef HAVE_SYS_AUXV_H
80 #include "path-util.h"
81 #include "exit-status.h"
85 #include "device-nodes.h"
90 #include "sparse-endian.h"
91 #include "formats-util.h"
92 #include "process-util.h"
93 #include "random-util.h"
94 #include "terminal-util.h"
95 #include "hostname-util.h"
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* first_word(const char *s, const char *word) {
159 /* Checks if the string starts with the specified word, either
160 * followed by NUL or by whitespace. Returns a pointer to the
161 * NUL or the first character after the whitespace. */
172 if (memcmp(s, word, wl) != 0)
179 if (!strchr(WHITESPACE, *p))
182 p += strspn(p, WHITESPACE);
186 size_t cescape_char(char c, char *buf) {
187 char * buf_old = buf;
233 /* For special chars we prefer octal over
234 * hexadecimal encoding, simply because glib's
235 * g_strescape() does the same */
236 if ((c < ' ') || (c >= 127)) {
238 *(buf++) = octchar((unsigned char) c >> 6);
239 *(buf++) = octchar((unsigned char) c >> 3);
240 *(buf++) = octchar((unsigned char) c);
246 return buf - buf_old;
249 int close_nointr(int fd) {
256 * Just ignore EINTR; a retry loop is the wrong thing to do on
259 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
260 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
261 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
262 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
270 int safe_close(int fd) {
273 * Like close_nointr() but cannot fail. Guarantees errno is
274 * unchanged. Is a NOP with negative fds passed, and returns
275 * -1, so that it can be used in this syntax:
277 * fd = safe_close(fd);
283 /* The kernel might return pretty much any error code
284 * via close(), but the fd will be closed anyway. The
285 * only condition we want to check for here is whether
286 * the fd was invalid at all... */
288 assert_se(close_nointr(fd) != -EBADF);
294 void close_many(const int fds[], unsigned n_fd) {
297 assert(fds || n_fd <= 0);
299 for (i = 0; i < n_fd; i++)
303 int unlink_noerrno(const char *path) {
314 int parse_boolean(const char *v) {
317 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
319 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
325 int parse_pid(const char *s, pid_t* ret_pid) {
326 unsigned long ul = 0;
333 r = safe_atolu(s, &ul);
339 if ((unsigned long) pid != ul)
349 int parse_uid(const char *s, uid_t* ret_uid) {
350 unsigned long ul = 0;
356 r = safe_atolu(s, &ul);
362 if ((unsigned long) uid != ul)
365 /* Some libc APIs use UID_INVALID as special placeholder */
366 if (uid == (uid_t) 0xFFFFFFFF)
369 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
370 if (uid == (uid_t) 0xFFFF)
379 int safe_atou(const char *s, unsigned *ret_u) {
387 l = strtoul(s, &x, 0);
389 if (!x || x == s || *x || errno)
390 return errno > 0 ? -errno : -EINVAL;
392 if ((unsigned long) (unsigned) l != l)
395 *ret_u = (unsigned) l;
399 int safe_atoi(const char *s, int *ret_i) {
407 l = strtol(s, &x, 0);
409 if (!x || x == s || *x || errno)
410 return errno > 0 ? -errno : -EINVAL;
412 if ((long) (int) l != l)
419 int safe_atou8(const char *s, uint8_t *ret) {
427 l = strtoul(s, &x, 0);
429 if (!x || x == s || *x || errno)
430 return errno > 0 ? -errno : -EINVAL;
432 if ((unsigned long) (uint8_t) l != l)
439 int safe_atou16(const char *s, uint16_t *ret) {
447 l = strtoul(s, &x, 0);
449 if (!x || x == s || *x || errno)
450 return errno > 0 ? -errno : -EINVAL;
452 if ((unsigned long) (uint16_t) l != l)
459 int safe_atoi16(const char *s, int16_t *ret) {
467 l = strtol(s, &x, 0);
469 if (!x || x == s || *x || errno)
470 return errno > 0 ? -errno : -EINVAL;
472 if ((long) (int16_t) l != l)
479 int safe_atollu(const char *s, long long unsigned *ret_llu) {
481 unsigned long long l;
487 l = strtoull(s, &x, 0);
489 if (!x || x == s || *x || errno)
490 return errno ? -errno : -EINVAL;
496 int safe_atolli(const char *s, long long int *ret_lli) {
504 l = strtoll(s, &x, 0);
506 if (!x || x == s || *x || errno)
507 return errno ? -errno : -EINVAL;
513 int safe_atod(const char *s, double *ret_d) {
521 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
522 if (loc == (locale_t) 0)
526 d = strtod_l(s, &x, loc);
528 if (!x || x == s || *x || errno) {
530 return errno ? -errno : -EINVAL;
538 static size_t strcspn_escaped(const char *s, const char *reject) {
539 bool escaped = false;
542 for (n=0; s[n]; n++) {
545 else if (s[n] == '\\')
547 else if (strchr(reject, s[n]))
551 /* if s ends in \, return index of previous char */
555 /* Split a string into words. */
556 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
562 assert(**state == '\0');
566 current += strspn(current, separator);
572 if (quoted && strchr("\'\"", *current)) {
573 char quotechars[2] = {*current, '\0'};
575 *l = strcspn_escaped(current + 1, quotechars);
576 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
577 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
578 /* right quote missing or garbage at the end */
582 *state = current++ + *l + 2;
584 *l = strcspn_escaped(current, separator);
585 if (current[*l] && !strchr(separator, current[*l])) {
586 /* unfinished escape */
590 *state = current + *l;
592 *l = strcspn(current, separator);
593 *state = current + *l;
599 int fchmod_umask(int fd, mode_t m) {
604 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
610 char *truncate_nl(char *s) {
613 s[strcspn(s, NEWLINE)] = 0;
617 char *strnappend(const char *s, const char *suffix, size_t b) {
625 return strndup(suffix, b);
634 if (b > ((size_t) -1) - a)
637 r = new(char, a+b+1);
642 memcpy(r+a, suffix, b);
648 char *strappend(const char *s, const char *suffix) {
649 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
652 int readlinkat_malloc(int fd, const char *p, char **ret) {
667 n = readlinkat(fd, p, c, l-1);
674 if ((size_t) n < l-1) {
685 int readlink_malloc(const char *p, char **ret) {
686 return readlinkat_malloc(AT_FDCWD, p, ret);
689 int readlink_value(const char *p, char **ret) {
690 _cleanup_free_ char *link = NULL;
694 r = readlink_malloc(p, &link);
698 value = basename(link);
702 value = strdup(value);
711 int readlink_and_make_absolute(const char *p, char **r) {
712 _cleanup_free_ char *target = NULL;
719 j = readlink_malloc(p, &target);
723 k = file_in_same_dir(p, target);
731 int readlink_and_canonicalize(const char *p, char **r) {
738 j = readlink_and_make_absolute(p, &t);
742 s = canonicalize_file_name(t);
749 path_kill_slashes(*r);
754 char *strstrip(char *s) {
757 /* Drops trailing whitespace. Modifies the string in
758 * place. Returns pointer to first non-space character */
760 s += strspn(s, WHITESPACE);
762 for (e = strchr(s, 0); e > s; e --)
763 if (!strchr(WHITESPACE, e[-1]))
771 char *delete_chars(char *s, const char *bad) {
774 /* Drops all whitespace, regardless where in the string */
776 for (f = s, t = s; *f; f++) {
788 char *file_in_same_dir(const char *path, const char *filename) {
795 /* This removes the last component of path and appends
796 * filename, unless the latter is absolute anyway or the
799 if (path_is_absolute(filename))
800 return strdup(filename);
802 e = strrchr(path, '/');
804 return strdup(filename);
806 k = strlen(filename);
807 ret = new(char, (e + 1 - path) + k + 1);
811 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
815 int rmdir_parents(const char *path, const char *stop) {
824 /* Skip trailing slashes */
825 while (l > 0 && path[l-1] == '/')
831 /* Skip last component */
832 while (l > 0 && path[l-1] != '/')
835 /* Skip trailing slashes */
836 while (l > 0 && path[l-1] == '/')
842 if (!(t = strndup(path, l)))
845 if (path_startswith(stop, t)) {
861 char hexchar(int x) {
862 static const char table[16] = "0123456789abcdef";
864 return table[x & 15];
867 int unhexchar(char c) {
869 if (c >= '0' && c <= '9')
872 if (c >= 'a' && c <= 'f')
875 if (c >= 'A' && c <= 'F')
881 char *hexmem(const void *p, size_t l) {
885 z = r = malloc(l * 2 + 1);
889 for (x = p; x < (const uint8_t*) p + l; x++) {
890 *(z++) = hexchar(*x >> 4);
891 *(z++) = hexchar(*x & 15);
898 void *unhexmem(const char *p, size_t l) {
904 z = r = malloc((l + 1) / 2 + 1);
908 for (x = p; x < p + l; x += 2) {
917 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
924 char octchar(int x) {
925 return '0' + (x & 7);
928 int unoctchar(char c) {
930 if (c >= '0' && c <= '7')
936 char decchar(int x) {
937 return '0' + (x % 10);
940 int undecchar(char c) {
942 if (c >= '0' && c <= '9')
948 char *cescape(const char *s) {
954 /* Does C style string escaping. May be reversed with
957 r = new(char, strlen(s)*4 + 1);
961 for (f = s, t = r; *f; f++)
962 t += cescape_char(*f, t);
969 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
976 /* Unescapes C style. Returns the unescaped character in ret,
977 * unless we encountered a \u sequence in which case the full
978 * unicode character is returned in ret_unicode, instead. */
980 if (length != (size_t) -1 && length < 1)
1017 /* This is an extension of the XDG syntax files */
1022 /* hexadecimal encoding */
1025 if (length != (size_t) -1 && length < 3)
1028 a = unhexchar(p[1]);
1032 b = unhexchar(p[2]);
1036 /* Don't allow NUL bytes */
1037 if (a == 0 && b == 0)
1040 *ret = (char) ((a << 4U) | b);
1046 /* C++11 style 16bit unicode */
1052 if (length != (size_t) -1 && length < 5)
1055 for (i = 0; i < 4; i++) {
1056 a[i] = unhexchar(p[1 + i]);
1061 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1063 /* Don't allow 0 chars */
1082 /* C++11 style 32bit unicode */
1088 if (length != (size_t) -1 && length < 9)
1091 for (i = 0; i < 8; i++) {
1092 a[i] = unhexchar(p[1 + i]);
1097 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1098 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1100 /* Don't allow 0 chars */
1104 /* Don't allow invalid code points */
1105 if (!unichar_is_valid(c))
1130 /* octal encoding */
1134 if (length != (size_t) -1 && length < 4)
1137 a = unoctchar(p[0]);
1141 b = unoctchar(p[1]);
1145 c = unoctchar(p[2]);
1149 /* don't allow NUL bytes */
1150 if (a == 0 && b == 0 && c == 0)
1153 /* Don't allow bytes above 255 */
1154 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1170 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1178 /* Undoes C style string escaping, and optionally prefixes it. */
1180 pl = prefix ? strlen(prefix) : 0;
1182 r = new(char, pl+length+1);
1187 memcpy(r, prefix, pl);
1189 for (f = s, t = r + pl; f < s + length; f++) {
1195 remaining = s + length - f;
1196 assert(remaining > 0);
1199 /* A literal literal, copy verbatim */
1204 if (remaining == 1) {
1205 if (flags & UNESCAPE_RELAX) {
1206 /* A trailing backslash, copy verbatim */
1215 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1217 if (flags & UNESCAPE_RELAX) {
1218 /* Invalid escape code, let's take it literal then */
1228 /* Non-Unicode? Let's encode this directly */
1231 /* Unicode? Then let's encode this in UTF-8 */
1232 t += utf8_encode_unichar(t, u);
1243 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1244 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1247 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1248 return cunescape_length(s, strlen(s), flags, ret);
1251 char *xescape(const char *s, const char *bad) {
1255 /* Escapes all chars in bad, in addition to \ and all special
1256 * chars, in \xFF style escaping. May be reversed with
1259 r = new(char, strlen(s) * 4 + 1);
1263 for (f = s, t = r; *f; f++) {
1265 if ((*f < ' ') || (*f >= 127) ||
1266 (*f == '\\') || strchr(bad, *f)) {
1269 *(t++) = hexchar(*f >> 4);
1270 *(t++) = hexchar(*f);
1280 char *ascii_strlower(char *t) {
1285 for (p = t; *p; p++)
1286 if (*p >= 'A' && *p <= 'Z')
1287 *p = *p - 'A' + 'a';
1292 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1296 filename[0] == '.' ||
1297 streq(filename, "lost+found") ||
1298 streq(filename, "aquota.user") ||
1299 streq(filename, "aquota.group") ||
1300 endswith(filename, ".rpmnew") ||
1301 endswith(filename, ".rpmsave") ||
1302 endswith(filename, ".rpmorig") ||
1303 endswith(filename, ".dpkg-old") ||
1304 endswith(filename, ".dpkg-new") ||
1305 endswith(filename, ".dpkg-tmp") ||
1306 endswith(filename, ".dpkg-dist") ||
1307 endswith(filename, ".dpkg-bak") ||
1308 endswith(filename, ".dpkg-backup") ||
1309 endswith(filename, ".dpkg-remove") ||
1310 endswith(filename, ".swp");
1313 bool hidden_file(const char *filename) {
1316 if (endswith(filename, "~"))
1319 return hidden_file_allow_backup(filename);
1322 int fd_nonblock(int fd, bool nonblock) {
1327 flags = fcntl(fd, F_GETFL, 0);
1332 nflags = flags | O_NONBLOCK;
1334 nflags = flags & ~O_NONBLOCK;
1336 if (nflags == flags)
1339 if (fcntl(fd, F_SETFL, nflags) < 0)
1345 int fd_cloexec(int fd, bool cloexec) {
1350 flags = fcntl(fd, F_GETFD, 0);
1355 nflags = flags | FD_CLOEXEC;
1357 nflags = flags & ~FD_CLOEXEC;
1359 if (nflags == flags)
1362 if (fcntl(fd, F_SETFD, nflags) < 0)
1368 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1371 assert(n_fdset == 0 || fdset);
1373 for (i = 0; i < n_fdset; i++)
1380 int close_all_fds(const int except[], unsigned n_except) {
1381 _cleanup_closedir_ DIR *d = NULL;
1385 assert(n_except == 0 || except);
1387 d = opendir("/proc/self/fd");
1392 /* When /proc isn't available (for example in chroots)
1393 * the fallback is brute forcing through the fd
1396 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1397 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1399 if (fd_in_set(fd, except, n_except))
1402 if (close_nointr(fd) < 0)
1403 if (errno != EBADF && r == 0)
1410 while ((de = readdir(d))) {
1413 if (hidden_file(de->d_name))
1416 if (safe_atoi(de->d_name, &fd) < 0)
1417 /* Let's better ignore this, just in case */
1426 if (fd_in_set(fd, except, n_except))
1429 if (close_nointr(fd) < 0) {
1430 /* Valgrind has its own FD and doesn't want to have it closed */
1431 if (errno != EBADF && r == 0)
1439 bool chars_intersect(const char *a, const char *b) {
1442 /* Returns true if any of the chars in a are in b. */
1443 for (p = a; *p; p++)
1450 bool fstype_is_network(const char *fstype) {
1451 static const char table[] =
1466 x = startswith(fstype, "fuse.");
1470 return nulstr_contains(table, fstype);
1473 int flush_fd(int fd) {
1474 struct pollfd pollfd = {
1484 r = poll(&pollfd, 1, 0);
1494 l = read(fd, buf, sizeof(buf));
1500 if (errno == EAGAIN)
1509 void safe_close_pair(int p[]) {
1513 /* Special case pairs which use the same fd in both
1515 p[0] = p[1] = safe_close(p[0]);
1519 p[0] = safe_close(p[0]);
1520 p[1] = safe_close(p[1]);
1523 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1530 while (nbytes > 0) {
1533 k = read(fd, p, nbytes);
1538 if (errno == EAGAIN && do_poll) {
1540 /* We knowingly ignore any return value here,
1541 * and expect that any error/EOF is reported
1544 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1548 return n > 0 ? n : -errno;
1562 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1565 n = loop_read(fd, buf, nbytes, do_poll);
1568 if ((size_t) n != nbytes)
1573 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1574 const uint8_t *p = buf;
1584 k = write(fd, p, nbytes);
1589 if (errno == EAGAIN && do_poll) {
1590 /* We knowingly ignore any return value here,
1591 * and expect that any error/EOF is reported
1594 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1601 if (nbytes > 0 && k == 0) /* Can't really happen */
1606 } while (nbytes > 0);
1611 int parse_size(const char *t, off_t base, off_t *size) {
1613 /* Soo, sometimes we want to parse IEC binary suffixes, and
1614 * sometimes SI decimal suffixes. This function can parse
1615 * both. Which one is the right way depends on the
1616 * context. Wikipedia suggests that SI is customary for
1617 * hardware metrics and network speeds, while IEC is
1618 * customary for most data sizes used by software and volatile
1619 * (RAM) memory. Hence be careful which one you pick!
1621 * In either case we use just K, M, G as suffix, and not Ki,
1622 * Mi, Gi or so (as IEC would suggest). That's because that's
1623 * frickin' ugly. But this means you really need to make sure
1624 * to document which base you are parsing when you use this
1629 unsigned long long factor;
1632 static const struct table iec[] = {
1633 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1634 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1635 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1636 { "G", 1024ULL*1024ULL*1024ULL },
1637 { "M", 1024ULL*1024ULL },
1643 static const struct table si[] = {
1644 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1645 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1646 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1647 { "G", 1000ULL*1000ULL*1000ULL },
1648 { "M", 1000ULL*1000ULL },
1654 const struct table *table;
1656 unsigned long long r = 0;
1657 unsigned n_entries, start_pos = 0;
1660 assert(base == 1000 || base == 1024);
1665 n_entries = ELEMENTSOF(si);
1668 n_entries = ELEMENTSOF(iec);
1674 unsigned long long l2;
1680 l = strtoll(p, &e, 10);
1693 if (*e >= '0' && *e <= '9') {
1696 /* strotoull itself would accept space/+/- */
1697 l2 = strtoull(e, &e2, 10);
1699 if (errno == ERANGE)
1702 /* Ignore failure. E.g. 10.M is valid */
1709 e += strspn(e, WHITESPACE);
1711 for (i = start_pos; i < n_entries; i++)
1712 if (startswith(e, table[i].suffix)) {
1713 unsigned long long tmp;
1714 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1716 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1717 if (tmp > ULLONG_MAX - r)
1721 if ((unsigned long long) (off_t) r != r)
1724 p = e + strlen(table[i].suffix);
1740 bool is_device_path(const char *path) {
1742 /* Returns true on paths that refer to a device, either in
1743 * sysfs or in /dev */
1746 path_startswith(path, "/dev/") ||
1747 path_startswith(path, "/sys/");
1750 int dir_is_empty(const char *path) {
1751 _cleanup_closedir_ DIR *d;
1762 if (!de && errno != 0)
1768 if (!hidden_file(de->d_name))
1773 char* dirname_malloc(const char *path) {
1774 char *d, *dir, *dir2;
1791 void rename_process(const char name[8]) {
1794 /* This is a like a poor man's setproctitle(). It changes the
1795 * comm field, argv[0], and also the glibc's internally used
1796 * name of the process. For the first one a limit of 16 chars
1797 * applies, to the second one usually one of 10 (i.e. length
1798 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1799 * "systemd"). If you pass a longer string it will be
1802 prctl(PR_SET_NAME, name);
1804 if (program_invocation_name)
1805 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1807 if (saved_argc > 0) {
1811 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1813 for (i = 1; i < saved_argc; i++) {
1817 memzero(saved_argv[i], strlen(saved_argv[i]));
1822 char *lookup_uid(uid_t uid) {
1825 _cleanup_free_ char *buf = NULL;
1826 struct passwd pwbuf, *pw = NULL;
1828 /* Shortcut things to avoid NSS lookups */
1830 return strdup("root");
1832 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1836 buf = malloc(bufsize);
1840 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1841 return strdup(pw->pw_name);
1843 if (asprintf(&name, UID_FMT, uid) < 0)
1849 char* getlogname_malloc(void) {
1853 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1858 return lookup_uid(uid);
1861 char *getusername_malloc(void) {
1868 return lookup_uid(getuid());
1871 bool is_temporary_fs(const struct statfs *s) {
1874 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
1875 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
1878 int fd_is_temporary_fs(int fd) {
1881 if (fstatfs(fd, &s) < 0)
1884 return is_temporary_fs(&s);
1887 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1890 /* Under the assumption that we are running privileged we
1891 * first change the access mode and only then hand out
1892 * ownership to avoid a window where access is too open. */
1894 if (mode != MODE_INVALID)
1895 if (chmod(path, mode) < 0)
1898 if (uid != UID_INVALID || gid != GID_INVALID)
1899 if (chown(path, uid, gid) < 0)
1905 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
1908 /* Under the assumption that we are running privileged we
1909 * first change the access mode and only then hand out
1910 * ownership to avoid a window where access is too open. */
1912 if (mode != MODE_INVALID)
1913 if (fchmod(fd, mode) < 0)
1916 if (uid != UID_INVALID || gid != GID_INVALID)
1917 if (fchown(fd, uid, gid) < 0)
1923 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
1927 /* Allocates the cpuset in the right size */
1930 if (!(r = CPU_ALLOC(n)))
1933 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
1934 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
1944 if (errno != EINVAL)
1951 int files_same(const char *filea, const char *fileb) {
1954 if (stat(filea, &a) < 0)
1957 if (stat(fileb, &b) < 0)
1960 return a.st_dev == b.st_dev &&
1961 a.st_ino == b.st_ino;
1964 int running_in_chroot(void) {
1967 ret = files_same("/proc/1/root", "/");
1974 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
1979 assert(percent <= 100);
1980 assert(new_length >= 3);
1982 if (old_length <= 3 || old_length <= new_length)
1983 return strndup(s, old_length);
1985 r = new0(char, new_length+1);
1989 x = (new_length * percent) / 100;
1991 if (x > new_length - 3)
1999 s + old_length - (new_length - x - 3),
2000 new_length - x - 3);
2005 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2009 unsigned k, len, len2;
2012 assert(percent <= 100);
2013 assert(new_length >= 3);
2015 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2016 if (ascii_is_valid(s))
2017 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2019 if (old_length <= 3 || old_length <= new_length)
2020 return strndup(s, old_length);
2022 x = (new_length * percent) / 100;
2024 if (x > new_length - 3)
2028 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2031 c = utf8_encoded_to_unichar(i);
2034 k += unichar_iswide(c) ? 2 : 1;
2037 if (k > x) /* last character was wide and went over quota */
2040 for (j = s + old_length; k < new_length && j > i; ) {
2043 j = utf8_prev_char(j);
2044 c = utf8_encoded_to_unichar(j);
2047 k += unichar_iswide(c) ? 2 : 1;
2051 /* we don't actually need to ellipsize */
2053 return memdup(s, old_length + 1);
2055 /* make space for ellipsis */
2056 j = utf8_next_char(j);
2059 len2 = s + old_length - j;
2060 e = new(char, len + 3 + len2 + 1);
2065 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2066 old_length, new_length, x, len, len2, k);
2070 e[len] = 0xe2; /* tri-dot ellipsis: … */
2074 memcpy(e + len + 3, j, len2 + 1);
2079 char *ellipsize(const char *s, size_t length, unsigned percent) {
2080 return ellipsize_mem(s, strlen(s), length, percent);
2083 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2084 _cleanup_close_ int fd;
2090 mkdir_parents(path, 0755);
2092 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2097 r = fchmod(fd, mode);
2102 if (uid != UID_INVALID || gid != GID_INVALID) {
2103 r = fchown(fd, uid, gid);
2108 if (stamp != USEC_INFINITY) {
2109 struct timespec ts[2];
2111 timespec_store(&ts[0], stamp);
2113 r = futimens(fd, ts);
2115 r = futimens(fd, NULL);
2122 int touch(const char *path) {
2123 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2126 static char *unquote(const char *s, const char* quotes) {
2130 /* This is rather stupid, simply removes the heading and
2131 * trailing quotes if there is one. Doesn't care about
2132 * escaping or anything.
2134 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2140 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2141 return strndup(s+1, l-2);
2146 noreturn void freeze(void) {
2148 /* Make sure nobody waits for us on a socket anymore */
2149 close_all_fds(NULL, 0);
2157 bool null_or_empty(struct stat *st) {
2160 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2163 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2169 int null_or_empty_path(const char *fn) {
2174 if (stat(fn, &st) < 0)
2177 return null_or_empty(&st);
2180 int null_or_empty_fd(int fd) {
2185 if (fstat(fd, &st) < 0)
2188 return null_or_empty(&st);
2191 DIR *xopendirat(int fd, const char *name, int flags) {
2195 assert(!(flags & O_CREAT));
2197 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2210 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2211 _cleanup_free_ char *t = NULL, *u = NULL;
2214 u = unquote(tagvalue, QUOTES);
2218 enc_len = strlen(u) * 4 + 1;
2219 t = new(char, enc_len);
2223 if (encode_devnode_name(u, t, enc_len) < 0)
2226 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2229 char *fstab_node_to_udev_node(const char *p) {
2232 if (startswith(p, "LABEL="))
2233 return tag_to_udev_node(p+6, "label");
2235 if (startswith(p, "UUID="))
2236 return tag_to_udev_node(p+5, "uuid");
2238 if (startswith(p, "PARTUUID="))
2239 return tag_to_udev_node(p+9, "partuuid");
2241 if (startswith(p, "PARTLABEL="))
2242 return tag_to_udev_node(p+10, "partlabel");
2247 bool dirent_is_file(const struct dirent *de) {
2250 if (hidden_file(de->d_name))
2253 if (de->d_type != DT_REG &&
2254 de->d_type != DT_LNK &&
2255 de->d_type != DT_UNKNOWN)
2261 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2264 if (de->d_type != DT_REG &&
2265 de->d_type != DT_LNK &&
2266 de->d_type != DT_UNKNOWN)
2269 if (hidden_file_allow_backup(de->d_name))
2272 return endswith(de->d_name, suffix);
2275 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2276 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2277 _cleanup_set_free_free_ Set *seen = NULL;
2280 /* We fork this all off from a child process so that we can
2281 * somewhat cleanly make use of SIGALRM to set a time limit */
2283 (void) reset_all_signal_handlers();
2284 (void) reset_signal_mask();
2286 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2288 pids = hashmap_new(NULL);
2292 seen = set_new(&string_hash_ops);
2296 STRV_FOREACH(directory, directories) {
2297 _cleanup_closedir_ DIR *d;
2300 d = opendir(*directory);
2302 if (errno == ENOENT)
2305 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2308 FOREACH_DIRENT(de, d, break) {
2309 _cleanup_free_ char *path = NULL;
2313 if (!dirent_is_file(de))
2316 if (set_contains(seen, de->d_name)) {
2317 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2321 r = set_put_strdup(seen, de->d_name);
2325 path = strjoin(*directory, "/", de->d_name, NULL);
2329 if (null_or_empty_path(path)) {
2330 log_debug("%s is empty (a mask).", path);
2336 log_error_errno(errno, "Failed to fork: %m");
2338 } else if (pid == 0) {
2341 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2351 return log_error_errno(errno, "Failed to execute %s: %m", path);
2354 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2356 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2363 /* Abort execution of this process after the timout. We simply
2364 * rely on SIGALRM as default action terminating the process,
2365 * and turn on alarm(). */
2367 if (timeout != USEC_INFINITY)
2368 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2370 while (!hashmap_isempty(pids)) {
2371 _cleanup_free_ char *path = NULL;
2374 pid = PTR_TO_UINT(hashmap_first_key(pids));
2377 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2380 wait_for_terminate_and_warn(path, pid, true);
2386 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2390 char **dirs = (char**) directories;
2392 assert(!strv_isempty(dirs));
2394 name = basename(dirs[0]);
2395 assert(!isempty(name));
2397 /* Executes all binaries in the directories in parallel and waits
2398 * for them to finish. Optionally a timeout is applied. If a file
2399 * with the same name exists in more than one directory, the
2400 * earliest one wins. */
2402 executor_pid = fork();
2403 if (executor_pid < 0) {
2404 log_error_errno(errno, "Failed to fork: %m");
2407 } else if (executor_pid == 0) {
2408 r = do_execute(dirs, timeout, argv);
2409 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2412 wait_for_terminate_and_warn(name, executor_pid, true);
2415 bool nulstr_contains(const char*nulstr, const char *needle) {
2421 NULSTR_FOREACH(i, nulstr)
2422 if (streq(i, needle))
2428 bool plymouth_running(void) {
2429 return access("/run/plymouth/pid", F_OK) >= 0;
2432 char* strshorten(char *s, size_t l) {
2441 bool machine_name_is_valid(const char *s) {
2443 if (!hostname_is_valid(s))
2446 /* Machine names should be useful hostnames, but also be
2447 * useful in unit names, hence we enforce a stricter length
2456 int pipe_eof(int fd) {
2457 struct pollfd pollfd = {
2459 .events = POLLIN|POLLHUP,
2464 r = poll(&pollfd, 1, 0);
2471 return pollfd.revents & POLLHUP;
2474 int fd_wait_for_event(int fd, int event, usec_t t) {
2476 struct pollfd pollfd = {
2484 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2491 return pollfd.revents;
2494 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2503 r = tempfn_xxxxxx(path, &t);
2507 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2513 f = fdopen(fd, "we");
2526 int symlink_atomic(const char *from, const char *to) {
2527 _cleanup_free_ char *t = NULL;
2533 r = tempfn_random(to, &t);
2537 if (symlink(from, t) < 0)
2540 if (rename(t, to) < 0) {
2548 int symlink_idempotent(const char *from, const char *to) {
2549 _cleanup_free_ char *p = NULL;
2555 if (symlink(from, to) < 0) {
2556 if (errno != EEXIST)
2559 r = readlink_malloc(to, &p);
2563 if (!streq(p, from))
2570 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2571 _cleanup_free_ char *t = NULL;
2576 r = tempfn_random(path, &t);
2580 if (mknod(t, mode, dev) < 0)
2583 if (rename(t, path) < 0) {
2591 int mkfifo_atomic(const char *path, mode_t mode) {
2592 _cleanup_free_ char *t = NULL;
2597 r = tempfn_random(path, &t);
2601 if (mkfifo(t, mode) < 0)
2604 if (rename(t, path) < 0) {
2612 bool display_is_local(const char *display) {
2616 display[0] == ':' &&
2617 display[1] >= '0' &&
2621 int socket_from_display(const char *display, char **path) {
2628 if (!display_is_local(display))
2631 k = strspn(display+1, "0123456789");
2633 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2637 c = stpcpy(f, "/tmp/.X11-unix/X");
2638 memcpy(c, display+1, k);
2647 const char **username,
2648 uid_t *uid, gid_t *gid,
2650 const char **shell) {
2658 /* We enforce some special rules for uid=0: in order to avoid
2659 * NSS lookups for root we hardcode its data. */
2661 if (streq(*username, "root") || streq(*username, "0")) {
2679 if (parse_uid(*username, &u) >= 0) {
2683 /* If there are multiple users with the same id, make
2684 * sure to leave $USER to the configured value instead
2685 * of the first occurrence in the database. However if
2686 * the uid was configured by a numeric uid, then let's
2687 * pick the real username from /etc/passwd. */
2689 *username = p->pw_name;
2692 p = getpwnam(*username);
2696 return errno > 0 ? -errno : -ESRCH;
2708 *shell = p->pw_shell;
2713 char* uid_to_name(uid_t uid) {
2718 return strdup("root");
2722 return strdup(p->pw_name);
2724 if (asprintf(&r, UID_FMT, uid) < 0)
2730 char* gid_to_name(gid_t gid) {
2735 return strdup("root");
2739 return strdup(p->gr_name);
2741 if (asprintf(&r, GID_FMT, gid) < 0)
2747 int get_group_creds(const char **groupname, gid_t *gid) {
2753 /* We enforce some special rules for gid=0: in order to avoid
2754 * NSS lookups for root we hardcode its data. */
2756 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2757 *groupname = "root";
2765 if (parse_gid(*groupname, &id) >= 0) {
2770 *groupname = g->gr_name;
2773 g = getgrnam(*groupname);
2777 return errno > 0 ? -errno : -ESRCH;
2785 int in_gid(gid_t gid) {
2787 int ngroups_max, r, i;
2789 if (getgid() == gid)
2792 if (getegid() == gid)
2795 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2796 assert(ngroups_max > 0);
2798 gids = alloca(sizeof(gid_t) * ngroups_max);
2800 r = getgroups(ngroups_max, gids);
2804 for (i = 0; i < r; i++)
2811 int in_group(const char *name) {
2815 r = get_group_creds(&name, &gid);
2822 int glob_exists(const char *path) {
2823 _cleanup_globfree_ glob_t g = {};
2829 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2831 if (k == GLOB_NOMATCH)
2833 else if (k == GLOB_NOSPACE)
2836 return !strv_isempty(g.gl_pathv);
2838 return errno ? -errno : -EIO;
2841 int glob_extend(char ***strv, const char *path) {
2842 _cleanup_globfree_ glob_t g = {};
2847 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
2849 if (k == GLOB_NOMATCH)
2851 else if (k == GLOB_NOSPACE)
2853 else if (k != 0 || strv_isempty(g.gl_pathv))
2854 return errno ? -errno : -EIO;
2856 STRV_FOREACH(p, g.gl_pathv) {
2857 k = strv_extend(strv, *p);
2865 int dirent_ensure_type(DIR *d, struct dirent *de) {
2871 if (de->d_type != DT_UNKNOWN)
2874 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
2878 S_ISREG(st.st_mode) ? DT_REG :
2879 S_ISDIR(st.st_mode) ? DT_DIR :
2880 S_ISLNK(st.st_mode) ? DT_LNK :
2881 S_ISFIFO(st.st_mode) ? DT_FIFO :
2882 S_ISSOCK(st.st_mode) ? DT_SOCK :
2883 S_ISCHR(st.st_mode) ? DT_CHR :
2884 S_ISBLK(st.st_mode) ? DT_BLK :
2890 int get_files_in_directory(const char *path, char ***list) {
2891 _cleanup_closedir_ DIR *d = NULL;
2892 size_t bufsize = 0, n = 0;
2893 _cleanup_strv_free_ char **l = NULL;
2897 /* Returns all files in a directory in *list, and the number
2898 * of files as return value. If list is NULL returns only the
2910 if (!de && errno != 0)
2915 dirent_ensure_type(d, de);
2917 if (!dirent_is_file(de))
2921 /* one extra slot is needed for the terminating NULL */
2922 if (!GREEDY_REALLOC(l, bufsize, n + 2))
2925 l[n] = strdup(de->d_name);
2936 l = NULL; /* avoid freeing */
2942 char *strjoin(const char *x, ...) {
2956 t = va_arg(ap, const char *);
2961 if (n > ((size_t) -1) - l) {
2985 t = va_arg(ap, const char *);
2999 bool is_main_thread(void) {
3000 static thread_local int cached = 0;
3002 if (_unlikely_(cached == 0))
3003 cached = getpid() == gettid() ? 1 : -1;
3008 int block_get_whole_disk(dev_t d, dev_t *ret) {
3015 /* If it has a queue this is good enough for us */
3016 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3019 r = access(p, F_OK);
3027 /* If it is a partition find the originating device */
3028 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3031 r = access(p, F_OK);
3037 /* Get parent dev_t */
3038 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3041 r = read_one_line_file(p, &s);
3047 r = sscanf(s, "%u:%u", &m, &n);
3053 /* Only return this if it is really good enough for us. */
3054 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3057 r = access(p, F_OK);
3061 *ret = makedev(m, n);
3068 static const char *const ioprio_class_table[] = {
3069 [IOPRIO_CLASS_NONE] = "none",
3070 [IOPRIO_CLASS_RT] = "realtime",
3071 [IOPRIO_CLASS_BE] = "best-effort",
3072 [IOPRIO_CLASS_IDLE] = "idle"
3075 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3077 static const char *const sigchld_code_table[] = {
3078 [CLD_EXITED] = "exited",
3079 [CLD_KILLED] = "killed",
3080 [CLD_DUMPED] = "dumped",
3081 [CLD_TRAPPED] = "trapped",
3082 [CLD_STOPPED] = "stopped",
3083 [CLD_CONTINUED] = "continued",
3086 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3088 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3089 [LOG_FAC(LOG_KERN)] = "kern",
3090 [LOG_FAC(LOG_USER)] = "user",
3091 [LOG_FAC(LOG_MAIL)] = "mail",
3092 [LOG_FAC(LOG_DAEMON)] = "daemon",
3093 [LOG_FAC(LOG_AUTH)] = "auth",
3094 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3095 [LOG_FAC(LOG_LPR)] = "lpr",
3096 [LOG_FAC(LOG_NEWS)] = "news",
3097 [LOG_FAC(LOG_UUCP)] = "uucp",
3098 [LOG_FAC(LOG_CRON)] = "cron",
3099 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3100 [LOG_FAC(LOG_FTP)] = "ftp",
3101 [LOG_FAC(LOG_LOCAL0)] = "local0",
3102 [LOG_FAC(LOG_LOCAL1)] = "local1",
3103 [LOG_FAC(LOG_LOCAL2)] = "local2",
3104 [LOG_FAC(LOG_LOCAL3)] = "local3",
3105 [LOG_FAC(LOG_LOCAL4)] = "local4",
3106 [LOG_FAC(LOG_LOCAL5)] = "local5",
3107 [LOG_FAC(LOG_LOCAL6)] = "local6",
3108 [LOG_FAC(LOG_LOCAL7)] = "local7"
3111 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3113 static const char *const log_level_table[] = {
3114 [LOG_EMERG] = "emerg",
3115 [LOG_ALERT] = "alert",
3116 [LOG_CRIT] = "crit",
3118 [LOG_WARNING] = "warning",
3119 [LOG_NOTICE] = "notice",
3120 [LOG_INFO] = "info",
3121 [LOG_DEBUG] = "debug"
3124 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3126 static const char* const sched_policy_table[] = {
3127 [SCHED_OTHER] = "other",
3128 [SCHED_BATCH] = "batch",
3129 [SCHED_IDLE] = "idle",
3130 [SCHED_FIFO] = "fifo",
3134 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3136 static const char* const rlimit_table[_RLIMIT_MAX] = {
3137 [RLIMIT_CPU] = "LimitCPU",
3138 [RLIMIT_FSIZE] = "LimitFSIZE",
3139 [RLIMIT_DATA] = "LimitDATA",
3140 [RLIMIT_STACK] = "LimitSTACK",
3141 [RLIMIT_CORE] = "LimitCORE",
3142 [RLIMIT_RSS] = "LimitRSS",
3143 [RLIMIT_NOFILE] = "LimitNOFILE",
3144 [RLIMIT_AS] = "LimitAS",
3145 [RLIMIT_NPROC] = "LimitNPROC",
3146 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3147 [RLIMIT_LOCKS] = "LimitLOCKS",
3148 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3149 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3150 [RLIMIT_NICE] = "LimitNICE",
3151 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3152 [RLIMIT_RTTIME] = "LimitRTTIME"
3155 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3157 static const char* const ip_tos_table[] = {
3158 [IPTOS_LOWDELAY] = "low-delay",
3159 [IPTOS_THROUGHPUT] = "throughput",
3160 [IPTOS_RELIABILITY] = "reliability",
3161 [IPTOS_LOWCOST] = "low-cost",
3164 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3166 bool kexec_loaded(void) {
3167 bool loaded = false;
3170 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3178 int prot_from_flags(int flags) {
3180 switch (flags & O_ACCMODE) {
3189 return PROT_READ|PROT_WRITE;
3196 char *format_bytes(char *buf, size_t l, off_t t) {
3199 static const struct {
3203 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3204 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3205 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3206 { "G", 1024ULL*1024ULL*1024ULL },
3207 { "M", 1024ULL*1024ULL },
3211 if (t == (off_t) -1)
3214 for (i = 0; i < ELEMENTSOF(table); i++) {
3216 if (t >= table[i].factor) {
3219 (unsigned long long) (t / table[i].factor),
3220 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3227 snprintf(buf, l, "%lluB", (unsigned long long) t);
3235 void* memdup(const void *p, size_t l) {
3248 int fd_inc_sndbuf(int fd, size_t n) {
3250 socklen_t l = sizeof(value);
3252 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3253 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3256 /* If we have the privileges we will ignore the kernel limit. */
3259 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3260 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3266 int fd_inc_rcvbuf(int fd, size_t n) {
3268 socklen_t l = sizeof(value);
3270 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3271 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3274 /* If we have the privileges we will ignore the kernel limit. */
3277 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3278 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3283 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3284 bool stdout_is_tty, stderr_is_tty;
3285 pid_t parent_pid, agent_pid;
3286 sigset_t ss, saved_ss;
3294 /* Spawns a temporary TTY agent, making sure it goes away when
3297 parent_pid = getpid();
3299 /* First we temporarily block all signals, so that the new
3300 * child has them blocked initially. This way, we can be sure
3301 * that SIGTERMs are not lost we might send to the agent. */
3302 assert_se(sigfillset(&ss) >= 0);
3303 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3306 if (agent_pid < 0) {
3307 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3311 if (agent_pid != 0) {
3312 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3319 * Make sure the agent goes away when the parent dies */
3320 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3321 _exit(EXIT_FAILURE);
3323 /* Make sure we actually can kill the agent, if we need to, in
3324 * case somebody invoked us from a shell script that trapped
3325 * SIGTERM or so... */
3326 (void) reset_all_signal_handlers();
3327 (void) reset_signal_mask();
3329 /* Check whether our parent died before we were able
3330 * to set the death signal and unblock the signals */
3331 if (getppid() != parent_pid)
3332 _exit(EXIT_SUCCESS);
3334 /* Don't leak fds to the agent */
3335 close_all_fds(except, n_except);
3337 stdout_is_tty = isatty(STDOUT_FILENO);
3338 stderr_is_tty = isatty(STDERR_FILENO);
3340 if (!stdout_is_tty || !stderr_is_tty) {
3343 /* Detach from stdout/stderr. and reopen
3344 * /dev/tty for them. This is important to
3345 * ensure that when systemctl is started via
3346 * popen() or a similar call that expects to
3347 * read EOF we actually do generate EOF and
3348 * not delay this indefinitely by because we
3349 * keep an unused copy of stdin around. */
3350 fd = open("/dev/tty", O_WRONLY);
3352 log_error_errno(errno, "Failed to open /dev/tty: %m");
3353 _exit(EXIT_FAILURE);
3357 dup2(fd, STDOUT_FILENO);
3360 dup2(fd, STDERR_FILENO);
3366 /* Count arguments */
3368 for (n = 0; va_arg(ap, char*); n++)
3373 l = alloca(sizeof(char *) * (n + 1));
3375 /* Fill in arguments */
3377 for (i = 0; i <= n; i++)
3378 l[i] = va_arg(ap, char*);
3382 _exit(EXIT_FAILURE);
3385 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3386 struct rlimit highest, fixed;
3390 if (setrlimit(resource, rlim) >= 0)
3396 /* So we failed to set the desired setrlimit, then let's try
3397 * to get as close as we can */
3398 assert_se(getrlimit(resource, &highest) == 0);
3400 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3401 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3403 if (setrlimit(resource, &fixed) < 0)
3409 bool http_etag_is_valid(const char *etag) {
3413 if (!endswith(etag, "\""))
3416 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3422 bool http_url_is_valid(const char *url) {
3428 p = startswith(url, "http://");
3430 p = startswith(url, "https://");
3437 return ascii_is_valid(p);
3440 bool documentation_url_is_valid(const char *url) {
3446 if (http_url_is_valid(url))
3449 p = startswith(url, "file:/");
3451 p = startswith(url, "info:");
3453 p = startswith(url, "man:");
3458 return ascii_is_valid(p);
3461 bool in_initrd(void) {
3462 static int saved = -1;
3468 /* We make two checks here:
3470 * 1. the flag file /etc/initrd-release must exist
3471 * 2. the root file system must be a memory file system
3473 * The second check is extra paranoia, since misdetecting an
3474 * initrd can have bad bad consequences due the initrd
3475 * emptying when transititioning to the main systemd.
3478 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3479 statfs("/", &s) >= 0 &&
3480 is_temporary_fs(&s);
3485 int get_home_dir(char **_h) {
3493 /* Take the user specified one */
3494 e = secure_getenv("HOME");
3495 if (e && path_is_absolute(e)) {
3504 /* Hardcode home directory for root to avoid NSS */
3507 h = strdup("/root");
3515 /* Check the database... */
3519 return errno > 0 ? -errno : -ESRCH;
3521 if (!path_is_absolute(p->pw_dir))
3524 h = strdup(p->pw_dir);
3532 int get_shell(char **_s) {
3540 /* Take the user specified one */
3541 e = getenv("SHELL");
3551 /* Hardcode home directory for root to avoid NSS */
3554 s = strdup("/bin/sh");
3562 /* Check the database... */
3566 return errno > 0 ? -errno : -ESRCH;
3568 if (!path_is_absolute(p->pw_shell))
3571 s = strdup(p->pw_shell);
3579 bool filename_is_valid(const char *p) {
3593 if (strlen(p) > FILENAME_MAX)
3599 bool string_is_safe(const char *p) {
3605 for (t = p; *t; t++) {
3606 if (*t > 0 && *t < ' ')
3609 if (strchr("\\\"\'\0x7f", *t))
3617 * Check if a string contains control characters. If 'ok' is non-NULL
3618 * it may be a string containing additional CCs to be considered OK.
3620 bool string_has_cc(const char *p, const char *ok) {
3625 for (t = p; *t; t++) {
3626 if (ok && strchr(ok, *t))
3629 if (*t > 0 && *t < ' ')
3639 bool path_is_safe(const char *p) {
3644 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3647 if (strlen(p)+1 > PATH_MAX)
3650 /* The following two checks are not really dangerous, but hey, they still are confusing */
3651 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3654 if (strstr(p, "//"))
3660 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3661 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3662 int (*compar) (const void *, const void *, void *), void *arg) {
3671 p = (void *)(((const char *) base) + (idx * size));
3672 comparison = compar(key, p, arg);
3675 else if (comparison > 0)
3683 void init_gettext(void) {
3684 setlocale(LC_ALL, "");
3685 textdomain(GETTEXT_PACKAGE);
3688 bool is_locale_utf8(void) {
3690 static int cached_answer = -1;
3692 if (cached_answer >= 0)
3695 if (!setlocale(LC_ALL, "")) {
3696 cached_answer = true;
3700 set = nl_langinfo(CODESET);
3702 cached_answer = true;
3706 if (streq(set, "UTF-8")) {
3707 cached_answer = true;
3711 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3712 * unset and everything can do to UTF-8 nowadays. */
3713 set = setlocale(LC_CTYPE, NULL);
3715 cached_answer = true;
3719 /* Check result, but ignore the result if C was set
3723 !getenv("LC_ALL") &&
3724 !getenv("LC_CTYPE") &&
3728 return (bool) cached_answer;
3731 const char *draw_special_char(DrawSpecialChar ch) {
3732 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
3735 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
3736 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
3737 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
3738 [DRAW_TREE_SPACE] = " ", /* */
3739 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
3740 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
3741 [DRAW_ARROW] = "\342\206\222", /* → */
3742 [DRAW_DASH] = "\342\200\223", /* – */
3745 /* ASCII fallback */ {
3746 [DRAW_TREE_VERTICAL] = "| ",
3747 [DRAW_TREE_BRANCH] = "|-",
3748 [DRAW_TREE_RIGHT] = "`-",
3749 [DRAW_TREE_SPACE] = " ",
3750 [DRAW_TRIANGULAR_BULLET] = ">",
3751 [DRAW_BLACK_CIRCLE] = "*",
3752 [DRAW_ARROW] = "->",
3757 return draw_table[!is_locale_utf8()][ch];
3760 char *strreplace(const char *text, const char *old_string, const char *new_string) {
3763 size_t l, old_len, new_len;
3769 old_len = strlen(old_string);
3770 new_len = strlen(new_string);
3783 if (!startswith(f, old_string)) {
3789 nl = l - old_len + new_len;
3790 a = realloc(r, nl + 1);
3798 t = stpcpy(t, new_string);
3810 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
3811 const char *i, *begin = NULL;
3816 } state = STATE_OTHER;
3818 size_t osz = 0, isz;
3824 /* Strips ANSI color and replaces TABs by 8 spaces */
3826 isz = _isz ? *_isz : strlen(*ibuf);
3828 f = open_memstream(&obuf, &osz);
3832 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
3837 if (i >= *ibuf + isz) /* EOT */
3839 else if (*i == '\x1B')
3840 state = STATE_ESCAPE;
3841 else if (*i == '\t')
3848 if (i >= *ibuf + isz) { /* EOT */
3851 } else if (*i == '[') {
3852 state = STATE_BRACKET;
3857 state = STATE_OTHER;
3864 if (i >= *ibuf + isz || /* EOT */
3865 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
3868 state = STATE_OTHER;
3870 } else if (*i == 'm')
3871 state = STATE_OTHER;
3893 int on_ac_power(void) {
3894 bool found_offline = false, found_online = false;
3895 _cleanup_closedir_ DIR *d = NULL;
3897 d = opendir("/sys/class/power_supply");
3899 return errno == ENOENT ? true : -errno;
3903 _cleanup_close_ int fd = -1, device = -1;
3909 if (!de && errno != 0)
3915 if (hidden_file(de->d_name))
3918 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
3920 if (errno == ENOENT || errno == ENOTDIR)
3926 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3928 if (errno == ENOENT)
3934 n = read(fd, contents, sizeof(contents));
3938 if (n != 6 || memcmp(contents, "Mains\n", 6))
3942 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3944 if (errno == ENOENT)
3950 n = read(fd, contents, sizeof(contents));
3954 if (n != 2 || contents[1] != '\n')
3957 if (contents[0] == '1') {
3958 found_online = true;
3960 } else if (contents[0] == '0')
3961 found_offline = true;
3966 return found_online || !found_offline;
3969 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
3976 if (!path_strv_resolve_uniq(search, root))
3979 STRV_FOREACH(i, search) {
3980 _cleanup_free_ char *p = NULL;
3984 p = strjoin(root, *i, "/", path, NULL);
3986 p = strjoin(*i, "/", path, NULL);
3996 if (errno != ENOENT)
4003 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4004 _cleanup_strv_free_ char **copy = NULL;
4010 if (path_is_absolute(path)) {
4013 f = fopen(path, mode);
4022 copy = strv_copy((char**) search);
4026 return search_and_fopen_internal(path, mode, root, copy, _f);
4029 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4030 _cleanup_strv_free_ char **s = NULL;
4032 if (path_is_absolute(path)) {
4035 f = fopen(path, mode);
4044 s = strv_split_nulstr(search);
4048 return search_and_fopen_internal(path, mode, root, s, _f);
4051 char *strextend(char **x, ...) {
4058 l = f = *x ? strlen(*x) : 0;
4065 t = va_arg(ap, const char *);
4070 if (n > ((size_t) -1) - l) {
4079 r = realloc(*x, l+1);
4089 t = va_arg(ap, const char *);
4103 char *strrep(const char *s, unsigned n) {
4111 p = r = malloc(l * n + 1);
4115 for (i = 0; i < n; i++)
4122 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4129 if (*allocated >= need)
4132 newalloc = MAX(need * 2, 64u / size);
4133 a = newalloc * size;
4135 /* check for overflows */
4136 if (a < size * need)
4144 *allocated = newalloc;
4148 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4157 q = greedy_realloc(p, allocated, need, size);
4161 if (*allocated > prev)
4162 memzero(q + prev * size, (*allocated - prev) * size);
4167 bool id128_is_valid(const char *s) {
4173 /* Simple formatted 128bit hex string */
4175 for (i = 0; i < l; i++) {
4178 if (!(c >= '0' && c <= '9') &&
4179 !(c >= 'a' && c <= 'z') &&
4180 !(c >= 'A' && c <= 'Z'))
4184 } else if (l == 36) {
4186 /* Formatted UUID */
4188 for (i = 0; i < l; i++) {
4191 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4195 if (!(c >= '0' && c <= '9') &&
4196 !(c >= 'a' && c <= 'z') &&
4197 !(c >= 'A' && c <= 'Z'))
4208 int split_pair(const char *s, const char *sep, char **l, char **r) {
4223 a = strndup(s, x - s);
4227 b = strdup(x + strlen(sep));
4239 int shall_restore_state(void) {
4240 _cleanup_free_ char *value = NULL;
4243 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4249 return parse_boolean(value) != 0;
4252 int proc_cmdline(char **ret) {
4255 if (detect_container(NULL) > 0)
4256 return get_process_cmdline(1, 0, false, ret);
4258 return read_one_line_file("/proc/cmdline", ret);
4261 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4262 _cleanup_free_ char *line = NULL;
4268 r = proc_cmdline(&line);
4274 _cleanup_free_ char *word = NULL;
4277 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4283 /* Filter out arguments that are intended only for the
4285 if (!in_initrd() && startswith(word, "rd."))
4288 value = strchr(word, '=');
4292 r = parse_item(word, value);
4300 int get_proc_cmdline_key(const char *key, char **value) {
4301 _cleanup_free_ char *line = NULL, *ret = NULL;
4308 r = proc_cmdline(&line);
4314 _cleanup_free_ char *word = NULL;
4317 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4323 /* Filter out arguments that are intended only for the
4325 if (!in_initrd() && startswith(word, "rd."))
4329 e = startswith(word, key);
4333 r = free_and_strdup(&ret, e);
4339 if (streq(word, key))
4353 int container_get_leader(const char *machine, pid_t *pid) {
4354 _cleanup_free_ char *s = NULL, *class = NULL;
4362 p = strjoina("/run/systemd/machines/", machine);
4363 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4371 if (!streq_ptr(class, "container"))
4374 r = parse_pid(s, &leader);
4384 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4385 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4393 mntns = procfs_file_alloca(pid, "ns/mnt");
4394 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4402 pidns = procfs_file_alloca(pid, "ns/pid");
4403 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4411 netns = procfs_file_alloca(pid, "ns/net");
4412 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4420 root = procfs_file_alloca(pid, "root");
4421 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4427 *pidns_fd = pidnsfd;
4430 *mntns_fd = mntnsfd;
4433 *netns_fd = netnsfd;
4438 pidnsfd = mntnsfd = netnsfd = -1;
4443 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4446 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4450 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4454 if (setns(netns_fd, CLONE_NEWNET) < 0)
4458 if (fchdir(root_fd) < 0)
4461 if (chroot(".") < 0)
4465 return reset_uid_gid();
4468 int getpeercred(int fd, struct ucred *ucred) {
4469 socklen_t n = sizeof(struct ucred);
4476 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4480 if (n != sizeof(struct ucred))
4483 /* Check if the data is actually useful and not suppressed due
4484 * to namespacing issues */
4487 if (u.uid == UID_INVALID)
4489 if (u.gid == GID_INVALID)
4496 int getpeersec(int fd, char **ret) {
4508 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4512 if (errno != ERANGE)
4519 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4535 /* This is much like like mkostemp() but is subject to umask(). */
4536 int mkostemp_safe(char *pattern, int flags) {
4537 _cleanup_umask_ mode_t u;
4544 fd = mkostemp(pattern, flags);
4551 int open_tmpfile(const char *path, int flags) {
4558 /* Try O_TMPFILE first, if it is supported */
4559 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
4564 /* Fall back to unguessable name + unlinking */
4565 p = strjoina(path, "/systemd-tmp-XXXXXX");
4567 fd = mkostemp_safe(p, flags);
4575 int fd_warn_permissions(const char *path, int fd) {
4578 if (fstat(fd, &st) < 0)
4581 if (st.st_mode & 0111)
4582 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4584 if (st.st_mode & 0002)
4585 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4587 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4588 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);
4593 unsigned long personality_from_string(const char *p) {
4595 /* Parse a personality specifier. We introduce our own
4596 * identifiers that indicate specific ABIs, rather than just
4597 * hints regarding the register size, since we want to keep
4598 * things open for multiple locally supported ABIs for the
4599 * same register size. We try to reuse the ABI identifiers
4600 * used by libseccomp. */
4602 #if defined(__x86_64__)
4604 if (streq(p, "x86"))
4607 if (streq(p, "x86-64"))
4610 #elif defined(__i386__)
4612 if (streq(p, "x86"))
4616 return PERSONALITY_INVALID;
4619 const char* personality_to_string(unsigned long p) {
4621 #if defined(__x86_64__)
4623 if (p == PER_LINUX32)
4629 #elif defined(__i386__)
4638 uint64_t physical_memory(void) {
4641 /* We return this as uint64_t in case we are running as 32bit
4642 * process on a 64bit kernel with huge amounts of memory */
4644 mem = sysconf(_SC_PHYS_PAGES);
4647 return (uint64_t) mem * (uint64_t) page_size();
4650 void hexdump(FILE *f, const void *p, size_t s) {
4651 const uint8_t *b = p;
4654 assert(s == 0 || b);
4659 fprintf(f, "%04x ", n);
4661 for (i = 0; i < 16; i++) {
4666 fprintf(f, "%02x ", b[i]);
4674 for (i = 0; i < 16; i++) {
4679 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4693 int update_reboot_param_file(const char *param) {
4698 r = write_string_file(REBOOT_PARAM_FILE, param);
4700 log_error("Failed to write reboot param to "
4701 REBOOT_PARAM_FILE": %s", strerror(-r));
4703 unlink(REBOOT_PARAM_FILE);
4708 int umount_recursive(const char *prefix, int flags) {
4712 /* Try to umount everything recursively below a
4713 * directory. Also, take care of stacked mounts, and keep
4714 * unmounting them until they are gone. */
4717 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4722 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4723 if (!proc_self_mountinfo)
4727 _cleanup_free_ char *path = NULL, *p = NULL;
4730 k = fscanf(proc_self_mountinfo,
4731 "%*s " /* (1) mount id */
4732 "%*s " /* (2) parent id */
4733 "%*s " /* (3) major:minor */
4734 "%*s " /* (4) root */
4735 "%ms " /* (5) mount point */
4736 "%*s" /* (6) mount options */
4737 "%*[^-]" /* (7) optional fields */
4738 "- " /* (8) separator */
4739 "%*s " /* (9) file system type */
4740 "%*s" /* (10) mount source */
4741 "%*s" /* (11) mount options 2 */
4742 "%*[^\n]", /* some rubbish at the end */
4751 r = cunescape(path, UNESCAPE_RELAX, &p);
4755 if (!path_startswith(p, prefix))
4758 if (umount2(p, flags) < 0) {
4774 static int get_mount_flags(const char *path, unsigned long *flags) {
4777 if (statvfs(path, &buf) < 0)
4779 *flags = buf.f_flag;
4783 int bind_remount_recursive(const char *prefix, bool ro) {
4784 _cleanup_set_free_free_ Set *done = NULL;
4785 _cleanup_free_ char *cleaned = NULL;
4788 /* Recursively remount a directory (and all its submounts)
4789 * read-only or read-write. If the directory is already
4790 * mounted, we reuse the mount and simply mark it
4791 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
4792 * operation). If it isn't we first make it one. Afterwards we
4793 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
4794 * submounts we can access, too. When mounts are stacked on
4795 * the same mount point we only care for each individual
4796 * "top-level" mount on each point, as we cannot
4797 * influence/access the underlying mounts anyway. We do not
4798 * have any effect on future submounts that might get
4799 * propagated, they migt be writable. This includes future
4800 * submounts that have been triggered via autofs. */
4802 cleaned = strdup(prefix);
4806 path_kill_slashes(cleaned);
4808 done = set_new(&string_hash_ops);
4813 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
4814 _cleanup_set_free_free_ Set *todo = NULL;
4815 bool top_autofs = false;
4817 unsigned long orig_flags;
4819 todo = set_new(&string_hash_ops);
4823 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
4824 if (!proc_self_mountinfo)
4828 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
4831 k = fscanf(proc_self_mountinfo,
4832 "%*s " /* (1) mount id */
4833 "%*s " /* (2) parent id */
4834 "%*s " /* (3) major:minor */
4835 "%*s " /* (4) root */
4836 "%ms " /* (5) mount point */
4837 "%*s" /* (6) mount options (superblock) */
4838 "%*[^-]" /* (7) optional fields */
4839 "- " /* (8) separator */
4840 "%ms " /* (9) file system type */
4841 "%*s" /* (10) mount source */
4842 "%*s" /* (11) mount options (bind mount) */
4843 "%*[^\n]", /* some rubbish at the end */
4853 r = cunescape(path, UNESCAPE_RELAX, &p);
4857 /* Let's ignore autofs mounts. If they aren't
4858 * triggered yet, we want to avoid triggering
4859 * them, as we don't make any guarantees for
4860 * future submounts anyway. If they are
4861 * already triggered, then we will find
4862 * another entry for this. */
4863 if (streq(type, "autofs")) {
4864 top_autofs = top_autofs || path_equal(cleaned, p);
4868 if (path_startswith(p, cleaned) &&
4869 !set_contains(done, p)) {
4871 r = set_consume(todo, p);
4881 /* If we have no submounts to process anymore and if
4882 * the root is either already done, or an autofs, we
4884 if (set_isempty(todo) &&
4885 (top_autofs || set_contains(done, cleaned)))
4888 if (!set_contains(done, cleaned) &&
4889 !set_contains(todo, cleaned)) {
4890 /* The prefix directory itself is not yet a
4891 * mount, make it one. */
4892 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
4896 (void) get_mount_flags(cleaned, &orig_flags);
4897 orig_flags &= ~MS_RDONLY;
4899 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
4902 x = strdup(cleaned);
4906 r = set_consume(done, x);
4911 while ((x = set_steal_first(todo))) {
4913 r = set_consume(done, x);
4919 /* Try to reuse the original flag set, but
4920 * don't care for errors, in case of
4921 * obstructed mounts */
4923 (void) get_mount_flags(x, &orig_flags);
4924 orig_flags &= ~MS_RDONLY;
4926 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
4928 /* Deal with mount points that are
4929 * obstructed by a later mount */
4931 if (errno != ENOENT)
4939 int fflush_and_check(FILE *f) {
4946 return errno ? -errno : -EIO;
4951 int tempfn_xxxxxx(const char *p, char **ret) {
4963 * /foo/bar/.#waldoXXXXXX
4967 if (!filename_is_valid(fn))
4970 t = new(char, strlen(p) + 2 + 6 + 1);
4974 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
4976 *ret = path_kill_slashes(t);
4980 int tempfn_random(const char *p, char **ret) {
4994 * /foo/bar/.#waldobaa2a261115984a9
4998 if (!filename_is_valid(fn))
5001 t = new(char, strlen(p) + 2 + 16 + 1);
5005 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5008 for (i = 0; i < 16; i++) {
5009 *(x++) = hexchar(u & 0xF);
5015 *ret = path_kill_slashes(t);
5019 int tempfn_random_child(const char *p, char **ret) {
5030 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5033 t = new(char, strlen(p) + 3 + 16 + 1);
5037 x = stpcpy(stpcpy(t, p), "/.#");
5040 for (i = 0; i < 16; i++) {
5041 *(x++) = hexchar(u & 0xF);
5047 *ret = path_kill_slashes(t);
5051 int take_password_lock(const char *root) {
5053 struct flock flock = {
5055 .l_whence = SEEK_SET,
5063 /* This is roughly the same as lckpwdf(), but not as awful. We
5064 * don't want to use alarm() and signals, hence we implement
5065 * our own trivial version of this.
5067 * Note that shadow-utils also takes per-database locks in
5068 * addition to lckpwdf(). However, we don't given that they
5069 * are redundant as they they invoke lckpwdf() first and keep
5070 * it during everything they do. The per-database locks are
5071 * awfully racy, and thus we just won't do them. */
5074 path = strjoina(root, "/etc/.pwd.lock");
5076 path = "/etc/.pwd.lock";
5078 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5082 r = fcntl(fd, F_SETLKW, &flock);
5091 int is_symlink(const char *path) {
5094 if (lstat(path, &info) < 0)
5097 return !!S_ISLNK(info.st_mode);
5100 int is_dir(const char* path, bool follow) {
5105 r = stat(path, &st);
5107 r = lstat(path, &st);
5111 return !!S_ISDIR(st.st_mode);
5114 int is_device_node(const char *path) {
5117 if (lstat(path, &info) < 0)
5120 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5123 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5124 _cleanup_free_ char *s = NULL;
5125 size_t allocated = 0, sz = 0;
5133 SINGLE_QUOTE_ESCAPE,
5135 DOUBLE_QUOTE_ESCAPE,
5143 /* Parses the first word of a string, and returns it in
5144 * *ret. Removes all quotes in the process. When parsing fails
5145 * (because of an uneven number of quotes or similar), leaves
5146 * the pointer *p at the first invalid character. */
5156 else if (strchr(WHITESPACE, c))
5166 state = SINGLE_QUOTE;
5168 state = VALUE_ESCAPE;
5170 state = DOUBLE_QUOTE;
5171 else if (strchr(WHITESPACE, c))
5174 if (!GREEDY_REALLOC(s, allocated, sz+2))
5184 if (flags & UNQUOTE_RELAX)
5189 if (!GREEDY_REALLOC(s, allocated, sz+7))
5192 if (flags & UNQUOTE_CUNESCAPE) {
5195 r = cunescape_one(*p, (size_t) -1, &c, &u);
5202 s[sz++] = c; /* normal explicit char */
5204 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5213 if (flags & UNQUOTE_RELAX)
5216 } else if (c == '\'')
5219 state = SINGLE_QUOTE_ESCAPE;
5221 if (!GREEDY_REALLOC(s, allocated, sz+2))
5229 case SINGLE_QUOTE_ESCAPE:
5231 if (flags & UNQUOTE_RELAX)
5236 if (!GREEDY_REALLOC(s, allocated, sz+7))
5239 if (flags & UNQUOTE_CUNESCAPE) {
5242 r = cunescape_one(*p, (size_t) -1, &c, &u);
5251 sz += utf8_encode_unichar(s + sz, u);
5255 state = SINGLE_QUOTE;
5264 state = DOUBLE_QUOTE_ESCAPE;
5266 if (!GREEDY_REALLOC(s, allocated, sz+2))
5274 case DOUBLE_QUOTE_ESCAPE:
5276 if (flags & UNQUOTE_RELAX)
5281 if (!GREEDY_REALLOC(s, allocated, sz+7))
5284 if (flags & UNQUOTE_CUNESCAPE) {
5287 r = cunescape_one(*p, (size_t) -1, &c, &u);
5296 sz += utf8_encode_unichar(s + sz, u);
5300 state = DOUBLE_QUOTE;
5306 if (!strchr(WHITESPACE, c))
5328 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5333 /* Parses a number of words from a string, stripping any
5334 * quotes if necessary. */
5338 /* Count how many words are expected */
5339 va_start(ap, flags);
5341 if (!va_arg(ap, char **))
5350 /* Read all words into a temporary array */
5351 l = newa0(char*, n);
5352 for (c = 0; c < n; c++) {
5354 r = unquote_first_word(p, &l[c], flags);
5358 for (j = 0; j < c; j++)
5368 /* If we managed to parse all words, return them in the passed
5370 va_start(ap, flags);
5371 for (i = 0; i < n; i++) {
5374 v = va_arg(ap, char **);
5384 int free_and_strdup(char **p, const char *s) {
5389 /* Replaces a string pointer with an strdup()ed new string,
5390 * possibly freeing the old one. */
5392 if (streq_ptr(*p, s))
5408 int ptsname_malloc(int fd, char **ret) {
5421 if (ptsname_r(fd, c, l) == 0) {
5425 if (errno != ERANGE) {
5435 int openpt_in_namespace(pid_t pid, int flags) {
5436 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5437 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5439 struct cmsghdr cmsghdr;
5440 uint8_t buf[CMSG_SPACE(sizeof(int))];
5442 struct msghdr mh = {
5443 .msg_control = &control,
5444 .msg_controllen = sizeof(control),
5446 struct cmsghdr *cmsg;
5453 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5457 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5467 pair[0] = safe_close(pair[0]);
5469 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5471 _exit(EXIT_FAILURE);
5473 master = posix_openpt(flags);
5475 _exit(EXIT_FAILURE);
5477 cmsg = CMSG_FIRSTHDR(&mh);
5478 cmsg->cmsg_level = SOL_SOCKET;
5479 cmsg->cmsg_type = SCM_RIGHTS;
5480 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5481 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5483 mh.msg_controllen = cmsg->cmsg_len;
5485 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5486 _exit(EXIT_FAILURE);
5488 _exit(EXIT_SUCCESS);
5491 pair[1] = safe_close(pair[1]);
5493 r = wait_for_terminate(child, &si);
5496 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5499 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5502 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5503 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5507 fds = (int*) CMSG_DATA(cmsg);
5508 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5511 close_many(fds, n_fds);
5521 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5522 _cleanup_close_ int fd = -1;
5525 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5527 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5531 l = fgetxattr(fd, attribute, value, size);
5538 static int parse_crtime(le64_t le, usec_t *usec) {
5544 if (u == 0 || u == (uint64_t) -1)
5551 int fd_getcrtime(int fd, usec_t *usec) {
5558 /* Until Linux gets a real concept of birthtime/creation time,
5559 * let's fake one with xattrs */
5561 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5564 if (n != sizeof(le))
5567 return parse_crtime(le, usec);
5570 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5574 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5577 if (n != sizeof(le))
5580 return parse_crtime(le, usec);
5583 int path_getcrtime(const char *p, usec_t *usec) {
5590 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5593 if (n != sizeof(le))
5596 return parse_crtime(le, usec);
5599 int fd_setcrtime(int fd, usec_t usec) {
5605 usec = now(CLOCK_REALTIME);
5607 le = htole64((uint64_t) usec);
5608 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5614 int same_fd(int a, int b) {
5615 struct stat sta, stb;
5622 /* Compares two file descriptors. Note that semantics are
5623 * quite different depending on whether we have kcmp() or we
5624 * don't. If we have kcmp() this will only return true for
5625 * dup()ed file descriptors, but not otherwise. If we don't
5626 * have kcmp() this will also return true for two fds of the same
5627 * file, created by separate open() calls. Since we use this
5628 * call mostly for filtering out duplicates in the fd store
5629 * this difference hopefully doesn't matter too much. */
5634 /* Try to use kcmp() if we have it. */
5636 r = kcmp(pid, pid, KCMP_FILE, a, b);
5641 if (errno != ENOSYS)
5644 /* We don't have kcmp(), use fstat() instead. */
5645 if (fstat(a, &sta) < 0)
5648 if (fstat(b, &stb) < 0)
5651 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
5654 /* We consider all device fds different, since two device fds
5655 * might refer to quite different device contexts even though
5656 * they share the same inode and backing dev_t. */
5658 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
5661 if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
5664 /* The fds refer to the same inode on disk, let's also check
5665 * if they have the same fd flags. This is useful to
5666 * distinguish the read and write side of a pipe created with
5668 fa = fcntl(a, F_GETFL);
5672 fb = fcntl(b, F_GETFL);
5679 int chattr_fd(int fd, unsigned value, unsigned mask) {
5680 unsigned old_attr, new_attr;
5685 if (fstat(fd, &st) < 0)
5688 /* Explicitly check whether this is a regular file or
5689 * directory. If it is anything else (such as a device node or
5690 * fifo), then the ioctl will not hit the file systems but
5691 * possibly drivers, where the ioctl might have different
5692 * effects. Notably, DRM is using the same ioctl() number. */
5694 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5700 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5703 new_attr = (old_attr & ~mask) | (value & mask);
5704 if (new_attr == old_attr)
5707 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5713 int chattr_path(const char *p, unsigned value, unsigned mask) {
5714 _cleanup_close_ int fd = -1;
5721 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5725 return chattr_fd(fd, value, mask);
5728 int read_attr_fd(int fd, unsigned *ret) {
5733 if (fstat(fd, &st) < 0)
5736 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5739 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5745 int read_attr_path(const char *p, unsigned *ret) {
5746 _cleanup_close_ int fd = -1;
5751 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5755 return read_attr_fd(fd, ret);
5758 static size_t nul_length(const uint8_t *p, size_t sz) {
5773 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
5774 const uint8_t *q, *w, *e;
5782 n = nul_length(q, e - q);
5784 /* If there are more than the specified run length of
5785 * NUL bytes, or if this is the beginning or the end
5786 * of the buffer, then seek instead of write */
5787 if ((n > run_length) ||
5788 (n > 0 && q == p) ||
5789 (n > 0 && q + n >= e)) {
5791 l = write(fd, w, q - w);
5798 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
5810 l = write(fd, w, q - w);
5817 return q - (const uint8_t*) p;
5820 void sigkill_wait(pid_t *pid) {
5826 if (kill(*pid, SIGKILL) > 0)
5827 (void) wait_for_terminate(*pid, NULL);
5830 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
5831 int a = 0, b = 0, c = 0;
5841 if (!strchr(*p, '>'))
5844 if ((*p)[2] == '>') {
5845 c = undecchar((*p)[1]);
5847 } else if ((*p)[3] == '>') {
5848 b = undecchar((*p)[1]);
5849 c = undecchar((*p)[2]);
5851 } else if ((*p)[4] == '>') {
5852 a = undecchar((*p)[1]);
5853 b = undecchar((*p)[2]);
5854 c = undecchar((*p)[3]);
5859 if (a < 0 || b < 0 || c < 0 ||
5860 (!with_facility && (a || b || c > 7)))
5864 *priority = a*100 + b*10 + c;
5866 *priority = (*priority & LOG_FACMASK) | c;
5872 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
5878 for (i = 0; i < len; ++i)
5879 if (streq_ptr(table[i], key))
5885 void cmsg_close_all(struct msghdr *mh) {
5886 struct cmsghdr *cmsg;
5890 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
5891 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
5892 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
5895 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
5899 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
5903 /* Even though renameat2() exists since Linux 3.15, btrfs added
5904 * support for it later. If it is not implemented, fallback to another
5906 if (errno != EINVAL)
5909 /* The link()/unlink() fallback does not work on directories. But
5910 * renameat() without RENAME_NOREPLACE gives the same semantics on
5911 * directories, except when newpath is an *empty* directory. This is
5913 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
5914 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
5915 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
5916 return ret >= 0 ? 0 : -errno;
5919 /* If it is not a directory, use the link()/unlink() fallback. */
5920 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
5924 ret = unlinkat(olddirfd, oldpath, 0);
5926 /* backup errno before the following unlinkat() alters it */
5928 (void) unlinkat(newdirfd, newpath, 0);
5936 char *shell_maybe_quote(const char *s) {
5942 /* Encloses a string in double quotes if necessary to make it
5943 * OK as shell string. */
5945 for (p = s; *p; p++)
5948 strchr(SHELL_NEED_QUOTES, *p))
5954 r = new(char, 1+strlen(s)*2+1+1);
5960 t = mempcpy(t, s, p - s);
5964 if (strchr(SHELL_NEED_ESCAPE, *p))
5976 int parse_mode(const char *s, mode_t *ret) {
5984 l = strtol(s, &x, 8);
5988 if (!x || x == s || *x)
5990 if (l < 0 || l > 07777)
5997 int mount_move_root(const char *path) {
6000 if (chdir(path) < 0)
6003 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
6006 if (chroot(".") < 0)
6015 int reset_uid_gid(void) {
6017 if (setgroups(0, NULL) < 0)
6020 if (setresgid(0, 0, 0) < 0)
6023 if (setresuid(0, 0, 0) < 0)