1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
41 #include <sys/prctl.h>
42 #include <sys/utsname.h>
44 #include <netinet/ip.h>
51 #include <sys/mount.h>
52 #include <linux/magic.h>
56 #include <sys/personality.h>
57 #include <sys/xattr.h>
58 #include <sys/statvfs.h>
62 /* When we include libgen.h because we need dirname() we immediately
63 * undefine basename() since libgen.h defines it as a macro to the XDG
64 * version which is really broken. */
68 #ifdef HAVE_SYS_AUXV_H
80 #include "path-util.h"
81 #include "exit-status.h"
85 #include "device-nodes.h"
90 #include "sparse-endian.h"
91 #include "formats-util.h"
92 #include "process-util.h"
93 #include "random-util.h"
94 #include "terminal-util.h"
96 /* Put this test here for a lack of better place */
97 assert_cc(EAGAIN == EWOULDBLOCK);
100 char **saved_argv = NULL;
102 size_t page_size(void) {
103 static thread_local size_t pgsz = 0;
106 if (_likely_(pgsz > 0))
109 r = sysconf(_SC_PAGESIZE);
116 bool streq_ptr(const char *a, const char *b) {
118 /* Like streq(), but tries to make sense of NULL pointers */
129 char* endswith(const char *s, const char *postfix) {
136 pl = strlen(postfix);
139 return (char*) s + sl;
144 if (memcmp(s + sl - pl, postfix, pl) != 0)
147 return (char*) s + sl - pl;
150 char* first_word(const char *s, const char *word) {
157 /* Checks if the string starts with the specified word, either
158 * followed by NUL or by whitespace. Returns a pointer to the
159 * NUL or the first character after the whitespace. */
170 if (memcmp(s, word, wl) != 0)
177 if (!strchr(WHITESPACE, *p))
180 p += strspn(p, WHITESPACE);
184 size_t cescape_char(char c, char *buf) {
185 char * buf_old = buf;
231 /* For special chars we prefer octal over
232 * hexadecimal encoding, simply because glib's
233 * g_strescape() does the same */
234 if ((c < ' ') || (c >= 127)) {
236 *(buf++) = octchar((unsigned char) c >> 6);
237 *(buf++) = octchar((unsigned char) c >> 3);
238 *(buf++) = octchar((unsigned char) c);
244 return buf - buf_old;
247 int close_nointr(int fd) {
254 * Just ignore EINTR; a retry loop is the wrong thing to do on
257 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
258 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
259 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
260 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
268 int safe_close(int fd) {
271 * Like close_nointr() but cannot fail. Guarantees errno is
272 * unchanged. Is a NOP with negative fds passed, and returns
273 * -1, so that it can be used in this syntax:
275 * fd = safe_close(fd);
281 /* The kernel might return pretty much any error code
282 * via close(), but the fd will be closed anyway. The
283 * only condition we want to check for here is whether
284 * the fd was invalid at all... */
286 assert_se(close_nointr(fd) != -EBADF);
292 void close_many(const int fds[], unsigned n_fd) {
295 assert(fds || n_fd <= 0);
297 for (i = 0; i < n_fd; i++)
301 int unlink_noerrno(const char *path) {
312 int parse_boolean(const char *v) {
315 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
317 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
323 int parse_pid(const char *s, pid_t* ret_pid) {
324 unsigned long ul = 0;
331 r = safe_atolu(s, &ul);
337 if ((unsigned long) pid != ul)
347 int parse_uid(const char *s, uid_t* ret_uid) {
348 unsigned long ul = 0;
355 r = safe_atolu(s, &ul);
361 if ((unsigned long) uid != ul)
364 /* Some libc APIs use UID_INVALID as special placeholder */
365 if (uid == (uid_t) 0xFFFFFFFF)
368 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
369 if (uid == (uid_t) 0xFFFF)
376 int safe_atou(const char *s, unsigned *ret_u) {
384 l = strtoul(s, &x, 0);
386 if (!x || x == s || *x || errno)
387 return errno > 0 ? -errno : -EINVAL;
389 if ((unsigned long) (unsigned) l != l)
392 *ret_u = (unsigned) l;
396 int safe_atoi(const char *s, int *ret_i) {
404 l = strtol(s, &x, 0);
406 if (!x || x == s || *x || errno)
407 return errno > 0 ? -errno : -EINVAL;
409 if ((long) (int) l != l)
416 int safe_atou8(const char *s, uint8_t *ret) {
424 l = strtoul(s, &x, 0);
426 if (!x || x == s || *x || errno)
427 return errno > 0 ? -errno : -EINVAL;
429 if ((unsigned long) (uint8_t) l != l)
436 int safe_atou16(const char *s, uint16_t *ret) {
444 l = strtoul(s, &x, 0);
446 if (!x || x == s || *x || errno)
447 return errno > 0 ? -errno : -EINVAL;
449 if ((unsigned long) (uint16_t) l != l)
456 int safe_atoi16(const char *s, int16_t *ret) {
464 l = strtol(s, &x, 0);
466 if (!x || x == s || *x || errno)
467 return errno > 0 ? -errno : -EINVAL;
469 if ((long) (int16_t) l != l)
476 int safe_atollu(const char *s, long long unsigned *ret_llu) {
478 unsigned long long l;
484 l = strtoull(s, &x, 0);
486 if (!x || x == s || *x || errno)
487 return errno ? -errno : -EINVAL;
493 int safe_atolli(const char *s, long long int *ret_lli) {
501 l = strtoll(s, &x, 0);
503 if (!x || x == s || *x || errno)
504 return errno ? -errno : -EINVAL;
510 int safe_atod(const char *s, double *ret_d) {
518 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
519 if (loc == (locale_t) 0)
523 d = strtod_l(s, &x, loc);
525 if (!x || x == s || *x || errno) {
527 return errno ? -errno : -EINVAL;
535 static size_t strcspn_escaped(const char *s, const char *reject) {
536 bool escaped = false;
539 for (n=0; s[n]; n++) {
542 else if (s[n] == '\\')
544 else if (strchr(reject, s[n]))
548 /* if s ends in \, return index of previous char */
552 /* Split a string into words. */
553 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
559 assert(**state == '\0');
563 current += strspn(current, separator);
569 if (quoted && strchr("\'\"", *current)) {
570 char quotechars[2] = {*current, '\0'};
572 *l = strcspn_escaped(current + 1, quotechars);
573 if (current[*l + 1] == '\0' ||
574 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
575 /* right quote missing or garbage at the end */
579 assert(current[*l + 1] == quotechars[0]);
580 *state = current++ + *l + 2;
582 *l = strcspn_escaped(current, separator);
583 if (current[*l] && !strchr(separator, current[*l])) {
584 /* unfinished escape */
588 *state = current + *l;
590 *l = strcspn(current, separator);
591 *state = current + *l;
597 int fchmod_umask(int fd, mode_t m) {
602 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
608 char *truncate_nl(char *s) {
611 s[strcspn(s, NEWLINE)] = 0;
615 char *strnappend(const char *s, const char *suffix, size_t b) {
623 return strndup(suffix, b);
632 if (b > ((size_t) -1) - a)
635 r = new(char, a+b+1);
640 memcpy(r+a, suffix, b);
646 char *strappend(const char *s, const char *suffix) {
647 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
650 int readlinkat_malloc(int fd, const char *p, char **ret) {
665 n = readlinkat(fd, p, c, l-1);
672 if ((size_t) n < l-1) {
683 int readlink_malloc(const char *p, char **ret) {
684 return readlinkat_malloc(AT_FDCWD, p, ret);
687 int readlink_value(const char *p, char **ret) {
688 _cleanup_free_ char *link = NULL;
692 r = readlink_malloc(p, &link);
696 value = basename(link);
700 value = strdup(value);
709 int readlink_and_make_absolute(const char *p, char **r) {
710 _cleanup_free_ char *target = NULL;
717 j = readlink_malloc(p, &target);
721 k = file_in_same_dir(p, target);
729 int readlink_and_canonicalize(const char *p, char **r) {
736 j = readlink_and_make_absolute(p, &t);
740 s = canonicalize_file_name(t);
747 path_kill_slashes(*r);
752 int reset_all_signal_handlers(void) {
755 for (sig = 1; sig < _NSIG; sig++) {
756 struct sigaction sa = {
757 .sa_handler = SIG_DFL,
758 .sa_flags = SA_RESTART,
761 /* These two cannot be caught... */
762 if (sig == SIGKILL || sig == SIGSTOP)
765 /* On Linux the first two RT signals are reserved by
766 * glibc, and sigaction() will return EINVAL for them. */
767 if ((sigaction(sig, &sa, NULL) < 0))
768 if (errno != EINVAL && r == 0)
775 int reset_signal_mask(void) {
778 if (sigemptyset(&ss) < 0)
781 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
787 char *strstrip(char *s) {
790 /* Drops trailing whitespace. Modifies the string in
791 * place. Returns pointer to first non-space character */
793 s += strspn(s, WHITESPACE);
795 for (e = strchr(s, 0); e > s; e --)
796 if (!strchr(WHITESPACE, e[-1]))
804 char *delete_chars(char *s, const char *bad) {
807 /* Drops all whitespace, regardless where in the string */
809 for (f = s, t = s; *f; f++) {
821 char *file_in_same_dir(const char *path, const char *filename) {
828 /* This removes the last component of path and appends
829 * filename, unless the latter is absolute anyway or the
832 if (path_is_absolute(filename))
833 return strdup(filename);
835 e = strrchr(path, '/');
837 return strdup(filename);
839 k = strlen(filename);
840 ret = new(char, (e + 1 - path) + k + 1);
844 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
848 int rmdir_parents(const char *path, const char *stop) {
857 /* Skip trailing slashes */
858 while (l > 0 && path[l-1] == '/')
864 /* Skip last component */
865 while (l > 0 && path[l-1] != '/')
868 /* Skip trailing slashes */
869 while (l > 0 && path[l-1] == '/')
875 if (!(t = strndup(path, l)))
878 if (path_startswith(stop, t)) {
894 char hexchar(int x) {
895 static const char table[16] = "0123456789abcdef";
897 return table[x & 15];
900 int unhexchar(char c) {
902 if (c >= '0' && c <= '9')
905 if (c >= 'a' && c <= 'f')
908 if (c >= 'A' && c <= 'F')
914 char *hexmem(const void *p, size_t l) {
918 z = r = malloc(l * 2 + 1);
922 for (x = p; x < (const uint8_t*) p + l; x++) {
923 *(z++) = hexchar(*x >> 4);
924 *(z++) = hexchar(*x & 15);
931 void *unhexmem(const char *p, size_t l) {
937 z = r = malloc((l + 1) / 2 + 1);
941 for (x = p; x < p + l; x += 2) {
950 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
957 char octchar(int x) {
958 return '0' + (x & 7);
961 int unoctchar(char c) {
963 if (c >= '0' && c <= '7')
969 char decchar(int x) {
970 return '0' + (x % 10);
973 int undecchar(char c) {
975 if (c >= '0' && c <= '9')
981 char *cescape(const char *s) {
987 /* Does C style string escaping. May be reversed with
990 r = new(char, strlen(s)*4 + 1);
994 for (f = s, t = r; *f; f++)
995 t += cescape_char(*f, t);
1002 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1009 /* Unescapes C style. Returns the unescaped character in ret,
1010 * unless we encountered a \u sequence in which case the full
1011 * unicode character is returned in ret_unicode, instead. */
1013 if (length != (size_t) -1 && length < 1)
1050 /* This is an extension of the XDG syntax files */
1055 /* hexadecimal encoding */
1058 if (length != (size_t) -1 && length < 3)
1061 a = unhexchar(p[1]);
1065 b = unhexchar(p[2]);
1069 /* Don't allow NUL bytes */
1070 if (a == 0 && b == 0)
1073 *ret = (char) ((a << 4U) | b);
1079 /* C++11 style 16bit unicode */
1085 if (length != (size_t) -1 && length < 5)
1088 for (i = 0; i < 4; i++) {
1089 a[i] = unhexchar(p[1 + i]);
1094 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1096 /* Don't allow 0 chars */
1115 /* C++11 style 32bit unicode */
1121 if (length != (size_t) -1 && length < 9)
1124 for (i = 0; i < 8; i++) {
1125 a[i] = unhexchar(p[1 + i]);
1130 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1131 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1133 /* Don't allow 0 chars */
1137 /* Don't allow invalid code points */
1138 if (!unichar_is_valid(c))
1163 /* octal encoding */
1167 if (length != (size_t) -1 && length < 4)
1170 a = unoctchar(p[0]);
1174 b = unoctchar(p[1]);
1178 c = unoctchar(p[2]);
1182 /* don't allow NUL bytes */
1183 if (a == 0 && b == 0 && c == 0)
1186 /* Don't allow bytes above 255 */
1187 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1203 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1211 /* Undoes C style string escaping, and optionally prefixes it. */
1213 pl = prefix ? strlen(prefix) : 0;
1215 r = new(char, pl+length+1);
1220 memcpy(r, prefix, pl);
1222 for (f = s, t = r + pl; f < s + length; f++) {
1228 remaining = s + length - f;
1229 assert(remaining > 0);
1232 /* A literal literal, copy verbatim */
1237 if (remaining == 1) {
1238 if (flags & UNESCAPE_RELAX) {
1239 /* A trailing backslash, copy verbatim */
1248 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1250 if (flags & UNESCAPE_RELAX) {
1251 /* Invalid escape code, let's take it literal then */
1261 /* Non-Unicode? Let's encode this directly */
1264 /* Unicode? Then let's encode this in UTF-8 */
1265 t += utf8_encode_unichar(t, u);
1276 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1277 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1280 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1281 return cunescape_length(s, strlen(s), flags, ret);
1284 char *xescape(const char *s, const char *bad) {
1288 /* Escapes all chars in bad, in addition to \ and all special
1289 * chars, in \xFF style escaping. May be reversed with
1292 r = new(char, strlen(s) * 4 + 1);
1296 for (f = s, t = r; *f; f++) {
1298 if ((*f < ' ') || (*f >= 127) ||
1299 (*f == '\\') || strchr(bad, *f)) {
1302 *(t++) = hexchar(*f >> 4);
1303 *(t++) = hexchar(*f);
1313 char *ascii_strlower(char *t) {
1318 for (p = t; *p; p++)
1319 if (*p >= 'A' && *p <= 'Z')
1320 *p = *p - 'A' + 'a';
1325 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1329 filename[0] == '.' ||
1330 streq(filename, "lost+found") ||
1331 streq(filename, "aquota.user") ||
1332 streq(filename, "aquota.group") ||
1333 endswith(filename, ".rpmnew") ||
1334 endswith(filename, ".rpmsave") ||
1335 endswith(filename, ".rpmorig") ||
1336 endswith(filename, ".dpkg-old") ||
1337 endswith(filename, ".dpkg-new") ||
1338 endswith(filename, ".dpkg-tmp") ||
1339 endswith(filename, ".dpkg-dist") ||
1340 endswith(filename, ".dpkg-bak") ||
1341 endswith(filename, ".dpkg-backup") ||
1342 endswith(filename, ".dpkg-remove") ||
1343 endswith(filename, ".swp");
1346 bool hidden_file(const char *filename) {
1349 if (endswith(filename, "~"))
1352 return hidden_file_allow_backup(filename);
1355 int fd_nonblock(int fd, bool nonblock) {
1360 flags = fcntl(fd, F_GETFL, 0);
1365 nflags = flags | O_NONBLOCK;
1367 nflags = flags & ~O_NONBLOCK;
1369 if (nflags == flags)
1372 if (fcntl(fd, F_SETFL, nflags) < 0)
1378 int fd_cloexec(int fd, bool cloexec) {
1383 flags = fcntl(fd, F_GETFD, 0);
1388 nflags = flags | FD_CLOEXEC;
1390 nflags = flags & ~FD_CLOEXEC;
1392 if (nflags == flags)
1395 if (fcntl(fd, F_SETFD, nflags) < 0)
1401 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1404 assert(n_fdset == 0 || fdset);
1406 for (i = 0; i < n_fdset; i++)
1413 int close_all_fds(const int except[], unsigned n_except) {
1414 _cleanup_closedir_ DIR *d = NULL;
1418 assert(n_except == 0 || except);
1420 d = opendir("/proc/self/fd");
1425 /* When /proc isn't available (for example in chroots)
1426 * the fallback is brute forcing through the fd
1429 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1430 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1432 if (fd_in_set(fd, except, n_except))
1435 if (close_nointr(fd) < 0)
1436 if (errno != EBADF && r == 0)
1443 while ((de = readdir(d))) {
1446 if (hidden_file(de->d_name))
1449 if (safe_atoi(de->d_name, &fd) < 0)
1450 /* Let's better ignore this, just in case */
1459 if (fd_in_set(fd, except, n_except))
1462 if (close_nointr(fd) < 0) {
1463 /* Valgrind has its own FD and doesn't want to have it closed */
1464 if (errno != EBADF && r == 0)
1472 bool chars_intersect(const char *a, const char *b) {
1475 /* Returns true if any of the chars in a are in b. */
1476 for (p = a; *p; p++)
1483 bool fstype_is_network(const char *fstype) {
1484 static const char table[] =
1499 x = startswith(fstype, "fuse.");
1503 return nulstr_contains(table, fstype);
1506 int flush_fd(int fd) {
1507 struct pollfd pollfd = {
1517 r = poll(&pollfd, 1, 0);
1527 l = read(fd, buf, sizeof(buf));
1533 if (errno == EAGAIN)
1542 int sigaction_many(const struct sigaction *sa, ...) {
1547 while ((sig = va_arg(ap, int)) > 0)
1548 if (sigaction(sig, sa, NULL) < 0)
1555 int ignore_signals(int sig, ...) {
1556 struct sigaction sa = {
1557 .sa_handler = SIG_IGN,
1558 .sa_flags = SA_RESTART,
1563 if (sigaction(sig, &sa, NULL) < 0)
1567 while ((sig = va_arg(ap, int)) > 0)
1568 if (sigaction(sig, &sa, NULL) < 0)
1575 int default_signals(int sig, ...) {
1576 struct sigaction sa = {
1577 .sa_handler = SIG_DFL,
1578 .sa_flags = SA_RESTART,
1583 if (sigaction(sig, &sa, NULL) < 0)
1587 while ((sig = va_arg(ap, int)) > 0)
1588 if (sigaction(sig, &sa, NULL) < 0)
1595 void safe_close_pair(int p[]) {
1599 /* Special case pairs which use the same fd in both
1601 p[0] = p[1] = safe_close(p[0]);
1605 p[0] = safe_close(p[0]);
1606 p[1] = safe_close(p[1]);
1609 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1616 while (nbytes > 0) {
1619 k = read(fd, p, nbytes);
1624 if (errno == EAGAIN && do_poll) {
1626 /* We knowingly ignore any return value here,
1627 * and expect that any error/EOF is reported
1630 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1634 return n > 0 ? n : -errno;
1648 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1651 n = loop_read(fd, buf, nbytes, do_poll);
1654 if ((size_t) n != nbytes)
1659 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1660 const uint8_t *p = buf;
1667 while (nbytes > 0) {
1670 k = write(fd, p, nbytes);
1675 if (errno == EAGAIN && do_poll) {
1676 /* We knowingly ignore any return value here,
1677 * and expect that any error/EOF is reported
1680 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1687 if (k == 0) /* Can't really happen */
1697 int parse_size(const char *t, off_t base, off_t *size) {
1699 /* Soo, sometimes we want to parse IEC binary suffxies, and
1700 * sometimes SI decimal suffixes. This function can parse
1701 * both. Which one is the right way depends on the
1702 * context. Wikipedia suggests that SI is customary for
1703 * hardrware metrics and network speeds, while IEC is
1704 * customary for most data sizes used by software and volatile
1705 * (RAM) memory. Hence be careful which one you pick!
1707 * In either case we use just K, M, G as suffix, and not Ki,
1708 * Mi, Gi or so (as IEC would suggest). That's because that's
1709 * frickin' ugly. But this means you really need to make sure
1710 * to document which base you are parsing when you use this
1715 unsigned long long factor;
1718 static const struct table iec[] = {
1719 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1720 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1721 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1722 { "G", 1024ULL*1024ULL*1024ULL },
1723 { "M", 1024ULL*1024ULL },
1729 static const struct table si[] = {
1730 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1731 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1732 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1733 { "G", 1000ULL*1000ULL*1000ULL },
1734 { "M", 1000ULL*1000ULL },
1740 const struct table *table;
1742 unsigned long long r = 0;
1743 unsigned n_entries, start_pos = 0;
1746 assert(base == 1000 || base == 1024);
1751 n_entries = ELEMENTSOF(si);
1754 n_entries = ELEMENTSOF(iec);
1760 unsigned long long l2;
1766 l = strtoll(p, &e, 10);
1779 if (*e >= '0' && *e <= '9') {
1782 /* strotoull itself would accept space/+/- */
1783 l2 = strtoull(e, &e2, 10);
1785 if (errno == ERANGE)
1788 /* Ignore failure. E.g. 10.M is valid */
1795 e += strspn(e, WHITESPACE);
1797 for (i = start_pos; i < n_entries; i++)
1798 if (startswith(e, table[i].suffix)) {
1799 unsigned long long tmp;
1800 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1802 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1803 if (tmp > ULLONG_MAX - r)
1807 if ((unsigned long long) (off_t) r != r)
1810 p = e + strlen(table[i].suffix);
1826 bool is_device_path(const char *path) {
1828 /* Returns true on paths that refer to a device, either in
1829 * sysfs or in /dev */
1832 path_startswith(path, "/dev/") ||
1833 path_startswith(path, "/sys/");
1836 int dir_is_empty(const char *path) {
1837 _cleanup_closedir_ DIR *d;
1848 if (!de && errno != 0)
1854 if (!hidden_file(de->d_name))
1859 char* dirname_malloc(const char *path) {
1860 char *d, *dir, *dir2;
1877 void rename_process(const char name[8]) {
1880 /* This is a like a poor man's setproctitle(). It changes the
1881 * comm field, argv[0], and also the glibc's internally used
1882 * name of the process. For the first one a limit of 16 chars
1883 * applies, to the second one usually one of 10 (i.e. length
1884 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1885 * "systemd"). If you pass a longer string it will be
1888 prctl(PR_SET_NAME, name);
1890 if (program_invocation_name)
1891 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1893 if (saved_argc > 0) {
1897 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1899 for (i = 1; i < saved_argc; i++) {
1903 memzero(saved_argv[i], strlen(saved_argv[i]));
1908 void sigset_add_many(sigset_t *ss, ...) {
1915 while ((sig = va_arg(ap, int)) > 0)
1916 assert_se(sigaddset(ss, sig) == 0);
1920 int sigprocmask_many(int how, ...) {
1925 assert_se(sigemptyset(&ss) == 0);
1928 while ((sig = va_arg(ap, int)) > 0)
1929 assert_se(sigaddset(&ss, sig) == 0);
1932 if (sigprocmask(how, &ss, NULL) < 0)
1938 char* gethostname_malloc(void) {
1941 assert_se(uname(&u) >= 0);
1943 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
1944 return strdup(u.nodename);
1946 return strdup(u.sysname);
1949 bool hostname_is_set(void) {
1952 assert_se(uname(&u) >= 0);
1954 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
1957 char *lookup_uid(uid_t uid) {
1960 _cleanup_free_ char *buf = NULL;
1961 struct passwd pwbuf, *pw = NULL;
1963 /* Shortcut things to avoid NSS lookups */
1965 return strdup("root");
1967 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1971 buf = malloc(bufsize);
1975 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1976 return strdup(pw->pw_name);
1978 if (asprintf(&name, UID_FMT, uid) < 0)
1984 char* getlogname_malloc(void) {
1988 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1993 return lookup_uid(uid);
1996 char *getusername_malloc(void) {
2003 return lookup_uid(getuid());
2006 bool is_temporary_fs(const struct statfs *s) {
2009 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2010 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2013 int fd_is_temporary_fs(int fd) {
2016 if (fstatfs(fd, &s) < 0)
2019 return is_temporary_fs(&s);
2022 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2025 /* Under the assumption that we are running privileged we
2026 * first change the access mode and only then hand out
2027 * ownership to avoid a window where access is too open. */
2029 if (mode != MODE_INVALID)
2030 if (chmod(path, mode) < 0)
2033 if (uid != UID_INVALID || gid != GID_INVALID)
2034 if (chown(path, uid, gid) < 0)
2040 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2043 /* Under the assumption that we are running privileged we
2044 * first change the access mode and only then hand out
2045 * ownership to avoid a window where access is too open. */
2047 if (mode != MODE_INVALID)
2048 if (fchmod(fd, mode) < 0)
2051 if (uid != UID_INVALID || gid != GID_INVALID)
2052 if (fchown(fd, uid, gid) < 0)
2058 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2062 /* Allocates the cpuset in the right size */
2065 if (!(r = CPU_ALLOC(n)))
2068 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2069 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2079 if (errno != EINVAL)
2086 char *replace_env(const char *format, char **env) {
2093 const char *e, *word = format;
2098 for (e = format; *e; e ++) {
2109 k = strnappend(r, word, e-word-1);
2119 } else if (*e == '$') {
2120 k = strnappend(r, word, e-word);
2137 t = strempty(strv_env_get_n(env, word+2, e-word-2));
2139 k = strappend(r, t);
2153 k = strnappend(r, word, e-word);
2165 char **replace_env_argv(char **argv, char **env) {
2167 unsigned k = 0, l = 0;
2169 l = strv_length(argv);
2171 ret = new(char*, l+1);
2175 STRV_FOREACH(i, argv) {
2177 /* If $FOO appears as single word, replace it by the split up variable */
2178 if ((*i)[0] == '$' && (*i)[1] != '{') {
2180 char **w, **m = NULL;
2183 e = strv_env_get(env, *i+1);
2187 r = strv_split_quoted(&m, e, UNQUOTE_RELAX);
2199 w = realloc(ret, sizeof(char*) * (l+1));
2209 memcpy(ret + k, m, q * sizeof(char*));
2217 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
2218 ret[k] = replace_env(*i, env);
2230 int files_same(const char *filea, const char *fileb) {
2233 if (stat(filea, &a) < 0)
2236 if (stat(fileb, &b) < 0)
2239 return a.st_dev == b.st_dev &&
2240 a.st_ino == b.st_ino;
2243 int running_in_chroot(void) {
2246 ret = files_same("/proc/1/root", "/");
2253 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2258 assert(percent <= 100);
2259 assert(new_length >= 3);
2261 if (old_length <= 3 || old_length <= new_length)
2262 return strndup(s, old_length);
2264 r = new0(char, new_length+1);
2268 x = (new_length * percent) / 100;
2270 if (x > new_length - 3)
2278 s + old_length - (new_length - x - 3),
2279 new_length - x - 3);
2284 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2288 unsigned k, len, len2;
2291 assert(percent <= 100);
2292 assert(new_length >= 3);
2294 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2295 if (ascii_is_valid(s))
2296 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2298 if (old_length <= 3 || old_length <= new_length)
2299 return strndup(s, old_length);
2301 x = (new_length * percent) / 100;
2303 if (x > new_length - 3)
2307 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2310 c = utf8_encoded_to_unichar(i);
2313 k += unichar_iswide(c) ? 2 : 1;
2316 if (k > x) /* last character was wide and went over quota */
2319 for (j = s + old_length; k < new_length && j > i; ) {
2322 j = utf8_prev_char(j);
2323 c = utf8_encoded_to_unichar(j);
2326 k += unichar_iswide(c) ? 2 : 1;
2330 /* we don't actually need to ellipsize */
2332 return memdup(s, old_length + 1);
2334 /* make space for ellipsis */
2335 j = utf8_next_char(j);
2338 len2 = s + old_length - j;
2339 e = new(char, len + 3 + len2 + 1);
2344 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2345 old_length, new_length, x, len, len2, k);
2349 e[len] = 0xe2; /* tri-dot ellipsis: … */
2353 memcpy(e + len + 3, j, len2 + 1);
2358 char *ellipsize(const char *s, size_t length, unsigned percent) {
2359 return ellipsize_mem(s, strlen(s), length, percent);
2362 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2363 _cleanup_close_ int fd;
2369 mkdir_parents(path, 0755);
2371 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2376 r = fchmod(fd, mode);
2381 if (uid != UID_INVALID || gid != GID_INVALID) {
2382 r = fchown(fd, uid, gid);
2387 if (stamp != USEC_INFINITY) {
2388 struct timespec ts[2];
2390 timespec_store(&ts[0], stamp);
2392 r = futimens(fd, ts);
2394 r = futimens(fd, NULL);
2401 int touch(const char *path) {
2402 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2405 static char *unquote(const char *s, const char* quotes) {
2409 /* This is rather stupid, simply removes the heading and
2410 * trailing quotes if there is one. Doesn't care about
2411 * escaping or anything.
2413 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2419 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2420 return strndup(s+1, l-2);
2425 noreturn void freeze(void) {
2427 /* Make sure nobody waits for us on a socket anymore */
2428 close_all_fds(NULL, 0);
2436 bool null_or_empty(struct stat *st) {
2439 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2442 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2448 int null_or_empty_path(const char *fn) {
2453 if (stat(fn, &st) < 0)
2456 return null_or_empty(&st);
2459 int null_or_empty_fd(int fd) {
2464 if (fstat(fd, &st) < 0)
2467 return null_or_empty(&st);
2470 DIR *xopendirat(int fd, const char *name, int flags) {
2474 assert(!(flags & O_CREAT));
2476 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2489 int signal_from_string_try_harder(const char *s) {
2493 signo = signal_from_string(s);
2495 if (startswith(s, "SIG"))
2496 return signal_from_string(s+3);
2501 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2502 _cleanup_free_ char *t = NULL, *u = NULL;
2505 u = unquote(tagvalue, QUOTES);
2509 enc_len = strlen(u) * 4 + 1;
2510 t = new(char, enc_len);
2514 if (encode_devnode_name(u, t, enc_len) < 0)
2517 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2520 char *fstab_node_to_udev_node(const char *p) {
2523 if (startswith(p, "LABEL="))
2524 return tag_to_udev_node(p+6, "label");
2526 if (startswith(p, "UUID="))
2527 return tag_to_udev_node(p+5, "uuid");
2529 if (startswith(p, "PARTUUID="))
2530 return tag_to_udev_node(p+9, "partuuid");
2532 if (startswith(p, "PARTLABEL="))
2533 return tag_to_udev_node(p+10, "partlabel");
2538 bool dirent_is_file(const struct dirent *de) {
2541 if (hidden_file(de->d_name))
2544 if (de->d_type != DT_REG &&
2545 de->d_type != DT_LNK &&
2546 de->d_type != DT_UNKNOWN)
2552 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2555 if (de->d_type != DT_REG &&
2556 de->d_type != DT_LNK &&
2557 de->d_type != DT_UNKNOWN)
2560 if (hidden_file_allow_backup(de->d_name))
2563 return endswith(de->d_name, suffix);
2566 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2567 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2568 _cleanup_set_free_free_ Set *seen = NULL;
2571 /* We fork this all off from a child process so that we can
2572 * somewhat cleanly make use of SIGALRM to set a time limit */
2574 reset_all_signal_handlers();
2575 reset_signal_mask();
2577 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2579 pids = hashmap_new(NULL);
2583 seen = set_new(&string_hash_ops);
2587 STRV_FOREACH(directory, directories) {
2588 _cleanup_closedir_ DIR *d;
2591 d = opendir(*directory);
2593 if (errno == ENOENT)
2596 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2599 FOREACH_DIRENT(de, d, break) {
2600 _cleanup_free_ char *path = NULL;
2604 if (!dirent_is_file(de))
2607 if (set_contains(seen, de->d_name)) {
2608 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2612 r = set_put_strdup(seen, de->d_name);
2616 path = strjoin(*directory, "/", de->d_name, NULL);
2620 if (null_or_empty_path(path)) {
2621 log_debug("%s is empty (a mask).", path);
2627 log_error_errno(errno, "Failed to fork: %m");
2629 } else if (pid == 0) {
2632 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2642 return log_error_errno(errno, "Failed to execute %s: %m", path);
2645 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2647 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2654 /* Abort execution of this process after the timout. We simply
2655 * rely on SIGALRM as default action terminating the process,
2656 * and turn on alarm(). */
2658 if (timeout != USEC_INFINITY)
2659 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2661 while (!hashmap_isempty(pids)) {
2662 _cleanup_free_ char *path = NULL;
2665 pid = PTR_TO_UINT(hashmap_first_key(pids));
2668 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2671 wait_for_terminate_and_warn(path, pid, true);
2677 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2681 char **dirs = (char**) directories;
2683 assert(!strv_isempty(dirs));
2685 name = basename(dirs[0]);
2686 assert(!isempty(name));
2688 /* Executes all binaries in the directories in parallel and waits
2689 * for them to finish. Optionally a timeout is applied. If a file
2690 * with the same name exists in more than one directory, the
2691 * earliest one wins. */
2693 executor_pid = fork();
2694 if (executor_pid < 0) {
2695 log_error_errno(errno, "Failed to fork: %m");
2698 } else if (executor_pid == 0) {
2699 r = do_execute(dirs, timeout, argv);
2700 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2703 wait_for_terminate_and_warn(name, executor_pid, true);
2706 bool nulstr_contains(const char*nulstr, const char *needle) {
2712 NULSTR_FOREACH(i, nulstr)
2713 if (streq(i, needle))
2719 bool plymouth_running(void) {
2720 return access("/run/plymouth/pid", F_OK) >= 0;
2723 char* strshorten(char *s, size_t l) {
2732 static bool hostname_valid_char(char c) {
2734 (c >= 'a' && c <= 'z') ||
2735 (c >= 'A' && c <= 'Z') ||
2736 (c >= '0' && c <= '9') ||
2742 bool hostname_is_valid(const char *s) {
2749 /* Doesn't accept empty hostnames, hostnames with trailing or
2750 * leading dots, and hostnames with multiple dots in a
2751 * sequence. Also ensures that the length stays below
2754 for (p = s, dot = true; *p; p++) {
2761 if (!hostname_valid_char(*p))
2771 if (p-s > HOST_NAME_MAX)
2777 char* hostname_cleanup(char *s, bool lowercase) {
2781 for (p = s, d = s, dot = true; *p; p++) {
2788 } else if (hostname_valid_char(*p)) {
2789 *(d++) = lowercase ? tolower(*p) : *p;
2800 strshorten(s, HOST_NAME_MAX);
2805 bool machine_name_is_valid(const char *s) {
2807 if (!hostname_is_valid(s))
2810 /* Machine names should be useful hostnames, but also be
2811 * useful in unit names, hence we enforce a stricter length
2820 int pipe_eof(int fd) {
2821 struct pollfd pollfd = {
2823 .events = POLLIN|POLLHUP,
2828 r = poll(&pollfd, 1, 0);
2835 return pollfd.revents & POLLHUP;
2838 int fd_wait_for_event(int fd, int event, usec_t t) {
2840 struct pollfd pollfd = {
2848 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2855 return pollfd.revents;
2858 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2867 r = tempfn_xxxxxx(path, &t);
2871 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2877 f = fdopen(fd, "we");
2890 int symlink_atomic(const char *from, const char *to) {
2891 _cleanup_free_ char *t = NULL;
2897 r = tempfn_random(to, &t);
2901 if (symlink(from, t) < 0)
2904 if (rename(t, to) < 0) {
2912 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2913 _cleanup_free_ char *t = NULL;
2918 r = tempfn_random(path, &t);
2922 if (mknod(t, mode, dev) < 0)
2925 if (rename(t, path) < 0) {
2933 int mkfifo_atomic(const char *path, mode_t mode) {
2934 _cleanup_free_ char *t = NULL;
2939 r = tempfn_random(path, &t);
2943 if (mkfifo(t, mode) < 0)
2946 if (rename(t, path) < 0) {
2954 bool display_is_local(const char *display) {
2958 display[0] == ':' &&
2959 display[1] >= '0' &&
2963 int socket_from_display(const char *display, char **path) {
2970 if (!display_is_local(display))
2973 k = strspn(display+1, "0123456789");
2975 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2979 c = stpcpy(f, "/tmp/.X11-unix/X");
2980 memcpy(c, display+1, k);
2989 const char **username,
2990 uid_t *uid, gid_t *gid,
2992 const char **shell) {
3000 /* We enforce some special rules for uid=0: in order to avoid
3001 * NSS lookups for root we hardcode its data. */
3003 if (streq(*username, "root") || streq(*username, "0")) {
3021 if (parse_uid(*username, &u) >= 0) {
3025 /* If there are multiple users with the same id, make
3026 * sure to leave $USER to the configured value instead
3027 * of the first occurrence in the database. However if
3028 * the uid was configured by a numeric uid, then let's
3029 * pick the real username from /etc/passwd. */
3031 *username = p->pw_name;
3034 p = getpwnam(*username);
3038 return errno > 0 ? -errno : -ESRCH;
3050 *shell = p->pw_shell;
3055 char* uid_to_name(uid_t uid) {
3060 return strdup("root");
3064 return strdup(p->pw_name);
3066 if (asprintf(&r, UID_FMT, uid) < 0)
3072 char* gid_to_name(gid_t gid) {
3077 return strdup("root");
3081 return strdup(p->gr_name);
3083 if (asprintf(&r, GID_FMT, gid) < 0)
3089 int get_group_creds(const char **groupname, gid_t *gid) {
3095 /* We enforce some special rules for gid=0: in order to avoid
3096 * NSS lookups for root we hardcode its data. */
3098 if (streq(*groupname, "root") || streq(*groupname, "0")) {
3099 *groupname = "root";
3107 if (parse_gid(*groupname, &id) >= 0) {
3112 *groupname = g->gr_name;
3115 g = getgrnam(*groupname);
3119 return errno > 0 ? -errno : -ESRCH;
3127 int in_gid(gid_t gid) {
3129 int ngroups_max, r, i;
3131 if (getgid() == gid)
3134 if (getegid() == gid)
3137 ngroups_max = sysconf(_SC_NGROUPS_MAX);
3138 assert(ngroups_max > 0);
3140 gids = alloca(sizeof(gid_t) * ngroups_max);
3142 r = getgroups(ngroups_max, gids);
3146 for (i = 0; i < r; i++)
3153 int in_group(const char *name) {
3157 r = get_group_creds(&name, &gid);
3164 int glob_exists(const char *path) {
3165 _cleanup_globfree_ glob_t g = {};
3171 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3173 if (k == GLOB_NOMATCH)
3175 else if (k == GLOB_NOSPACE)
3178 return !strv_isempty(g.gl_pathv);
3180 return errno ? -errno : -EIO;
3183 int glob_extend(char ***strv, const char *path) {
3184 _cleanup_globfree_ glob_t g = {};
3189 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3191 if (k == GLOB_NOMATCH)
3193 else if (k == GLOB_NOSPACE)
3195 else if (k != 0 || strv_isempty(g.gl_pathv))
3196 return errno ? -errno : -EIO;
3198 STRV_FOREACH(p, g.gl_pathv) {
3199 k = strv_extend(strv, *p);
3207 int dirent_ensure_type(DIR *d, struct dirent *de) {
3213 if (de->d_type != DT_UNKNOWN)
3216 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3220 S_ISREG(st.st_mode) ? DT_REG :
3221 S_ISDIR(st.st_mode) ? DT_DIR :
3222 S_ISLNK(st.st_mode) ? DT_LNK :
3223 S_ISFIFO(st.st_mode) ? DT_FIFO :
3224 S_ISSOCK(st.st_mode) ? DT_SOCK :
3225 S_ISCHR(st.st_mode) ? DT_CHR :
3226 S_ISBLK(st.st_mode) ? DT_BLK :
3232 int get_files_in_directory(const char *path, char ***list) {
3233 _cleanup_closedir_ DIR *d = NULL;
3234 size_t bufsize = 0, n = 0;
3235 _cleanup_strv_free_ char **l = NULL;
3239 /* Returns all files in a directory in *list, and the number
3240 * of files as return value. If list is NULL returns only the
3252 if (!de && errno != 0)
3257 dirent_ensure_type(d, de);
3259 if (!dirent_is_file(de))
3263 /* one extra slot is needed for the terminating NULL */
3264 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3267 l[n] = strdup(de->d_name);
3278 l = NULL; /* avoid freeing */
3284 char *strjoin(const char *x, ...) {
3298 t = va_arg(ap, const char *);
3303 if (n > ((size_t) -1) - l) {
3327 t = va_arg(ap, const char *);
3341 bool is_main_thread(void) {
3342 static thread_local int cached = 0;
3344 if (_unlikely_(cached == 0))
3345 cached = getpid() == gettid() ? 1 : -1;
3350 int block_get_whole_disk(dev_t d, dev_t *ret) {
3357 /* If it has a queue this is good enough for us */
3358 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3361 r = access(p, F_OK);
3369 /* If it is a partition find the originating device */
3370 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3373 r = access(p, F_OK);
3379 /* Get parent dev_t */
3380 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3383 r = read_one_line_file(p, &s);
3389 r = sscanf(s, "%u:%u", &m, &n);
3395 /* Only return this if it is really good enough for us. */
3396 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3399 r = access(p, F_OK);
3403 *ret = makedev(m, n);
3410 static const char *const ioprio_class_table[] = {
3411 [IOPRIO_CLASS_NONE] = "none",
3412 [IOPRIO_CLASS_RT] = "realtime",
3413 [IOPRIO_CLASS_BE] = "best-effort",
3414 [IOPRIO_CLASS_IDLE] = "idle"
3417 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3419 static const char *const sigchld_code_table[] = {
3420 [CLD_EXITED] = "exited",
3421 [CLD_KILLED] = "killed",
3422 [CLD_DUMPED] = "dumped",
3423 [CLD_TRAPPED] = "trapped",
3424 [CLD_STOPPED] = "stopped",
3425 [CLD_CONTINUED] = "continued",
3428 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3430 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3431 [LOG_FAC(LOG_KERN)] = "kern",
3432 [LOG_FAC(LOG_USER)] = "user",
3433 [LOG_FAC(LOG_MAIL)] = "mail",
3434 [LOG_FAC(LOG_DAEMON)] = "daemon",
3435 [LOG_FAC(LOG_AUTH)] = "auth",
3436 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3437 [LOG_FAC(LOG_LPR)] = "lpr",
3438 [LOG_FAC(LOG_NEWS)] = "news",
3439 [LOG_FAC(LOG_UUCP)] = "uucp",
3440 [LOG_FAC(LOG_CRON)] = "cron",
3441 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3442 [LOG_FAC(LOG_FTP)] = "ftp",
3443 [LOG_FAC(LOG_LOCAL0)] = "local0",
3444 [LOG_FAC(LOG_LOCAL1)] = "local1",
3445 [LOG_FAC(LOG_LOCAL2)] = "local2",
3446 [LOG_FAC(LOG_LOCAL3)] = "local3",
3447 [LOG_FAC(LOG_LOCAL4)] = "local4",
3448 [LOG_FAC(LOG_LOCAL5)] = "local5",
3449 [LOG_FAC(LOG_LOCAL6)] = "local6",
3450 [LOG_FAC(LOG_LOCAL7)] = "local7"
3453 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3455 static const char *const log_level_table[] = {
3456 [LOG_EMERG] = "emerg",
3457 [LOG_ALERT] = "alert",
3458 [LOG_CRIT] = "crit",
3460 [LOG_WARNING] = "warning",
3461 [LOG_NOTICE] = "notice",
3462 [LOG_INFO] = "info",
3463 [LOG_DEBUG] = "debug"
3466 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3468 static const char* const sched_policy_table[] = {
3469 [SCHED_OTHER] = "other",
3470 [SCHED_BATCH] = "batch",
3471 [SCHED_IDLE] = "idle",
3472 [SCHED_FIFO] = "fifo",
3476 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3478 static const char* const rlimit_table[_RLIMIT_MAX] = {
3479 [RLIMIT_CPU] = "LimitCPU",
3480 [RLIMIT_FSIZE] = "LimitFSIZE",
3481 [RLIMIT_DATA] = "LimitDATA",
3482 [RLIMIT_STACK] = "LimitSTACK",
3483 [RLIMIT_CORE] = "LimitCORE",
3484 [RLIMIT_RSS] = "LimitRSS",
3485 [RLIMIT_NOFILE] = "LimitNOFILE",
3486 [RLIMIT_AS] = "LimitAS",
3487 [RLIMIT_NPROC] = "LimitNPROC",
3488 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3489 [RLIMIT_LOCKS] = "LimitLOCKS",
3490 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3491 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3492 [RLIMIT_NICE] = "LimitNICE",
3493 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3494 [RLIMIT_RTTIME] = "LimitRTTIME"
3497 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3499 static const char* const ip_tos_table[] = {
3500 [IPTOS_LOWDELAY] = "low-delay",
3501 [IPTOS_THROUGHPUT] = "throughput",
3502 [IPTOS_RELIABILITY] = "reliability",
3503 [IPTOS_LOWCOST] = "low-cost",
3506 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3508 static const char *const __signal_table[] = {
3525 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3536 [SIGVTALRM] = "VTALRM",
3538 [SIGWINCH] = "WINCH",
3544 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3546 const char *signal_to_string(int signo) {
3547 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3550 name = __signal_to_string(signo);
3554 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3555 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3557 snprintf(buf, sizeof(buf), "%d", signo);
3562 int signal_from_string(const char *s) {
3567 signo = __signal_from_string(s);
3571 if (startswith(s, "RTMIN+")) {
3575 if (safe_atou(s, &u) >= 0) {
3576 signo = (int) u + offset;
3577 if (signo > 0 && signo < _NSIG)
3583 bool kexec_loaded(void) {
3584 bool loaded = false;
3587 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3595 int prot_from_flags(int flags) {
3597 switch (flags & O_ACCMODE) {
3606 return PROT_READ|PROT_WRITE;
3613 char *format_bytes(char *buf, size_t l, off_t t) {
3616 static const struct {
3620 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3621 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3622 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3623 { "G", 1024ULL*1024ULL*1024ULL },
3624 { "M", 1024ULL*1024ULL },
3628 if (t == (off_t) -1)
3631 for (i = 0; i < ELEMENTSOF(table); i++) {
3633 if (t >= table[i].factor) {
3636 (unsigned long long) (t / table[i].factor),
3637 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3644 snprintf(buf, l, "%lluB", (unsigned long long) t);
3652 void* memdup(const void *p, size_t l) {
3665 int fd_inc_sndbuf(int fd, size_t n) {
3667 socklen_t l = sizeof(value);
3669 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3670 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3673 /* If we have the privileges we will ignore the kernel limit. */
3676 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3677 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3683 int fd_inc_rcvbuf(int fd, size_t n) {
3685 socklen_t l = sizeof(value);
3687 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3688 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3691 /* If we have the privileges we will ignore the kernel limit. */
3694 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3695 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3700 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3701 bool stdout_is_tty, stderr_is_tty;
3702 pid_t parent_pid, agent_pid;
3703 sigset_t ss, saved_ss;
3711 /* Spawns a temporary TTY agent, making sure it goes away when
3714 parent_pid = getpid();
3716 /* First we temporarily block all signals, so that the new
3717 * child has them blocked initially. This way, we can be sure
3718 * that SIGTERMs are not lost we might send to the agent. */
3719 assert_se(sigfillset(&ss) >= 0);
3720 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3723 if (agent_pid < 0) {
3724 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3728 if (agent_pid != 0) {
3729 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3736 * Make sure the agent goes away when the parent dies */
3737 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3738 _exit(EXIT_FAILURE);
3740 /* Make sure we actually can kill the agent, if we need to, in
3741 * case somebody invoked us from a shell script that trapped
3742 * SIGTERM or so... */
3743 reset_all_signal_handlers();
3744 reset_signal_mask();
3746 /* Check whether our parent died before we were able
3747 * to set the death signal and unblock the signals */
3748 if (getppid() != parent_pid)
3749 _exit(EXIT_SUCCESS);
3751 /* Don't leak fds to the agent */
3752 close_all_fds(except, n_except);
3754 stdout_is_tty = isatty(STDOUT_FILENO);
3755 stderr_is_tty = isatty(STDERR_FILENO);
3757 if (!stdout_is_tty || !stderr_is_tty) {
3760 /* Detach from stdout/stderr. and reopen
3761 * /dev/tty for them. This is important to
3762 * ensure that when systemctl is started via
3763 * popen() or a similar call that expects to
3764 * read EOF we actually do generate EOF and
3765 * not delay this indefinitely by because we
3766 * keep an unused copy of stdin around. */
3767 fd = open("/dev/tty", O_WRONLY);
3769 log_error_errno(errno, "Failed to open /dev/tty: %m");
3770 _exit(EXIT_FAILURE);
3774 dup2(fd, STDOUT_FILENO);
3777 dup2(fd, STDERR_FILENO);
3783 /* Count arguments */
3785 for (n = 0; va_arg(ap, char*); n++)
3790 l = alloca(sizeof(char *) * (n + 1));
3792 /* Fill in arguments */
3794 for (i = 0; i <= n; i++)
3795 l[i] = va_arg(ap, char*);
3799 _exit(EXIT_FAILURE);
3802 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3803 struct rlimit highest, fixed;
3807 if (setrlimit(resource, rlim) >= 0)
3813 /* So we failed to set the desired setrlimit, then let's try
3814 * to get as close as we can */
3815 assert_se(getrlimit(resource, &highest) == 0);
3817 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3818 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3820 if (setrlimit(resource, &fixed) < 0)
3826 bool http_etag_is_valid(const char *etag) {
3830 if (!endswith(etag, "\""))
3833 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3839 bool http_url_is_valid(const char *url) {
3845 p = startswith(url, "http://");
3847 p = startswith(url, "https://");
3854 return ascii_is_valid(p);
3857 bool documentation_url_is_valid(const char *url) {
3863 if (http_url_is_valid(url))
3866 p = startswith(url, "file:/");
3868 p = startswith(url, "info:");
3870 p = startswith(url, "man:");
3875 return ascii_is_valid(p);
3878 bool in_initrd(void) {
3879 static int saved = -1;
3885 /* We make two checks here:
3887 * 1. the flag file /etc/initrd-release must exist
3888 * 2. the root file system must be a memory file system
3890 * The second check is extra paranoia, since misdetecting an
3891 * initrd can have bad bad consequences due the initrd
3892 * emptying when transititioning to the main systemd.
3895 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3896 statfs("/", &s) >= 0 &&
3897 is_temporary_fs(&s);
3902 int get_home_dir(char **_h) {
3910 /* Take the user specified one */
3911 e = secure_getenv("HOME");
3912 if (e && path_is_absolute(e)) {
3921 /* Hardcode home directory for root to avoid NSS */
3924 h = strdup("/root");
3932 /* Check the database... */
3936 return errno > 0 ? -errno : -ESRCH;
3938 if (!path_is_absolute(p->pw_dir))
3941 h = strdup(p->pw_dir);
3949 int get_shell(char **_s) {
3957 /* Take the user specified one */
3958 e = getenv("SHELL");
3968 /* Hardcode home directory for root to avoid NSS */
3971 s = strdup("/bin/sh");
3979 /* Check the database... */
3983 return errno > 0 ? -errno : -ESRCH;
3985 if (!path_is_absolute(p->pw_shell))
3988 s = strdup(p->pw_shell);
3996 bool filename_is_valid(const char *p) {
4010 if (strlen(p) > FILENAME_MAX)
4016 bool string_is_safe(const char *p) {
4022 for (t = p; *t; t++) {
4023 if (*t > 0 && *t < ' ')
4026 if (strchr("\\\"\'\0x7f", *t))
4034 * Check if a string contains control characters. If 'ok' is non-NULL
4035 * it may be a string containing additional CCs to be considered OK.
4037 bool string_has_cc(const char *p, const char *ok) {
4042 for (t = p; *t; t++) {
4043 if (ok && strchr(ok, *t))
4046 if (*t > 0 && *t < ' ')
4056 bool path_is_safe(const char *p) {
4061 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
4064 if (strlen(p) > PATH_MAX)
4067 /* The following two checks are not really dangerous, but hey, they still are confusing */
4068 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
4071 if (strstr(p, "//"))
4077 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4078 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
4079 int (*compar) (const void *, const void *, void *), void *arg) {
4088 p = (void *)(((const char *) base) + (idx * size));
4089 comparison = compar(key, p, arg);
4092 else if (comparison > 0)
4100 void init_gettext(void) {
4101 setlocale(LC_ALL, "");
4102 textdomain(GETTEXT_PACKAGE);
4105 bool is_locale_utf8(void) {
4107 static int cached_answer = -1;
4109 if (cached_answer >= 0)
4112 if (!setlocale(LC_ALL, "")) {
4113 cached_answer = true;
4117 set = nl_langinfo(CODESET);
4119 cached_answer = true;
4123 if (streq(set, "UTF-8")) {
4124 cached_answer = true;
4128 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4129 * unset and everything can do to UTF-8 nowadays. */
4130 set = setlocale(LC_CTYPE, NULL);
4132 cached_answer = true;
4136 /* Check result, but ignore the result if C was set
4140 !getenv("LC_ALL") &&
4141 !getenv("LC_CTYPE") &&
4145 return (bool) cached_answer;
4148 const char *draw_special_char(DrawSpecialChar ch) {
4149 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
4152 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
4153 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
4154 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
4155 [DRAW_TREE_SPACE] = " ", /* */
4156 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
4157 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
4158 [DRAW_ARROW] = "\342\206\222", /* → */
4159 [DRAW_DASH] = "\342\200\223", /* – */
4162 /* ASCII fallback */ {
4163 [DRAW_TREE_VERTICAL] = "| ",
4164 [DRAW_TREE_BRANCH] = "|-",
4165 [DRAW_TREE_RIGHT] = "`-",
4166 [DRAW_TREE_SPACE] = " ",
4167 [DRAW_TRIANGULAR_BULLET] = ">",
4168 [DRAW_BLACK_CIRCLE] = "*",
4169 [DRAW_ARROW] = "->",
4174 return draw_table[!is_locale_utf8()][ch];
4177 char *strreplace(const char *text, const char *old_string, const char *new_string) {
4180 size_t l, old_len, new_len;
4186 old_len = strlen(old_string);
4187 new_len = strlen(new_string);
4200 if (!startswith(f, old_string)) {
4206 nl = l - old_len + new_len;
4207 a = realloc(r, nl + 1);
4215 t = stpcpy(t, new_string);
4227 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4228 const char *i, *begin = NULL;
4233 } state = STATE_OTHER;
4235 size_t osz = 0, isz;
4241 /* Strips ANSI color and replaces TABs by 8 spaces */
4243 isz = _isz ? *_isz : strlen(*ibuf);
4245 f = open_memstream(&obuf, &osz);
4249 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4254 if (i >= *ibuf + isz) /* EOT */
4256 else if (*i == '\x1B')
4257 state = STATE_ESCAPE;
4258 else if (*i == '\t')
4265 if (i >= *ibuf + isz) { /* EOT */
4268 } else if (*i == '[') {
4269 state = STATE_BRACKET;
4274 state = STATE_OTHER;
4281 if (i >= *ibuf + isz || /* EOT */
4282 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4285 state = STATE_OTHER;
4287 } else if (*i == 'm')
4288 state = STATE_OTHER;
4310 int on_ac_power(void) {
4311 bool found_offline = false, found_online = false;
4312 _cleanup_closedir_ DIR *d = NULL;
4314 d = opendir("/sys/class/power_supply");
4316 return errno == ENOENT ? true : -errno;
4320 _cleanup_close_ int fd = -1, device = -1;
4326 if (!de && errno != 0)
4332 if (hidden_file(de->d_name))
4335 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4337 if (errno == ENOENT || errno == ENOTDIR)
4343 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4345 if (errno == ENOENT)
4351 n = read(fd, contents, sizeof(contents));
4355 if (n != 6 || memcmp(contents, "Mains\n", 6))
4359 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4361 if (errno == ENOENT)
4367 n = read(fd, contents, sizeof(contents));
4371 if (n != 2 || contents[1] != '\n')
4374 if (contents[0] == '1') {
4375 found_online = true;
4377 } else if (contents[0] == '0')
4378 found_offline = true;
4383 return found_online || !found_offline;
4386 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4393 if (!path_strv_resolve_uniq(search, root))
4396 STRV_FOREACH(i, search) {
4397 _cleanup_free_ char *p = NULL;
4401 p = strjoin(root, *i, "/", path, NULL);
4403 p = strjoin(*i, "/", path, NULL);
4413 if (errno != ENOENT)
4420 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4421 _cleanup_strv_free_ char **copy = NULL;
4427 if (path_is_absolute(path)) {
4430 f = fopen(path, mode);
4439 copy = strv_copy((char**) search);
4443 return search_and_fopen_internal(path, mode, root, copy, _f);
4446 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4447 _cleanup_strv_free_ char **s = NULL;
4449 if (path_is_absolute(path)) {
4452 f = fopen(path, mode);
4461 s = strv_split_nulstr(search);
4465 return search_and_fopen_internal(path, mode, root, s, _f);
4468 char *strextend(char **x, ...) {
4475 l = f = *x ? strlen(*x) : 0;
4482 t = va_arg(ap, const char *);
4487 if (n > ((size_t) -1) - l) {
4496 r = realloc(*x, l+1);
4506 t = va_arg(ap, const char *);
4520 char *strrep(const char *s, unsigned n) {
4528 p = r = malloc(l * n + 1);
4532 for (i = 0; i < n; i++)
4539 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4546 if (*allocated >= need)
4549 newalloc = MAX(need * 2, 64u / size);
4550 a = newalloc * size;
4552 /* check for overflows */
4553 if (a < size * need)
4561 *allocated = newalloc;
4565 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4574 q = greedy_realloc(p, allocated, need, size);
4578 if (*allocated > prev)
4579 memzero(q + prev * size, (*allocated - prev) * size);
4584 bool id128_is_valid(const char *s) {
4590 /* Simple formatted 128bit hex string */
4592 for (i = 0; i < l; i++) {
4595 if (!(c >= '0' && c <= '9') &&
4596 !(c >= 'a' && c <= 'z') &&
4597 !(c >= 'A' && c <= 'Z'))
4601 } else if (l == 36) {
4603 /* Formatted UUID */
4605 for (i = 0; i < l; i++) {
4608 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4612 if (!(c >= '0' && c <= '9') &&
4613 !(c >= 'a' && c <= 'z') &&
4614 !(c >= 'A' && c <= 'Z'))
4625 int split_pair(const char *s, const char *sep, char **l, char **r) {
4640 a = strndup(s, x - s);
4644 b = strdup(x + strlen(sep));
4656 int shall_restore_state(void) {
4657 _cleanup_free_ char *value = NULL;
4660 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4666 return parse_boolean(value) != 0;
4669 int proc_cmdline(char **ret) {
4672 if (detect_container(NULL) > 0)
4673 return get_process_cmdline(1, 0, false, ret);
4675 return read_one_line_file("/proc/cmdline", ret);
4678 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4679 _cleanup_free_ char *line = NULL;
4685 r = proc_cmdline(&line);
4691 _cleanup_free_ char *word = NULL;
4694 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4700 /* Filter out arguments that are intended only for the
4702 if (!in_initrd() && startswith(word, "rd."))
4705 value = strchr(word, '=');
4709 r = parse_item(word, value);
4717 int get_proc_cmdline_key(const char *key, char **value) {
4718 _cleanup_free_ char *line = NULL, *ret = NULL;
4725 r = proc_cmdline(&line);
4731 _cleanup_free_ char *word = NULL;
4734 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4740 /* Filter out arguments that are intended only for the
4742 if (!in_initrd() && startswith(word, "rd."))
4746 e = startswith(word, key);
4750 r = free_and_strdup(&ret, e);
4756 if (streq(word, key))
4770 int container_get_leader(const char *machine, pid_t *pid) {
4771 _cleanup_free_ char *s = NULL, *class = NULL;
4779 p = strjoina("/run/systemd/machines/", machine);
4780 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4788 if (!streq_ptr(class, "container"))
4791 r = parse_pid(s, &leader);
4801 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4802 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4810 mntns = procfs_file_alloca(pid, "ns/mnt");
4811 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4819 pidns = procfs_file_alloca(pid, "ns/pid");
4820 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4828 netns = procfs_file_alloca(pid, "ns/net");
4829 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4837 root = procfs_file_alloca(pid, "root");
4838 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4844 *pidns_fd = pidnsfd;
4847 *mntns_fd = mntnsfd;
4850 *netns_fd = netnsfd;
4855 pidnsfd = mntnsfd = netnsfd = -1;
4860 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4863 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4867 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4871 if (setns(netns_fd, CLONE_NEWNET) < 0)
4875 if (fchdir(root_fd) < 0)
4878 if (chroot(".") < 0)
4882 if (setresgid(0, 0, 0) < 0)
4885 if (setgroups(0, NULL) < 0)
4888 if (setresuid(0, 0, 0) < 0)
4894 int getpeercred(int fd, struct ucred *ucred) {
4895 socklen_t n = sizeof(struct ucred);
4902 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4906 if (n != sizeof(struct ucred))
4909 /* Check if the data is actually useful and not suppressed due
4910 * to namespacing issues */
4913 if (u.uid == UID_INVALID)
4915 if (u.gid == GID_INVALID)
4922 int getpeersec(int fd, char **ret) {
4934 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4938 if (errno != ERANGE)
4945 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4961 /* This is much like like mkostemp() but is subject to umask(). */
4962 int mkostemp_safe(char *pattern, int flags) {
4963 _cleanup_umask_ mode_t u;
4970 fd = mkostemp(pattern, flags);
4977 int open_tmpfile(const char *path, int flags) {
4984 /* Try O_TMPFILE first, if it is supported */
4985 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
4990 /* Fall back to unguessable name + unlinking */
4991 p = strjoina(path, "/systemd-tmp-XXXXXX");
4993 fd = mkostemp_safe(p, flags);
5001 int fd_warn_permissions(const char *path, int fd) {
5004 if (fstat(fd, &st) < 0)
5007 if (st.st_mode & 0111)
5008 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
5010 if (st.st_mode & 0002)
5011 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
5013 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
5014 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);
5019 unsigned long personality_from_string(const char *p) {
5021 /* Parse a personality specifier. We introduce our own
5022 * identifiers that indicate specific ABIs, rather than just
5023 * hints regarding the register size, since we want to keep
5024 * things open for multiple locally supported ABIs for the
5025 * same register size. We try to reuse the ABI identifiers
5026 * used by libseccomp. */
5028 #if defined(__x86_64__)
5030 if (streq(p, "x86"))
5033 if (streq(p, "x86-64"))
5036 #elif defined(__i386__)
5038 if (streq(p, "x86"))
5042 /* personality(7) documents that 0xffffffffUL is used for
5043 * querying the current personality, hence let's use that here
5044 * as error indicator. */
5045 return 0xffffffffUL;
5048 const char* personality_to_string(unsigned long p) {
5050 #if defined(__x86_64__)
5052 if (p == PER_LINUX32)
5058 #elif defined(__i386__)
5067 uint64_t physical_memory(void) {
5070 /* We return this as uint64_t in case we are running as 32bit
5071 * process on a 64bit kernel with huge amounts of memory */
5073 mem = sysconf(_SC_PHYS_PAGES);
5076 return (uint64_t) mem * (uint64_t) page_size();
5079 void hexdump(FILE *f, const void *p, size_t s) {
5080 const uint8_t *b = p;
5083 assert(s == 0 || b);
5088 fprintf(f, "%04x ", n);
5090 for (i = 0; i < 16; i++) {
5095 fprintf(f, "%02x ", b[i]);
5103 for (i = 0; i < 16; i++) {
5108 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
5122 int update_reboot_param_file(const char *param) {
5127 r = write_string_file(REBOOT_PARAM_FILE, param);
5129 log_error("Failed to write reboot param to "
5130 REBOOT_PARAM_FILE": %s", strerror(-r));
5132 unlink(REBOOT_PARAM_FILE);
5137 int umount_recursive(const char *prefix, int flags) {
5141 /* Try to umount everything recursively below a
5142 * directory. Also, take care of stacked mounts, and keep
5143 * unmounting them until they are gone. */
5146 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5151 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5152 if (!proc_self_mountinfo)
5156 _cleanup_free_ char *path = NULL, *p = NULL;
5159 k = fscanf(proc_self_mountinfo,
5160 "%*s " /* (1) mount id */
5161 "%*s " /* (2) parent id */
5162 "%*s " /* (3) major:minor */
5163 "%*s " /* (4) root */
5164 "%ms " /* (5) mount point */
5165 "%*s" /* (6) mount options */
5166 "%*[^-]" /* (7) optional fields */
5167 "- " /* (8) separator */
5168 "%*s " /* (9) file system type */
5169 "%*s" /* (10) mount source */
5170 "%*s" /* (11) mount options 2 */
5171 "%*[^\n]", /* some rubbish at the end */
5180 r = cunescape(path, UNESCAPE_RELAX, &p);
5184 if (!path_startswith(p, prefix))
5187 if (umount2(p, flags) < 0) {
5203 static int get_mount_flags(const char *path, unsigned long *flags) {
5206 if (statvfs(path, &buf) < 0)
5208 *flags = buf.f_flag;
5212 int bind_remount_recursive(const char *prefix, bool ro) {
5213 _cleanup_set_free_free_ Set *done = NULL;
5214 _cleanup_free_ char *cleaned = NULL;
5217 /* Recursively remount a directory (and all its submounts)
5218 * read-only or read-write. If the directory is already
5219 * mounted, we reuse the mount and simply mark it
5220 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5221 * operation). If it isn't we first make it one. Afterwards we
5222 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5223 * submounts we can access, too. When mounts are stacked on
5224 * the same mount point we only care for each individual
5225 * "top-level" mount on each point, as we cannot
5226 * influence/access the underlying mounts anyway. We do not
5227 * have any effect on future submounts that might get
5228 * propagated, they migt be writable. This includes future
5229 * submounts that have been triggered via autofs. */
5231 cleaned = strdup(prefix);
5235 path_kill_slashes(cleaned);
5237 done = set_new(&string_hash_ops);
5242 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5243 _cleanup_set_free_free_ Set *todo = NULL;
5244 bool top_autofs = false;
5246 unsigned long orig_flags;
5248 todo = set_new(&string_hash_ops);
5252 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5253 if (!proc_self_mountinfo)
5257 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5260 k = fscanf(proc_self_mountinfo,
5261 "%*s " /* (1) mount id */
5262 "%*s " /* (2) parent id */
5263 "%*s " /* (3) major:minor */
5264 "%*s " /* (4) root */
5265 "%ms " /* (5) mount point */
5266 "%*s" /* (6) mount options (superblock) */
5267 "%*[^-]" /* (7) optional fields */
5268 "- " /* (8) separator */
5269 "%ms " /* (9) file system type */
5270 "%*s" /* (10) mount source */
5271 "%*s" /* (11) mount options (bind mount) */
5272 "%*[^\n]", /* some rubbish at the end */
5282 r = cunescape(path, UNESCAPE_RELAX, &p);
5286 /* Let's ignore autofs mounts. If they aren't
5287 * triggered yet, we want to avoid triggering
5288 * them, as we don't make any guarantees for
5289 * future submounts anyway. If they are
5290 * already triggered, then we will find
5291 * another entry for this. */
5292 if (streq(type, "autofs")) {
5293 top_autofs = top_autofs || path_equal(cleaned, p);
5297 if (path_startswith(p, cleaned) &&
5298 !set_contains(done, p)) {
5300 r = set_consume(todo, p);
5310 /* If we have no submounts to process anymore and if
5311 * the root is either already done, or an autofs, we
5313 if (set_isempty(todo) &&
5314 (top_autofs || set_contains(done, cleaned)))
5317 if (!set_contains(done, cleaned) &&
5318 !set_contains(todo, cleaned)) {
5319 /* The prefix directory itself is not yet a
5320 * mount, make it one. */
5321 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5325 (void) get_mount_flags(cleaned, &orig_flags);
5326 orig_flags &= ~MS_RDONLY;
5328 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5331 x = strdup(cleaned);
5335 r = set_consume(done, x);
5340 while ((x = set_steal_first(todo))) {
5342 r = set_consume(done, x);
5348 /* Try to reuse the original flag set, but
5349 * don't care for errors, in case of
5350 * obstructed mounts */
5352 (void) get_mount_flags(x, &orig_flags);
5353 orig_flags &= ~MS_RDONLY;
5355 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5357 /* Deal with mount points that are
5358 * obstructed by a later mount */
5360 if (errno != ENOENT)
5368 int fflush_and_check(FILE *f) {
5375 return errno ? -errno : -EIO;
5380 int tempfn_xxxxxx(const char *p, char **ret) {
5392 * /foo/bar/.#waldoXXXXXX
5396 if (!filename_is_valid(fn))
5399 t = new(char, strlen(p) + 2 + 6 + 1);
5403 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5405 *ret = path_kill_slashes(t);
5409 int tempfn_random(const char *p, char **ret) {
5423 * /foo/bar/.#waldobaa2a261115984a9
5427 if (!filename_is_valid(fn))
5430 t = new(char, strlen(p) + 2 + 16 + 1);
5434 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5437 for (i = 0; i < 16; i++) {
5438 *(x++) = hexchar(u & 0xF);
5444 *ret = path_kill_slashes(t);
5448 int tempfn_random_child(const char *p, char **ret) {
5459 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5462 t = new(char, strlen(p) + 3 + 16 + 1);
5466 x = stpcpy(stpcpy(t, p), "/.#");
5469 for (i = 0; i < 16; i++) {
5470 *(x++) = hexchar(u & 0xF);
5476 *ret = path_kill_slashes(t);
5480 /* make sure the hostname is not "localhost" */
5481 bool is_localhost(const char *hostname) {
5484 /* This tries to identify local host and domain names
5485 * described in RFC6761 plus the redhatism of .localdomain */
5487 return streq(hostname, "localhost") ||
5488 streq(hostname, "localhost.") ||
5489 streq(hostname, "localdomain.") ||
5490 streq(hostname, "localdomain") ||
5491 endswith(hostname, ".localhost") ||
5492 endswith(hostname, ".localhost.") ||
5493 endswith(hostname, ".localdomain") ||
5494 endswith(hostname, ".localdomain.");
5497 int take_password_lock(const char *root) {
5499 struct flock flock = {
5501 .l_whence = SEEK_SET,
5509 /* This is roughly the same as lckpwdf(), but not as awful. We
5510 * don't want to use alarm() and signals, hence we implement
5511 * our own trivial version of this.
5513 * Note that shadow-utils also takes per-database locks in
5514 * addition to lckpwdf(). However, we don't given that they
5515 * are redundant as they they invoke lckpwdf() first and keep
5516 * it during everything they do. The per-database locks are
5517 * awfully racy, and thus we just won't do them. */
5520 path = strjoina(root, "/etc/.pwd.lock");
5522 path = "/etc/.pwd.lock";
5524 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5528 r = fcntl(fd, F_SETLKW, &flock);
5537 int is_symlink(const char *path) {
5540 if (lstat(path, &info) < 0)
5543 return !!S_ISLNK(info.st_mode);
5546 int is_dir(const char* path, bool follow) {
5551 r = stat(path, &st);
5553 r = lstat(path, &st);
5557 return !!S_ISDIR(st.st_mode);
5560 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5561 _cleanup_free_ char *s = NULL;
5562 size_t allocated = 0, sz = 0;
5570 SINGLE_QUOTE_ESCAPE,
5572 DOUBLE_QUOTE_ESCAPE,
5580 /* Parses the first word of a string, and returns it in
5581 * *ret. Removes all quotes in the process. When parsing fails
5582 * (because of an uneven number of quotes or similar), leaves
5583 * the pointer *p at the first invalid character. */
5593 else if (strchr(WHITESPACE, c))
5603 state = SINGLE_QUOTE;
5605 state = VALUE_ESCAPE;
5607 state = DOUBLE_QUOTE;
5608 else if (strchr(WHITESPACE, c))
5611 if (!GREEDY_REALLOC(s, allocated, sz+2))
5621 if (flags & UNQUOTE_RELAX)
5626 if (!GREEDY_REALLOC(s, allocated, sz+7))
5629 if (flags & UNQUOTE_CUNESCAPE) {
5632 r = cunescape_one(*p, (size_t) -1, &c, &u);
5639 s[sz++] = c; /* normal explicit char */
5641 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5650 if (flags & UNQUOTE_RELAX)
5653 } else if (c == '\'')
5656 state = SINGLE_QUOTE_ESCAPE;
5658 if (!GREEDY_REALLOC(s, allocated, sz+2))
5666 case SINGLE_QUOTE_ESCAPE:
5668 if (flags & UNQUOTE_RELAX)
5673 if (!GREEDY_REALLOC(s, allocated, sz+7))
5676 if (flags & UNQUOTE_CUNESCAPE) {
5679 r = cunescape_one(*p, (size_t) -1, &c, &u);
5688 sz += utf8_encode_unichar(s + sz, u);
5692 state = SINGLE_QUOTE;
5701 state = DOUBLE_QUOTE_ESCAPE;
5703 if (!GREEDY_REALLOC(s, allocated, sz+2))
5711 case DOUBLE_QUOTE_ESCAPE:
5713 if (flags & UNQUOTE_RELAX)
5718 if (!GREEDY_REALLOC(s, allocated, sz+7))
5721 if (flags & UNQUOTE_CUNESCAPE) {
5724 r = cunescape_one(*p, (size_t) -1, &c, &u);
5733 sz += utf8_encode_unichar(s + sz, u);
5737 state = DOUBLE_QUOTE;
5743 if (!strchr(WHITESPACE, c))
5765 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5770 /* Parses a number of words from a string, stripping any
5771 * quotes if necessary. */
5775 /* Count how many words are expected */
5776 va_start(ap, flags);
5778 if (!va_arg(ap, char **))
5787 /* Read all words into a temporary array */
5788 l = newa0(char*, n);
5789 for (c = 0; c < n; c++) {
5791 r = unquote_first_word(p, &l[c], flags);
5795 for (j = 0; j < c; j++)
5805 /* If we managed to parse all words, return them in the passed
5807 va_start(ap, flags);
5808 for (i = 0; i < n; i++) {
5811 v = va_arg(ap, char **);
5821 int free_and_strdup(char **p, const char *s) {
5826 /* Replaces a string pointer with an strdup()ed new string,
5827 * possibly freeing the old one. */
5842 int sethostname_idempotent(const char *s) {
5844 char buf[HOST_NAME_MAX + 1] = {};
5848 r = gethostname(buf, sizeof(buf));
5855 r = sethostname(s, strlen(s));
5862 int ptsname_malloc(int fd, char **ret) {
5875 if (ptsname_r(fd, c, l) == 0) {
5879 if (errno != ERANGE) {
5889 int openpt_in_namespace(pid_t pid, int flags) {
5890 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5891 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5893 struct cmsghdr cmsghdr;
5894 uint8_t buf[CMSG_SPACE(sizeof(int))];
5896 struct msghdr mh = {
5897 .msg_control = &control,
5898 .msg_controllen = sizeof(control),
5900 struct cmsghdr *cmsg;
5907 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5911 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5921 pair[0] = safe_close(pair[0]);
5923 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5925 _exit(EXIT_FAILURE);
5927 master = posix_openpt(flags);
5929 _exit(EXIT_FAILURE);
5931 cmsg = CMSG_FIRSTHDR(&mh);
5932 cmsg->cmsg_level = SOL_SOCKET;
5933 cmsg->cmsg_type = SCM_RIGHTS;
5934 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5935 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5937 mh.msg_controllen = cmsg->cmsg_len;
5939 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5940 _exit(EXIT_FAILURE);
5942 _exit(EXIT_SUCCESS);
5945 pair[1] = safe_close(pair[1]);
5947 r = wait_for_terminate(child, &si);
5950 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5953 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5956 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5957 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5961 fds = (int*) CMSG_DATA(cmsg);
5962 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5965 close_many(fds, n_fds);
5975 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5976 _cleanup_close_ int fd = -1;
5979 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5981 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5985 l = fgetxattr(fd, attribute, value, size);
5992 static int parse_crtime(le64_t le, usec_t *usec) {
5998 if (u == 0 || u == (uint64_t) -1)
6005 int fd_getcrtime(int fd, usec_t *usec) {
6012 /* Until Linux gets a real concept of birthtime/creation time,
6013 * let's fake one with xattrs */
6015 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
6018 if (n != sizeof(le))
6021 return parse_crtime(le, usec);
6024 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
6028 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
6031 if (n != sizeof(le))
6034 return parse_crtime(le, usec);
6037 int path_getcrtime(const char *p, usec_t *usec) {
6044 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
6047 if (n != sizeof(le))
6050 return parse_crtime(le, usec);
6053 int fd_setcrtime(int fd, usec_t usec) {
6059 usec = now(CLOCK_REALTIME);
6061 le = htole64((uint64_t) usec);
6062 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
6068 int chattr_fd(int fd, unsigned value, unsigned mask) {
6069 unsigned old_attr, new_attr;
6076 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
6079 new_attr = (old_attr & ~mask) | (value & mask);
6080 if (new_attr == old_attr)
6083 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
6089 int chattr_path(const char *p, unsigned value, unsigned mask) {
6090 _cleanup_close_ int fd = -1;
6097 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6101 return chattr_fd(fd, value, mask);
6104 int read_attr_fd(int fd, unsigned *ret) {
6107 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
6113 int read_attr_path(const char *p, unsigned *ret) {
6114 _cleanup_close_ int fd = -1;
6119 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6123 return read_attr_fd(fd, ret);
6126 int make_lock_file(const char *p, int operation, LockFile *ret) {
6127 _cleanup_close_ int fd = -1;
6128 _cleanup_free_ char *t = NULL;
6132 * We use UNPOSIX locks if they are available. They have nice
6133 * semantics, and are mostly compatible with NFS. However,
6134 * they are only available on new kernels. When we detect we
6135 * are running on an older kernel, then we fall back to good
6136 * old BSD locks. They also have nice semantics, but are
6137 * slightly problematic on NFS, where they are upgraded to
6138 * POSIX locks, even though locally they are orthogonal to
6148 .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
6149 .l_whence = SEEK_SET,
6153 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
6157 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
6160 /* If the kernel is too old, use good old BSD locks */
6161 if (errno == EINVAL)
6162 r = flock(fd, operation);
6165 return errno == EAGAIN ? -EBUSY : -errno;
6168 /* If we acquired the lock, let's check if the file
6169 * still exists in the file system. If not, then the
6170 * previous exclusive owner removed it and then closed
6171 * it. In such a case our acquired lock is worthless,
6172 * hence try again. */
6177 if (st.st_nlink > 0)
6180 fd = safe_close(fd);
6185 ret->operation = operation;
6193 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
6201 if (!filename_is_valid(fn))
6204 t = newa(char, strlen(p) + 2 + 4 + 1);
6205 stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
6207 return make_lock_file(t, operation, ret);
6210 void release_lock_file(LockFile *f) {
6218 /* If we are the exclusive owner we can safely delete
6219 * the lock file itself. If we are not the exclusive
6220 * owner, we can try becoming it. */
6223 (f->operation & ~LOCK_NB) == LOCK_SH) {
6224 static const struct flock fl = {
6226 .l_whence = SEEK_SET,
6229 r = fcntl(f->fd, F_OFD_SETLK, &fl);
6230 if (r < 0 && errno == EINVAL)
6231 r = flock(f->fd, LOCK_EX|LOCK_NB);
6234 f->operation = LOCK_EX|LOCK_NB;
6237 if ((f->operation & ~LOCK_NB) == LOCK_EX)
6238 unlink_noerrno(f->path);
6244 f->fd = safe_close(f->fd);
6248 static size_t nul_length(const uint8_t *p, size_t sz) {
6263 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
6264 const uint8_t *q, *w, *e;
6272 n = nul_length(q, e - q);
6274 /* If there are more than the specified run length of
6275 * NUL bytes, or if this is the beginning or the end
6276 * of the buffer, then seek instead of write */
6277 if ((n > run_length) ||
6278 (n > 0 && q == p) ||
6279 (n > 0 && q + n >= e)) {
6281 l = write(fd, w, q - w);
6288 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6300 l = write(fd, w, q - w);
6307 return q - (const uint8_t*) p;
6310 void sigkill_wait(pid_t *pid) {
6316 if (kill(*pid, SIGKILL) > 0)
6317 (void) wait_for_terminate(*pid, NULL);
6320 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6321 int a = 0, b = 0, c = 0;
6331 if (!strchr(*p, '>'))
6334 if ((*p)[2] == '>') {
6335 c = undecchar((*p)[1]);
6337 } else if ((*p)[3] == '>') {
6338 b = undecchar((*p)[1]);
6339 c = undecchar((*p)[2]);
6341 } else if ((*p)[4] == '>') {
6342 a = undecchar((*p)[1]);
6343 b = undecchar((*p)[2]);
6344 c = undecchar((*p)[3]);
6349 if (a < 0 || b < 0 || c < 0 ||
6350 (!with_facility && (a || b || c > 7)))
6354 *priority = a*100 + b*10 + c;
6356 *priority = (*priority & LOG_FACMASK) | c;
6362 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6368 for (i = 0; i < len; ++i)
6369 if (streq_ptr(table[i], key))
6375 void cmsg_close_all(struct msghdr *mh) {
6376 struct cmsghdr *cmsg;
6380 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6381 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6382 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6385 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6389 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6393 /* Even though renameat2() exists since Linux 3.15, btrfs added
6394 * support for it later. If it is not implemented, fallback to another
6396 if (errno != EINVAL)
6399 /* The link()/unlink() fallback does not work on directories. But
6400 * renameat() without RENAME_NOREPLACE gives the same semantics on
6401 * directories, except when newpath is an *empty* directory. This is
6403 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6404 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6405 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6406 return ret >= 0 ? 0 : -errno;
6409 /* If it is not a directory, use the link()/unlink() fallback. */
6410 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6414 ret = unlinkat(olddirfd, oldpath, 0);
6416 /* backup errno before the following unlinkat() alters it */
6418 (void) unlinkat(newdirfd, newpath, 0);
6426 char *shell_maybe_quote(const char *s) {
6432 /* Encloses a string in double quotes if necessary to make it
6433 * OK as shell string. */
6435 for (p = s; *p; p++)
6438 strchr(SHELL_NEED_QUOTES, *p))
6444 r = new(char, 1+strlen(s)*2+1+1);
6450 t = mempcpy(t, s, p - s);
6454 if (strchr(SHELL_NEED_ESCAPE, *p))
6466 int parse_mode(const char *s, mode_t *ret) {
6474 l = strtol(s, &x, 8);
6478 if (!x || x == s || *x)
6480 if (l < 0 || l > 07777)