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;
354 r = safe_atolu(s, &ul);
360 if ((unsigned long) uid != ul)
363 /* Some libc APIs use UID_INVALID as special placeholder */
364 if (uid == (uid_t) 0xFFFFFFFF)
367 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
368 if (uid == (uid_t) 0xFFFF)
377 int safe_atou(const char *s, unsigned *ret_u) {
385 l = strtoul(s, &x, 0);
387 if (!x || x == s || *x || errno)
388 return errno > 0 ? -errno : -EINVAL;
390 if ((unsigned long) (unsigned) l != l)
393 *ret_u = (unsigned) l;
397 int safe_atoi(const char *s, int *ret_i) {
405 l = strtol(s, &x, 0);
407 if (!x || x == s || *x || errno)
408 return errno > 0 ? -errno : -EINVAL;
410 if ((long) (int) l != l)
417 int safe_atou8(const char *s, uint8_t *ret) {
425 l = strtoul(s, &x, 0);
427 if (!x || x == s || *x || errno)
428 return errno > 0 ? -errno : -EINVAL;
430 if ((unsigned long) (uint8_t) l != l)
437 int safe_atou16(const char *s, uint16_t *ret) {
445 l = strtoul(s, &x, 0);
447 if (!x || x == s || *x || errno)
448 return errno > 0 ? -errno : -EINVAL;
450 if ((unsigned long) (uint16_t) l != l)
457 int safe_atoi16(const char *s, int16_t *ret) {
465 l = strtol(s, &x, 0);
467 if (!x || x == s || *x || errno)
468 return errno > 0 ? -errno : -EINVAL;
470 if ((long) (int16_t) l != l)
477 int safe_atollu(const char *s, long long unsigned *ret_llu) {
479 unsigned long long l;
485 l = strtoull(s, &x, 0);
487 if (!x || x == s || *x || errno)
488 return errno ? -errno : -EINVAL;
494 int safe_atolli(const char *s, long long int *ret_lli) {
502 l = strtoll(s, &x, 0);
504 if (!x || x == s || *x || errno)
505 return errno ? -errno : -EINVAL;
511 int safe_atod(const char *s, double *ret_d) {
519 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
520 if (loc == (locale_t) 0)
524 d = strtod_l(s, &x, loc);
526 if (!x || x == s || *x || errno) {
528 return errno ? -errno : -EINVAL;
536 static size_t strcspn_escaped(const char *s, const char *reject) {
537 bool escaped = false;
540 for (n=0; s[n]; n++) {
543 else if (s[n] == '\\')
545 else if (strchr(reject, s[n]))
549 /* if s ends in \, return index of previous char */
553 /* Split a string into words. */
554 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
560 assert(**state == '\0');
564 current += strspn(current, separator);
570 if (quoted && strchr("\'\"", *current)) {
571 char quotechars[2] = {*current, '\0'};
573 *l = strcspn_escaped(current + 1, quotechars);
574 if (current[*l + 1] == '\0' ||
575 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
576 /* right quote missing or garbage at the end */
580 assert(current[*l + 1] == quotechars[0]);
581 *state = current++ + *l + 2;
583 *l = strcspn_escaped(current, separator);
584 if (current[*l] && !strchr(separator, current[*l])) {
585 /* unfinished escape */
589 *state = current + *l;
591 *l = strcspn(current, separator);
592 *state = current + *l;
598 int fchmod_umask(int fd, mode_t m) {
603 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
609 char *truncate_nl(char *s) {
612 s[strcspn(s, NEWLINE)] = 0;
616 char *strnappend(const char *s, const char *suffix, size_t b) {
624 return strndup(suffix, b);
633 if (b > ((size_t) -1) - a)
636 r = new(char, a+b+1);
641 memcpy(r+a, suffix, b);
647 char *strappend(const char *s, const char *suffix) {
648 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
651 int readlinkat_malloc(int fd, const char *p, char **ret) {
666 n = readlinkat(fd, p, c, l-1);
673 if ((size_t) n < l-1) {
684 int readlink_malloc(const char *p, char **ret) {
685 return readlinkat_malloc(AT_FDCWD, p, ret);
688 int readlink_value(const char *p, char **ret) {
689 _cleanup_free_ char *link = NULL;
693 r = readlink_malloc(p, &link);
697 value = basename(link);
701 value = strdup(value);
710 int readlink_and_make_absolute(const char *p, char **r) {
711 _cleanup_free_ char *target = NULL;
718 j = readlink_malloc(p, &target);
722 k = file_in_same_dir(p, target);
730 int readlink_and_canonicalize(const char *p, char **r) {
737 j = readlink_and_make_absolute(p, &t);
741 s = canonicalize_file_name(t);
748 path_kill_slashes(*r);
753 int reset_all_signal_handlers(void) {
756 for (sig = 1; sig < _NSIG; sig++) {
757 struct sigaction sa = {
758 .sa_handler = SIG_DFL,
759 .sa_flags = SA_RESTART,
762 /* These two cannot be caught... */
763 if (sig == SIGKILL || sig == SIGSTOP)
766 /* On Linux the first two RT signals are reserved by
767 * glibc, and sigaction() will return EINVAL for them. */
768 if ((sigaction(sig, &sa, NULL) < 0))
769 if (errno != EINVAL && r == 0)
776 int reset_signal_mask(void) {
779 if (sigemptyset(&ss) < 0)
782 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
788 char *strstrip(char *s) {
791 /* Drops trailing whitespace. Modifies the string in
792 * place. Returns pointer to first non-space character */
794 s += strspn(s, WHITESPACE);
796 for (e = strchr(s, 0); e > s; e --)
797 if (!strchr(WHITESPACE, e[-1]))
805 char *delete_chars(char *s, const char *bad) {
808 /* Drops all whitespace, regardless where in the string */
810 for (f = s, t = s; *f; f++) {
822 char *file_in_same_dir(const char *path, const char *filename) {
829 /* This removes the last component of path and appends
830 * filename, unless the latter is absolute anyway or the
833 if (path_is_absolute(filename))
834 return strdup(filename);
836 e = strrchr(path, '/');
838 return strdup(filename);
840 k = strlen(filename);
841 ret = new(char, (e + 1 - path) + k + 1);
845 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
849 int rmdir_parents(const char *path, const char *stop) {
858 /* Skip trailing slashes */
859 while (l > 0 && path[l-1] == '/')
865 /* Skip last component */
866 while (l > 0 && path[l-1] != '/')
869 /* Skip trailing slashes */
870 while (l > 0 && path[l-1] == '/')
876 if (!(t = strndup(path, l)))
879 if (path_startswith(stop, t)) {
895 char hexchar(int x) {
896 static const char table[16] = "0123456789abcdef";
898 return table[x & 15];
901 int unhexchar(char c) {
903 if (c >= '0' && c <= '9')
906 if (c >= 'a' && c <= 'f')
909 if (c >= 'A' && c <= 'F')
915 char *hexmem(const void *p, size_t l) {
919 z = r = malloc(l * 2 + 1);
923 for (x = p; x < (const uint8_t*) p + l; x++) {
924 *(z++) = hexchar(*x >> 4);
925 *(z++) = hexchar(*x & 15);
932 void *unhexmem(const char *p, size_t l) {
938 z = r = malloc((l + 1) / 2 + 1);
942 for (x = p; x < p + l; x += 2) {
951 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
958 char octchar(int x) {
959 return '0' + (x & 7);
962 int unoctchar(char c) {
964 if (c >= '0' && c <= '7')
970 char decchar(int x) {
971 return '0' + (x % 10);
974 int undecchar(char c) {
976 if (c >= '0' && c <= '9')
982 char *cescape(const char *s) {
988 /* Does C style string escaping. May be reversed with
991 r = new(char, strlen(s)*4 + 1);
995 for (f = s, t = r; *f; f++)
996 t += cescape_char(*f, t);
1003 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1010 /* Unescapes C style. Returns the unescaped character in ret,
1011 * unless we encountered a \u sequence in which case the full
1012 * unicode character is returned in ret_unicode, instead. */
1014 if (length != (size_t) -1 && length < 1)
1051 /* This is an extension of the XDG syntax files */
1056 /* hexadecimal encoding */
1059 if (length != (size_t) -1 && length < 3)
1062 a = unhexchar(p[1]);
1066 b = unhexchar(p[2]);
1070 /* Don't allow NUL bytes */
1071 if (a == 0 && b == 0)
1074 *ret = (char) ((a << 4U) | b);
1080 /* C++11 style 16bit unicode */
1086 if (length != (size_t) -1 && length < 5)
1089 for (i = 0; i < 4; i++) {
1090 a[i] = unhexchar(p[1 + i]);
1095 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1097 /* Don't allow 0 chars */
1116 /* C++11 style 32bit unicode */
1122 if (length != (size_t) -1 && length < 9)
1125 for (i = 0; i < 8; i++) {
1126 a[i] = unhexchar(p[1 + i]);
1131 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1132 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1134 /* Don't allow 0 chars */
1138 /* Don't allow invalid code points */
1139 if (!unichar_is_valid(c))
1164 /* octal encoding */
1168 if (length != (size_t) -1 && length < 4)
1171 a = unoctchar(p[0]);
1175 b = unoctchar(p[1]);
1179 c = unoctchar(p[2]);
1183 /* don't allow NUL bytes */
1184 if (a == 0 && b == 0 && c == 0)
1187 /* Don't allow bytes above 255 */
1188 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1204 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1212 /* Undoes C style string escaping, and optionally prefixes it. */
1214 pl = prefix ? strlen(prefix) : 0;
1216 r = new(char, pl+length+1);
1221 memcpy(r, prefix, pl);
1223 for (f = s, t = r + pl; f < s + length; f++) {
1229 remaining = s + length - f;
1230 assert(remaining > 0);
1233 /* A literal literal, copy verbatim */
1238 if (remaining == 1) {
1239 if (flags & UNESCAPE_RELAX) {
1240 /* A trailing backslash, copy verbatim */
1249 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1251 if (flags & UNESCAPE_RELAX) {
1252 /* Invalid escape code, let's take it literal then */
1262 /* Non-Unicode? Let's encode this directly */
1265 /* Unicode? Then let's encode this in UTF-8 */
1266 t += utf8_encode_unichar(t, u);
1277 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1278 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1281 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1282 return cunescape_length(s, strlen(s), flags, ret);
1285 char *xescape(const char *s, const char *bad) {
1289 /* Escapes all chars in bad, in addition to \ and all special
1290 * chars, in \xFF style escaping. May be reversed with
1293 r = new(char, strlen(s) * 4 + 1);
1297 for (f = s, t = r; *f; f++) {
1299 if ((*f < ' ') || (*f >= 127) ||
1300 (*f == '\\') || strchr(bad, *f)) {
1303 *(t++) = hexchar(*f >> 4);
1304 *(t++) = hexchar(*f);
1314 char *ascii_strlower(char *t) {
1319 for (p = t; *p; p++)
1320 if (*p >= 'A' && *p <= 'Z')
1321 *p = *p - 'A' + 'a';
1326 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1330 filename[0] == '.' ||
1331 streq(filename, "lost+found") ||
1332 streq(filename, "aquota.user") ||
1333 streq(filename, "aquota.group") ||
1334 endswith(filename, ".rpmnew") ||
1335 endswith(filename, ".rpmsave") ||
1336 endswith(filename, ".rpmorig") ||
1337 endswith(filename, ".dpkg-old") ||
1338 endswith(filename, ".dpkg-new") ||
1339 endswith(filename, ".dpkg-tmp") ||
1340 endswith(filename, ".dpkg-dist") ||
1341 endswith(filename, ".dpkg-bak") ||
1342 endswith(filename, ".dpkg-backup") ||
1343 endswith(filename, ".dpkg-remove") ||
1344 endswith(filename, ".swp");
1347 bool hidden_file(const char *filename) {
1350 if (endswith(filename, "~"))
1353 return hidden_file_allow_backup(filename);
1356 int fd_nonblock(int fd, bool nonblock) {
1361 flags = fcntl(fd, F_GETFL, 0);
1366 nflags = flags | O_NONBLOCK;
1368 nflags = flags & ~O_NONBLOCK;
1370 if (nflags == flags)
1373 if (fcntl(fd, F_SETFL, nflags) < 0)
1379 int fd_cloexec(int fd, bool cloexec) {
1384 flags = fcntl(fd, F_GETFD, 0);
1389 nflags = flags | FD_CLOEXEC;
1391 nflags = flags & ~FD_CLOEXEC;
1393 if (nflags == flags)
1396 if (fcntl(fd, F_SETFD, nflags) < 0)
1402 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1405 assert(n_fdset == 0 || fdset);
1407 for (i = 0; i < n_fdset; i++)
1414 int close_all_fds(const int except[], unsigned n_except) {
1415 _cleanup_closedir_ DIR *d = NULL;
1419 assert(n_except == 0 || except);
1421 d = opendir("/proc/self/fd");
1426 /* When /proc isn't available (for example in chroots)
1427 * the fallback is brute forcing through the fd
1430 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1431 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1433 if (fd_in_set(fd, except, n_except))
1436 if (close_nointr(fd) < 0)
1437 if (errno != EBADF && r == 0)
1444 while ((de = readdir(d))) {
1447 if (hidden_file(de->d_name))
1450 if (safe_atoi(de->d_name, &fd) < 0)
1451 /* Let's better ignore this, just in case */
1460 if (fd_in_set(fd, except, n_except))
1463 if (close_nointr(fd) < 0) {
1464 /* Valgrind has its own FD and doesn't want to have it closed */
1465 if (errno != EBADF && r == 0)
1473 bool chars_intersect(const char *a, const char *b) {
1476 /* Returns true if any of the chars in a are in b. */
1477 for (p = a; *p; p++)
1484 bool fstype_is_network(const char *fstype) {
1485 static const char table[] =
1500 x = startswith(fstype, "fuse.");
1504 return nulstr_contains(table, fstype);
1507 int flush_fd(int fd) {
1508 struct pollfd pollfd = {
1518 r = poll(&pollfd, 1, 0);
1528 l = read(fd, buf, sizeof(buf));
1534 if (errno == EAGAIN)
1543 int sigaction_many(const struct sigaction *sa, ...) {
1548 while ((sig = va_arg(ap, int)) > 0)
1549 if (sigaction(sig, sa, NULL) < 0)
1556 int ignore_signals(int sig, ...) {
1557 struct sigaction sa = {
1558 .sa_handler = SIG_IGN,
1559 .sa_flags = SA_RESTART,
1564 if (sigaction(sig, &sa, NULL) < 0)
1568 while ((sig = va_arg(ap, int)) > 0)
1569 if (sigaction(sig, &sa, NULL) < 0)
1576 int default_signals(int sig, ...) {
1577 struct sigaction sa = {
1578 .sa_handler = SIG_DFL,
1579 .sa_flags = SA_RESTART,
1584 if (sigaction(sig, &sa, NULL) < 0)
1588 while ((sig = va_arg(ap, int)) > 0)
1589 if (sigaction(sig, &sa, NULL) < 0)
1596 void safe_close_pair(int p[]) {
1600 /* Special case pairs which use the same fd in both
1602 p[0] = p[1] = safe_close(p[0]);
1606 p[0] = safe_close(p[0]);
1607 p[1] = safe_close(p[1]);
1610 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1617 while (nbytes > 0) {
1620 k = read(fd, p, nbytes);
1625 if (errno == EAGAIN && do_poll) {
1627 /* We knowingly ignore any return value here,
1628 * and expect that any error/EOF is reported
1631 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
1635 return n > 0 ? n : -errno;
1649 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
1652 n = loop_read(fd, buf, nbytes, do_poll);
1655 if ((size_t) n != nbytes)
1660 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
1661 const uint8_t *p = buf;
1668 while (nbytes > 0) {
1671 k = write(fd, p, nbytes);
1676 if (errno == EAGAIN && do_poll) {
1677 /* We knowingly ignore any return value here,
1678 * and expect that any error/EOF is reported
1681 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
1688 if (k == 0) /* Can't really happen */
1698 int parse_size(const char *t, off_t base, off_t *size) {
1700 /* Soo, sometimes we want to parse IEC binary suffxies, and
1701 * sometimes SI decimal suffixes. This function can parse
1702 * both. Which one is the right way depends on the
1703 * context. Wikipedia suggests that SI is customary for
1704 * hardware metrics and network speeds, while IEC is
1705 * customary for most data sizes used by software and volatile
1706 * (RAM) memory. Hence be careful which one you pick!
1708 * In either case we use just K, M, G as suffix, and not Ki,
1709 * Mi, Gi or so (as IEC would suggest). That's because that's
1710 * frickin' ugly. But this means you really need to make sure
1711 * to document which base you are parsing when you use this
1716 unsigned long long factor;
1719 static const struct table iec[] = {
1720 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1721 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
1722 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
1723 { "G", 1024ULL*1024ULL*1024ULL },
1724 { "M", 1024ULL*1024ULL },
1730 static const struct table si[] = {
1731 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1732 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
1733 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
1734 { "G", 1000ULL*1000ULL*1000ULL },
1735 { "M", 1000ULL*1000ULL },
1741 const struct table *table;
1743 unsigned long long r = 0;
1744 unsigned n_entries, start_pos = 0;
1747 assert(base == 1000 || base == 1024);
1752 n_entries = ELEMENTSOF(si);
1755 n_entries = ELEMENTSOF(iec);
1761 unsigned long long l2;
1767 l = strtoll(p, &e, 10);
1780 if (*e >= '0' && *e <= '9') {
1783 /* strotoull itself would accept space/+/- */
1784 l2 = strtoull(e, &e2, 10);
1786 if (errno == ERANGE)
1789 /* Ignore failure. E.g. 10.M is valid */
1796 e += strspn(e, WHITESPACE);
1798 for (i = start_pos; i < n_entries; i++)
1799 if (startswith(e, table[i].suffix)) {
1800 unsigned long long tmp;
1801 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
1803 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
1804 if (tmp > ULLONG_MAX - r)
1808 if ((unsigned long long) (off_t) r != r)
1811 p = e + strlen(table[i].suffix);
1827 bool is_device_path(const char *path) {
1829 /* Returns true on paths that refer to a device, either in
1830 * sysfs or in /dev */
1833 path_startswith(path, "/dev/") ||
1834 path_startswith(path, "/sys/");
1837 int dir_is_empty(const char *path) {
1838 _cleanup_closedir_ DIR *d;
1849 if (!de && errno != 0)
1855 if (!hidden_file(de->d_name))
1860 char* dirname_malloc(const char *path) {
1861 char *d, *dir, *dir2;
1878 void rename_process(const char name[8]) {
1881 /* This is a like a poor man's setproctitle(). It changes the
1882 * comm field, argv[0], and also the glibc's internally used
1883 * name of the process. For the first one a limit of 16 chars
1884 * applies, to the second one usually one of 10 (i.e. length
1885 * of "/sbin/init"), to the third one one of 7 (i.e. length of
1886 * "systemd"). If you pass a longer string it will be
1889 prctl(PR_SET_NAME, name);
1891 if (program_invocation_name)
1892 strncpy(program_invocation_name, name, strlen(program_invocation_name));
1894 if (saved_argc > 0) {
1898 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
1900 for (i = 1; i < saved_argc; i++) {
1904 memzero(saved_argv[i], strlen(saved_argv[i]));
1909 void sigset_add_many(sigset_t *ss, ...) {
1916 while ((sig = va_arg(ap, int)) > 0)
1917 assert_se(sigaddset(ss, sig) == 0);
1921 int sigprocmask_many(int how, ...) {
1926 assert_se(sigemptyset(&ss) == 0);
1929 while ((sig = va_arg(ap, int)) > 0)
1930 assert_se(sigaddset(&ss, sig) == 0);
1933 if (sigprocmask(how, &ss, NULL) < 0)
1939 char* gethostname_malloc(void) {
1942 assert_se(uname(&u) >= 0);
1944 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
1945 return strdup(u.nodename);
1947 return strdup(u.sysname);
1950 bool hostname_is_set(void) {
1953 assert_se(uname(&u) >= 0);
1955 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
1958 char *lookup_uid(uid_t uid) {
1961 _cleanup_free_ char *buf = NULL;
1962 struct passwd pwbuf, *pw = NULL;
1964 /* Shortcut things to avoid NSS lookups */
1966 return strdup("root");
1968 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1972 buf = malloc(bufsize);
1976 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
1977 return strdup(pw->pw_name);
1979 if (asprintf(&name, UID_FMT, uid) < 0)
1985 char* getlogname_malloc(void) {
1989 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
1994 return lookup_uid(uid);
1997 char *getusername_malloc(void) {
2004 return lookup_uid(getuid());
2007 bool is_temporary_fs(const struct statfs *s) {
2010 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2011 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2014 int fd_is_temporary_fs(int fd) {
2017 if (fstatfs(fd, &s) < 0)
2020 return is_temporary_fs(&s);
2023 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2026 /* Under the assumption that we are running privileged we
2027 * first change the access mode and only then hand out
2028 * ownership to avoid a window where access is too open. */
2030 if (mode != MODE_INVALID)
2031 if (chmod(path, mode) < 0)
2034 if (uid != UID_INVALID || gid != GID_INVALID)
2035 if (chown(path, uid, gid) < 0)
2041 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2044 /* Under the assumption that we are running privileged we
2045 * first change the access mode and only then hand out
2046 * ownership to avoid a window where access is too open. */
2048 if (mode != MODE_INVALID)
2049 if (fchmod(fd, mode) < 0)
2052 if (uid != UID_INVALID || gid != GID_INVALID)
2053 if (fchown(fd, uid, gid) < 0)
2059 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2063 /* Allocates the cpuset in the right size */
2066 if (!(r = CPU_ALLOC(n)))
2069 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2070 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2080 if (errno != EINVAL)
2087 int files_same(const char *filea, const char *fileb) {
2090 if (stat(filea, &a) < 0)
2093 if (stat(fileb, &b) < 0)
2096 return a.st_dev == b.st_dev &&
2097 a.st_ino == b.st_ino;
2100 int running_in_chroot(void) {
2103 ret = files_same("/proc/1/root", "/");
2110 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2115 assert(percent <= 100);
2116 assert(new_length >= 3);
2118 if (old_length <= 3 || old_length <= new_length)
2119 return strndup(s, old_length);
2121 r = new0(char, new_length+1);
2125 x = (new_length * percent) / 100;
2127 if (x > new_length - 3)
2135 s + old_length - (new_length - x - 3),
2136 new_length - x - 3);
2141 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2145 unsigned k, len, len2;
2148 assert(percent <= 100);
2149 assert(new_length >= 3);
2151 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2152 if (ascii_is_valid(s))
2153 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2155 if (old_length <= 3 || old_length <= new_length)
2156 return strndup(s, old_length);
2158 x = (new_length * percent) / 100;
2160 if (x > new_length - 3)
2164 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2167 c = utf8_encoded_to_unichar(i);
2170 k += unichar_iswide(c) ? 2 : 1;
2173 if (k > x) /* last character was wide and went over quota */
2176 for (j = s + old_length; k < new_length && j > i; ) {
2179 j = utf8_prev_char(j);
2180 c = utf8_encoded_to_unichar(j);
2183 k += unichar_iswide(c) ? 2 : 1;
2187 /* we don't actually need to ellipsize */
2189 return memdup(s, old_length + 1);
2191 /* make space for ellipsis */
2192 j = utf8_next_char(j);
2195 len2 = s + old_length - j;
2196 e = new(char, len + 3 + len2 + 1);
2201 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2202 old_length, new_length, x, len, len2, k);
2206 e[len] = 0xe2; /* tri-dot ellipsis: … */
2210 memcpy(e + len + 3, j, len2 + 1);
2215 char *ellipsize(const char *s, size_t length, unsigned percent) {
2216 return ellipsize_mem(s, strlen(s), length, percent);
2219 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2220 _cleanup_close_ int fd;
2226 mkdir_parents(path, 0755);
2228 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2233 r = fchmod(fd, mode);
2238 if (uid != UID_INVALID || gid != GID_INVALID) {
2239 r = fchown(fd, uid, gid);
2244 if (stamp != USEC_INFINITY) {
2245 struct timespec ts[2];
2247 timespec_store(&ts[0], stamp);
2249 r = futimens(fd, ts);
2251 r = futimens(fd, NULL);
2258 int touch(const char *path) {
2259 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2262 static char *unquote(const char *s, const char* quotes) {
2266 /* This is rather stupid, simply removes the heading and
2267 * trailing quotes if there is one. Doesn't care about
2268 * escaping or anything.
2270 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2276 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2277 return strndup(s+1, l-2);
2282 noreturn void freeze(void) {
2284 /* Make sure nobody waits for us on a socket anymore */
2285 close_all_fds(NULL, 0);
2293 bool null_or_empty(struct stat *st) {
2296 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2299 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2305 int null_or_empty_path(const char *fn) {
2310 if (stat(fn, &st) < 0)
2313 return null_or_empty(&st);
2316 int null_or_empty_fd(int fd) {
2321 if (fstat(fd, &st) < 0)
2324 return null_or_empty(&st);
2327 DIR *xopendirat(int fd, const char *name, int flags) {
2331 assert(!(flags & O_CREAT));
2333 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2346 int signal_from_string_try_harder(const char *s) {
2350 signo = signal_from_string(s);
2352 if (startswith(s, "SIG"))
2353 return signal_from_string(s+3);
2358 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2359 _cleanup_free_ char *t = NULL, *u = NULL;
2362 u = unquote(tagvalue, QUOTES);
2366 enc_len = strlen(u) * 4 + 1;
2367 t = new(char, enc_len);
2371 if (encode_devnode_name(u, t, enc_len) < 0)
2374 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2377 char *fstab_node_to_udev_node(const char *p) {
2380 if (startswith(p, "LABEL="))
2381 return tag_to_udev_node(p+6, "label");
2383 if (startswith(p, "UUID="))
2384 return tag_to_udev_node(p+5, "uuid");
2386 if (startswith(p, "PARTUUID="))
2387 return tag_to_udev_node(p+9, "partuuid");
2389 if (startswith(p, "PARTLABEL="))
2390 return tag_to_udev_node(p+10, "partlabel");
2395 bool dirent_is_file(const struct dirent *de) {
2398 if (hidden_file(de->d_name))
2401 if (de->d_type != DT_REG &&
2402 de->d_type != DT_LNK &&
2403 de->d_type != DT_UNKNOWN)
2409 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2412 if (de->d_type != DT_REG &&
2413 de->d_type != DT_LNK &&
2414 de->d_type != DT_UNKNOWN)
2417 if (hidden_file_allow_backup(de->d_name))
2420 return endswith(de->d_name, suffix);
2423 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2424 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2425 _cleanup_set_free_free_ Set *seen = NULL;
2428 /* We fork this all off from a child process so that we can
2429 * somewhat cleanly make use of SIGALRM to set a time limit */
2431 reset_all_signal_handlers();
2432 reset_signal_mask();
2434 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2436 pids = hashmap_new(NULL);
2440 seen = set_new(&string_hash_ops);
2444 STRV_FOREACH(directory, directories) {
2445 _cleanup_closedir_ DIR *d;
2448 d = opendir(*directory);
2450 if (errno == ENOENT)
2453 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2456 FOREACH_DIRENT(de, d, break) {
2457 _cleanup_free_ char *path = NULL;
2461 if (!dirent_is_file(de))
2464 if (set_contains(seen, de->d_name)) {
2465 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2469 r = set_put_strdup(seen, de->d_name);
2473 path = strjoin(*directory, "/", de->d_name, NULL);
2477 if (null_or_empty_path(path)) {
2478 log_debug("%s is empty (a mask).", path);
2484 log_error_errno(errno, "Failed to fork: %m");
2486 } else if (pid == 0) {
2489 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2499 return log_error_errno(errno, "Failed to execute %s: %m", path);
2502 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2504 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2511 /* Abort execution of this process after the timout. We simply
2512 * rely on SIGALRM as default action terminating the process,
2513 * and turn on alarm(). */
2515 if (timeout != USEC_INFINITY)
2516 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2518 while (!hashmap_isempty(pids)) {
2519 _cleanup_free_ char *path = NULL;
2522 pid = PTR_TO_UINT(hashmap_first_key(pids));
2525 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2528 wait_for_terminate_and_warn(path, pid, true);
2534 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2538 char **dirs = (char**) directories;
2540 assert(!strv_isempty(dirs));
2542 name = basename(dirs[0]);
2543 assert(!isempty(name));
2545 /* Executes all binaries in the directories in parallel and waits
2546 * for them to finish. Optionally a timeout is applied. If a file
2547 * with the same name exists in more than one directory, the
2548 * earliest one wins. */
2550 executor_pid = fork();
2551 if (executor_pid < 0) {
2552 log_error_errno(errno, "Failed to fork: %m");
2555 } else if (executor_pid == 0) {
2556 r = do_execute(dirs, timeout, argv);
2557 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2560 wait_for_terminate_and_warn(name, executor_pid, true);
2563 bool nulstr_contains(const char*nulstr, const char *needle) {
2569 NULSTR_FOREACH(i, nulstr)
2570 if (streq(i, needle))
2576 bool plymouth_running(void) {
2577 return access("/run/plymouth/pid", F_OK) >= 0;
2580 char* strshorten(char *s, size_t l) {
2589 static bool hostname_valid_char(char c) {
2591 (c >= 'a' && c <= 'z') ||
2592 (c >= 'A' && c <= 'Z') ||
2593 (c >= '0' && c <= '9') ||
2599 bool hostname_is_valid(const char *s) {
2606 /* Doesn't accept empty hostnames, hostnames with trailing or
2607 * leading dots, and hostnames with multiple dots in a
2608 * sequence. Also ensures that the length stays below
2611 for (p = s, dot = true; *p; p++) {
2618 if (!hostname_valid_char(*p))
2628 if (p-s > HOST_NAME_MAX)
2634 char* hostname_cleanup(char *s, bool lowercase) {
2638 for (p = s, d = s, dot = true; *p; p++) {
2645 } else if (hostname_valid_char(*p)) {
2646 *(d++) = lowercase ? tolower(*p) : *p;
2657 strshorten(s, HOST_NAME_MAX);
2662 bool machine_name_is_valid(const char *s) {
2664 if (!hostname_is_valid(s))
2667 /* Machine names should be useful hostnames, but also be
2668 * useful in unit names, hence we enforce a stricter length
2677 int pipe_eof(int fd) {
2678 struct pollfd pollfd = {
2680 .events = POLLIN|POLLHUP,
2685 r = poll(&pollfd, 1, 0);
2692 return pollfd.revents & POLLHUP;
2695 int fd_wait_for_event(int fd, int event, usec_t t) {
2697 struct pollfd pollfd = {
2705 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2712 return pollfd.revents;
2715 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2724 r = tempfn_xxxxxx(path, &t);
2728 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2734 f = fdopen(fd, "we");
2747 int symlink_atomic(const char *from, const char *to) {
2748 _cleanup_free_ char *t = NULL;
2754 r = tempfn_random(to, &t);
2758 if (symlink(from, t) < 0)
2761 if (rename(t, to) < 0) {
2769 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2770 _cleanup_free_ char *t = NULL;
2775 r = tempfn_random(path, &t);
2779 if (mknod(t, mode, dev) < 0)
2782 if (rename(t, path) < 0) {
2790 int mkfifo_atomic(const char *path, mode_t mode) {
2791 _cleanup_free_ char *t = NULL;
2796 r = tempfn_random(path, &t);
2800 if (mkfifo(t, mode) < 0)
2803 if (rename(t, path) < 0) {
2811 bool display_is_local(const char *display) {
2815 display[0] == ':' &&
2816 display[1] >= '0' &&
2820 int socket_from_display(const char *display, char **path) {
2827 if (!display_is_local(display))
2830 k = strspn(display+1, "0123456789");
2832 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2836 c = stpcpy(f, "/tmp/.X11-unix/X");
2837 memcpy(c, display+1, k);
2846 const char **username,
2847 uid_t *uid, gid_t *gid,
2849 const char **shell) {
2857 /* We enforce some special rules for uid=0: in order to avoid
2858 * NSS lookups for root we hardcode its data. */
2860 if (streq(*username, "root") || streq(*username, "0")) {
2878 if (parse_uid(*username, &u) >= 0) {
2882 /* If there are multiple users with the same id, make
2883 * sure to leave $USER to the configured value instead
2884 * of the first occurrence in the database. However if
2885 * the uid was configured by a numeric uid, then let's
2886 * pick the real username from /etc/passwd. */
2888 *username = p->pw_name;
2891 p = getpwnam(*username);
2895 return errno > 0 ? -errno : -ESRCH;
2907 *shell = p->pw_shell;
2912 char* uid_to_name(uid_t uid) {
2917 return strdup("root");
2921 return strdup(p->pw_name);
2923 if (asprintf(&r, UID_FMT, uid) < 0)
2929 char* gid_to_name(gid_t gid) {
2934 return strdup("root");
2938 return strdup(p->gr_name);
2940 if (asprintf(&r, GID_FMT, gid) < 0)
2946 int get_group_creds(const char **groupname, gid_t *gid) {
2952 /* We enforce some special rules for gid=0: in order to avoid
2953 * NSS lookups for root we hardcode its data. */
2955 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2956 *groupname = "root";
2964 if (parse_gid(*groupname, &id) >= 0) {
2969 *groupname = g->gr_name;
2972 g = getgrnam(*groupname);
2976 return errno > 0 ? -errno : -ESRCH;
2984 int in_gid(gid_t gid) {
2986 int ngroups_max, r, i;
2988 if (getgid() == gid)
2991 if (getegid() == gid)
2994 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2995 assert(ngroups_max > 0);
2997 gids = alloca(sizeof(gid_t) * ngroups_max);
2999 r = getgroups(ngroups_max, gids);
3003 for (i = 0; i < r; i++)
3010 int in_group(const char *name) {
3014 r = get_group_creds(&name, &gid);
3021 int glob_exists(const char *path) {
3022 _cleanup_globfree_ glob_t g = {};
3028 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3030 if (k == GLOB_NOMATCH)
3032 else if (k == GLOB_NOSPACE)
3035 return !strv_isempty(g.gl_pathv);
3037 return errno ? -errno : -EIO;
3040 int glob_extend(char ***strv, const char *path) {
3041 _cleanup_globfree_ glob_t g = {};
3046 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3048 if (k == GLOB_NOMATCH)
3050 else if (k == GLOB_NOSPACE)
3052 else if (k != 0 || strv_isempty(g.gl_pathv))
3053 return errno ? -errno : -EIO;
3055 STRV_FOREACH(p, g.gl_pathv) {
3056 k = strv_extend(strv, *p);
3064 int dirent_ensure_type(DIR *d, struct dirent *de) {
3070 if (de->d_type != DT_UNKNOWN)
3073 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3077 S_ISREG(st.st_mode) ? DT_REG :
3078 S_ISDIR(st.st_mode) ? DT_DIR :
3079 S_ISLNK(st.st_mode) ? DT_LNK :
3080 S_ISFIFO(st.st_mode) ? DT_FIFO :
3081 S_ISSOCK(st.st_mode) ? DT_SOCK :
3082 S_ISCHR(st.st_mode) ? DT_CHR :
3083 S_ISBLK(st.st_mode) ? DT_BLK :
3089 int get_files_in_directory(const char *path, char ***list) {
3090 _cleanup_closedir_ DIR *d = NULL;
3091 size_t bufsize = 0, n = 0;
3092 _cleanup_strv_free_ char **l = NULL;
3096 /* Returns all files in a directory in *list, and the number
3097 * of files as return value. If list is NULL returns only the
3109 if (!de && errno != 0)
3114 dirent_ensure_type(d, de);
3116 if (!dirent_is_file(de))
3120 /* one extra slot is needed for the terminating NULL */
3121 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3124 l[n] = strdup(de->d_name);
3135 l = NULL; /* avoid freeing */
3141 char *strjoin(const char *x, ...) {
3155 t = va_arg(ap, const char *);
3160 if (n > ((size_t) -1) - l) {
3184 t = va_arg(ap, const char *);
3198 bool is_main_thread(void) {
3199 static thread_local int cached = 0;
3201 if (_unlikely_(cached == 0))
3202 cached = getpid() == gettid() ? 1 : -1;
3207 int block_get_whole_disk(dev_t d, dev_t *ret) {
3214 /* If it has a queue this is good enough for us */
3215 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3218 r = access(p, F_OK);
3226 /* If it is a partition find the originating device */
3227 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3230 r = access(p, F_OK);
3236 /* Get parent dev_t */
3237 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3240 r = read_one_line_file(p, &s);
3246 r = sscanf(s, "%u:%u", &m, &n);
3252 /* Only return this if it is really good enough for us. */
3253 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3256 r = access(p, F_OK);
3260 *ret = makedev(m, n);
3267 static const char *const ioprio_class_table[] = {
3268 [IOPRIO_CLASS_NONE] = "none",
3269 [IOPRIO_CLASS_RT] = "realtime",
3270 [IOPRIO_CLASS_BE] = "best-effort",
3271 [IOPRIO_CLASS_IDLE] = "idle"
3274 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3276 static const char *const sigchld_code_table[] = {
3277 [CLD_EXITED] = "exited",
3278 [CLD_KILLED] = "killed",
3279 [CLD_DUMPED] = "dumped",
3280 [CLD_TRAPPED] = "trapped",
3281 [CLD_STOPPED] = "stopped",
3282 [CLD_CONTINUED] = "continued",
3285 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3287 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3288 [LOG_FAC(LOG_KERN)] = "kern",
3289 [LOG_FAC(LOG_USER)] = "user",
3290 [LOG_FAC(LOG_MAIL)] = "mail",
3291 [LOG_FAC(LOG_DAEMON)] = "daemon",
3292 [LOG_FAC(LOG_AUTH)] = "auth",
3293 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3294 [LOG_FAC(LOG_LPR)] = "lpr",
3295 [LOG_FAC(LOG_NEWS)] = "news",
3296 [LOG_FAC(LOG_UUCP)] = "uucp",
3297 [LOG_FAC(LOG_CRON)] = "cron",
3298 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3299 [LOG_FAC(LOG_FTP)] = "ftp",
3300 [LOG_FAC(LOG_LOCAL0)] = "local0",
3301 [LOG_FAC(LOG_LOCAL1)] = "local1",
3302 [LOG_FAC(LOG_LOCAL2)] = "local2",
3303 [LOG_FAC(LOG_LOCAL3)] = "local3",
3304 [LOG_FAC(LOG_LOCAL4)] = "local4",
3305 [LOG_FAC(LOG_LOCAL5)] = "local5",
3306 [LOG_FAC(LOG_LOCAL6)] = "local6",
3307 [LOG_FAC(LOG_LOCAL7)] = "local7"
3310 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3312 static const char *const log_level_table[] = {
3313 [LOG_EMERG] = "emerg",
3314 [LOG_ALERT] = "alert",
3315 [LOG_CRIT] = "crit",
3317 [LOG_WARNING] = "warning",
3318 [LOG_NOTICE] = "notice",
3319 [LOG_INFO] = "info",
3320 [LOG_DEBUG] = "debug"
3323 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3325 static const char* const sched_policy_table[] = {
3326 [SCHED_OTHER] = "other",
3327 [SCHED_BATCH] = "batch",
3328 [SCHED_IDLE] = "idle",
3329 [SCHED_FIFO] = "fifo",
3333 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3335 static const char* const rlimit_table[_RLIMIT_MAX] = {
3336 [RLIMIT_CPU] = "LimitCPU",
3337 [RLIMIT_FSIZE] = "LimitFSIZE",
3338 [RLIMIT_DATA] = "LimitDATA",
3339 [RLIMIT_STACK] = "LimitSTACK",
3340 [RLIMIT_CORE] = "LimitCORE",
3341 [RLIMIT_RSS] = "LimitRSS",
3342 [RLIMIT_NOFILE] = "LimitNOFILE",
3343 [RLIMIT_AS] = "LimitAS",
3344 [RLIMIT_NPROC] = "LimitNPROC",
3345 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3346 [RLIMIT_LOCKS] = "LimitLOCKS",
3347 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3348 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3349 [RLIMIT_NICE] = "LimitNICE",
3350 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3351 [RLIMIT_RTTIME] = "LimitRTTIME"
3354 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3356 static const char* const ip_tos_table[] = {
3357 [IPTOS_LOWDELAY] = "low-delay",
3358 [IPTOS_THROUGHPUT] = "throughput",
3359 [IPTOS_RELIABILITY] = "reliability",
3360 [IPTOS_LOWCOST] = "low-cost",
3363 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3365 static const char *const __signal_table[] = {
3382 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3393 [SIGVTALRM] = "VTALRM",
3395 [SIGWINCH] = "WINCH",
3401 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3403 const char *signal_to_string(int signo) {
3404 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3407 name = __signal_to_string(signo);
3411 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3412 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3414 snprintf(buf, sizeof(buf), "%d", signo);
3419 int signal_from_string(const char *s) {
3424 signo = __signal_from_string(s);
3428 if (startswith(s, "RTMIN+")) {
3432 if (safe_atou(s, &u) >= 0) {
3433 signo = (int) u + offset;
3434 if (signo > 0 && signo < _NSIG)
3440 bool kexec_loaded(void) {
3441 bool loaded = false;
3444 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3452 int prot_from_flags(int flags) {
3454 switch (flags & O_ACCMODE) {
3463 return PROT_READ|PROT_WRITE;
3470 char *format_bytes(char *buf, size_t l, off_t t) {
3473 static const struct {
3477 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3478 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3479 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3480 { "G", 1024ULL*1024ULL*1024ULL },
3481 { "M", 1024ULL*1024ULL },
3485 if (t == (off_t) -1)
3488 for (i = 0; i < ELEMENTSOF(table); i++) {
3490 if (t >= table[i].factor) {
3493 (unsigned long long) (t / table[i].factor),
3494 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3501 snprintf(buf, l, "%lluB", (unsigned long long) t);
3509 void* memdup(const void *p, size_t l) {
3522 int fd_inc_sndbuf(int fd, size_t n) {
3524 socklen_t l = sizeof(value);
3526 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3527 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3530 /* If we have the privileges we will ignore the kernel limit. */
3533 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3534 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3540 int fd_inc_rcvbuf(int fd, size_t n) {
3542 socklen_t l = sizeof(value);
3544 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3545 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3548 /* If we have the privileges we will ignore the kernel limit. */
3551 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3552 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3557 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3558 bool stdout_is_tty, stderr_is_tty;
3559 pid_t parent_pid, agent_pid;
3560 sigset_t ss, saved_ss;
3568 /* Spawns a temporary TTY agent, making sure it goes away when
3571 parent_pid = getpid();
3573 /* First we temporarily block all signals, so that the new
3574 * child has them blocked initially. This way, we can be sure
3575 * that SIGTERMs are not lost we might send to the agent. */
3576 assert_se(sigfillset(&ss) >= 0);
3577 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3580 if (agent_pid < 0) {
3581 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3585 if (agent_pid != 0) {
3586 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3593 * Make sure the agent goes away when the parent dies */
3594 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3595 _exit(EXIT_FAILURE);
3597 /* Make sure we actually can kill the agent, if we need to, in
3598 * case somebody invoked us from a shell script that trapped
3599 * SIGTERM or so... */
3600 reset_all_signal_handlers();
3601 reset_signal_mask();
3603 /* Check whether our parent died before we were able
3604 * to set the death signal and unblock the signals */
3605 if (getppid() != parent_pid)
3606 _exit(EXIT_SUCCESS);
3608 /* Don't leak fds to the agent */
3609 close_all_fds(except, n_except);
3611 stdout_is_tty = isatty(STDOUT_FILENO);
3612 stderr_is_tty = isatty(STDERR_FILENO);
3614 if (!stdout_is_tty || !stderr_is_tty) {
3617 /* Detach from stdout/stderr. and reopen
3618 * /dev/tty for them. This is important to
3619 * ensure that when systemctl is started via
3620 * popen() or a similar call that expects to
3621 * read EOF we actually do generate EOF and
3622 * not delay this indefinitely by because we
3623 * keep an unused copy of stdin around. */
3624 fd = open("/dev/tty", O_WRONLY);
3626 log_error_errno(errno, "Failed to open /dev/tty: %m");
3627 _exit(EXIT_FAILURE);
3631 dup2(fd, STDOUT_FILENO);
3634 dup2(fd, STDERR_FILENO);
3640 /* Count arguments */
3642 for (n = 0; va_arg(ap, char*); n++)
3647 l = alloca(sizeof(char *) * (n + 1));
3649 /* Fill in arguments */
3651 for (i = 0; i <= n; i++)
3652 l[i] = va_arg(ap, char*);
3656 _exit(EXIT_FAILURE);
3659 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3660 struct rlimit highest, fixed;
3664 if (setrlimit(resource, rlim) >= 0)
3670 /* So we failed to set the desired setrlimit, then let's try
3671 * to get as close as we can */
3672 assert_se(getrlimit(resource, &highest) == 0);
3674 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3675 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3677 if (setrlimit(resource, &fixed) < 0)
3683 bool http_etag_is_valid(const char *etag) {
3687 if (!endswith(etag, "\""))
3690 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3696 bool http_url_is_valid(const char *url) {
3702 p = startswith(url, "http://");
3704 p = startswith(url, "https://");
3711 return ascii_is_valid(p);
3714 bool documentation_url_is_valid(const char *url) {
3720 if (http_url_is_valid(url))
3723 p = startswith(url, "file:/");
3725 p = startswith(url, "info:");
3727 p = startswith(url, "man:");
3732 return ascii_is_valid(p);
3735 bool in_initrd(void) {
3736 static int saved = -1;
3742 /* We make two checks here:
3744 * 1. the flag file /etc/initrd-release must exist
3745 * 2. the root file system must be a memory file system
3747 * The second check is extra paranoia, since misdetecting an
3748 * initrd can have bad bad consequences due the initrd
3749 * emptying when transititioning to the main systemd.
3752 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3753 statfs("/", &s) >= 0 &&
3754 is_temporary_fs(&s);
3759 int get_home_dir(char **_h) {
3767 /* Take the user specified one */
3768 e = secure_getenv("HOME");
3769 if (e && path_is_absolute(e)) {
3778 /* Hardcode home directory for root to avoid NSS */
3781 h = strdup("/root");
3789 /* Check the database... */
3793 return errno > 0 ? -errno : -ESRCH;
3795 if (!path_is_absolute(p->pw_dir))
3798 h = strdup(p->pw_dir);
3806 int get_shell(char **_s) {
3814 /* Take the user specified one */
3815 e = getenv("SHELL");
3825 /* Hardcode home directory for root to avoid NSS */
3828 s = strdup("/bin/sh");
3836 /* Check the database... */
3840 return errno > 0 ? -errno : -ESRCH;
3842 if (!path_is_absolute(p->pw_shell))
3845 s = strdup(p->pw_shell);
3853 bool filename_is_valid(const char *p) {
3867 if (strlen(p) > FILENAME_MAX)
3873 bool string_is_safe(const char *p) {
3879 for (t = p; *t; t++) {
3880 if (*t > 0 && *t < ' ')
3883 if (strchr("\\\"\'\0x7f", *t))
3891 * Check if a string contains control characters. If 'ok' is non-NULL
3892 * it may be a string containing additional CCs to be considered OK.
3894 bool string_has_cc(const char *p, const char *ok) {
3899 for (t = p; *t; t++) {
3900 if (ok && strchr(ok, *t))
3903 if (*t > 0 && *t < ' ')
3913 bool path_is_safe(const char *p) {
3918 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3921 if (strlen(p) > PATH_MAX)
3924 /* The following two checks are not really dangerous, but hey, they still are confusing */
3925 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3928 if (strstr(p, "//"))
3934 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3935 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3936 int (*compar) (const void *, const void *, void *), void *arg) {
3945 p = (void *)(((const char *) base) + (idx * size));
3946 comparison = compar(key, p, arg);
3949 else if (comparison > 0)
3957 void init_gettext(void) {
3958 setlocale(LC_ALL, "");
3959 textdomain(GETTEXT_PACKAGE);
3962 bool is_locale_utf8(void) {
3964 static int cached_answer = -1;
3966 if (cached_answer >= 0)
3969 if (!setlocale(LC_ALL, "")) {
3970 cached_answer = true;
3974 set = nl_langinfo(CODESET);
3976 cached_answer = true;
3980 if (streq(set, "UTF-8")) {
3981 cached_answer = true;
3985 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3986 * unset and everything can do to UTF-8 nowadays. */
3987 set = setlocale(LC_CTYPE, NULL);
3989 cached_answer = true;
3993 /* Check result, but ignore the result if C was set
3997 !getenv("LC_ALL") &&
3998 !getenv("LC_CTYPE") &&
4002 return (bool) cached_answer;
4005 const char *draw_special_char(DrawSpecialChar ch) {
4006 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
4009 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
4010 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
4011 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
4012 [DRAW_TREE_SPACE] = " ", /* */
4013 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
4014 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
4015 [DRAW_ARROW] = "\342\206\222", /* → */
4016 [DRAW_DASH] = "\342\200\223", /* – */
4019 /* ASCII fallback */ {
4020 [DRAW_TREE_VERTICAL] = "| ",
4021 [DRAW_TREE_BRANCH] = "|-",
4022 [DRAW_TREE_RIGHT] = "`-",
4023 [DRAW_TREE_SPACE] = " ",
4024 [DRAW_TRIANGULAR_BULLET] = ">",
4025 [DRAW_BLACK_CIRCLE] = "*",
4026 [DRAW_ARROW] = "->",
4031 return draw_table[!is_locale_utf8()][ch];
4034 char *strreplace(const char *text, const char *old_string, const char *new_string) {
4037 size_t l, old_len, new_len;
4043 old_len = strlen(old_string);
4044 new_len = strlen(new_string);
4057 if (!startswith(f, old_string)) {
4063 nl = l - old_len + new_len;
4064 a = realloc(r, nl + 1);
4072 t = stpcpy(t, new_string);
4084 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4085 const char *i, *begin = NULL;
4090 } state = STATE_OTHER;
4092 size_t osz = 0, isz;
4098 /* Strips ANSI color and replaces TABs by 8 spaces */
4100 isz = _isz ? *_isz : strlen(*ibuf);
4102 f = open_memstream(&obuf, &osz);
4106 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4111 if (i >= *ibuf + isz) /* EOT */
4113 else if (*i == '\x1B')
4114 state = STATE_ESCAPE;
4115 else if (*i == '\t')
4122 if (i >= *ibuf + isz) { /* EOT */
4125 } else if (*i == '[') {
4126 state = STATE_BRACKET;
4131 state = STATE_OTHER;
4138 if (i >= *ibuf + isz || /* EOT */
4139 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4142 state = STATE_OTHER;
4144 } else if (*i == 'm')
4145 state = STATE_OTHER;
4167 int on_ac_power(void) {
4168 bool found_offline = false, found_online = false;
4169 _cleanup_closedir_ DIR *d = NULL;
4171 d = opendir("/sys/class/power_supply");
4173 return errno == ENOENT ? true : -errno;
4177 _cleanup_close_ int fd = -1, device = -1;
4183 if (!de && errno != 0)
4189 if (hidden_file(de->d_name))
4192 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4194 if (errno == ENOENT || errno == ENOTDIR)
4200 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4202 if (errno == ENOENT)
4208 n = read(fd, contents, sizeof(contents));
4212 if (n != 6 || memcmp(contents, "Mains\n", 6))
4216 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4218 if (errno == ENOENT)
4224 n = read(fd, contents, sizeof(contents));
4228 if (n != 2 || contents[1] != '\n')
4231 if (contents[0] == '1') {
4232 found_online = true;
4234 } else if (contents[0] == '0')
4235 found_offline = true;
4240 return found_online || !found_offline;
4243 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4250 if (!path_strv_resolve_uniq(search, root))
4253 STRV_FOREACH(i, search) {
4254 _cleanup_free_ char *p = NULL;
4258 p = strjoin(root, *i, "/", path, NULL);
4260 p = strjoin(*i, "/", path, NULL);
4270 if (errno != ENOENT)
4277 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4278 _cleanup_strv_free_ char **copy = NULL;
4284 if (path_is_absolute(path)) {
4287 f = fopen(path, mode);
4296 copy = strv_copy((char**) search);
4300 return search_and_fopen_internal(path, mode, root, copy, _f);
4303 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4304 _cleanup_strv_free_ char **s = NULL;
4306 if (path_is_absolute(path)) {
4309 f = fopen(path, mode);
4318 s = strv_split_nulstr(search);
4322 return search_and_fopen_internal(path, mode, root, s, _f);
4325 char *strextend(char **x, ...) {
4332 l = f = *x ? strlen(*x) : 0;
4339 t = va_arg(ap, const char *);
4344 if (n > ((size_t) -1) - l) {
4353 r = realloc(*x, l+1);
4363 t = va_arg(ap, const char *);
4377 char *strrep(const char *s, unsigned n) {
4385 p = r = malloc(l * n + 1);
4389 for (i = 0; i < n; i++)
4396 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4403 if (*allocated >= need)
4406 newalloc = MAX(need * 2, 64u / size);
4407 a = newalloc * size;
4409 /* check for overflows */
4410 if (a < size * need)
4418 *allocated = newalloc;
4422 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4431 q = greedy_realloc(p, allocated, need, size);
4435 if (*allocated > prev)
4436 memzero(q + prev * size, (*allocated - prev) * size);
4441 bool id128_is_valid(const char *s) {
4447 /* Simple formatted 128bit hex string */
4449 for (i = 0; i < l; i++) {
4452 if (!(c >= '0' && c <= '9') &&
4453 !(c >= 'a' && c <= 'z') &&
4454 !(c >= 'A' && c <= 'Z'))
4458 } else if (l == 36) {
4460 /* Formatted UUID */
4462 for (i = 0; i < l; i++) {
4465 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4469 if (!(c >= '0' && c <= '9') &&
4470 !(c >= 'a' && c <= 'z') &&
4471 !(c >= 'A' && c <= 'Z'))
4482 int split_pair(const char *s, const char *sep, char **l, char **r) {
4497 a = strndup(s, x - s);
4501 b = strdup(x + strlen(sep));
4513 int shall_restore_state(void) {
4514 _cleanup_free_ char *value = NULL;
4517 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4523 return parse_boolean(value) != 0;
4526 int proc_cmdline(char **ret) {
4529 if (detect_container(NULL) > 0)
4530 return get_process_cmdline(1, 0, false, ret);
4532 return read_one_line_file("/proc/cmdline", ret);
4535 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4536 _cleanup_free_ char *line = NULL;
4542 r = proc_cmdline(&line);
4548 _cleanup_free_ char *word = NULL;
4551 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4557 /* Filter out arguments that are intended only for the
4559 if (!in_initrd() && startswith(word, "rd."))
4562 value = strchr(word, '=');
4566 r = parse_item(word, value);
4574 int get_proc_cmdline_key(const char *key, char **value) {
4575 _cleanup_free_ char *line = NULL, *ret = NULL;
4582 r = proc_cmdline(&line);
4588 _cleanup_free_ char *word = NULL;
4591 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4597 /* Filter out arguments that are intended only for the
4599 if (!in_initrd() && startswith(word, "rd."))
4603 e = startswith(word, key);
4607 r = free_and_strdup(&ret, e);
4613 if (streq(word, key))
4627 int container_get_leader(const char *machine, pid_t *pid) {
4628 _cleanup_free_ char *s = NULL, *class = NULL;
4636 p = strjoina("/run/systemd/machines/", machine);
4637 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4645 if (!streq_ptr(class, "container"))
4648 r = parse_pid(s, &leader);
4658 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4659 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4667 mntns = procfs_file_alloca(pid, "ns/mnt");
4668 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4676 pidns = procfs_file_alloca(pid, "ns/pid");
4677 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4685 netns = procfs_file_alloca(pid, "ns/net");
4686 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4694 root = procfs_file_alloca(pid, "root");
4695 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4701 *pidns_fd = pidnsfd;
4704 *mntns_fd = mntnsfd;
4707 *netns_fd = netnsfd;
4712 pidnsfd = mntnsfd = netnsfd = -1;
4717 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4720 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4724 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4728 if (setns(netns_fd, CLONE_NEWNET) < 0)
4732 if (fchdir(root_fd) < 0)
4735 if (chroot(".") < 0)
4739 if (setresgid(0, 0, 0) < 0)
4742 if (setgroups(0, NULL) < 0)
4745 if (setresuid(0, 0, 0) < 0)
4751 int getpeercred(int fd, struct ucred *ucred) {
4752 socklen_t n = sizeof(struct ucred);
4759 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4763 if (n != sizeof(struct ucred))
4766 /* Check if the data is actually useful and not suppressed due
4767 * to namespacing issues */
4770 if (u.uid == UID_INVALID)
4772 if (u.gid == GID_INVALID)
4779 int getpeersec(int fd, char **ret) {
4791 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4795 if (errno != ERANGE)
4802 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4818 /* This is much like like mkostemp() but is subject to umask(). */
4819 int mkostemp_safe(char *pattern, int flags) {
4820 _cleanup_umask_ mode_t u;
4827 fd = mkostemp(pattern, flags);
4834 int open_tmpfile(const char *path, int flags) {
4841 /* Try O_TMPFILE first, if it is supported */
4842 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
4847 /* Fall back to unguessable name + unlinking */
4848 p = strjoina(path, "/systemd-tmp-XXXXXX");
4850 fd = mkostemp_safe(p, flags);
4858 int fd_warn_permissions(const char *path, int fd) {
4861 if (fstat(fd, &st) < 0)
4864 if (st.st_mode & 0111)
4865 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4867 if (st.st_mode & 0002)
4868 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4870 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4871 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);
4876 unsigned long personality_from_string(const char *p) {
4878 /* Parse a personality specifier. We introduce our own
4879 * identifiers that indicate specific ABIs, rather than just
4880 * hints regarding the register size, since we want to keep
4881 * things open for multiple locally supported ABIs for the
4882 * same register size. We try to reuse the ABI identifiers
4883 * used by libseccomp. */
4885 #if defined(__x86_64__)
4887 if (streq(p, "x86"))
4890 if (streq(p, "x86-64"))
4893 #elif defined(__i386__)
4895 if (streq(p, "x86"))
4899 /* personality(7) documents that 0xffffffffUL is used for
4900 * querying the current personality, hence let's use that here
4901 * as error indicator. */
4902 return 0xffffffffUL;
4905 const char* personality_to_string(unsigned long p) {
4907 #if defined(__x86_64__)
4909 if (p == PER_LINUX32)
4915 #elif defined(__i386__)
4924 uint64_t physical_memory(void) {
4927 /* We return this as uint64_t in case we are running as 32bit
4928 * process on a 64bit kernel with huge amounts of memory */
4930 mem = sysconf(_SC_PHYS_PAGES);
4933 return (uint64_t) mem * (uint64_t) page_size();
4936 void hexdump(FILE *f, const void *p, size_t s) {
4937 const uint8_t *b = p;
4940 assert(s == 0 || b);
4945 fprintf(f, "%04x ", n);
4947 for (i = 0; i < 16; i++) {
4952 fprintf(f, "%02x ", b[i]);
4960 for (i = 0; i < 16; i++) {
4965 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4979 int update_reboot_param_file(const char *param) {
4984 r = write_string_file(REBOOT_PARAM_FILE, param);
4986 log_error("Failed to write reboot param to "
4987 REBOOT_PARAM_FILE": %s", strerror(-r));
4989 unlink(REBOOT_PARAM_FILE);
4994 int umount_recursive(const char *prefix, int flags) {
4998 /* Try to umount everything recursively below a
4999 * directory. Also, take care of stacked mounts, and keep
5000 * unmounting them until they are gone. */
5003 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5008 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5009 if (!proc_self_mountinfo)
5013 _cleanup_free_ char *path = NULL, *p = NULL;
5016 k = fscanf(proc_self_mountinfo,
5017 "%*s " /* (1) mount id */
5018 "%*s " /* (2) parent id */
5019 "%*s " /* (3) major:minor */
5020 "%*s " /* (4) root */
5021 "%ms " /* (5) mount point */
5022 "%*s" /* (6) mount options */
5023 "%*[^-]" /* (7) optional fields */
5024 "- " /* (8) separator */
5025 "%*s " /* (9) file system type */
5026 "%*s" /* (10) mount source */
5027 "%*s" /* (11) mount options 2 */
5028 "%*[^\n]", /* some rubbish at the end */
5037 r = cunescape(path, UNESCAPE_RELAX, &p);
5041 if (!path_startswith(p, prefix))
5044 if (umount2(p, flags) < 0) {
5060 static int get_mount_flags(const char *path, unsigned long *flags) {
5063 if (statvfs(path, &buf) < 0)
5065 *flags = buf.f_flag;
5069 int bind_remount_recursive(const char *prefix, bool ro) {
5070 _cleanup_set_free_free_ Set *done = NULL;
5071 _cleanup_free_ char *cleaned = NULL;
5074 /* Recursively remount a directory (and all its submounts)
5075 * read-only or read-write. If the directory is already
5076 * mounted, we reuse the mount and simply mark it
5077 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5078 * operation). If it isn't we first make it one. Afterwards we
5079 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5080 * submounts we can access, too. When mounts are stacked on
5081 * the same mount point we only care for each individual
5082 * "top-level" mount on each point, as we cannot
5083 * influence/access the underlying mounts anyway. We do not
5084 * have any effect on future submounts that might get
5085 * propagated, they migt be writable. This includes future
5086 * submounts that have been triggered via autofs. */
5088 cleaned = strdup(prefix);
5092 path_kill_slashes(cleaned);
5094 done = set_new(&string_hash_ops);
5099 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5100 _cleanup_set_free_free_ Set *todo = NULL;
5101 bool top_autofs = false;
5103 unsigned long orig_flags;
5105 todo = set_new(&string_hash_ops);
5109 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5110 if (!proc_self_mountinfo)
5114 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5117 k = fscanf(proc_self_mountinfo,
5118 "%*s " /* (1) mount id */
5119 "%*s " /* (2) parent id */
5120 "%*s " /* (3) major:minor */
5121 "%*s " /* (4) root */
5122 "%ms " /* (5) mount point */
5123 "%*s" /* (6) mount options (superblock) */
5124 "%*[^-]" /* (7) optional fields */
5125 "- " /* (8) separator */
5126 "%ms " /* (9) file system type */
5127 "%*s" /* (10) mount source */
5128 "%*s" /* (11) mount options (bind mount) */
5129 "%*[^\n]", /* some rubbish at the end */
5139 r = cunescape(path, UNESCAPE_RELAX, &p);
5143 /* Let's ignore autofs mounts. If they aren't
5144 * triggered yet, we want to avoid triggering
5145 * them, as we don't make any guarantees for
5146 * future submounts anyway. If they are
5147 * already triggered, then we will find
5148 * another entry for this. */
5149 if (streq(type, "autofs")) {
5150 top_autofs = top_autofs || path_equal(cleaned, p);
5154 if (path_startswith(p, cleaned) &&
5155 !set_contains(done, p)) {
5157 r = set_consume(todo, p);
5167 /* If we have no submounts to process anymore and if
5168 * the root is either already done, or an autofs, we
5170 if (set_isempty(todo) &&
5171 (top_autofs || set_contains(done, cleaned)))
5174 if (!set_contains(done, cleaned) &&
5175 !set_contains(todo, cleaned)) {
5176 /* The prefix directory itself is not yet a
5177 * mount, make it one. */
5178 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5182 (void) get_mount_flags(cleaned, &orig_flags);
5183 orig_flags &= ~MS_RDONLY;
5185 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5188 x = strdup(cleaned);
5192 r = set_consume(done, x);
5197 while ((x = set_steal_first(todo))) {
5199 r = set_consume(done, x);
5205 /* Try to reuse the original flag set, but
5206 * don't care for errors, in case of
5207 * obstructed mounts */
5209 (void) get_mount_flags(x, &orig_flags);
5210 orig_flags &= ~MS_RDONLY;
5212 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5214 /* Deal with mount points that are
5215 * obstructed by a later mount */
5217 if (errno != ENOENT)
5225 int fflush_and_check(FILE *f) {
5232 return errno ? -errno : -EIO;
5237 int tempfn_xxxxxx(const char *p, char **ret) {
5249 * /foo/bar/.#waldoXXXXXX
5253 if (!filename_is_valid(fn))
5256 t = new(char, strlen(p) + 2 + 6 + 1);
5260 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5262 *ret = path_kill_slashes(t);
5266 int tempfn_random(const char *p, char **ret) {
5280 * /foo/bar/.#waldobaa2a261115984a9
5284 if (!filename_is_valid(fn))
5287 t = new(char, strlen(p) + 2 + 16 + 1);
5291 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5294 for (i = 0; i < 16; i++) {
5295 *(x++) = hexchar(u & 0xF);
5301 *ret = path_kill_slashes(t);
5305 int tempfn_random_child(const char *p, char **ret) {
5316 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5319 t = new(char, strlen(p) + 3 + 16 + 1);
5323 x = stpcpy(stpcpy(t, p), "/.#");
5326 for (i = 0; i < 16; i++) {
5327 *(x++) = hexchar(u & 0xF);
5333 *ret = path_kill_slashes(t);
5337 /* make sure the hostname is not "localhost" */
5338 bool is_localhost(const char *hostname) {
5341 /* This tries to identify local host and domain names
5342 * described in RFC6761 plus the redhatism of .localdomain */
5344 return streq(hostname, "localhost") ||
5345 streq(hostname, "localhost.") ||
5346 streq(hostname, "localdomain.") ||
5347 streq(hostname, "localdomain") ||
5348 endswith(hostname, ".localhost") ||
5349 endswith(hostname, ".localhost.") ||
5350 endswith(hostname, ".localdomain") ||
5351 endswith(hostname, ".localdomain.");
5354 int take_password_lock(const char *root) {
5356 struct flock flock = {
5358 .l_whence = SEEK_SET,
5366 /* This is roughly the same as lckpwdf(), but not as awful. We
5367 * don't want to use alarm() and signals, hence we implement
5368 * our own trivial version of this.
5370 * Note that shadow-utils also takes per-database locks in
5371 * addition to lckpwdf(). However, we don't given that they
5372 * are redundant as they they invoke lckpwdf() first and keep
5373 * it during everything they do. The per-database locks are
5374 * awfully racy, and thus we just won't do them. */
5377 path = strjoina(root, "/etc/.pwd.lock");
5379 path = "/etc/.pwd.lock";
5381 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5385 r = fcntl(fd, F_SETLKW, &flock);
5394 int is_symlink(const char *path) {
5397 if (lstat(path, &info) < 0)
5400 return !!S_ISLNK(info.st_mode);
5403 int is_dir(const char* path, bool follow) {
5408 r = stat(path, &st);
5410 r = lstat(path, &st);
5414 return !!S_ISDIR(st.st_mode);
5417 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5418 _cleanup_free_ char *s = NULL;
5419 size_t allocated = 0, sz = 0;
5427 SINGLE_QUOTE_ESCAPE,
5429 DOUBLE_QUOTE_ESCAPE,
5437 /* Parses the first word of a string, and returns it in
5438 * *ret. Removes all quotes in the process. When parsing fails
5439 * (because of an uneven number of quotes or similar), leaves
5440 * the pointer *p at the first invalid character. */
5450 else if (strchr(WHITESPACE, c))
5460 state = SINGLE_QUOTE;
5462 state = VALUE_ESCAPE;
5464 state = DOUBLE_QUOTE;
5465 else if (strchr(WHITESPACE, c))
5468 if (!GREEDY_REALLOC(s, allocated, sz+2))
5478 if (flags & UNQUOTE_RELAX)
5483 if (!GREEDY_REALLOC(s, allocated, sz+7))
5486 if (flags & UNQUOTE_CUNESCAPE) {
5489 r = cunescape_one(*p, (size_t) -1, &c, &u);
5496 s[sz++] = c; /* normal explicit char */
5498 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5507 if (flags & UNQUOTE_RELAX)
5510 } else if (c == '\'')
5513 state = SINGLE_QUOTE_ESCAPE;
5515 if (!GREEDY_REALLOC(s, allocated, sz+2))
5523 case SINGLE_QUOTE_ESCAPE:
5525 if (flags & UNQUOTE_RELAX)
5530 if (!GREEDY_REALLOC(s, allocated, sz+7))
5533 if (flags & UNQUOTE_CUNESCAPE) {
5536 r = cunescape_one(*p, (size_t) -1, &c, &u);
5545 sz += utf8_encode_unichar(s + sz, u);
5549 state = SINGLE_QUOTE;
5558 state = DOUBLE_QUOTE_ESCAPE;
5560 if (!GREEDY_REALLOC(s, allocated, sz+2))
5568 case DOUBLE_QUOTE_ESCAPE:
5570 if (flags & UNQUOTE_RELAX)
5575 if (!GREEDY_REALLOC(s, allocated, sz+7))
5578 if (flags & UNQUOTE_CUNESCAPE) {
5581 r = cunescape_one(*p, (size_t) -1, &c, &u);
5590 sz += utf8_encode_unichar(s + sz, u);
5594 state = DOUBLE_QUOTE;
5600 if (!strchr(WHITESPACE, c))
5622 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5627 /* Parses a number of words from a string, stripping any
5628 * quotes if necessary. */
5632 /* Count how many words are expected */
5633 va_start(ap, flags);
5635 if (!va_arg(ap, char **))
5644 /* Read all words into a temporary array */
5645 l = newa0(char*, n);
5646 for (c = 0; c < n; c++) {
5648 r = unquote_first_word(p, &l[c], flags);
5652 for (j = 0; j < c; j++)
5662 /* If we managed to parse all words, return them in the passed
5664 va_start(ap, flags);
5665 for (i = 0; i < n; i++) {
5668 v = va_arg(ap, char **);
5678 int free_and_strdup(char **p, const char *s) {
5683 /* Replaces a string pointer with an strdup()ed new string,
5684 * possibly freeing the old one. */
5699 int sethostname_idempotent(const char *s) {
5701 char buf[HOST_NAME_MAX + 1] = {};
5705 r = gethostname(buf, sizeof(buf));
5712 r = sethostname(s, strlen(s));
5719 int ptsname_malloc(int fd, char **ret) {
5732 if (ptsname_r(fd, c, l) == 0) {
5736 if (errno != ERANGE) {
5746 int openpt_in_namespace(pid_t pid, int flags) {
5747 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5748 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5750 struct cmsghdr cmsghdr;
5751 uint8_t buf[CMSG_SPACE(sizeof(int))];
5753 struct msghdr mh = {
5754 .msg_control = &control,
5755 .msg_controllen = sizeof(control),
5757 struct cmsghdr *cmsg;
5764 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5768 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5778 pair[0] = safe_close(pair[0]);
5780 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5782 _exit(EXIT_FAILURE);
5784 master = posix_openpt(flags);
5786 _exit(EXIT_FAILURE);
5788 cmsg = CMSG_FIRSTHDR(&mh);
5789 cmsg->cmsg_level = SOL_SOCKET;
5790 cmsg->cmsg_type = SCM_RIGHTS;
5791 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5792 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5794 mh.msg_controllen = cmsg->cmsg_len;
5796 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5797 _exit(EXIT_FAILURE);
5799 _exit(EXIT_SUCCESS);
5802 pair[1] = safe_close(pair[1]);
5804 r = wait_for_terminate(child, &si);
5807 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5810 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5813 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5814 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5818 fds = (int*) CMSG_DATA(cmsg);
5819 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5822 close_many(fds, n_fds);
5832 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5833 _cleanup_close_ int fd = -1;
5836 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5838 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5842 l = fgetxattr(fd, attribute, value, size);
5849 static int parse_crtime(le64_t le, usec_t *usec) {
5855 if (u == 0 || u == (uint64_t) -1)
5862 int fd_getcrtime(int fd, usec_t *usec) {
5869 /* Until Linux gets a real concept of birthtime/creation time,
5870 * let's fake one with xattrs */
5872 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5875 if (n != sizeof(le))
5878 return parse_crtime(le, usec);
5881 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5885 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5888 if (n != sizeof(le))
5891 return parse_crtime(le, usec);
5894 int path_getcrtime(const char *p, usec_t *usec) {
5901 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5904 if (n != sizeof(le))
5907 return parse_crtime(le, usec);
5910 int fd_setcrtime(int fd, usec_t usec) {
5916 usec = now(CLOCK_REALTIME);
5918 le = htole64((uint64_t) usec);
5919 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5925 int chattr_fd(int fd, unsigned value, unsigned mask) {
5926 unsigned old_attr, new_attr;
5931 if (fstat(fd, &st) < 0)
5934 /* Explicitly check whether this is a regular file or
5935 * directory. If it is anything else (such as a device node or
5936 * fifo), then the ioctl will not hit the file systems but
5937 * possibly drivers, where the ioctl might have different
5938 * effects. Notably, DRM is using the same ioctl() number. */
5940 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5946 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5949 new_attr = (old_attr & ~mask) | (value & mask);
5950 if (new_attr == old_attr)
5953 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5959 int chattr_path(const char *p, unsigned value, unsigned mask) {
5960 _cleanup_close_ int fd = -1;
5967 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5971 return chattr_fd(fd, value, mask);
5974 int read_attr_fd(int fd, unsigned *ret) {
5979 if (fstat(fd, &st) < 0)
5982 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
5985 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5991 int read_attr_path(const char *p, unsigned *ret) {
5992 _cleanup_close_ int fd = -1;
5997 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6001 return read_attr_fd(fd, ret);
6004 int make_lock_file(const char *p, int operation, LockFile *ret) {
6005 _cleanup_close_ int fd = -1;
6006 _cleanup_free_ char *t = NULL;
6010 * We use UNPOSIX locks if they are available. They have nice
6011 * semantics, and are mostly compatible with NFS. However,
6012 * they are only available on new kernels. When we detect we
6013 * are running on an older kernel, then we fall back to good
6014 * old BSD locks. They also have nice semantics, but are
6015 * slightly problematic on NFS, where they are upgraded to
6016 * POSIX locks, even though locally they are orthogonal to
6026 .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
6027 .l_whence = SEEK_SET,
6031 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
6035 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
6038 /* If the kernel is too old, use good old BSD locks */
6039 if (errno == EINVAL)
6040 r = flock(fd, operation);
6043 return errno == EAGAIN ? -EBUSY : -errno;
6046 /* If we acquired the lock, let's check if the file
6047 * still exists in the file system. If not, then the
6048 * previous exclusive owner removed it and then closed
6049 * it. In such a case our acquired lock is worthless,
6050 * hence try again. */
6055 if (st.st_nlink > 0)
6058 fd = safe_close(fd);
6063 ret->operation = operation;
6071 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
6079 if (!filename_is_valid(fn))
6082 t = newa(char, strlen(p) + 2 + 4 + 1);
6083 stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
6085 return make_lock_file(t, operation, ret);
6088 void release_lock_file(LockFile *f) {
6096 /* If we are the exclusive owner we can safely delete
6097 * the lock file itself. If we are not the exclusive
6098 * owner, we can try becoming it. */
6101 (f->operation & ~LOCK_NB) == LOCK_SH) {
6102 static const struct flock fl = {
6104 .l_whence = SEEK_SET,
6107 r = fcntl(f->fd, F_OFD_SETLK, &fl);
6108 if (r < 0 && errno == EINVAL)
6109 r = flock(f->fd, LOCK_EX|LOCK_NB);
6112 f->operation = LOCK_EX|LOCK_NB;
6115 if ((f->operation & ~LOCK_NB) == LOCK_EX)
6116 unlink_noerrno(f->path);
6122 f->fd = safe_close(f->fd);
6126 static size_t nul_length(const uint8_t *p, size_t sz) {
6141 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
6142 const uint8_t *q, *w, *e;
6150 n = nul_length(q, e - q);
6152 /* If there are more than the specified run length of
6153 * NUL bytes, or if this is the beginning or the end
6154 * of the buffer, then seek instead of write */
6155 if ((n > run_length) ||
6156 (n > 0 && q == p) ||
6157 (n > 0 && q + n >= e)) {
6159 l = write(fd, w, q - w);
6166 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6178 l = write(fd, w, q - w);
6185 return q - (const uint8_t*) p;
6188 void sigkill_wait(pid_t *pid) {
6194 if (kill(*pid, SIGKILL) > 0)
6195 (void) wait_for_terminate(*pid, NULL);
6198 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6199 int a = 0, b = 0, c = 0;
6209 if (!strchr(*p, '>'))
6212 if ((*p)[2] == '>') {
6213 c = undecchar((*p)[1]);
6215 } else if ((*p)[3] == '>') {
6216 b = undecchar((*p)[1]);
6217 c = undecchar((*p)[2]);
6219 } else if ((*p)[4] == '>') {
6220 a = undecchar((*p)[1]);
6221 b = undecchar((*p)[2]);
6222 c = undecchar((*p)[3]);
6227 if (a < 0 || b < 0 || c < 0 ||
6228 (!with_facility && (a || b || c > 7)))
6232 *priority = a*100 + b*10 + c;
6234 *priority = (*priority & LOG_FACMASK) | c;
6240 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6246 for (i = 0; i < len; ++i)
6247 if (streq_ptr(table[i], key))
6253 void cmsg_close_all(struct msghdr *mh) {
6254 struct cmsghdr *cmsg;
6258 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6259 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6260 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6263 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6267 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6271 /* Even though renameat2() exists since Linux 3.15, btrfs added
6272 * support for it later. If it is not implemented, fallback to another
6274 if (errno != EINVAL)
6277 /* The link()/unlink() fallback does not work on directories. But
6278 * renameat() without RENAME_NOREPLACE gives the same semantics on
6279 * directories, except when newpath is an *empty* directory. This is
6281 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6282 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6283 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6284 return ret >= 0 ? 0 : -errno;
6287 /* If it is not a directory, use the link()/unlink() fallback. */
6288 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6292 ret = unlinkat(olddirfd, oldpath, 0);
6294 /* backup errno before the following unlinkat() alters it */
6296 (void) unlinkat(newdirfd, newpath, 0);
6304 char *shell_maybe_quote(const char *s) {
6310 /* Encloses a string in double quotes if necessary to make it
6311 * OK as shell string. */
6313 for (p = s; *p; p++)
6316 strchr(SHELL_NEED_QUOTES, *p))
6322 r = new(char, 1+strlen(s)*2+1+1);
6328 t = mempcpy(t, s, p - s);
6332 if (strchr(SHELL_NEED_ESCAPE, *p))
6344 int parse_mode(const char *s, mode_t *ret) {
6352 l = strtol(s, &x, 8);
6356 if (!x || x == s || *x)
6358 if (l < 0 || l > 07777)