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 int files_same(const char *filea, const char *fileb) {
2089 if (stat(filea, &a) < 0)
2092 if (stat(fileb, &b) < 0)
2095 return a.st_dev == b.st_dev &&
2096 a.st_ino == b.st_ino;
2099 int running_in_chroot(void) {
2102 ret = files_same("/proc/1/root", "/");
2109 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2114 assert(percent <= 100);
2115 assert(new_length >= 3);
2117 if (old_length <= 3 || old_length <= new_length)
2118 return strndup(s, old_length);
2120 r = new0(char, new_length+1);
2124 x = (new_length * percent) / 100;
2126 if (x > new_length - 3)
2134 s + old_length - (new_length - x - 3),
2135 new_length - x - 3);
2140 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2144 unsigned k, len, len2;
2147 assert(percent <= 100);
2148 assert(new_length >= 3);
2150 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2151 if (ascii_is_valid(s))
2152 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2154 if (old_length <= 3 || old_length <= new_length)
2155 return strndup(s, old_length);
2157 x = (new_length * percent) / 100;
2159 if (x > new_length - 3)
2163 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2166 c = utf8_encoded_to_unichar(i);
2169 k += unichar_iswide(c) ? 2 : 1;
2172 if (k > x) /* last character was wide and went over quota */
2175 for (j = s + old_length; k < new_length && j > i; ) {
2178 j = utf8_prev_char(j);
2179 c = utf8_encoded_to_unichar(j);
2182 k += unichar_iswide(c) ? 2 : 1;
2186 /* we don't actually need to ellipsize */
2188 return memdup(s, old_length + 1);
2190 /* make space for ellipsis */
2191 j = utf8_next_char(j);
2194 len2 = s + old_length - j;
2195 e = new(char, len + 3 + len2 + 1);
2200 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2201 old_length, new_length, x, len, len2, k);
2205 e[len] = 0xe2; /* tri-dot ellipsis: … */
2209 memcpy(e + len + 3, j, len2 + 1);
2214 char *ellipsize(const char *s, size_t length, unsigned percent) {
2215 return ellipsize_mem(s, strlen(s), length, percent);
2218 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2219 _cleanup_close_ int fd;
2225 mkdir_parents(path, 0755);
2227 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2232 r = fchmod(fd, mode);
2237 if (uid != UID_INVALID || gid != GID_INVALID) {
2238 r = fchown(fd, uid, gid);
2243 if (stamp != USEC_INFINITY) {
2244 struct timespec ts[2];
2246 timespec_store(&ts[0], stamp);
2248 r = futimens(fd, ts);
2250 r = futimens(fd, NULL);
2257 int touch(const char *path) {
2258 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2261 static char *unquote(const char *s, const char* quotes) {
2265 /* This is rather stupid, simply removes the heading and
2266 * trailing quotes if there is one. Doesn't care about
2267 * escaping or anything.
2269 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2275 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2276 return strndup(s+1, l-2);
2281 noreturn void freeze(void) {
2283 /* Make sure nobody waits for us on a socket anymore */
2284 close_all_fds(NULL, 0);
2292 bool null_or_empty(struct stat *st) {
2295 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2298 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2304 int null_or_empty_path(const char *fn) {
2309 if (stat(fn, &st) < 0)
2312 return null_or_empty(&st);
2315 int null_or_empty_fd(int fd) {
2320 if (fstat(fd, &st) < 0)
2323 return null_or_empty(&st);
2326 DIR *xopendirat(int fd, const char *name, int flags) {
2330 assert(!(flags & O_CREAT));
2332 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2345 int signal_from_string_try_harder(const char *s) {
2349 signo = signal_from_string(s);
2351 if (startswith(s, "SIG"))
2352 return signal_from_string(s+3);
2357 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2358 _cleanup_free_ char *t = NULL, *u = NULL;
2361 u = unquote(tagvalue, QUOTES);
2365 enc_len = strlen(u) * 4 + 1;
2366 t = new(char, enc_len);
2370 if (encode_devnode_name(u, t, enc_len) < 0)
2373 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2376 char *fstab_node_to_udev_node(const char *p) {
2379 if (startswith(p, "LABEL="))
2380 return tag_to_udev_node(p+6, "label");
2382 if (startswith(p, "UUID="))
2383 return tag_to_udev_node(p+5, "uuid");
2385 if (startswith(p, "PARTUUID="))
2386 return tag_to_udev_node(p+9, "partuuid");
2388 if (startswith(p, "PARTLABEL="))
2389 return tag_to_udev_node(p+10, "partlabel");
2394 bool dirent_is_file(const struct dirent *de) {
2397 if (hidden_file(de->d_name))
2400 if (de->d_type != DT_REG &&
2401 de->d_type != DT_LNK &&
2402 de->d_type != DT_UNKNOWN)
2408 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2411 if (de->d_type != DT_REG &&
2412 de->d_type != DT_LNK &&
2413 de->d_type != DT_UNKNOWN)
2416 if (hidden_file_allow_backup(de->d_name))
2419 return endswith(de->d_name, suffix);
2422 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2423 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2424 _cleanup_set_free_free_ Set *seen = NULL;
2427 /* We fork this all off from a child process so that we can
2428 * somewhat cleanly make use of SIGALRM to set a time limit */
2430 reset_all_signal_handlers();
2431 reset_signal_mask();
2433 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2435 pids = hashmap_new(NULL);
2439 seen = set_new(&string_hash_ops);
2443 STRV_FOREACH(directory, directories) {
2444 _cleanup_closedir_ DIR *d;
2447 d = opendir(*directory);
2449 if (errno == ENOENT)
2452 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2455 FOREACH_DIRENT(de, d, break) {
2456 _cleanup_free_ char *path = NULL;
2460 if (!dirent_is_file(de))
2463 if (set_contains(seen, de->d_name)) {
2464 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2468 r = set_put_strdup(seen, de->d_name);
2472 path = strjoin(*directory, "/", de->d_name, NULL);
2476 if (null_or_empty_path(path)) {
2477 log_debug("%s is empty (a mask).", path);
2483 log_error_errno(errno, "Failed to fork: %m");
2485 } else if (pid == 0) {
2488 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2498 return log_error_errno(errno, "Failed to execute %s: %m", path);
2501 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2503 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2510 /* Abort execution of this process after the timout. We simply
2511 * rely on SIGALRM as default action terminating the process,
2512 * and turn on alarm(). */
2514 if (timeout != USEC_INFINITY)
2515 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2517 while (!hashmap_isempty(pids)) {
2518 _cleanup_free_ char *path = NULL;
2521 pid = PTR_TO_UINT(hashmap_first_key(pids));
2524 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2527 wait_for_terminate_and_warn(path, pid, true);
2533 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2537 char **dirs = (char**) directories;
2539 assert(!strv_isempty(dirs));
2541 name = basename(dirs[0]);
2542 assert(!isempty(name));
2544 /* Executes all binaries in the directories in parallel and waits
2545 * for them to finish. Optionally a timeout is applied. If a file
2546 * with the same name exists in more than one directory, the
2547 * earliest one wins. */
2549 executor_pid = fork();
2550 if (executor_pid < 0) {
2551 log_error_errno(errno, "Failed to fork: %m");
2554 } else if (executor_pid == 0) {
2555 r = do_execute(dirs, timeout, argv);
2556 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2559 wait_for_terminate_and_warn(name, executor_pid, true);
2562 bool nulstr_contains(const char*nulstr, const char *needle) {
2568 NULSTR_FOREACH(i, nulstr)
2569 if (streq(i, needle))
2575 bool plymouth_running(void) {
2576 return access("/run/plymouth/pid", F_OK) >= 0;
2579 char* strshorten(char *s, size_t l) {
2588 static bool hostname_valid_char(char c) {
2590 (c >= 'a' && c <= 'z') ||
2591 (c >= 'A' && c <= 'Z') ||
2592 (c >= '0' && c <= '9') ||
2598 bool hostname_is_valid(const char *s) {
2605 /* Doesn't accept empty hostnames, hostnames with trailing or
2606 * leading dots, and hostnames with multiple dots in a
2607 * sequence. Also ensures that the length stays below
2610 for (p = s, dot = true; *p; p++) {
2617 if (!hostname_valid_char(*p))
2627 if (p-s > HOST_NAME_MAX)
2633 char* hostname_cleanup(char *s, bool lowercase) {
2637 for (p = s, d = s, dot = true; *p; p++) {
2644 } else if (hostname_valid_char(*p)) {
2645 *(d++) = lowercase ? tolower(*p) : *p;
2656 strshorten(s, HOST_NAME_MAX);
2661 bool machine_name_is_valid(const char *s) {
2663 if (!hostname_is_valid(s))
2666 /* Machine names should be useful hostnames, but also be
2667 * useful in unit names, hence we enforce a stricter length
2676 int pipe_eof(int fd) {
2677 struct pollfd pollfd = {
2679 .events = POLLIN|POLLHUP,
2684 r = poll(&pollfd, 1, 0);
2691 return pollfd.revents & POLLHUP;
2694 int fd_wait_for_event(int fd, int event, usec_t t) {
2696 struct pollfd pollfd = {
2704 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
2711 return pollfd.revents;
2714 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
2723 r = tempfn_xxxxxx(path, &t);
2727 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
2733 f = fdopen(fd, "we");
2746 int symlink_atomic(const char *from, const char *to) {
2747 _cleanup_free_ char *t = NULL;
2753 r = tempfn_random(to, &t);
2757 if (symlink(from, t) < 0)
2760 if (rename(t, to) < 0) {
2768 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
2769 _cleanup_free_ char *t = NULL;
2774 r = tempfn_random(path, &t);
2778 if (mknod(t, mode, dev) < 0)
2781 if (rename(t, path) < 0) {
2789 int mkfifo_atomic(const char *path, mode_t mode) {
2790 _cleanup_free_ char *t = NULL;
2795 r = tempfn_random(path, &t);
2799 if (mkfifo(t, mode) < 0)
2802 if (rename(t, path) < 0) {
2810 bool display_is_local(const char *display) {
2814 display[0] == ':' &&
2815 display[1] >= '0' &&
2819 int socket_from_display(const char *display, char **path) {
2826 if (!display_is_local(display))
2829 k = strspn(display+1, "0123456789");
2831 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
2835 c = stpcpy(f, "/tmp/.X11-unix/X");
2836 memcpy(c, display+1, k);
2845 const char **username,
2846 uid_t *uid, gid_t *gid,
2848 const char **shell) {
2856 /* We enforce some special rules for uid=0: in order to avoid
2857 * NSS lookups for root we hardcode its data. */
2859 if (streq(*username, "root") || streq(*username, "0")) {
2877 if (parse_uid(*username, &u) >= 0) {
2881 /* If there are multiple users with the same id, make
2882 * sure to leave $USER to the configured value instead
2883 * of the first occurrence in the database. However if
2884 * the uid was configured by a numeric uid, then let's
2885 * pick the real username from /etc/passwd. */
2887 *username = p->pw_name;
2890 p = getpwnam(*username);
2894 return errno > 0 ? -errno : -ESRCH;
2906 *shell = p->pw_shell;
2911 char* uid_to_name(uid_t uid) {
2916 return strdup("root");
2920 return strdup(p->pw_name);
2922 if (asprintf(&r, UID_FMT, uid) < 0)
2928 char* gid_to_name(gid_t gid) {
2933 return strdup("root");
2937 return strdup(p->gr_name);
2939 if (asprintf(&r, GID_FMT, gid) < 0)
2945 int get_group_creds(const char **groupname, gid_t *gid) {
2951 /* We enforce some special rules for gid=0: in order to avoid
2952 * NSS lookups for root we hardcode its data. */
2954 if (streq(*groupname, "root") || streq(*groupname, "0")) {
2955 *groupname = "root";
2963 if (parse_gid(*groupname, &id) >= 0) {
2968 *groupname = g->gr_name;
2971 g = getgrnam(*groupname);
2975 return errno > 0 ? -errno : -ESRCH;
2983 int in_gid(gid_t gid) {
2985 int ngroups_max, r, i;
2987 if (getgid() == gid)
2990 if (getegid() == gid)
2993 ngroups_max = sysconf(_SC_NGROUPS_MAX);
2994 assert(ngroups_max > 0);
2996 gids = alloca(sizeof(gid_t) * ngroups_max);
2998 r = getgroups(ngroups_max, gids);
3002 for (i = 0; i < r; i++)
3009 int in_group(const char *name) {
3013 r = get_group_creds(&name, &gid);
3020 int glob_exists(const char *path) {
3021 _cleanup_globfree_ glob_t g = {};
3027 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3029 if (k == GLOB_NOMATCH)
3031 else if (k == GLOB_NOSPACE)
3034 return !strv_isempty(g.gl_pathv);
3036 return errno ? -errno : -EIO;
3039 int glob_extend(char ***strv, const char *path) {
3040 _cleanup_globfree_ glob_t g = {};
3045 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3047 if (k == GLOB_NOMATCH)
3049 else if (k == GLOB_NOSPACE)
3051 else if (k != 0 || strv_isempty(g.gl_pathv))
3052 return errno ? -errno : -EIO;
3054 STRV_FOREACH(p, g.gl_pathv) {
3055 k = strv_extend(strv, *p);
3063 int dirent_ensure_type(DIR *d, struct dirent *de) {
3069 if (de->d_type != DT_UNKNOWN)
3072 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3076 S_ISREG(st.st_mode) ? DT_REG :
3077 S_ISDIR(st.st_mode) ? DT_DIR :
3078 S_ISLNK(st.st_mode) ? DT_LNK :
3079 S_ISFIFO(st.st_mode) ? DT_FIFO :
3080 S_ISSOCK(st.st_mode) ? DT_SOCK :
3081 S_ISCHR(st.st_mode) ? DT_CHR :
3082 S_ISBLK(st.st_mode) ? DT_BLK :
3088 int get_files_in_directory(const char *path, char ***list) {
3089 _cleanup_closedir_ DIR *d = NULL;
3090 size_t bufsize = 0, n = 0;
3091 _cleanup_strv_free_ char **l = NULL;
3095 /* Returns all files in a directory in *list, and the number
3096 * of files as return value. If list is NULL returns only the
3108 if (!de && errno != 0)
3113 dirent_ensure_type(d, de);
3115 if (!dirent_is_file(de))
3119 /* one extra slot is needed for the terminating NULL */
3120 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3123 l[n] = strdup(de->d_name);
3134 l = NULL; /* avoid freeing */
3140 char *strjoin(const char *x, ...) {
3154 t = va_arg(ap, const char *);
3159 if (n > ((size_t) -1) - l) {
3183 t = va_arg(ap, const char *);
3197 bool is_main_thread(void) {
3198 static thread_local int cached = 0;
3200 if (_unlikely_(cached == 0))
3201 cached = getpid() == gettid() ? 1 : -1;
3206 int block_get_whole_disk(dev_t d, dev_t *ret) {
3213 /* If it has a queue this is good enough for us */
3214 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3217 r = access(p, F_OK);
3225 /* If it is a partition find the originating device */
3226 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3229 r = access(p, F_OK);
3235 /* Get parent dev_t */
3236 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3239 r = read_one_line_file(p, &s);
3245 r = sscanf(s, "%u:%u", &m, &n);
3251 /* Only return this if it is really good enough for us. */
3252 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3255 r = access(p, F_OK);
3259 *ret = makedev(m, n);
3266 static const char *const ioprio_class_table[] = {
3267 [IOPRIO_CLASS_NONE] = "none",
3268 [IOPRIO_CLASS_RT] = "realtime",
3269 [IOPRIO_CLASS_BE] = "best-effort",
3270 [IOPRIO_CLASS_IDLE] = "idle"
3273 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3275 static const char *const sigchld_code_table[] = {
3276 [CLD_EXITED] = "exited",
3277 [CLD_KILLED] = "killed",
3278 [CLD_DUMPED] = "dumped",
3279 [CLD_TRAPPED] = "trapped",
3280 [CLD_STOPPED] = "stopped",
3281 [CLD_CONTINUED] = "continued",
3284 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3286 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3287 [LOG_FAC(LOG_KERN)] = "kern",
3288 [LOG_FAC(LOG_USER)] = "user",
3289 [LOG_FAC(LOG_MAIL)] = "mail",
3290 [LOG_FAC(LOG_DAEMON)] = "daemon",
3291 [LOG_FAC(LOG_AUTH)] = "auth",
3292 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3293 [LOG_FAC(LOG_LPR)] = "lpr",
3294 [LOG_FAC(LOG_NEWS)] = "news",
3295 [LOG_FAC(LOG_UUCP)] = "uucp",
3296 [LOG_FAC(LOG_CRON)] = "cron",
3297 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3298 [LOG_FAC(LOG_FTP)] = "ftp",
3299 [LOG_FAC(LOG_LOCAL0)] = "local0",
3300 [LOG_FAC(LOG_LOCAL1)] = "local1",
3301 [LOG_FAC(LOG_LOCAL2)] = "local2",
3302 [LOG_FAC(LOG_LOCAL3)] = "local3",
3303 [LOG_FAC(LOG_LOCAL4)] = "local4",
3304 [LOG_FAC(LOG_LOCAL5)] = "local5",
3305 [LOG_FAC(LOG_LOCAL6)] = "local6",
3306 [LOG_FAC(LOG_LOCAL7)] = "local7"
3309 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3311 static const char *const log_level_table[] = {
3312 [LOG_EMERG] = "emerg",
3313 [LOG_ALERT] = "alert",
3314 [LOG_CRIT] = "crit",
3316 [LOG_WARNING] = "warning",
3317 [LOG_NOTICE] = "notice",
3318 [LOG_INFO] = "info",
3319 [LOG_DEBUG] = "debug"
3322 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3324 static const char* const sched_policy_table[] = {
3325 [SCHED_OTHER] = "other",
3326 [SCHED_BATCH] = "batch",
3327 [SCHED_IDLE] = "idle",
3328 [SCHED_FIFO] = "fifo",
3332 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3334 static const char* const rlimit_table[_RLIMIT_MAX] = {
3335 [RLIMIT_CPU] = "LimitCPU",
3336 [RLIMIT_FSIZE] = "LimitFSIZE",
3337 [RLIMIT_DATA] = "LimitDATA",
3338 [RLIMIT_STACK] = "LimitSTACK",
3339 [RLIMIT_CORE] = "LimitCORE",
3340 [RLIMIT_RSS] = "LimitRSS",
3341 [RLIMIT_NOFILE] = "LimitNOFILE",
3342 [RLIMIT_AS] = "LimitAS",
3343 [RLIMIT_NPROC] = "LimitNPROC",
3344 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3345 [RLIMIT_LOCKS] = "LimitLOCKS",
3346 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3347 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3348 [RLIMIT_NICE] = "LimitNICE",
3349 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3350 [RLIMIT_RTTIME] = "LimitRTTIME"
3353 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3355 static const char* const ip_tos_table[] = {
3356 [IPTOS_LOWDELAY] = "low-delay",
3357 [IPTOS_THROUGHPUT] = "throughput",
3358 [IPTOS_RELIABILITY] = "reliability",
3359 [IPTOS_LOWCOST] = "low-cost",
3362 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3364 static const char *const __signal_table[] = {
3381 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3392 [SIGVTALRM] = "VTALRM",
3394 [SIGWINCH] = "WINCH",
3400 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
3402 const char *signal_to_string(int signo) {
3403 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
3406 name = __signal_to_string(signo);
3410 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
3411 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
3413 snprintf(buf, sizeof(buf), "%d", signo);
3418 int signal_from_string(const char *s) {
3423 signo = __signal_from_string(s);
3427 if (startswith(s, "RTMIN+")) {
3431 if (safe_atou(s, &u) >= 0) {
3432 signo = (int) u + offset;
3433 if (signo > 0 && signo < _NSIG)
3439 bool kexec_loaded(void) {
3440 bool loaded = false;
3443 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3451 int prot_from_flags(int flags) {
3453 switch (flags & O_ACCMODE) {
3462 return PROT_READ|PROT_WRITE;
3469 char *format_bytes(char *buf, size_t l, off_t t) {
3472 static const struct {
3476 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3477 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3478 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3479 { "G", 1024ULL*1024ULL*1024ULL },
3480 { "M", 1024ULL*1024ULL },
3484 if (t == (off_t) -1)
3487 for (i = 0; i < ELEMENTSOF(table); i++) {
3489 if (t >= table[i].factor) {
3492 (unsigned long long) (t / table[i].factor),
3493 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
3500 snprintf(buf, l, "%lluB", (unsigned long long) t);
3508 void* memdup(const void *p, size_t l) {
3521 int fd_inc_sndbuf(int fd, size_t n) {
3523 socklen_t l = sizeof(value);
3525 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3526 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3529 /* If we have the privileges we will ignore the kernel limit. */
3532 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3533 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3539 int fd_inc_rcvbuf(int fd, size_t n) {
3541 socklen_t l = sizeof(value);
3543 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3544 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3547 /* If we have the privileges we will ignore the kernel limit. */
3550 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3551 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3556 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3557 bool stdout_is_tty, stderr_is_tty;
3558 pid_t parent_pid, agent_pid;
3559 sigset_t ss, saved_ss;
3567 /* Spawns a temporary TTY agent, making sure it goes away when
3570 parent_pid = getpid();
3572 /* First we temporarily block all signals, so that the new
3573 * child has them blocked initially. This way, we can be sure
3574 * that SIGTERMs are not lost we might send to the agent. */
3575 assert_se(sigfillset(&ss) >= 0);
3576 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3579 if (agent_pid < 0) {
3580 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3584 if (agent_pid != 0) {
3585 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3592 * Make sure the agent goes away when the parent dies */
3593 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3594 _exit(EXIT_FAILURE);
3596 /* Make sure we actually can kill the agent, if we need to, in
3597 * case somebody invoked us from a shell script that trapped
3598 * SIGTERM or so... */
3599 reset_all_signal_handlers();
3600 reset_signal_mask();
3602 /* Check whether our parent died before we were able
3603 * to set the death signal and unblock the signals */
3604 if (getppid() != parent_pid)
3605 _exit(EXIT_SUCCESS);
3607 /* Don't leak fds to the agent */
3608 close_all_fds(except, n_except);
3610 stdout_is_tty = isatty(STDOUT_FILENO);
3611 stderr_is_tty = isatty(STDERR_FILENO);
3613 if (!stdout_is_tty || !stderr_is_tty) {
3616 /* Detach from stdout/stderr. and reopen
3617 * /dev/tty for them. This is important to
3618 * ensure that when systemctl is started via
3619 * popen() or a similar call that expects to
3620 * read EOF we actually do generate EOF and
3621 * not delay this indefinitely by because we
3622 * keep an unused copy of stdin around. */
3623 fd = open("/dev/tty", O_WRONLY);
3625 log_error_errno(errno, "Failed to open /dev/tty: %m");
3626 _exit(EXIT_FAILURE);
3630 dup2(fd, STDOUT_FILENO);
3633 dup2(fd, STDERR_FILENO);
3639 /* Count arguments */
3641 for (n = 0; va_arg(ap, char*); n++)
3646 l = alloca(sizeof(char *) * (n + 1));
3648 /* Fill in arguments */
3650 for (i = 0; i <= n; i++)
3651 l[i] = va_arg(ap, char*);
3655 _exit(EXIT_FAILURE);
3658 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3659 struct rlimit highest, fixed;
3663 if (setrlimit(resource, rlim) >= 0)
3669 /* So we failed to set the desired setrlimit, then let's try
3670 * to get as close as we can */
3671 assert_se(getrlimit(resource, &highest) == 0);
3673 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3674 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3676 if (setrlimit(resource, &fixed) < 0)
3682 bool http_etag_is_valid(const char *etag) {
3686 if (!endswith(etag, "\""))
3689 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
3695 bool http_url_is_valid(const char *url) {
3701 p = startswith(url, "http://");
3703 p = startswith(url, "https://");
3710 return ascii_is_valid(p);
3713 bool documentation_url_is_valid(const char *url) {
3719 if (http_url_is_valid(url))
3722 p = startswith(url, "file:/");
3724 p = startswith(url, "info:");
3726 p = startswith(url, "man:");
3731 return ascii_is_valid(p);
3734 bool in_initrd(void) {
3735 static int saved = -1;
3741 /* We make two checks here:
3743 * 1. the flag file /etc/initrd-release must exist
3744 * 2. the root file system must be a memory file system
3746 * The second check is extra paranoia, since misdetecting an
3747 * initrd can have bad bad consequences due the initrd
3748 * emptying when transititioning to the main systemd.
3751 saved = access("/etc/initrd-release", F_OK) >= 0 &&
3752 statfs("/", &s) >= 0 &&
3753 is_temporary_fs(&s);
3758 int get_home_dir(char **_h) {
3766 /* Take the user specified one */
3767 e = secure_getenv("HOME");
3768 if (e && path_is_absolute(e)) {
3777 /* Hardcode home directory for root to avoid NSS */
3780 h = strdup("/root");
3788 /* Check the database... */
3792 return errno > 0 ? -errno : -ESRCH;
3794 if (!path_is_absolute(p->pw_dir))
3797 h = strdup(p->pw_dir);
3805 int get_shell(char **_s) {
3813 /* Take the user specified one */
3814 e = getenv("SHELL");
3824 /* Hardcode home directory for root to avoid NSS */
3827 s = strdup("/bin/sh");
3835 /* Check the database... */
3839 return errno > 0 ? -errno : -ESRCH;
3841 if (!path_is_absolute(p->pw_shell))
3844 s = strdup(p->pw_shell);
3852 bool filename_is_valid(const char *p) {
3866 if (strlen(p) > FILENAME_MAX)
3872 bool string_is_safe(const char *p) {
3878 for (t = p; *t; t++) {
3879 if (*t > 0 && *t < ' ')
3882 if (strchr("\\\"\'\0x7f", *t))
3890 * Check if a string contains control characters. If 'ok' is non-NULL
3891 * it may be a string containing additional CCs to be considered OK.
3893 bool string_has_cc(const char *p, const char *ok) {
3898 for (t = p; *t; t++) {
3899 if (ok && strchr(ok, *t))
3902 if (*t > 0 && *t < ' ')
3912 bool path_is_safe(const char *p) {
3917 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
3920 if (strlen(p) > PATH_MAX)
3923 /* The following two checks are not really dangerous, but hey, they still are confusing */
3924 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
3927 if (strstr(p, "//"))
3933 /* hey glibc, APIs with callbacks without a user pointer are so useless */
3934 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
3935 int (*compar) (const void *, const void *, void *), void *arg) {
3944 p = (void *)(((const char *) base) + (idx * size));
3945 comparison = compar(key, p, arg);
3948 else if (comparison > 0)
3956 void init_gettext(void) {
3957 setlocale(LC_ALL, "");
3958 textdomain(GETTEXT_PACKAGE);
3961 bool is_locale_utf8(void) {
3963 static int cached_answer = -1;
3965 if (cached_answer >= 0)
3968 if (!setlocale(LC_ALL, "")) {
3969 cached_answer = true;
3973 set = nl_langinfo(CODESET);
3975 cached_answer = true;
3979 if (streq(set, "UTF-8")) {
3980 cached_answer = true;
3984 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
3985 * unset and everything can do to UTF-8 nowadays. */
3986 set = setlocale(LC_CTYPE, NULL);
3988 cached_answer = true;
3992 /* Check result, but ignore the result if C was set
3996 !getenv("LC_ALL") &&
3997 !getenv("LC_CTYPE") &&
4001 return (bool) cached_answer;
4004 const char *draw_special_char(DrawSpecialChar ch) {
4005 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
4008 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
4009 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
4010 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
4011 [DRAW_TREE_SPACE] = " ", /* */
4012 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
4013 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
4014 [DRAW_ARROW] = "\342\206\222", /* → */
4015 [DRAW_DASH] = "\342\200\223", /* – */
4018 /* ASCII fallback */ {
4019 [DRAW_TREE_VERTICAL] = "| ",
4020 [DRAW_TREE_BRANCH] = "|-",
4021 [DRAW_TREE_RIGHT] = "`-",
4022 [DRAW_TREE_SPACE] = " ",
4023 [DRAW_TRIANGULAR_BULLET] = ">",
4024 [DRAW_BLACK_CIRCLE] = "*",
4025 [DRAW_ARROW] = "->",
4030 return draw_table[!is_locale_utf8()][ch];
4033 char *strreplace(const char *text, const char *old_string, const char *new_string) {
4036 size_t l, old_len, new_len;
4042 old_len = strlen(old_string);
4043 new_len = strlen(new_string);
4056 if (!startswith(f, old_string)) {
4062 nl = l - old_len + new_len;
4063 a = realloc(r, nl + 1);
4071 t = stpcpy(t, new_string);
4083 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4084 const char *i, *begin = NULL;
4089 } state = STATE_OTHER;
4091 size_t osz = 0, isz;
4097 /* Strips ANSI color and replaces TABs by 8 spaces */
4099 isz = _isz ? *_isz : strlen(*ibuf);
4101 f = open_memstream(&obuf, &osz);
4105 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4110 if (i >= *ibuf + isz) /* EOT */
4112 else if (*i == '\x1B')
4113 state = STATE_ESCAPE;
4114 else if (*i == '\t')
4121 if (i >= *ibuf + isz) { /* EOT */
4124 } else if (*i == '[') {
4125 state = STATE_BRACKET;
4130 state = STATE_OTHER;
4137 if (i >= *ibuf + isz || /* EOT */
4138 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4141 state = STATE_OTHER;
4143 } else if (*i == 'm')
4144 state = STATE_OTHER;
4166 int on_ac_power(void) {
4167 bool found_offline = false, found_online = false;
4168 _cleanup_closedir_ DIR *d = NULL;
4170 d = opendir("/sys/class/power_supply");
4172 return errno == ENOENT ? true : -errno;
4176 _cleanup_close_ int fd = -1, device = -1;
4182 if (!de && errno != 0)
4188 if (hidden_file(de->d_name))
4191 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4193 if (errno == ENOENT || errno == ENOTDIR)
4199 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4201 if (errno == ENOENT)
4207 n = read(fd, contents, sizeof(contents));
4211 if (n != 6 || memcmp(contents, "Mains\n", 6))
4215 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4217 if (errno == ENOENT)
4223 n = read(fd, contents, sizeof(contents));
4227 if (n != 2 || contents[1] != '\n')
4230 if (contents[0] == '1') {
4231 found_online = true;
4233 } else if (contents[0] == '0')
4234 found_offline = true;
4239 return found_online || !found_offline;
4242 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4249 if (!path_strv_resolve_uniq(search, root))
4252 STRV_FOREACH(i, search) {
4253 _cleanup_free_ char *p = NULL;
4257 p = strjoin(root, *i, "/", path, NULL);
4259 p = strjoin(*i, "/", path, NULL);
4269 if (errno != ENOENT)
4276 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4277 _cleanup_strv_free_ char **copy = NULL;
4283 if (path_is_absolute(path)) {
4286 f = fopen(path, mode);
4295 copy = strv_copy((char**) search);
4299 return search_and_fopen_internal(path, mode, root, copy, _f);
4302 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4303 _cleanup_strv_free_ char **s = NULL;
4305 if (path_is_absolute(path)) {
4308 f = fopen(path, mode);
4317 s = strv_split_nulstr(search);
4321 return search_and_fopen_internal(path, mode, root, s, _f);
4324 char *strextend(char **x, ...) {
4331 l = f = *x ? strlen(*x) : 0;
4338 t = va_arg(ap, const char *);
4343 if (n > ((size_t) -1) - l) {
4352 r = realloc(*x, l+1);
4362 t = va_arg(ap, const char *);
4376 char *strrep(const char *s, unsigned n) {
4384 p = r = malloc(l * n + 1);
4388 for (i = 0; i < n; i++)
4395 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4402 if (*allocated >= need)
4405 newalloc = MAX(need * 2, 64u / size);
4406 a = newalloc * size;
4408 /* check for overflows */
4409 if (a < size * need)
4417 *allocated = newalloc;
4421 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4430 q = greedy_realloc(p, allocated, need, size);
4434 if (*allocated > prev)
4435 memzero(q + prev * size, (*allocated - prev) * size);
4440 bool id128_is_valid(const char *s) {
4446 /* Simple formatted 128bit hex string */
4448 for (i = 0; i < l; i++) {
4451 if (!(c >= '0' && c <= '9') &&
4452 !(c >= 'a' && c <= 'z') &&
4453 !(c >= 'A' && c <= 'Z'))
4457 } else if (l == 36) {
4459 /* Formatted UUID */
4461 for (i = 0; i < l; i++) {
4464 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4468 if (!(c >= '0' && c <= '9') &&
4469 !(c >= 'a' && c <= 'z') &&
4470 !(c >= 'A' && c <= 'Z'))
4481 int split_pair(const char *s, const char *sep, char **l, char **r) {
4496 a = strndup(s, x - s);
4500 b = strdup(x + strlen(sep));
4512 int shall_restore_state(void) {
4513 _cleanup_free_ char *value = NULL;
4516 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4522 return parse_boolean(value) != 0;
4525 int proc_cmdline(char **ret) {
4528 if (detect_container(NULL) > 0)
4529 return get_process_cmdline(1, 0, false, ret);
4531 return read_one_line_file("/proc/cmdline", ret);
4534 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4535 _cleanup_free_ char *line = NULL;
4541 r = proc_cmdline(&line);
4547 _cleanup_free_ char *word = NULL;
4550 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4556 /* Filter out arguments that are intended only for the
4558 if (!in_initrd() && startswith(word, "rd."))
4561 value = strchr(word, '=');
4565 r = parse_item(word, value);
4573 int get_proc_cmdline_key(const char *key, char **value) {
4574 _cleanup_free_ char *line = NULL, *ret = NULL;
4581 r = proc_cmdline(&line);
4587 _cleanup_free_ char *word = NULL;
4590 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
4596 /* Filter out arguments that are intended only for the
4598 if (!in_initrd() && startswith(word, "rd."))
4602 e = startswith(word, key);
4606 r = free_and_strdup(&ret, e);
4612 if (streq(word, key))
4626 int container_get_leader(const char *machine, pid_t *pid) {
4627 _cleanup_free_ char *s = NULL, *class = NULL;
4635 p = strjoina("/run/systemd/machines/", machine);
4636 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4644 if (!streq_ptr(class, "container"))
4647 r = parse_pid(s, &leader);
4657 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
4658 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
4666 mntns = procfs_file_alloca(pid, "ns/mnt");
4667 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4675 pidns = procfs_file_alloca(pid, "ns/pid");
4676 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4684 netns = procfs_file_alloca(pid, "ns/net");
4685 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4693 root = procfs_file_alloca(pid, "root");
4694 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
4700 *pidns_fd = pidnsfd;
4703 *mntns_fd = mntnsfd;
4706 *netns_fd = netnsfd;
4711 pidnsfd = mntnsfd = netnsfd = -1;
4716 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
4719 if (setns(pidns_fd, CLONE_NEWPID) < 0)
4723 if (setns(mntns_fd, CLONE_NEWNS) < 0)
4727 if (setns(netns_fd, CLONE_NEWNET) < 0)
4731 if (fchdir(root_fd) < 0)
4734 if (chroot(".") < 0)
4738 if (setresgid(0, 0, 0) < 0)
4741 if (setgroups(0, NULL) < 0)
4744 if (setresuid(0, 0, 0) < 0)
4750 int getpeercred(int fd, struct ucred *ucred) {
4751 socklen_t n = sizeof(struct ucred);
4758 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
4762 if (n != sizeof(struct ucred))
4765 /* Check if the data is actually useful and not suppressed due
4766 * to namespacing issues */
4769 if (u.uid == UID_INVALID)
4771 if (u.gid == GID_INVALID)
4778 int getpeersec(int fd, char **ret) {
4790 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4794 if (errno != ERANGE)
4801 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
4817 /* This is much like like mkostemp() but is subject to umask(). */
4818 int mkostemp_safe(char *pattern, int flags) {
4819 _cleanup_umask_ mode_t u;
4826 fd = mkostemp(pattern, flags);
4833 int open_tmpfile(const char *path, int flags) {
4840 /* Try O_TMPFILE first, if it is supported */
4841 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
4846 /* Fall back to unguessable name + unlinking */
4847 p = strjoina(path, "/systemd-tmp-XXXXXX");
4849 fd = mkostemp_safe(p, flags);
4857 int fd_warn_permissions(const char *path, int fd) {
4860 if (fstat(fd, &st) < 0)
4863 if (st.st_mode & 0111)
4864 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
4866 if (st.st_mode & 0002)
4867 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
4869 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
4870 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);
4875 unsigned long personality_from_string(const char *p) {
4877 /* Parse a personality specifier. We introduce our own
4878 * identifiers that indicate specific ABIs, rather than just
4879 * hints regarding the register size, since we want to keep
4880 * things open for multiple locally supported ABIs for the
4881 * same register size. We try to reuse the ABI identifiers
4882 * used by libseccomp. */
4884 #if defined(__x86_64__)
4886 if (streq(p, "x86"))
4889 if (streq(p, "x86-64"))
4892 #elif defined(__i386__)
4894 if (streq(p, "x86"))
4898 /* personality(7) documents that 0xffffffffUL is used for
4899 * querying the current personality, hence let's use that here
4900 * as error indicator. */
4901 return 0xffffffffUL;
4904 const char* personality_to_string(unsigned long p) {
4906 #if defined(__x86_64__)
4908 if (p == PER_LINUX32)
4914 #elif defined(__i386__)
4923 uint64_t physical_memory(void) {
4926 /* We return this as uint64_t in case we are running as 32bit
4927 * process on a 64bit kernel with huge amounts of memory */
4929 mem = sysconf(_SC_PHYS_PAGES);
4932 return (uint64_t) mem * (uint64_t) page_size();
4935 void hexdump(FILE *f, const void *p, size_t s) {
4936 const uint8_t *b = p;
4939 assert(s == 0 || b);
4944 fprintf(f, "%04x ", n);
4946 for (i = 0; i < 16; i++) {
4951 fprintf(f, "%02x ", b[i]);
4959 for (i = 0; i < 16; i++) {
4964 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
4978 int update_reboot_param_file(const char *param) {
4983 r = write_string_file(REBOOT_PARAM_FILE, param);
4985 log_error("Failed to write reboot param to "
4986 REBOOT_PARAM_FILE": %s", strerror(-r));
4988 unlink(REBOOT_PARAM_FILE);
4993 int umount_recursive(const char *prefix, int flags) {
4997 /* Try to umount everything recursively below a
4998 * directory. Also, take care of stacked mounts, and keep
4999 * unmounting them until they are gone. */
5002 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5007 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5008 if (!proc_self_mountinfo)
5012 _cleanup_free_ char *path = NULL, *p = NULL;
5015 k = fscanf(proc_self_mountinfo,
5016 "%*s " /* (1) mount id */
5017 "%*s " /* (2) parent id */
5018 "%*s " /* (3) major:minor */
5019 "%*s " /* (4) root */
5020 "%ms " /* (5) mount point */
5021 "%*s" /* (6) mount options */
5022 "%*[^-]" /* (7) optional fields */
5023 "- " /* (8) separator */
5024 "%*s " /* (9) file system type */
5025 "%*s" /* (10) mount source */
5026 "%*s" /* (11) mount options 2 */
5027 "%*[^\n]", /* some rubbish at the end */
5036 r = cunescape(path, UNESCAPE_RELAX, &p);
5040 if (!path_startswith(p, prefix))
5043 if (umount2(p, flags) < 0) {
5059 static int get_mount_flags(const char *path, unsigned long *flags) {
5062 if (statvfs(path, &buf) < 0)
5064 *flags = buf.f_flag;
5068 int bind_remount_recursive(const char *prefix, bool ro) {
5069 _cleanup_set_free_free_ Set *done = NULL;
5070 _cleanup_free_ char *cleaned = NULL;
5073 /* Recursively remount a directory (and all its submounts)
5074 * read-only or read-write. If the directory is already
5075 * mounted, we reuse the mount and simply mark it
5076 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5077 * operation). If it isn't we first make it one. Afterwards we
5078 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5079 * submounts we can access, too. When mounts are stacked on
5080 * the same mount point we only care for each individual
5081 * "top-level" mount on each point, as we cannot
5082 * influence/access the underlying mounts anyway. We do not
5083 * have any effect on future submounts that might get
5084 * propagated, they migt be writable. This includes future
5085 * submounts that have been triggered via autofs. */
5087 cleaned = strdup(prefix);
5091 path_kill_slashes(cleaned);
5093 done = set_new(&string_hash_ops);
5098 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5099 _cleanup_set_free_free_ Set *todo = NULL;
5100 bool top_autofs = false;
5102 unsigned long orig_flags;
5104 todo = set_new(&string_hash_ops);
5108 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5109 if (!proc_self_mountinfo)
5113 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5116 k = fscanf(proc_self_mountinfo,
5117 "%*s " /* (1) mount id */
5118 "%*s " /* (2) parent id */
5119 "%*s " /* (3) major:minor */
5120 "%*s " /* (4) root */
5121 "%ms " /* (5) mount point */
5122 "%*s" /* (6) mount options (superblock) */
5123 "%*[^-]" /* (7) optional fields */
5124 "- " /* (8) separator */
5125 "%ms " /* (9) file system type */
5126 "%*s" /* (10) mount source */
5127 "%*s" /* (11) mount options (bind mount) */
5128 "%*[^\n]", /* some rubbish at the end */
5138 r = cunescape(path, UNESCAPE_RELAX, &p);
5142 /* Let's ignore autofs mounts. If they aren't
5143 * triggered yet, we want to avoid triggering
5144 * them, as we don't make any guarantees for
5145 * future submounts anyway. If they are
5146 * already triggered, then we will find
5147 * another entry for this. */
5148 if (streq(type, "autofs")) {
5149 top_autofs = top_autofs || path_equal(cleaned, p);
5153 if (path_startswith(p, cleaned) &&
5154 !set_contains(done, p)) {
5156 r = set_consume(todo, p);
5166 /* If we have no submounts to process anymore and if
5167 * the root is either already done, or an autofs, we
5169 if (set_isempty(todo) &&
5170 (top_autofs || set_contains(done, cleaned)))
5173 if (!set_contains(done, cleaned) &&
5174 !set_contains(todo, cleaned)) {
5175 /* The prefix directory itself is not yet a
5176 * mount, make it one. */
5177 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5181 (void) get_mount_flags(cleaned, &orig_flags);
5182 orig_flags &= ~MS_RDONLY;
5184 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5187 x = strdup(cleaned);
5191 r = set_consume(done, x);
5196 while ((x = set_steal_first(todo))) {
5198 r = set_consume(done, x);
5204 /* Try to reuse the original flag set, but
5205 * don't care for errors, in case of
5206 * obstructed mounts */
5208 (void) get_mount_flags(x, &orig_flags);
5209 orig_flags &= ~MS_RDONLY;
5211 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5213 /* Deal with mount points that are
5214 * obstructed by a later mount */
5216 if (errno != ENOENT)
5224 int fflush_and_check(FILE *f) {
5231 return errno ? -errno : -EIO;
5236 int tempfn_xxxxxx(const char *p, char **ret) {
5248 * /foo/bar/.#waldoXXXXXX
5252 if (!filename_is_valid(fn))
5255 t = new(char, strlen(p) + 2 + 6 + 1);
5259 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
5261 *ret = path_kill_slashes(t);
5265 int tempfn_random(const char *p, char **ret) {
5279 * /foo/bar/.#waldobaa2a261115984a9
5283 if (!filename_is_valid(fn))
5286 t = new(char, strlen(p) + 2 + 16 + 1);
5290 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
5293 for (i = 0; i < 16; i++) {
5294 *(x++) = hexchar(u & 0xF);
5300 *ret = path_kill_slashes(t);
5304 int tempfn_random_child(const char *p, char **ret) {
5315 * /foo/bar/waldo/.#3c2b6219aa75d7d0
5318 t = new(char, strlen(p) + 3 + 16 + 1);
5322 x = stpcpy(stpcpy(t, p), "/.#");
5325 for (i = 0; i < 16; i++) {
5326 *(x++) = hexchar(u & 0xF);
5332 *ret = path_kill_slashes(t);
5336 /* make sure the hostname is not "localhost" */
5337 bool is_localhost(const char *hostname) {
5340 /* This tries to identify local host and domain names
5341 * described in RFC6761 plus the redhatism of .localdomain */
5343 return streq(hostname, "localhost") ||
5344 streq(hostname, "localhost.") ||
5345 streq(hostname, "localdomain.") ||
5346 streq(hostname, "localdomain") ||
5347 endswith(hostname, ".localhost") ||
5348 endswith(hostname, ".localhost.") ||
5349 endswith(hostname, ".localdomain") ||
5350 endswith(hostname, ".localdomain.");
5353 int take_password_lock(const char *root) {
5355 struct flock flock = {
5357 .l_whence = SEEK_SET,
5365 /* This is roughly the same as lckpwdf(), but not as awful. We
5366 * don't want to use alarm() and signals, hence we implement
5367 * our own trivial version of this.
5369 * Note that shadow-utils also takes per-database locks in
5370 * addition to lckpwdf(). However, we don't given that they
5371 * are redundant as they they invoke lckpwdf() first and keep
5372 * it during everything they do. The per-database locks are
5373 * awfully racy, and thus we just won't do them. */
5376 path = strjoina(root, "/etc/.pwd.lock");
5378 path = "/etc/.pwd.lock";
5380 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5384 r = fcntl(fd, F_SETLKW, &flock);
5393 int is_symlink(const char *path) {
5396 if (lstat(path, &info) < 0)
5399 return !!S_ISLNK(info.st_mode);
5402 int is_dir(const char* path, bool follow) {
5407 r = stat(path, &st);
5409 r = lstat(path, &st);
5413 return !!S_ISDIR(st.st_mode);
5416 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
5417 _cleanup_free_ char *s = NULL;
5418 size_t allocated = 0, sz = 0;
5426 SINGLE_QUOTE_ESCAPE,
5428 DOUBLE_QUOTE_ESCAPE,
5436 /* Parses the first word of a string, and returns it in
5437 * *ret. Removes all quotes in the process. When parsing fails
5438 * (because of an uneven number of quotes or similar), leaves
5439 * the pointer *p at the first invalid character. */
5449 else if (strchr(WHITESPACE, c))
5459 state = SINGLE_QUOTE;
5461 state = VALUE_ESCAPE;
5463 state = DOUBLE_QUOTE;
5464 else if (strchr(WHITESPACE, c))
5467 if (!GREEDY_REALLOC(s, allocated, sz+2))
5477 if (flags & UNQUOTE_RELAX)
5482 if (!GREEDY_REALLOC(s, allocated, sz+7))
5485 if (flags & UNQUOTE_CUNESCAPE) {
5488 r = cunescape_one(*p, (size_t) -1, &c, &u);
5495 s[sz++] = c; /* normal explicit char */
5497 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5506 if (flags & UNQUOTE_RELAX)
5509 } else if (c == '\'')
5512 state = SINGLE_QUOTE_ESCAPE;
5514 if (!GREEDY_REALLOC(s, allocated, sz+2))
5522 case SINGLE_QUOTE_ESCAPE:
5524 if (flags & UNQUOTE_RELAX)
5529 if (!GREEDY_REALLOC(s, allocated, sz+7))
5532 if (flags & UNQUOTE_CUNESCAPE) {
5535 r = cunescape_one(*p, (size_t) -1, &c, &u);
5544 sz += utf8_encode_unichar(s + sz, u);
5548 state = SINGLE_QUOTE;
5557 state = DOUBLE_QUOTE_ESCAPE;
5559 if (!GREEDY_REALLOC(s, allocated, sz+2))
5567 case DOUBLE_QUOTE_ESCAPE:
5569 if (flags & UNQUOTE_RELAX)
5574 if (!GREEDY_REALLOC(s, allocated, sz+7))
5577 if (flags & UNQUOTE_CUNESCAPE) {
5580 r = cunescape_one(*p, (size_t) -1, &c, &u);
5589 sz += utf8_encode_unichar(s + sz, u);
5593 state = DOUBLE_QUOTE;
5599 if (!strchr(WHITESPACE, c))
5621 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
5626 /* Parses a number of words from a string, stripping any
5627 * quotes if necessary. */
5631 /* Count how many words are expected */
5632 va_start(ap, flags);
5634 if (!va_arg(ap, char **))
5643 /* Read all words into a temporary array */
5644 l = newa0(char*, n);
5645 for (c = 0; c < n; c++) {
5647 r = unquote_first_word(p, &l[c], flags);
5651 for (j = 0; j < c; j++)
5661 /* If we managed to parse all words, return them in the passed
5663 va_start(ap, flags);
5664 for (i = 0; i < n; i++) {
5667 v = va_arg(ap, char **);
5677 int free_and_strdup(char **p, const char *s) {
5682 /* Replaces a string pointer with an strdup()ed new string,
5683 * possibly freeing the old one. */
5698 int sethostname_idempotent(const char *s) {
5700 char buf[HOST_NAME_MAX + 1] = {};
5704 r = gethostname(buf, sizeof(buf));
5711 r = sethostname(s, strlen(s));
5718 int ptsname_malloc(int fd, char **ret) {
5731 if (ptsname_r(fd, c, l) == 0) {
5735 if (errno != ERANGE) {
5745 int openpt_in_namespace(pid_t pid, int flags) {
5746 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
5747 _cleanup_close_pair_ int pair[2] = { -1, -1 };
5749 struct cmsghdr cmsghdr;
5750 uint8_t buf[CMSG_SPACE(sizeof(int))];
5752 struct msghdr mh = {
5753 .msg_control = &control,
5754 .msg_controllen = sizeof(control),
5756 struct cmsghdr *cmsg;
5763 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
5767 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
5777 pair[0] = safe_close(pair[0]);
5779 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
5781 _exit(EXIT_FAILURE);
5783 master = posix_openpt(flags);
5785 _exit(EXIT_FAILURE);
5787 cmsg = CMSG_FIRSTHDR(&mh);
5788 cmsg->cmsg_level = SOL_SOCKET;
5789 cmsg->cmsg_type = SCM_RIGHTS;
5790 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
5791 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
5793 mh.msg_controllen = cmsg->cmsg_len;
5795 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
5796 _exit(EXIT_FAILURE);
5798 _exit(EXIT_SUCCESS);
5801 pair[1] = safe_close(pair[1]);
5803 r = wait_for_terminate(child, &si);
5806 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
5809 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
5812 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
5813 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
5817 fds = (int*) CMSG_DATA(cmsg);
5818 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
5821 close_many(fds, n_fds);
5831 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
5832 _cleanup_close_ int fd = -1;
5835 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
5837 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
5841 l = fgetxattr(fd, attribute, value, size);
5848 static int parse_crtime(le64_t le, usec_t *usec) {
5854 if (u == 0 || u == (uint64_t) -1)
5861 int fd_getcrtime(int fd, usec_t *usec) {
5868 /* Until Linux gets a real concept of birthtime/creation time,
5869 * let's fake one with xattrs */
5871 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
5874 if (n != sizeof(le))
5877 return parse_crtime(le, usec);
5880 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
5884 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
5887 if (n != sizeof(le))
5890 return parse_crtime(le, usec);
5893 int path_getcrtime(const char *p, usec_t *usec) {
5900 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
5903 if (n != sizeof(le))
5906 return parse_crtime(le, usec);
5909 int fd_setcrtime(int fd, usec_t usec) {
5915 usec = now(CLOCK_REALTIME);
5917 le = htole64((uint64_t) usec);
5918 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
5924 int chattr_fd(int fd, unsigned value, unsigned mask) {
5925 unsigned old_attr, new_attr;
5932 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
5935 new_attr = (old_attr & ~mask) | (value & mask);
5936 if (new_attr == old_attr)
5939 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
5945 int chattr_path(const char *p, unsigned value, unsigned mask) {
5946 _cleanup_close_ int fd = -1;
5953 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5957 return chattr_fd(fd, value, mask);
5960 int read_attr_fd(int fd, unsigned *ret) {
5963 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
5969 int read_attr_path(const char *p, unsigned *ret) {
5970 _cleanup_close_ int fd = -1;
5975 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
5979 return read_attr_fd(fd, ret);
5982 int make_lock_file(const char *p, int operation, LockFile *ret) {
5983 _cleanup_close_ int fd = -1;
5984 _cleanup_free_ char *t = NULL;
5988 * We use UNPOSIX locks if they are available. They have nice
5989 * semantics, and are mostly compatible with NFS. However,
5990 * they are only available on new kernels. When we detect we
5991 * are running on an older kernel, then we fall back to good
5992 * old BSD locks. They also have nice semantics, but are
5993 * slightly problematic on NFS, where they are upgraded to
5994 * POSIX locks, even though locally they are orthogonal to
6004 .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
6005 .l_whence = SEEK_SET,
6009 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
6013 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
6016 /* If the kernel is too old, use good old BSD locks */
6017 if (errno == EINVAL)
6018 r = flock(fd, operation);
6021 return errno == EAGAIN ? -EBUSY : -errno;
6024 /* If we acquired the lock, let's check if the file
6025 * still exists in the file system. If not, then the
6026 * previous exclusive owner removed it and then closed
6027 * it. In such a case our acquired lock is worthless,
6028 * hence try again. */
6033 if (st.st_nlink > 0)
6036 fd = safe_close(fd);
6041 ret->operation = operation;
6049 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
6057 if (!filename_is_valid(fn))
6060 t = newa(char, strlen(p) + 2 + 4 + 1);
6061 stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
6063 return make_lock_file(t, operation, ret);
6066 void release_lock_file(LockFile *f) {
6074 /* If we are the exclusive owner we can safely delete
6075 * the lock file itself. If we are not the exclusive
6076 * owner, we can try becoming it. */
6079 (f->operation & ~LOCK_NB) == LOCK_SH) {
6080 static const struct flock fl = {
6082 .l_whence = SEEK_SET,
6085 r = fcntl(f->fd, F_OFD_SETLK, &fl);
6086 if (r < 0 && errno == EINVAL)
6087 r = flock(f->fd, LOCK_EX|LOCK_NB);
6090 f->operation = LOCK_EX|LOCK_NB;
6093 if ((f->operation & ~LOCK_NB) == LOCK_EX)
6094 unlink_noerrno(f->path);
6100 f->fd = safe_close(f->fd);
6104 static size_t nul_length(const uint8_t *p, size_t sz) {
6119 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
6120 const uint8_t *q, *w, *e;
6128 n = nul_length(q, e - q);
6130 /* If there are more than the specified run length of
6131 * NUL bytes, or if this is the beginning or the end
6132 * of the buffer, then seek instead of write */
6133 if ((n > run_length) ||
6134 (n > 0 && q == p) ||
6135 (n > 0 && q + n >= e)) {
6137 l = write(fd, w, q - w);
6144 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6156 l = write(fd, w, q - w);
6163 return q - (const uint8_t*) p;
6166 void sigkill_wait(pid_t *pid) {
6172 if (kill(*pid, SIGKILL) > 0)
6173 (void) wait_for_terminate(*pid, NULL);
6176 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6177 int a = 0, b = 0, c = 0;
6187 if (!strchr(*p, '>'))
6190 if ((*p)[2] == '>') {
6191 c = undecchar((*p)[1]);
6193 } else if ((*p)[3] == '>') {
6194 b = undecchar((*p)[1]);
6195 c = undecchar((*p)[2]);
6197 } else if ((*p)[4] == '>') {
6198 a = undecchar((*p)[1]);
6199 b = undecchar((*p)[2]);
6200 c = undecchar((*p)[3]);
6205 if (a < 0 || b < 0 || c < 0 ||
6206 (!with_facility && (a || b || c > 7)))
6210 *priority = a*100 + b*10 + c;
6212 *priority = (*priority & LOG_FACMASK) | c;
6218 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6224 for (i = 0; i < len; ++i)
6225 if (streq_ptr(table[i], key))
6231 void cmsg_close_all(struct msghdr *mh) {
6232 struct cmsghdr *cmsg;
6236 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
6237 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6238 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6241 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6245 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6249 /* Even though renameat2() exists since Linux 3.15, btrfs added
6250 * support for it later. If it is not implemented, fallback to another
6252 if (errno != EINVAL)
6255 /* The link()/unlink() fallback does not work on directories. But
6256 * renameat() without RENAME_NOREPLACE gives the same semantics on
6257 * directories, except when newpath is an *empty* directory. This is
6259 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6260 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6261 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6262 return ret >= 0 ? 0 : -errno;
6265 /* If it is not a directory, use the link()/unlink() fallback. */
6266 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6270 ret = unlinkat(olddirfd, oldpath, 0);
6272 /* backup errno before the following unlinkat() alters it */
6274 (void) unlinkat(newdirfd, newpath, 0);
6282 char *shell_maybe_quote(const char *s) {
6288 /* Encloses a string in double quotes if necessary to make it
6289 * OK as shell string. */
6291 for (p = s; *p; p++)
6294 strchr(SHELL_NEED_QUOTES, *p))
6300 r = new(char, 1+strlen(s)*2+1+1);
6306 t = mempcpy(t, s, p - s);
6310 if (strchr(SHELL_NEED_ESCAPE, *p))
6322 int parse_mode(const char *s, mode_t *ret) {
6330 l = strtol(s, &x, 8);
6334 if (!x || x == s || *x)
6336 if (l < 0 || l > 07777)