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>
39 #include <linux/tiocl.h>
44 #include <sys/prctl.h>
45 #include <sys/utsname.h>
47 #include <netinet/ip.h>
55 #include <sys/mount.h>
56 #include <linux/magic.h>
60 #include <sys/personality.h>
61 #include <sys/xattr.h>
62 #include <sys/statvfs.h>
66 /* When we include libgen.h because we need dirname() we immediately
67 * undefine basename() since libgen.h defines it as a macro to the XDG
68 * version which is really broken. */
72 #ifdef HAVE_SYS_AUXV_H
84 #include "path-util.h"
85 #include "exit-status.h"
89 #include "device-nodes.h"
94 #include "sparse-endian.h"
95 #include "formats-util.h"
96 #include "process-util.h"
97 #include "random-util.h"
99 /* Put this test here for a lack of better place */
100 assert_cc(EAGAIN == EWOULDBLOCK);
103 char **saved_argv = NULL;
105 static volatile unsigned cached_columns = 0;
106 static volatile unsigned cached_lines = 0;
108 size_t page_size(void) {
109 static thread_local size_t pgsz = 0;
112 if (_likely_(pgsz > 0))
115 r = sysconf(_SC_PAGESIZE);
122 bool streq_ptr(const char *a, const char *b) {
124 /* Like streq(), but tries to make sense of NULL pointers */
135 char* endswith(const char *s, const char *postfix) {
142 pl = strlen(postfix);
145 return (char*) s + sl;
150 if (memcmp(s + sl - pl, postfix, pl) != 0)
153 return (char*) s + sl - pl;
156 char* first_word(const char *s, const char *word) {
163 /* Checks if the string starts with the specified word, either
164 * followed by NUL or by whitespace. Returns a pointer to the
165 * NUL or the first character after the whitespace. */
176 if (memcmp(s, word, wl) != 0)
183 if (!strchr(WHITESPACE, *p))
186 p += strspn(p, WHITESPACE);
190 size_t cescape_char(char c, char *buf) {
191 char * buf_old = buf;
237 /* For special chars we prefer octal over
238 * hexadecimal encoding, simply because glib's
239 * g_strescape() does the same */
240 if ((c < ' ') || (c >= 127)) {
242 *(buf++) = octchar((unsigned char) c >> 6);
243 *(buf++) = octchar((unsigned char) c >> 3);
244 *(buf++) = octchar((unsigned char) c);
250 return buf - buf_old;
253 int close_nointr(int fd) {
260 * Just ignore EINTR; a retry loop is the wrong thing to do on
263 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
264 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
265 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
266 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
274 int safe_close(int fd) {
277 * Like close_nointr() but cannot fail. Guarantees errno is
278 * unchanged. Is a NOP with negative fds passed, and returns
279 * -1, so that it can be used in this syntax:
281 * fd = safe_close(fd);
287 /* The kernel might return pretty much any error code
288 * via close(), but the fd will be closed anyway. The
289 * only condition we want to check for here is whether
290 * the fd was invalid at all... */
292 assert_se(close_nointr(fd) != -EBADF);
298 void close_many(const int fds[], unsigned n_fd) {
301 assert(fds || n_fd <= 0);
303 for (i = 0; i < n_fd; i++)
307 int unlink_noerrno(const char *path) {
318 int parse_boolean(const char *v) {
321 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
323 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
329 int parse_pid(const char *s, pid_t* ret_pid) {
330 unsigned long ul = 0;
337 r = safe_atolu(s, &ul);
343 if ((unsigned long) pid != ul)
353 int parse_uid(const char *s, uid_t* ret_uid) {
354 unsigned long ul = 0;
361 r = safe_atolu(s, &ul);
367 if ((unsigned long) uid != ul)
370 /* Some libc APIs use UID_INVALID as special placeholder */
371 if (uid == (uid_t) 0xFFFFFFFF)
374 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
375 if (uid == (uid_t) 0xFFFF)
382 int safe_atou(const char *s, unsigned *ret_u) {
390 l = strtoul(s, &x, 0);
392 if (!x || x == s || *x || errno)
393 return errno > 0 ? -errno : -EINVAL;
395 if ((unsigned long) (unsigned) l != l)
398 *ret_u = (unsigned) l;
402 int safe_atoi(const char *s, int *ret_i) {
410 l = strtol(s, &x, 0);
412 if (!x || x == s || *x || errno)
413 return errno > 0 ? -errno : -EINVAL;
415 if ((long) (int) l != l)
422 int safe_atou8(const char *s, uint8_t *ret) {
430 l = strtoul(s, &x, 0);
432 if (!x || x == s || *x || errno)
433 return errno > 0 ? -errno : -EINVAL;
435 if ((unsigned long) (uint8_t) l != l)
442 int safe_atou16(const char *s, uint16_t *ret) {
450 l = strtoul(s, &x, 0);
452 if (!x || x == s || *x || errno)
453 return errno > 0 ? -errno : -EINVAL;
455 if ((unsigned long) (uint16_t) l != l)
462 int safe_atoi16(const char *s, int16_t *ret) {
470 l = strtol(s, &x, 0);
472 if (!x || x == s || *x || errno)
473 return errno > 0 ? -errno : -EINVAL;
475 if ((long) (int16_t) l != l)
482 int safe_atollu(const char *s, long long unsigned *ret_llu) {
484 unsigned long long l;
490 l = strtoull(s, &x, 0);
492 if (!x || x == s || *x || errno)
493 return errno ? -errno : -EINVAL;
499 int safe_atolli(const char *s, long long int *ret_lli) {
507 l = strtoll(s, &x, 0);
509 if (!x || x == s || *x || errno)
510 return errno ? -errno : -EINVAL;
516 int safe_atod(const char *s, double *ret_d) {
524 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
525 if (loc == (locale_t) 0)
529 d = strtod_l(s, &x, loc);
531 if (!x || x == s || *x || errno) {
533 return errno ? -errno : -EINVAL;
541 static size_t strcspn_escaped(const char *s, const char *reject) {
542 bool escaped = false;
545 for (n=0; s[n]; n++) {
548 else if (s[n] == '\\')
550 else if (strchr(reject, s[n]))
554 /* if s ends in \, return index of previous char */
558 /* Split a string into words. */
559 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
565 assert(**state == '\0');
569 current += strspn(current, separator);
575 if (quoted && strchr("\'\"", *current)) {
576 char quotechars[2] = {*current, '\0'};
578 *l = strcspn_escaped(current + 1, quotechars);
579 if (current[*l + 1] == '\0' ||
580 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
581 /* right quote missing or garbage at the end */
585 assert(current[*l + 1] == quotechars[0]);
586 *state = current++ + *l + 2;
588 *l = strcspn_escaped(current, separator);
589 if (current[*l] && !strchr(separator, current[*l])) {
590 /* unfinished escape */
594 *state = current + *l;
596 *l = strcspn(current, separator);
597 *state = current + *l;
603 int fchmod_umask(int fd, mode_t m) {
608 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
614 char *truncate_nl(char *s) {
617 s[strcspn(s, NEWLINE)] = 0;
621 char *strnappend(const char *s, const char *suffix, size_t b) {
629 return strndup(suffix, b);
638 if (b > ((size_t) -1) - a)
641 r = new(char, a+b+1);
646 memcpy(r+a, suffix, b);
652 char *strappend(const char *s, const char *suffix) {
653 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
656 int readlinkat_malloc(int fd, const char *p, char **ret) {
671 n = readlinkat(fd, p, c, l-1);
678 if ((size_t) n < l-1) {
689 int readlink_malloc(const char *p, char **ret) {
690 return readlinkat_malloc(AT_FDCWD, p, ret);
693 int readlink_value(const char *p, char **ret) {
694 _cleanup_free_ char *link = NULL;
698 r = readlink_malloc(p, &link);
702 value = basename(link);
706 value = strdup(value);
715 int readlink_and_make_absolute(const char *p, char **r) {
716 _cleanup_free_ char *target = NULL;
723 j = readlink_malloc(p, &target);
727 k = file_in_same_dir(p, target);
735 int readlink_and_canonicalize(const char *p, char **r) {
742 j = readlink_and_make_absolute(p, &t);
746 s = canonicalize_file_name(t);
753 path_kill_slashes(*r);
758 int reset_all_signal_handlers(void) {
761 for (sig = 1; sig < _NSIG; sig++) {
762 struct sigaction sa = {
763 .sa_handler = SIG_DFL,
764 .sa_flags = SA_RESTART,
767 /* These two cannot be caught... */
768 if (sig == SIGKILL || sig == SIGSTOP)
771 /* On Linux the first two RT signals are reserved by
772 * glibc, and sigaction() will return EINVAL for them. */
773 if ((sigaction(sig, &sa, NULL) < 0))
774 if (errno != EINVAL && r == 0)
781 int reset_signal_mask(void) {
784 if (sigemptyset(&ss) < 0)
787 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
793 char *strstrip(char *s) {
796 /* Drops trailing whitespace. Modifies the string in
797 * place. Returns pointer to first non-space character */
799 s += strspn(s, WHITESPACE);
801 for (e = strchr(s, 0); e > s; e --)
802 if (!strchr(WHITESPACE, e[-1]))
810 char *delete_chars(char *s, const char *bad) {
813 /* Drops all whitespace, regardless where in the string */
815 for (f = s, t = s; *f; f++) {
827 char *file_in_same_dir(const char *path, const char *filename) {
834 /* This removes the last component of path and appends
835 * filename, unless the latter is absolute anyway or the
838 if (path_is_absolute(filename))
839 return strdup(filename);
841 e = strrchr(path, '/');
843 return strdup(filename);
845 k = strlen(filename);
846 ret = new(char, (e + 1 - path) + k + 1);
850 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
854 int rmdir_parents(const char *path, const char *stop) {
863 /* Skip trailing slashes */
864 while (l > 0 && path[l-1] == '/')
870 /* Skip last component */
871 while (l > 0 && path[l-1] != '/')
874 /* Skip trailing slashes */
875 while (l > 0 && path[l-1] == '/')
881 if (!(t = strndup(path, l)))
884 if (path_startswith(stop, t)) {
900 char hexchar(int x) {
901 static const char table[16] = "0123456789abcdef";
903 return table[x & 15];
906 int unhexchar(char c) {
908 if (c >= '0' && c <= '9')
911 if (c >= 'a' && c <= 'f')
914 if (c >= 'A' && c <= 'F')
920 char *hexmem(const void *p, size_t l) {
924 z = r = malloc(l * 2 + 1);
928 for (x = p; x < (const uint8_t*) p + l; x++) {
929 *(z++) = hexchar(*x >> 4);
930 *(z++) = hexchar(*x & 15);
937 void *unhexmem(const char *p, size_t l) {
943 z = r = malloc((l + 1) / 2 + 1);
947 for (x = p; x < p + l; x += 2) {
956 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
963 char octchar(int x) {
964 return '0' + (x & 7);
967 int unoctchar(char c) {
969 if (c >= '0' && c <= '7')
975 char decchar(int x) {
976 return '0' + (x % 10);
979 int undecchar(char c) {
981 if (c >= '0' && c <= '9')
987 char *cescape(const char *s) {
993 /* Does C style string escaping. May be reversed with
996 r = new(char, strlen(s)*4 + 1);
1000 for (f = s, t = r; *f; f++)
1001 t += cescape_char(*f, t);
1008 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1015 /* Unescapes C style. Returns the unescaped character in ret,
1016 * unless we encountered a \u sequence in which case the full
1017 * unicode character is returned in ret_unicode, instead. */
1019 if (length != (size_t) -1 && length < 1)
1056 /* This is an extension of the XDG syntax files */
1061 /* hexadecimal encoding */
1064 if (length != (size_t) -1 && length < 3)
1067 a = unhexchar(p[1]);
1071 b = unhexchar(p[2]);
1075 /* Don't allow NUL bytes */
1076 if (a == 0 && b == 0)
1079 *ret = (char) ((a << 4U) | b);
1085 /* C++11 style 16bit unicode */
1091 if (length != (size_t) -1 && length < 5)
1094 for (i = 0; i < 4; i++) {
1095 a[i] = unhexchar(p[1 + i]);
1100 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1102 /* Don't allow 0 chars */
1121 /* C++11 style 32bit unicode */
1127 if (length != (size_t) -1 && length < 9)
1130 for (i = 0; i < 8; i++) {
1131 a[i] = unhexchar(p[1 + i]);
1136 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1137 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1139 /* Don't allow 0 chars */
1143 /* Don't allow invalid code points */
1144 if (!unichar_is_valid(c))
1169 /* octal encoding */
1173 if (length != (size_t) -1 && length < 4)
1176 a = unoctchar(p[0]);
1180 b = unoctchar(p[1]);
1184 c = unoctchar(p[2]);
1188 /* don't allow NUL bytes */
1189 if (a == 0 && b == 0 && c == 0)
1192 /* Don't allow bytes above 255 */
1193 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1209 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1217 /* Undoes C style string escaping, and optionally prefixes it. */
1219 pl = prefix ? strlen(prefix) : 0;
1221 r = new(char, pl+length+1);
1226 memcpy(r, prefix, pl);
1228 for (f = s, t = r + pl; f < s + length; f++) {
1234 remaining = s + length - f;
1235 assert(remaining > 0);
1238 /* A literal literal, copy verbatim */
1243 if (remaining == 1) {
1244 if (flags & UNESCAPE_RELAX) {
1245 /* A trailing backslash, copy verbatim */
1254 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1256 if (flags & UNESCAPE_RELAX) {
1257 /* Invalid escape code, let's take it literal then */
1267 /* Non-Unicode? Let's encode this directly */
1270 /* Unicode? Then let's encode this in UTF-8 */
1271 t += utf8_encode_unichar(t, u);
1282 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1283 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1286 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1287 return cunescape_length(s, strlen(s), flags, ret);
1290 char *xescape(const char *s, const char *bad) {
1294 /* Escapes all chars in bad, in addition to \ and all special
1295 * chars, in \xFF style escaping. May be reversed with
1298 r = new(char, strlen(s) * 4 + 1);
1302 for (f = s, t = r; *f; f++) {
1304 if ((*f < ' ') || (*f >= 127) ||
1305 (*f == '\\') || strchr(bad, *f)) {
1308 *(t++) = hexchar(*f >> 4);
1309 *(t++) = hexchar(*f);
1319 char *ascii_strlower(char *t) {
1324 for (p = t; *p; p++)
1325 if (*p >= 'A' && *p <= 'Z')
1326 *p = *p - 'A' + 'a';
1331 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1335 filename[0] == '.' ||
1336 streq(filename, "lost+found") ||
1337 streq(filename, "aquota.user") ||
1338 streq(filename, "aquota.group") ||
1339 endswith(filename, ".rpmnew") ||
1340 endswith(filename, ".rpmsave") ||
1341 endswith(filename, ".rpmorig") ||
1342 endswith(filename, ".dpkg-old") ||
1343 endswith(filename, ".dpkg-new") ||
1344 endswith(filename, ".dpkg-tmp") ||
1345 endswith(filename, ".dpkg-dist") ||
1346 endswith(filename, ".dpkg-bak") ||
1347 endswith(filename, ".dpkg-backup") ||
1348 endswith(filename, ".dpkg-remove") ||
1349 endswith(filename, ".swp");
1352 bool hidden_file(const char *filename) {
1355 if (endswith(filename, "~"))
1358 return hidden_file_allow_backup(filename);
1361 int fd_nonblock(int fd, bool nonblock) {
1366 flags = fcntl(fd, F_GETFL, 0);
1371 nflags = flags | O_NONBLOCK;
1373 nflags = flags & ~O_NONBLOCK;
1375 if (nflags == flags)
1378 if (fcntl(fd, F_SETFL, nflags) < 0)
1384 int fd_cloexec(int fd, bool cloexec) {
1389 flags = fcntl(fd, F_GETFD, 0);
1394 nflags = flags | FD_CLOEXEC;
1396 nflags = flags & ~FD_CLOEXEC;
1398 if (nflags == flags)
1401 if (fcntl(fd, F_SETFD, nflags) < 0)
1407 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1410 assert(n_fdset == 0 || fdset);
1412 for (i = 0; i < n_fdset; i++)
1419 int close_all_fds(const int except[], unsigned n_except) {
1420 _cleanup_closedir_ DIR *d = NULL;
1424 assert(n_except == 0 || except);
1426 d = opendir("/proc/self/fd");
1431 /* When /proc isn't available (for example in chroots)
1432 * the fallback is brute forcing through the fd
1435 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1436 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1438 if (fd_in_set(fd, except, n_except))
1441 if (close_nointr(fd) < 0)
1442 if (errno != EBADF && r == 0)
1449 while ((de = readdir(d))) {
1452 if (hidden_file(de->d_name))
1455 if (safe_atoi(de->d_name, &fd) < 0)
1456 /* Let's better ignore this, just in case */
1465 if (fd_in_set(fd, except, n_except))
1468 if (close_nointr(fd) < 0) {
1469 /* Valgrind has its own FD and doesn't want to have it closed */
1470 if (errno != EBADF && r == 0)
1478 bool chars_intersect(const char *a, const char *b) {
1481 /* Returns true if any of the chars in a are in b. */
1482 for (p = a; *p; p++)
1489 bool fstype_is_network(const char *fstype) {
1490 static const char table[] =
1505 x = startswith(fstype, "fuse.");
1509 return nulstr_contains(table, fstype);
1513 _cleanup_close_ int fd;
1515 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1521 TIOCL_GETKMSGREDIRECT,
1525 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1528 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1531 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1537 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1538 struct termios old_termios, new_termios;
1539 char c, line[LINE_MAX];
1544 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1545 new_termios = old_termios;
1547 new_termios.c_lflag &= ~ICANON;
1548 new_termios.c_cc[VMIN] = 1;
1549 new_termios.c_cc[VTIME] = 0;
1551 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1554 if (t != USEC_INFINITY) {
1555 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1556 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1561 k = fread(&c, 1, 1, f);
1563 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1569 *need_nl = c != '\n';
1576 if (t != USEC_INFINITY) {
1577 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1582 if (!fgets(line, sizeof(line), f))
1583 return errno ? -errno : -EIO;
1587 if (strlen(line) != 1)
1597 int ask_char(char *ret, const char *replies, const char *text, ...) {
1607 bool need_nl = true;
1610 fputs(ANSI_HIGHLIGHT_ON, stdout);
1617 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1621 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1624 if (r == -EBADMSG) {
1625 puts("Bad input, please try again.");
1636 if (strchr(replies, c)) {
1641 puts("Read unexpected character, please try again.");
1645 int ask_string(char **ret, const char *text, ...) {
1650 char line[LINE_MAX];
1654 fputs(ANSI_HIGHLIGHT_ON, stdout);
1661 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1666 if (!fgets(line, sizeof(line), stdin))
1667 return errno ? -errno : -EIO;
1669 if (!endswith(line, "\n"))
1688 int reset_terminal_fd(int fd, bool switch_to_text) {
1689 struct termios termios;
1692 /* Set terminal to some sane defaults */
1696 /* We leave locked terminal attributes untouched, so that
1697 * Plymouth may set whatever it wants to set, and we don't
1698 * interfere with that. */
1700 /* Disable exclusive mode, just in case */
1701 ioctl(fd, TIOCNXCL);
1703 /* Switch to text mode */
1705 ioctl(fd, KDSETMODE, KD_TEXT);
1707 /* Enable console unicode mode */
1708 ioctl(fd, KDSKBMODE, K_UNICODE);
1710 if (tcgetattr(fd, &termios) < 0) {
1715 /* We only reset the stuff that matters to the software. How
1716 * hardware is set up we don't touch assuming that somebody
1717 * else will do that for us */
1719 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1720 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1721 termios.c_oflag |= ONLCR;
1722 termios.c_cflag |= CREAD;
1723 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1725 termios.c_cc[VINTR] = 03; /* ^C */
1726 termios.c_cc[VQUIT] = 034; /* ^\ */
1727 termios.c_cc[VERASE] = 0177;
1728 termios.c_cc[VKILL] = 025; /* ^X */
1729 termios.c_cc[VEOF] = 04; /* ^D */
1730 termios.c_cc[VSTART] = 021; /* ^Q */
1731 termios.c_cc[VSTOP] = 023; /* ^S */
1732 termios.c_cc[VSUSP] = 032; /* ^Z */
1733 termios.c_cc[VLNEXT] = 026; /* ^V */
1734 termios.c_cc[VWERASE] = 027; /* ^W */
1735 termios.c_cc[VREPRINT] = 022; /* ^R */
1736 termios.c_cc[VEOL] = 0;
1737 termios.c_cc[VEOL2] = 0;
1739 termios.c_cc[VTIME] = 0;
1740 termios.c_cc[VMIN] = 1;
1742 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1746 /* Just in case, flush all crap out */
1747 tcflush(fd, TCIOFLUSH);
1752 int reset_terminal(const char *name) {
1753 _cleanup_close_ int fd = -1;
1755 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1759 return reset_terminal_fd(fd, true);
1762 int open_terminal(const char *name, int mode) {
1767 * If a TTY is in the process of being closed opening it might
1768 * cause EIO. This is horribly awful, but unlikely to be
1769 * changed in the kernel. Hence we work around this problem by
1770 * retrying a couple of times.
1772 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1775 assert(!(mode & O_CREAT));
1778 fd = open(name, mode, 0);
1785 /* Max 1s in total */
1789 usleep(50 * USEC_PER_MSEC);
1807 int flush_fd(int fd) {
1808 struct pollfd pollfd = {
1818 r = poll(&pollfd, 1, 0);
1828 l = read(fd, buf, sizeof(buf));
1834 if (errno == EAGAIN)
1843 int acquire_terminal(
1847 bool ignore_tiocstty_eperm,
1850 int fd = -1, notify = -1, r = 0, wd = -1;
1855 /* We use inotify to be notified when the tty is closed. We
1856 * create the watch before checking if we can actually acquire
1857 * it, so that we don't lose any event.
1859 * Note: strictly speaking this actually watches for the
1860 * device being closed, it does *not* really watch whether a
1861 * tty loses its controlling process. However, unless some
1862 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1863 * its tty otherwise this will not become a problem. As long
1864 * as the administrator makes sure not configure any service
1865 * on the same tty as an untrusted user this should not be a
1866 * problem. (Which he probably should not do anyway.) */
1868 if (timeout != USEC_INFINITY)
1869 ts = now(CLOCK_MONOTONIC);
1871 if (!fail && !force) {
1872 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
1878 wd = inotify_add_watch(notify, name, IN_CLOSE);
1886 struct sigaction sa_old, sa_new = {
1887 .sa_handler = SIG_IGN,
1888 .sa_flags = SA_RESTART,
1892 r = flush_fd(notify);
1897 /* We pass here O_NOCTTY only so that we can check the return
1898 * value TIOCSCTTY and have a reliable way to figure out if we
1899 * successfully became the controlling process of the tty */
1900 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1904 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1905 * if we already own the tty. */
1906 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1908 /* First, try to get the tty */
1909 if (ioctl(fd, TIOCSCTTY, force) < 0)
1912 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1914 /* Sometimes it makes sense to ignore TIOCSCTTY
1915 * returning EPERM, i.e. when very likely we already
1916 * are have this controlling terminal. */
1917 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1920 if (r < 0 && (force || fail || r != -EPERM)) {
1929 assert(notify >= 0);
1932 union inotify_event_buffer buffer;
1933 struct inotify_event *e;
1936 if (timeout != USEC_INFINITY) {
1939 n = now(CLOCK_MONOTONIC);
1940 if (ts + timeout < n) {
1945 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1955 l = read(notify, &buffer, sizeof(buffer));
1957 if (errno == EINTR || errno == EAGAIN)
1964 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1965 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1974 /* We close the tty fd here since if the old session
1975 * ended our handle will be dead. It's important that
1976 * we do this after sleeping, so that we don't enter
1977 * an endless loop. */
1978 fd = safe_close(fd);
1983 r = reset_terminal_fd(fd, true);
1985 log_warning_errno(r, "Failed to reset terminal: %m");
1996 int release_terminal(void) {
1997 static const struct sigaction sa_new = {
1998 .sa_handler = SIG_IGN,
1999 .sa_flags = SA_RESTART,
2002 _cleanup_close_ int fd = -1;
2003 struct sigaction sa_old;
2006 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2010 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2011 * by our own TIOCNOTTY */
2012 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2014 if (ioctl(fd, TIOCNOTTY) < 0)
2017 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2022 int sigaction_many(const struct sigaction *sa, ...) {
2027 while ((sig = va_arg(ap, int)) > 0)
2028 if (sigaction(sig, sa, NULL) < 0)
2035 int ignore_signals(int sig, ...) {
2036 struct sigaction sa = {
2037 .sa_handler = SIG_IGN,
2038 .sa_flags = SA_RESTART,
2043 if (sigaction(sig, &sa, NULL) < 0)
2047 while ((sig = va_arg(ap, int)) > 0)
2048 if (sigaction(sig, &sa, NULL) < 0)
2055 int default_signals(int sig, ...) {
2056 struct sigaction sa = {
2057 .sa_handler = SIG_DFL,
2058 .sa_flags = SA_RESTART,
2063 if (sigaction(sig, &sa, NULL) < 0)
2067 while ((sig = va_arg(ap, int)) > 0)
2068 if (sigaction(sig, &sa, NULL) < 0)
2075 void safe_close_pair(int p[]) {
2079 /* Special case pairs which use the same fd in both
2081 p[0] = p[1] = safe_close(p[0]);
2085 p[0] = safe_close(p[0]);
2086 p[1] = safe_close(p[1]);
2089 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2096 while (nbytes > 0) {
2099 k = read(fd, p, nbytes);
2104 if (errno == EAGAIN && do_poll) {
2106 /* We knowingly ignore any return value here,
2107 * and expect that any error/EOF is reported
2110 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2114 return n > 0 ? n : -errno;
2128 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
2131 n = loop_read(fd, buf, nbytes, do_poll);
2134 if ((size_t) n != nbytes)
2139 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2140 const uint8_t *p = buf;
2147 while (nbytes > 0) {
2150 k = write(fd, p, nbytes);
2155 if (errno == EAGAIN && do_poll) {
2156 /* We knowingly ignore any return value here,
2157 * and expect that any error/EOF is reported
2160 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2167 if (k == 0) /* Can't really happen */
2177 int parse_size(const char *t, off_t base, off_t *size) {
2179 /* Soo, sometimes we want to parse IEC binary suffxies, and
2180 * sometimes SI decimal suffixes. This function can parse
2181 * both. Which one is the right way depends on the
2182 * context. Wikipedia suggests that SI is customary for
2183 * hardrware metrics and network speeds, while IEC is
2184 * customary for most data sizes used by software and volatile
2185 * (RAM) memory. Hence be careful which one you pick!
2187 * In either case we use just K, M, G as suffix, and not Ki,
2188 * Mi, Gi or so (as IEC would suggest). That's because that's
2189 * frickin' ugly. But this means you really need to make sure
2190 * to document which base you are parsing when you use this
2195 unsigned long long factor;
2198 static const struct table iec[] = {
2199 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2200 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2201 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2202 { "G", 1024ULL*1024ULL*1024ULL },
2203 { "M", 1024ULL*1024ULL },
2209 static const struct table si[] = {
2210 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2211 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2212 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2213 { "G", 1000ULL*1000ULL*1000ULL },
2214 { "M", 1000ULL*1000ULL },
2220 const struct table *table;
2222 unsigned long long r = 0;
2223 unsigned n_entries, start_pos = 0;
2226 assert(base == 1000 || base == 1024);
2231 n_entries = ELEMENTSOF(si);
2234 n_entries = ELEMENTSOF(iec);
2240 unsigned long long l2;
2246 l = strtoll(p, &e, 10);
2259 if (*e >= '0' && *e <= '9') {
2262 /* strotoull itself would accept space/+/- */
2263 l2 = strtoull(e, &e2, 10);
2265 if (errno == ERANGE)
2268 /* Ignore failure. E.g. 10.M is valid */
2275 e += strspn(e, WHITESPACE);
2277 for (i = start_pos; i < n_entries; i++)
2278 if (startswith(e, table[i].suffix)) {
2279 unsigned long long tmp;
2280 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2282 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2283 if (tmp > ULLONG_MAX - r)
2287 if ((unsigned long long) (off_t) r != r)
2290 p = e + strlen(table[i].suffix);
2306 int make_stdio(int fd) {
2311 r = dup2(fd, STDIN_FILENO);
2312 s = dup2(fd, STDOUT_FILENO);
2313 t = dup2(fd, STDERR_FILENO);
2318 if (r < 0 || s < 0 || t < 0)
2321 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2322 * dup2() was a NOP and the bit hence possibly set. */
2323 fd_cloexec(STDIN_FILENO, false);
2324 fd_cloexec(STDOUT_FILENO, false);
2325 fd_cloexec(STDERR_FILENO, false);
2330 int make_null_stdio(void) {
2333 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2337 return make_stdio(null_fd);
2340 bool is_device_path(const char *path) {
2342 /* Returns true on paths that refer to a device, either in
2343 * sysfs or in /dev */
2346 path_startswith(path, "/dev/") ||
2347 path_startswith(path, "/sys/");
2350 int dir_is_empty(const char *path) {
2351 _cleanup_closedir_ DIR *d;
2362 if (!de && errno != 0)
2368 if (!hidden_file(de->d_name))
2373 char* dirname_malloc(const char *path) {
2374 char *d, *dir, *dir2;
2391 void rename_process(const char name[8]) {
2394 /* This is a like a poor man's setproctitle(). It changes the
2395 * comm field, argv[0], and also the glibc's internally used
2396 * name of the process. For the first one a limit of 16 chars
2397 * applies, to the second one usually one of 10 (i.e. length
2398 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2399 * "systemd"). If you pass a longer string it will be
2402 prctl(PR_SET_NAME, name);
2404 if (program_invocation_name)
2405 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2407 if (saved_argc > 0) {
2411 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2413 for (i = 1; i < saved_argc; i++) {
2417 memzero(saved_argv[i], strlen(saved_argv[i]));
2422 void sigset_add_many(sigset_t *ss, ...) {
2429 while ((sig = va_arg(ap, int)) > 0)
2430 assert_se(sigaddset(ss, sig) == 0);
2434 int sigprocmask_many(int how, ...) {
2439 assert_se(sigemptyset(&ss) == 0);
2442 while ((sig = va_arg(ap, int)) > 0)
2443 assert_se(sigaddset(&ss, sig) == 0);
2446 if (sigprocmask(how, &ss, NULL) < 0)
2452 char* gethostname_malloc(void) {
2455 assert_se(uname(&u) >= 0);
2457 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2458 return strdup(u.nodename);
2460 return strdup(u.sysname);
2463 bool hostname_is_set(void) {
2466 assert_se(uname(&u) >= 0);
2468 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2471 char *lookup_uid(uid_t uid) {
2474 _cleanup_free_ char *buf = NULL;
2475 struct passwd pwbuf, *pw = NULL;
2477 /* Shortcut things to avoid NSS lookups */
2479 return strdup("root");
2481 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2485 buf = malloc(bufsize);
2489 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2490 return strdup(pw->pw_name);
2492 if (asprintf(&name, UID_FMT, uid) < 0)
2498 char* getlogname_malloc(void) {
2502 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2507 return lookup_uid(uid);
2510 char *getusername_malloc(void) {
2517 return lookup_uid(getuid());
2520 int getttyname_malloc(int fd, char **ret) {
2530 r = ttyname_r(fd, path, sizeof(path));
2535 p = startswith(path, "/dev/");
2536 c = strdup(p ?: path);
2553 int getttyname_harder(int fd, char **r) {
2557 k = getttyname_malloc(fd, &s);
2561 if (streq(s, "tty")) {
2563 return get_ctty(0, NULL, r);
2570 int get_ctty_devnr(pid_t pid, dev_t *d) {
2572 _cleanup_free_ char *line = NULL;
2574 unsigned long ttynr;
2578 p = procfs_file_alloca(pid, "stat");
2579 r = read_one_line_file(p, &line);
2583 p = strrchr(line, ')');
2593 "%*d " /* session */
2598 if (major(ttynr) == 0 && minor(ttynr) == 0)
2607 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2608 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2609 _cleanup_free_ char *s = NULL;
2616 k = get_ctty_devnr(pid, &devnr);
2620 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2622 k = readlink_malloc(fn, &s);
2628 /* This is an ugly hack */
2629 if (major(devnr) == 136) {
2630 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
2633 /* Probably something like the ptys which have no
2634 * symlink in /dev/char. Let's return something
2635 * vaguely useful. */
2642 if (startswith(s, "/dev/"))
2644 else if (startswith(s, "../"))
2661 bool is_temporary_fs(const struct statfs *s) {
2664 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2665 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2668 int fd_is_temporary_fs(int fd) {
2671 if (fstatfs(fd, &s) < 0)
2674 return is_temporary_fs(&s);
2677 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2680 /* Under the assumption that we are running privileged we
2681 * first change the access mode and only then hand out
2682 * ownership to avoid a window where access is too open. */
2684 if (mode != MODE_INVALID)
2685 if (chmod(path, mode) < 0)
2688 if (uid != UID_INVALID || gid != GID_INVALID)
2689 if (chown(path, uid, gid) < 0)
2695 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2698 /* Under the assumption that we are running privileged we
2699 * first change the access mode and only then hand out
2700 * ownership to avoid a window where access is too open. */
2702 if (mode != MODE_INVALID)
2703 if (fchmod(fd, mode) < 0)
2706 if (uid != UID_INVALID || gid != GID_INVALID)
2707 if (fchown(fd, uid, gid) < 0)
2713 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2717 /* Allocates the cpuset in the right size */
2720 if (!(r = CPU_ALLOC(n)))
2723 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2724 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2734 if (errno != EINVAL)
2741 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2742 static const char status_indent[] = " "; /* "[" STATUS "] " */
2743 _cleanup_free_ char *s = NULL;
2744 _cleanup_close_ int fd = -1;
2745 struct iovec iovec[6] = {};
2747 static bool prev_ephemeral;
2751 /* This is independent of logging, as status messages are
2752 * optional and go exclusively to the console. */
2754 if (vasprintf(&s, format, ap) < 0)
2757 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2770 sl = status ? sizeof(status_indent)-1 : 0;
2776 e = ellipsize(s, emax, 50);
2784 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2785 prev_ephemeral = ephemeral;
2788 if (!isempty(status)) {
2789 IOVEC_SET_STRING(iovec[n++], "[");
2790 IOVEC_SET_STRING(iovec[n++], status);
2791 IOVEC_SET_STRING(iovec[n++], "] ");
2793 IOVEC_SET_STRING(iovec[n++], status_indent);
2796 IOVEC_SET_STRING(iovec[n++], s);
2798 IOVEC_SET_STRING(iovec[n++], "\n");
2800 if (writev(fd, iovec, n) < 0)
2806 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2812 va_start(ap, format);
2813 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2819 char *replace_env(const char *format, char **env) {
2826 const char *e, *word = format;
2831 for (e = format; *e; e ++) {
2842 k = strnappend(r, word, e-word-1);
2852 } else if (*e == '$') {
2853 k = strnappend(r, word, e-word);
2870 t = strempty(strv_env_get_n(env, word+2, e-word-2));
2872 k = strappend(r, t);
2886 k = strnappend(r, word, e-word);
2898 char **replace_env_argv(char **argv, char **env) {
2900 unsigned k = 0, l = 0;
2902 l = strv_length(argv);
2904 ret = new(char*, l+1);
2908 STRV_FOREACH(i, argv) {
2910 /* If $FOO appears as single word, replace it by the split up variable */
2911 if ((*i)[0] == '$' && (*i)[1] != '{') {
2913 char **w, **m = NULL;
2916 e = strv_env_get(env, *i+1);
2920 r = strv_split_quoted(&m, e, UNQUOTE_RELAX);
2932 w = realloc(ret, sizeof(char*) * (l+1));
2942 memcpy(ret + k, m, q * sizeof(char*));
2950 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
2951 ret[k] = replace_env(*i, env);
2963 int fd_columns(int fd) {
2964 struct winsize ws = {};
2966 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
2975 unsigned columns(void) {
2979 if (_likely_(cached_columns > 0))
2980 return cached_columns;
2983 e = getenv("COLUMNS");
2985 (void) safe_atoi(e, &c);
2988 c = fd_columns(STDOUT_FILENO);
2994 return cached_columns;
2997 int fd_lines(int fd) {
2998 struct winsize ws = {};
3000 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3009 unsigned lines(void) {
3013 if (_likely_(cached_lines > 0))
3014 return cached_lines;
3017 e = getenv("LINES");
3019 (void) safe_atoi(e, &l);
3022 l = fd_lines(STDOUT_FILENO);
3028 return cached_lines;
3031 /* intended to be used as a SIGWINCH sighandler */
3032 void columns_lines_cache_reset(int signum) {
3038 static int cached_on_tty = -1;
3040 if (_unlikely_(cached_on_tty < 0))
3041 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3043 return cached_on_tty;
3046 int files_same(const char *filea, const char *fileb) {
3049 if (stat(filea, &a) < 0)
3052 if (stat(fileb, &b) < 0)
3055 return a.st_dev == b.st_dev &&
3056 a.st_ino == b.st_ino;
3059 int running_in_chroot(void) {
3062 ret = files_same("/proc/1/root", "/");
3069 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3074 assert(percent <= 100);
3075 assert(new_length >= 3);
3077 if (old_length <= 3 || old_length <= new_length)
3078 return strndup(s, old_length);
3080 r = new0(char, new_length+1);
3084 x = (new_length * percent) / 100;
3086 if (x > new_length - 3)
3094 s + old_length - (new_length - x - 3),
3095 new_length - x - 3);
3100 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3104 unsigned k, len, len2;
3107 assert(percent <= 100);
3108 assert(new_length >= 3);
3110 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3111 if (ascii_is_valid(s))
3112 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3114 if (old_length <= 3 || old_length <= new_length)
3115 return strndup(s, old_length);
3117 x = (new_length * percent) / 100;
3119 if (x > new_length - 3)
3123 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3126 c = utf8_encoded_to_unichar(i);
3129 k += unichar_iswide(c) ? 2 : 1;
3132 if (k > x) /* last character was wide and went over quota */
3135 for (j = s + old_length; k < new_length && j > i; ) {
3138 j = utf8_prev_char(j);
3139 c = utf8_encoded_to_unichar(j);
3142 k += unichar_iswide(c) ? 2 : 1;
3146 /* we don't actually need to ellipsize */
3148 return memdup(s, old_length + 1);
3150 /* make space for ellipsis */
3151 j = utf8_next_char(j);
3154 len2 = s + old_length - j;
3155 e = new(char, len + 3 + len2 + 1);
3160 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3161 old_length, new_length, x, len, len2, k);
3165 e[len] = 0xe2; /* tri-dot ellipsis: … */
3169 memcpy(e + len + 3, j, len2 + 1);
3174 char *ellipsize(const char *s, size_t length, unsigned percent) {
3175 return ellipsize_mem(s, strlen(s), length, percent);
3178 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3179 _cleanup_close_ int fd;
3185 mkdir_parents(path, 0755);
3187 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3192 r = fchmod(fd, mode);
3197 if (uid != UID_INVALID || gid != GID_INVALID) {
3198 r = fchown(fd, uid, gid);
3203 if (stamp != USEC_INFINITY) {
3204 struct timespec ts[2];
3206 timespec_store(&ts[0], stamp);
3208 r = futimens(fd, ts);
3210 r = futimens(fd, NULL);
3217 int touch(const char *path) {
3218 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3221 static char *unquote(const char *s, const char* quotes) {
3225 /* This is rather stupid, simply removes the heading and
3226 * trailing quotes if there is one. Doesn't care about
3227 * escaping or anything.
3229 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
3235 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3236 return strndup(s+1, l-2);
3241 noreturn void freeze(void) {
3243 /* Make sure nobody waits for us on a socket anymore */
3244 close_all_fds(NULL, 0);
3252 bool null_or_empty(struct stat *st) {
3255 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3258 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3264 int null_or_empty_path(const char *fn) {
3269 if (stat(fn, &st) < 0)
3272 return null_or_empty(&st);
3275 int null_or_empty_fd(int fd) {
3280 if (fstat(fd, &st) < 0)
3283 return null_or_empty(&st);
3286 DIR *xopendirat(int fd, const char *name, int flags) {
3290 assert(!(flags & O_CREAT));
3292 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3305 int signal_from_string_try_harder(const char *s) {
3309 signo = signal_from_string(s);
3311 if (startswith(s, "SIG"))
3312 return signal_from_string(s+3);
3317 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3318 _cleanup_free_ char *t = NULL, *u = NULL;
3321 u = unquote(tagvalue, QUOTES);
3325 enc_len = strlen(u) * 4 + 1;
3326 t = new(char, enc_len);
3330 if (encode_devnode_name(u, t, enc_len) < 0)
3333 return strjoin("/dev/disk/by-", by, "/", t, NULL);
3336 char *fstab_node_to_udev_node(const char *p) {
3339 if (startswith(p, "LABEL="))
3340 return tag_to_udev_node(p+6, "label");
3342 if (startswith(p, "UUID="))
3343 return tag_to_udev_node(p+5, "uuid");
3345 if (startswith(p, "PARTUUID="))
3346 return tag_to_udev_node(p+9, "partuuid");
3348 if (startswith(p, "PARTLABEL="))
3349 return tag_to_udev_node(p+10, "partlabel");
3354 bool tty_is_vc(const char *tty) {
3357 return vtnr_from_tty(tty) >= 0;
3360 bool tty_is_console(const char *tty) {
3363 if (startswith(tty, "/dev/"))
3366 return streq(tty, "console");
3369 int vtnr_from_tty(const char *tty) {
3374 if (startswith(tty, "/dev/"))
3377 if (!startswith(tty, "tty") )
3380 if (tty[3] < '0' || tty[3] > '9')
3383 r = safe_atoi(tty+3, &i);
3387 if (i < 0 || i > 63)
3393 char *resolve_dev_console(char **active) {
3396 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3397 * (i.e. not read-only-mounted which is a sign for container setups) */
3399 if (path_is_read_only_fs("/sys") > 0)
3402 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3405 /* If multiple log outputs are configured the last one is what
3406 * /dev/console points to */
3407 tty = strrchr(*active, ' ');
3413 if (streq(tty, "tty0")) {
3416 /* Get the active VC (e.g. tty1) */
3417 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3419 tty = *active = tmp;
3426 bool tty_is_vc_resolve(const char *tty) {
3427 _cleanup_free_ char *active = NULL;
3431 if (startswith(tty, "/dev/"))
3434 if (streq(tty, "console")) {
3435 tty = resolve_dev_console(&active);
3440 return tty_is_vc(tty);
3443 const char *default_term_for_tty(const char *tty) {
3446 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
3449 bool dirent_is_file(const struct dirent *de) {
3452 if (hidden_file(de->d_name))
3455 if (de->d_type != DT_REG &&
3456 de->d_type != DT_LNK &&
3457 de->d_type != DT_UNKNOWN)
3463 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3466 if (de->d_type != DT_REG &&
3467 de->d_type != DT_LNK &&
3468 de->d_type != DT_UNKNOWN)
3471 if (hidden_file_allow_backup(de->d_name))
3474 return endswith(de->d_name, suffix);
3477 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
3478 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
3479 _cleanup_set_free_free_ Set *seen = NULL;
3482 /* We fork this all off from a child process so that we can
3483 * somewhat cleanly make use of SIGALRM to set a time limit */
3485 reset_all_signal_handlers();
3486 reset_signal_mask();
3488 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3490 pids = hashmap_new(NULL);
3494 seen = set_new(&string_hash_ops);
3498 STRV_FOREACH(directory, directories) {
3499 _cleanup_closedir_ DIR *d;
3502 d = opendir(*directory);
3504 if (errno == ENOENT)
3507 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
3510 FOREACH_DIRENT(de, d, break) {
3511 _cleanup_free_ char *path = NULL;
3515 if (!dirent_is_file(de))
3518 if (set_contains(seen, de->d_name)) {
3519 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
3523 r = set_put_strdup(seen, de->d_name);
3527 path = strjoin(*directory, "/", de->d_name, NULL);
3531 if (null_or_empty_path(path)) {
3532 log_debug("%s is empty (a mask).", path);
3538 log_error_errno(errno, "Failed to fork: %m");
3540 } else if (pid == 0) {
3543 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3553 return log_error_errno(errno, "Failed to execute %s: %m", path);
3556 log_debug("Spawned %s as " PID_FMT ".", path, pid);
3558 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3565 /* Abort execution of this process after the timout. We simply
3566 * rely on SIGALRM as default action terminating the process,
3567 * and turn on alarm(). */
3569 if (timeout != USEC_INFINITY)
3570 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3572 while (!hashmap_isempty(pids)) {
3573 _cleanup_free_ char *path = NULL;
3576 pid = PTR_TO_UINT(hashmap_first_key(pids));
3579 path = hashmap_remove(pids, UINT_TO_PTR(pid));
3582 wait_for_terminate_and_warn(path, pid, true);
3588 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
3592 char **dirs = (char**) directories;
3594 assert(!strv_isempty(dirs));
3596 name = basename(dirs[0]);
3597 assert(!isempty(name));
3599 /* Executes all binaries in the directories in parallel and waits
3600 * for them to finish. Optionally a timeout is applied. If a file
3601 * with the same name exists in more than one directory, the
3602 * earliest one wins. */
3604 executor_pid = fork();
3605 if (executor_pid < 0) {
3606 log_error_errno(errno, "Failed to fork: %m");
3609 } else if (executor_pid == 0) {
3610 r = do_execute(dirs, timeout, argv);
3611 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
3614 wait_for_terminate_and_warn(name, executor_pid, true);
3617 bool nulstr_contains(const char*nulstr, const char *needle) {
3623 NULSTR_FOREACH(i, nulstr)
3624 if (streq(i, needle))
3630 bool plymouth_running(void) {
3631 return access("/run/plymouth/pid", F_OK) >= 0;
3634 char* strshorten(char *s, size_t l) {
3643 static bool hostname_valid_char(char c) {
3645 (c >= 'a' && c <= 'z') ||
3646 (c >= 'A' && c <= 'Z') ||
3647 (c >= '0' && c <= '9') ||
3653 bool hostname_is_valid(const char *s) {
3660 /* Doesn't accept empty hostnames, hostnames with trailing or
3661 * leading dots, and hostnames with multiple dots in a
3662 * sequence. Also ensures that the length stays below
3665 for (p = s, dot = true; *p; p++) {
3672 if (!hostname_valid_char(*p))
3682 if (p-s > HOST_NAME_MAX)
3688 char* hostname_cleanup(char *s, bool lowercase) {
3692 for (p = s, d = s, dot = true; *p; p++) {
3699 } else if (hostname_valid_char(*p)) {
3700 *(d++) = lowercase ? tolower(*p) : *p;
3711 strshorten(s, HOST_NAME_MAX);
3716 bool machine_name_is_valid(const char *s) {
3718 if (!hostname_is_valid(s))
3721 /* Machine names should be useful hostnames, but also be
3722 * useful in unit names, hence we enforce a stricter length
3731 int pipe_eof(int fd) {
3732 struct pollfd pollfd = {
3734 .events = POLLIN|POLLHUP,
3739 r = poll(&pollfd, 1, 0);
3746 return pollfd.revents & POLLHUP;
3749 int fd_wait_for_event(int fd, int event, usec_t t) {
3751 struct pollfd pollfd = {
3759 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
3766 return pollfd.revents;
3769 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3778 r = tempfn_xxxxxx(path, &t);
3782 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3788 f = fdopen(fd, "we");
3801 int terminal_vhangup_fd(int fd) {
3804 if (ioctl(fd, TIOCVHANGUP) < 0)
3810 int terminal_vhangup(const char *name) {
3811 _cleanup_close_ int fd;
3813 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3817 return terminal_vhangup_fd(fd);
3820 int vt_disallocate(const char *name) {
3824 /* Deallocate the VT if possible. If not possible
3825 * (i.e. because it is the active one), at least clear it
3826 * entirely (including the scrollback buffer) */
3828 if (!startswith(name, "/dev/"))
3831 if (!tty_is_vc(name)) {
3832 /* So this is not a VT. I guess we cannot deallocate
3833 * it then. But let's at least clear the screen */
3835 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3840 "\033[r" /* clear scrolling region */
3841 "\033[H" /* move home */
3842 "\033[2J", /* clear screen */
3849 if (!startswith(name, "/dev/tty"))
3852 r = safe_atou(name+8, &u);
3859 /* Try to deallocate */
3860 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3864 r = ioctl(fd, VT_DISALLOCATE, u);
3873 /* Couldn't deallocate, so let's clear it fully with
3875 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3880 "\033[r" /* clear scrolling region */
3881 "\033[H" /* move home */
3882 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3889 int symlink_atomic(const char *from, const char *to) {
3890 _cleanup_free_ char *t = NULL;
3896 r = tempfn_random(to, &t);
3900 if (symlink(from, t) < 0)
3903 if (rename(t, to) < 0) {
3911 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
3912 _cleanup_free_ char *t = NULL;
3917 r = tempfn_random(path, &t);
3921 if (mknod(t, mode, dev) < 0)
3924 if (rename(t, path) < 0) {
3932 int mkfifo_atomic(const char *path, mode_t mode) {
3933 _cleanup_free_ char *t = NULL;
3938 r = tempfn_random(path, &t);
3942 if (mkfifo(t, mode) < 0)
3945 if (rename(t, path) < 0) {
3953 bool display_is_local(const char *display) {
3957 display[0] == ':' &&
3958 display[1] >= '0' &&
3962 int socket_from_display(const char *display, char **path) {
3969 if (!display_is_local(display))
3972 k = strspn(display+1, "0123456789");
3974 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
3978 c = stpcpy(f, "/tmp/.X11-unix/X");
3979 memcpy(c, display+1, k);
3988 const char **username,
3989 uid_t *uid, gid_t *gid,
3991 const char **shell) {
3999 /* We enforce some special rules for uid=0: in order to avoid
4000 * NSS lookups for root we hardcode its data. */
4002 if (streq(*username, "root") || streq(*username, "0")) {
4020 if (parse_uid(*username, &u) >= 0) {
4024 /* If there are multiple users with the same id, make
4025 * sure to leave $USER to the configured value instead
4026 * of the first occurrence in the database. However if
4027 * the uid was configured by a numeric uid, then let's
4028 * pick the real username from /etc/passwd. */
4030 *username = p->pw_name;
4033 p = getpwnam(*username);
4037 return errno > 0 ? -errno : -ESRCH;
4049 *shell = p->pw_shell;
4054 char* uid_to_name(uid_t uid) {
4059 return strdup("root");
4063 return strdup(p->pw_name);
4065 if (asprintf(&r, UID_FMT, uid) < 0)
4071 char* gid_to_name(gid_t gid) {
4076 return strdup("root");
4080 return strdup(p->gr_name);
4082 if (asprintf(&r, GID_FMT, gid) < 0)
4088 int get_group_creds(const char **groupname, gid_t *gid) {
4094 /* We enforce some special rules for gid=0: in order to avoid
4095 * NSS lookups for root we hardcode its data. */
4097 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4098 *groupname = "root";
4106 if (parse_gid(*groupname, &id) >= 0) {
4111 *groupname = g->gr_name;
4114 g = getgrnam(*groupname);
4118 return errno > 0 ? -errno : -ESRCH;
4126 int in_gid(gid_t gid) {
4128 int ngroups_max, r, i;
4130 if (getgid() == gid)
4133 if (getegid() == gid)
4136 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4137 assert(ngroups_max > 0);
4139 gids = alloca(sizeof(gid_t) * ngroups_max);
4141 r = getgroups(ngroups_max, gids);
4145 for (i = 0; i < r; i++)
4152 int in_group(const char *name) {
4156 r = get_group_creds(&name, &gid);
4163 int glob_exists(const char *path) {
4164 _cleanup_globfree_ glob_t g = {};
4170 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4172 if (k == GLOB_NOMATCH)
4174 else if (k == GLOB_NOSPACE)
4177 return !strv_isempty(g.gl_pathv);
4179 return errno ? -errno : -EIO;
4182 int glob_extend(char ***strv, const char *path) {
4183 _cleanup_globfree_ glob_t g = {};
4188 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4190 if (k == GLOB_NOMATCH)
4192 else if (k == GLOB_NOSPACE)
4194 else if (k != 0 || strv_isempty(g.gl_pathv))
4195 return errno ? -errno : -EIO;
4197 STRV_FOREACH(p, g.gl_pathv) {
4198 k = strv_extend(strv, *p);
4206 int dirent_ensure_type(DIR *d, struct dirent *de) {
4212 if (de->d_type != DT_UNKNOWN)
4215 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4219 S_ISREG(st.st_mode) ? DT_REG :
4220 S_ISDIR(st.st_mode) ? DT_DIR :
4221 S_ISLNK(st.st_mode) ? DT_LNK :
4222 S_ISFIFO(st.st_mode) ? DT_FIFO :
4223 S_ISSOCK(st.st_mode) ? DT_SOCK :
4224 S_ISCHR(st.st_mode) ? DT_CHR :
4225 S_ISBLK(st.st_mode) ? DT_BLK :
4231 int get_files_in_directory(const char *path, char ***list) {
4232 _cleanup_closedir_ DIR *d = NULL;
4233 size_t bufsize = 0, n = 0;
4234 _cleanup_strv_free_ char **l = NULL;
4238 /* Returns all files in a directory in *list, and the number
4239 * of files as return value. If list is NULL returns only the
4251 if (!de && errno != 0)
4256 dirent_ensure_type(d, de);
4258 if (!dirent_is_file(de))
4262 /* one extra slot is needed for the terminating NULL */
4263 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4266 l[n] = strdup(de->d_name);
4277 l = NULL; /* avoid freeing */
4283 char *strjoin(const char *x, ...) {
4297 t = va_arg(ap, const char *);
4302 if (n > ((size_t) -1) - l) {
4326 t = va_arg(ap, const char *);
4340 bool is_main_thread(void) {
4341 static thread_local int cached = 0;
4343 if (_unlikely_(cached == 0))
4344 cached = getpid() == gettid() ? 1 : -1;
4349 int block_get_whole_disk(dev_t d, dev_t *ret) {
4356 /* If it has a queue this is good enough for us */
4357 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4360 r = access(p, F_OK);
4368 /* If it is a partition find the originating device */
4369 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4372 r = access(p, F_OK);
4378 /* Get parent dev_t */
4379 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4382 r = read_one_line_file(p, &s);
4388 r = sscanf(s, "%u:%u", &m, &n);
4394 /* Only return this if it is really good enough for us. */
4395 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4398 r = access(p, F_OK);
4402 *ret = makedev(m, n);
4409 static const char *const ioprio_class_table[] = {
4410 [IOPRIO_CLASS_NONE] = "none",
4411 [IOPRIO_CLASS_RT] = "realtime",
4412 [IOPRIO_CLASS_BE] = "best-effort",
4413 [IOPRIO_CLASS_IDLE] = "idle"
4416 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4418 static const char *const sigchld_code_table[] = {
4419 [CLD_EXITED] = "exited",
4420 [CLD_KILLED] = "killed",
4421 [CLD_DUMPED] = "dumped",
4422 [CLD_TRAPPED] = "trapped",
4423 [CLD_STOPPED] = "stopped",
4424 [CLD_CONTINUED] = "continued",
4427 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4429 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4430 [LOG_FAC(LOG_KERN)] = "kern",
4431 [LOG_FAC(LOG_USER)] = "user",
4432 [LOG_FAC(LOG_MAIL)] = "mail",
4433 [LOG_FAC(LOG_DAEMON)] = "daemon",
4434 [LOG_FAC(LOG_AUTH)] = "auth",
4435 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4436 [LOG_FAC(LOG_LPR)] = "lpr",
4437 [LOG_FAC(LOG_NEWS)] = "news",
4438 [LOG_FAC(LOG_UUCP)] = "uucp",
4439 [LOG_FAC(LOG_CRON)] = "cron",
4440 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4441 [LOG_FAC(LOG_FTP)] = "ftp",
4442 [LOG_FAC(LOG_LOCAL0)] = "local0",
4443 [LOG_FAC(LOG_LOCAL1)] = "local1",
4444 [LOG_FAC(LOG_LOCAL2)] = "local2",
4445 [LOG_FAC(LOG_LOCAL3)] = "local3",
4446 [LOG_FAC(LOG_LOCAL4)] = "local4",
4447 [LOG_FAC(LOG_LOCAL5)] = "local5",
4448 [LOG_FAC(LOG_LOCAL6)] = "local6",
4449 [LOG_FAC(LOG_LOCAL7)] = "local7"
4452 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4454 static const char *const log_level_table[] = {
4455 [LOG_EMERG] = "emerg",
4456 [LOG_ALERT] = "alert",
4457 [LOG_CRIT] = "crit",
4459 [LOG_WARNING] = "warning",
4460 [LOG_NOTICE] = "notice",
4461 [LOG_INFO] = "info",
4462 [LOG_DEBUG] = "debug"
4465 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4467 static const char* const sched_policy_table[] = {
4468 [SCHED_OTHER] = "other",
4469 [SCHED_BATCH] = "batch",
4470 [SCHED_IDLE] = "idle",
4471 [SCHED_FIFO] = "fifo",
4475 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4477 static const char* const rlimit_table[_RLIMIT_MAX] = {
4478 [RLIMIT_CPU] = "LimitCPU",
4479 [RLIMIT_FSIZE] = "LimitFSIZE",
4480 [RLIMIT_DATA] = "LimitDATA",
4481 [RLIMIT_STACK] = "LimitSTACK",
4482 [RLIMIT_CORE] = "LimitCORE",
4483 [RLIMIT_RSS] = "LimitRSS",
4484 [RLIMIT_NOFILE] = "LimitNOFILE",
4485 [RLIMIT_AS] = "LimitAS",
4486 [RLIMIT_NPROC] = "LimitNPROC",
4487 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4488 [RLIMIT_LOCKS] = "LimitLOCKS",
4489 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4490 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4491 [RLIMIT_NICE] = "LimitNICE",
4492 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4493 [RLIMIT_RTTIME] = "LimitRTTIME"
4496 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4498 static const char* const ip_tos_table[] = {
4499 [IPTOS_LOWDELAY] = "low-delay",
4500 [IPTOS_THROUGHPUT] = "throughput",
4501 [IPTOS_RELIABILITY] = "reliability",
4502 [IPTOS_LOWCOST] = "low-cost",
4505 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4507 static const char *const __signal_table[] = {
4524 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4535 [SIGVTALRM] = "VTALRM",
4537 [SIGWINCH] = "WINCH",
4543 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4545 const char *signal_to_string(int signo) {
4546 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4549 name = __signal_to_string(signo);
4553 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4554 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4556 snprintf(buf, sizeof(buf), "%d", signo);
4561 int signal_from_string(const char *s) {
4566 signo = __signal_from_string(s);
4570 if (startswith(s, "RTMIN+")) {
4574 if (safe_atou(s, &u) >= 0) {
4575 signo = (int) u + offset;
4576 if (signo > 0 && signo < _NSIG)
4582 bool kexec_loaded(void) {
4583 bool loaded = false;
4586 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4594 int prot_from_flags(int flags) {
4596 switch (flags & O_ACCMODE) {
4605 return PROT_READ|PROT_WRITE;
4612 char *format_bytes(char *buf, size_t l, off_t t) {
4615 static const struct {
4619 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4620 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4621 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4622 { "G", 1024ULL*1024ULL*1024ULL },
4623 { "M", 1024ULL*1024ULL },
4627 if (t == (off_t) -1)
4630 for (i = 0; i < ELEMENTSOF(table); i++) {
4632 if (t >= table[i].factor) {
4635 (unsigned long long) (t / table[i].factor),
4636 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4643 snprintf(buf, l, "%lluB", (unsigned long long) t);
4651 void* memdup(const void *p, size_t l) {
4664 int fd_inc_sndbuf(int fd, size_t n) {
4666 socklen_t l = sizeof(value);
4668 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4669 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4672 /* If we have the privileges we will ignore the kernel limit. */
4675 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
4676 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
4682 int fd_inc_rcvbuf(int fd, size_t n) {
4684 socklen_t l = sizeof(value);
4686 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4687 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4690 /* If we have the privileges we will ignore the kernel limit. */
4693 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
4694 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
4699 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4700 bool stdout_is_tty, stderr_is_tty;
4701 pid_t parent_pid, agent_pid;
4702 sigset_t ss, saved_ss;
4710 /* Spawns a temporary TTY agent, making sure it goes away when
4713 parent_pid = getpid();
4715 /* First we temporarily block all signals, so that the new
4716 * child has them blocked initially. This way, we can be sure
4717 * that SIGTERMs are not lost we might send to the agent. */
4718 assert_se(sigfillset(&ss) >= 0);
4719 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
4722 if (agent_pid < 0) {
4723 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
4727 if (agent_pid != 0) {
4728 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
4735 * Make sure the agent goes away when the parent dies */
4736 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4737 _exit(EXIT_FAILURE);
4739 /* Make sure we actually can kill the agent, if we need to, in
4740 * case somebody invoked us from a shell script that trapped
4741 * SIGTERM or so... */
4742 reset_all_signal_handlers();
4743 reset_signal_mask();
4745 /* Check whether our parent died before we were able
4746 * to set the death signal and unblock the signals */
4747 if (getppid() != parent_pid)
4748 _exit(EXIT_SUCCESS);
4750 /* Don't leak fds to the agent */
4751 close_all_fds(except, n_except);
4753 stdout_is_tty = isatty(STDOUT_FILENO);
4754 stderr_is_tty = isatty(STDERR_FILENO);
4756 if (!stdout_is_tty || !stderr_is_tty) {
4759 /* Detach from stdout/stderr. and reopen
4760 * /dev/tty for them. This is important to
4761 * ensure that when systemctl is started via
4762 * popen() or a similar call that expects to
4763 * read EOF we actually do generate EOF and
4764 * not delay this indefinitely by because we
4765 * keep an unused copy of stdin around. */
4766 fd = open("/dev/tty", O_WRONLY);
4768 log_error_errno(errno, "Failed to open /dev/tty: %m");
4769 _exit(EXIT_FAILURE);
4773 dup2(fd, STDOUT_FILENO);
4776 dup2(fd, STDERR_FILENO);
4782 /* Count arguments */
4784 for (n = 0; va_arg(ap, char*); n++)
4789 l = alloca(sizeof(char *) * (n + 1));
4791 /* Fill in arguments */
4793 for (i = 0; i <= n; i++)
4794 l[i] = va_arg(ap, char*);
4798 _exit(EXIT_FAILURE);
4801 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4802 struct rlimit highest, fixed;
4806 if (setrlimit(resource, rlim) >= 0)
4812 /* So we failed to set the desired setrlimit, then let's try
4813 * to get as close as we can */
4814 assert_se(getrlimit(resource, &highest) == 0);
4816 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4817 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4819 if (setrlimit(resource, &fixed) < 0)
4825 bool http_etag_is_valid(const char *etag) {
4829 if (!endswith(etag, "\""))
4832 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
4838 bool http_url_is_valid(const char *url) {
4844 p = startswith(url, "http://");
4846 p = startswith(url, "https://");
4853 return ascii_is_valid(p);
4856 bool documentation_url_is_valid(const char *url) {
4862 if (http_url_is_valid(url))
4865 p = startswith(url, "file:/");
4867 p = startswith(url, "info:");
4869 p = startswith(url, "man:");
4874 return ascii_is_valid(p);
4877 bool in_initrd(void) {
4878 static int saved = -1;
4884 /* We make two checks here:
4886 * 1. the flag file /etc/initrd-release must exist
4887 * 2. the root file system must be a memory file system
4889 * The second check is extra paranoia, since misdetecting an
4890 * initrd can have bad bad consequences due the initrd
4891 * emptying when transititioning to the main systemd.
4894 saved = access("/etc/initrd-release", F_OK) >= 0 &&
4895 statfs("/", &s) >= 0 &&
4896 is_temporary_fs(&s);
4901 void warn_melody(void) {
4902 _cleanup_close_ int fd = -1;
4904 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
4908 /* Yeah, this is synchronous. Kinda sucks. But well... */
4910 ioctl(fd, KIOCSOUND, (int)(1193180/440));
4911 usleep(125*USEC_PER_MSEC);
4913 ioctl(fd, KIOCSOUND, (int)(1193180/220));
4914 usleep(125*USEC_PER_MSEC);
4916 ioctl(fd, KIOCSOUND, (int)(1193180/220));
4917 usleep(125*USEC_PER_MSEC);
4919 ioctl(fd, KIOCSOUND, 0);
4922 int make_console_stdio(void) {
4925 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
4927 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
4929 return log_error_errno(fd, "Failed to acquire terminal: %m");
4933 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
4938 int get_home_dir(char **_h) {
4946 /* Take the user specified one */
4947 e = secure_getenv("HOME");
4948 if (e && path_is_absolute(e)) {
4957 /* Hardcode home directory for root to avoid NSS */
4960 h = strdup("/root");
4968 /* Check the database... */
4972 return errno > 0 ? -errno : -ESRCH;
4974 if (!path_is_absolute(p->pw_dir))
4977 h = strdup(p->pw_dir);
4985 int get_shell(char **_s) {
4993 /* Take the user specified one */
4994 e = getenv("SHELL");
5004 /* Hardcode home directory for root to avoid NSS */
5007 s = strdup("/bin/sh");
5015 /* Check the database... */
5019 return errno > 0 ? -errno : -ESRCH;
5021 if (!path_is_absolute(p->pw_shell))
5024 s = strdup(p->pw_shell);
5032 bool filename_is_valid(const char *p) {
5046 if (strlen(p) > FILENAME_MAX)
5052 bool string_is_safe(const char *p) {
5058 for (t = p; *t; t++) {
5059 if (*t > 0 && *t < ' ')
5062 if (strchr("\\\"\'\0x7f", *t))
5070 * Check if a string contains control characters. If 'ok' is non-NULL
5071 * it may be a string containing additional CCs to be considered OK.
5073 bool string_has_cc(const char *p, const char *ok) {
5078 for (t = p; *t; t++) {
5079 if (ok && strchr(ok, *t))
5082 if (*t > 0 && *t < ' ')
5092 bool path_is_safe(const char *p) {
5097 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5100 if (strlen(p) > PATH_MAX)
5103 /* The following two checks are not really dangerous, but hey, they still are confusing */
5104 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5107 if (strstr(p, "//"))
5113 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5114 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5115 int (*compar) (const void *, const void *, void *), void *arg) {
5124 p = (void *)(((const char *) base) + (idx * size));
5125 comparison = compar(key, p, arg);
5128 else if (comparison > 0)
5136 void init_gettext(void) {
5137 setlocale(LC_ALL, "");
5138 textdomain(GETTEXT_PACKAGE);
5141 bool is_locale_utf8(void) {
5143 static int cached_answer = -1;
5145 if (cached_answer >= 0)
5148 if (!setlocale(LC_ALL, "")) {
5149 cached_answer = true;
5153 set = nl_langinfo(CODESET);
5155 cached_answer = true;
5159 if (streq(set, "UTF-8")) {
5160 cached_answer = true;
5164 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5165 * unset and everything can do to UTF-8 nowadays. */
5166 set = setlocale(LC_CTYPE, NULL);
5168 cached_answer = true;
5172 /* Check result, but ignore the result if C was set
5176 !getenv("LC_ALL") &&
5177 !getenv("LC_CTYPE") &&
5181 return (bool) cached_answer;
5184 const char *draw_special_char(DrawSpecialChar ch) {
5185 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5188 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
5189 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5190 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5191 [DRAW_TREE_SPACE] = " ", /* */
5192 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5193 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5194 [DRAW_ARROW] = "\342\206\222", /* → */
5195 [DRAW_DASH] = "\342\200\223", /* – */
5198 /* ASCII fallback */ {
5199 [DRAW_TREE_VERTICAL] = "| ",
5200 [DRAW_TREE_BRANCH] = "|-",
5201 [DRAW_TREE_RIGHT] = "`-",
5202 [DRAW_TREE_SPACE] = " ",
5203 [DRAW_TRIANGULAR_BULLET] = ">",
5204 [DRAW_BLACK_CIRCLE] = "*",
5205 [DRAW_ARROW] = "->",
5210 return draw_table[!is_locale_utf8()][ch];
5213 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5216 size_t l, old_len, new_len;
5222 old_len = strlen(old_string);
5223 new_len = strlen(new_string);
5236 if (!startswith(f, old_string)) {
5242 nl = l - old_len + new_len;
5243 a = realloc(r, nl + 1);
5251 t = stpcpy(t, new_string);
5263 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5264 const char *i, *begin = NULL;
5269 } state = STATE_OTHER;
5271 size_t osz = 0, isz;
5277 /* Strips ANSI color and replaces TABs by 8 spaces */
5279 isz = _isz ? *_isz : strlen(*ibuf);
5281 f = open_memstream(&obuf, &osz);
5285 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5290 if (i >= *ibuf + isz) /* EOT */
5292 else if (*i == '\x1B')
5293 state = STATE_ESCAPE;
5294 else if (*i == '\t')
5301 if (i >= *ibuf + isz) { /* EOT */
5304 } else if (*i == '[') {
5305 state = STATE_BRACKET;
5310 state = STATE_OTHER;
5317 if (i >= *ibuf + isz || /* EOT */
5318 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5321 state = STATE_OTHER;
5323 } else if (*i == 'm')
5324 state = STATE_OTHER;
5346 int on_ac_power(void) {
5347 bool found_offline = false, found_online = false;
5348 _cleanup_closedir_ DIR *d = NULL;
5350 d = opendir("/sys/class/power_supply");
5352 return errno == ENOENT ? true : -errno;
5356 _cleanup_close_ int fd = -1, device = -1;
5362 if (!de && errno != 0)
5368 if (hidden_file(de->d_name))
5371 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5373 if (errno == ENOENT || errno == ENOTDIR)
5379 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5381 if (errno == ENOENT)
5387 n = read(fd, contents, sizeof(contents));
5391 if (n != 6 || memcmp(contents, "Mains\n", 6))
5395 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5397 if (errno == ENOENT)
5403 n = read(fd, contents, sizeof(contents));
5407 if (n != 2 || contents[1] != '\n')
5410 if (contents[0] == '1') {
5411 found_online = true;
5413 } else if (contents[0] == '0')
5414 found_offline = true;
5419 return found_online || !found_offline;
5422 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
5429 if (!path_strv_resolve_uniq(search, root))
5432 STRV_FOREACH(i, search) {
5433 _cleanup_free_ char *p = NULL;
5437 p = strjoin(root, *i, "/", path, NULL);
5439 p = strjoin(*i, "/", path, NULL);
5449 if (errno != ENOENT)
5456 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
5457 _cleanup_strv_free_ char **copy = NULL;
5463 if (path_is_absolute(path)) {
5466 f = fopen(path, mode);
5475 copy = strv_copy((char**) search);
5479 return search_and_fopen_internal(path, mode, root, copy, _f);
5482 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
5483 _cleanup_strv_free_ char **s = NULL;
5485 if (path_is_absolute(path)) {
5488 f = fopen(path, mode);
5497 s = strv_split_nulstr(search);
5501 return search_and_fopen_internal(path, mode, root, s, _f);
5504 char *strextend(char **x, ...) {
5511 l = f = *x ? strlen(*x) : 0;
5518 t = va_arg(ap, const char *);
5523 if (n > ((size_t) -1) - l) {
5532 r = realloc(*x, l+1);
5542 t = va_arg(ap, const char *);
5556 char *strrep(const char *s, unsigned n) {
5564 p = r = malloc(l * n + 1);
5568 for (i = 0; i < n; i++)
5575 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
5582 if (*allocated >= need)
5585 newalloc = MAX(need * 2, 64u / size);
5586 a = newalloc * size;
5588 /* check for overflows */
5589 if (a < size * need)
5597 *allocated = newalloc;
5601 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
5610 q = greedy_realloc(p, allocated, need, size);
5614 if (*allocated > prev)
5615 memzero(q + prev * size, (*allocated - prev) * size);
5620 bool id128_is_valid(const char *s) {
5626 /* Simple formatted 128bit hex string */
5628 for (i = 0; i < l; i++) {
5631 if (!(c >= '0' && c <= '9') &&
5632 !(c >= 'a' && c <= 'z') &&
5633 !(c >= 'A' && c <= 'Z'))
5637 } else if (l == 36) {
5639 /* Formatted UUID */
5641 for (i = 0; i < l; i++) {
5644 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5648 if (!(c >= '0' && c <= '9') &&
5649 !(c >= 'a' && c <= 'z') &&
5650 !(c >= 'A' && c <= 'Z'))
5661 int split_pair(const char *s, const char *sep, char **l, char **r) {
5676 a = strndup(s, x - s);
5680 b = strdup(x + strlen(sep));
5692 int shall_restore_state(void) {
5693 _cleanup_free_ char *value = NULL;
5696 r = get_proc_cmdline_key("systemd.restore_state=", &value);
5702 return parse_boolean(value) != 0;
5705 int proc_cmdline(char **ret) {
5708 if (detect_container(NULL) > 0)
5709 return get_process_cmdline(1, 0, false, ret);
5711 return read_one_line_file("/proc/cmdline", ret);
5714 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
5715 _cleanup_free_ char *line = NULL;
5721 r = proc_cmdline(&line);
5727 _cleanup_free_ char *word = NULL;
5730 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
5736 /* Filter out arguments that are intended only for the
5738 if (!in_initrd() && startswith(word, "rd."))
5741 value = strchr(word, '=');
5745 r = parse_item(word, value);
5753 int get_proc_cmdline_key(const char *key, char **value) {
5754 _cleanup_free_ char *line = NULL, *ret = NULL;
5761 r = proc_cmdline(&line);
5767 _cleanup_free_ char *word = NULL;
5770 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
5776 /* Filter out arguments that are intended only for the
5778 if (!in_initrd() && startswith(word, "rd."))
5782 e = startswith(word, key);
5786 r = free_and_strdup(&ret, e);
5792 if (streq(word, key))
5806 int container_get_leader(const char *machine, pid_t *pid) {
5807 _cleanup_free_ char *s = NULL, *class = NULL;
5815 p = strjoina("/run/systemd/machines/", machine);
5816 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
5824 if (!streq_ptr(class, "container"))
5827 r = parse_pid(s, &leader);
5837 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
5838 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
5846 mntns = procfs_file_alloca(pid, "ns/mnt");
5847 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5855 pidns = procfs_file_alloca(pid, "ns/pid");
5856 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5864 netns = procfs_file_alloca(pid, "ns/net");
5865 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5873 root = procfs_file_alloca(pid, "root");
5874 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
5880 *pidns_fd = pidnsfd;
5883 *mntns_fd = mntnsfd;
5886 *netns_fd = netnsfd;
5891 pidnsfd = mntnsfd = netnsfd = -1;
5896 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
5899 if (setns(pidns_fd, CLONE_NEWPID) < 0)
5903 if (setns(mntns_fd, CLONE_NEWNS) < 0)
5907 if (setns(netns_fd, CLONE_NEWNET) < 0)
5911 if (fchdir(root_fd) < 0)
5914 if (chroot(".") < 0)
5918 if (setresgid(0, 0, 0) < 0)
5921 if (setgroups(0, NULL) < 0)
5924 if (setresuid(0, 0, 0) < 0)
5930 int getpeercred(int fd, struct ucred *ucred) {
5931 socklen_t n = sizeof(struct ucred);
5938 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
5942 if (n != sizeof(struct ucred))
5945 /* Check if the data is actually useful and not suppressed due
5946 * to namespacing issues */
5949 if (u.uid == UID_INVALID)
5951 if (u.gid == GID_INVALID)
5958 int getpeersec(int fd, char **ret) {
5970 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
5974 if (errno != ERANGE)
5981 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
5997 /* This is much like like mkostemp() but is subject to umask(). */
5998 int mkostemp_safe(char *pattern, int flags) {
5999 _cleanup_umask_ mode_t u;
6006 fd = mkostemp(pattern, flags);
6013 int open_tmpfile(const char *path, int flags) {
6020 /* Try O_TMPFILE first, if it is supported */
6021 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6026 /* Fall back to unguessable name + unlinking */
6027 p = strjoina(path, "/systemd-tmp-XXXXXX");
6029 fd = mkostemp_safe(p, flags);
6037 int fd_warn_permissions(const char *path, int fd) {
6040 if (fstat(fd, &st) < 0)
6043 if (st.st_mode & 0111)
6044 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6046 if (st.st_mode & 0002)
6047 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6049 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6050 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);
6055 unsigned long personality_from_string(const char *p) {
6057 /* Parse a personality specifier. We introduce our own
6058 * identifiers that indicate specific ABIs, rather than just
6059 * hints regarding the register size, since we want to keep
6060 * things open for multiple locally supported ABIs for the
6061 * same register size. We try to reuse the ABI identifiers
6062 * used by libseccomp. */
6064 #if defined(__x86_64__)
6066 if (streq(p, "x86"))
6069 if (streq(p, "x86-64"))
6072 #elif defined(__i386__)
6074 if (streq(p, "x86"))
6078 /* personality(7) documents that 0xffffffffUL is used for
6079 * querying the current personality, hence let's use that here
6080 * as error indicator. */
6081 return 0xffffffffUL;
6084 const char* personality_to_string(unsigned long p) {
6086 #if defined(__x86_64__)
6088 if (p == PER_LINUX32)
6094 #elif defined(__i386__)
6103 uint64_t physical_memory(void) {
6106 /* We return this as uint64_t in case we are running as 32bit
6107 * process on a 64bit kernel with huge amounts of memory */
6109 mem = sysconf(_SC_PHYS_PAGES);
6112 return (uint64_t) mem * (uint64_t) page_size();
6115 void hexdump(FILE *f, const void *p, size_t s) {
6116 const uint8_t *b = p;
6119 assert(s == 0 || b);
6124 fprintf(f, "%04x ", n);
6126 for (i = 0; i < 16; i++) {
6131 fprintf(f, "%02x ", b[i]);
6139 for (i = 0; i < 16; i++) {
6144 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6158 int update_reboot_param_file(const char *param) {
6163 r = write_string_file(REBOOT_PARAM_FILE, param);
6165 log_error("Failed to write reboot param to "
6166 REBOOT_PARAM_FILE": %s", strerror(-r));
6168 unlink(REBOOT_PARAM_FILE);
6173 int umount_recursive(const char *prefix, int flags) {
6177 /* Try to umount everything recursively below a
6178 * directory. Also, take care of stacked mounts, and keep
6179 * unmounting them until they are gone. */
6182 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6187 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6188 if (!proc_self_mountinfo)
6192 _cleanup_free_ char *path = NULL, *p = NULL;
6195 k = fscanf(proc_self_mountinfo,
6196 "%*s " /* (1) mount id */
6197 "%*s " /* (2) parent id */
6198 "%*s " /* (3) major:minor */
6199 "%*s " /* (4) root */
6200 "%ms " /* (5) mount point */
6201 "%*s" /* (6) mount options */
6202 "%*[^-]" /* (7) optional fields */
6203 "- " /* (8) separator */
6204 "%*s " /* (9) file system type */
6205 "%*s" /* (10) mount source */
6206 "%*s" /* (11) mount options 2 */
6207 "%*[^\n]", /* some rubbish at the end */
6216 r = cunescape(path, UNESCAPE_RELAX, &p);
6220 if (!path_startswith(p, prefix))
6223 if (umount2(p, flags) < 0) {
6239 static int get_mount_flags(const char *path, unsigned long *flags) {
6242 if (statvfs(path, &buf) < 0)
6244 *flags = buf.f_flag;
6248 int bind_remount_recursive(const char *prefix, bool ro) {
6249 _cleanup_set_free_free_ Set *done = NULL;
6250 _cleanup_free_ char *cleaned = NULL;
6253 /* Recursively remount a directory (and all its submounts)
6254 * read-only or read-write. If the directory is already
6255 * mounted, we reuse the mount and simply mark it
6256 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6257 * operation). If it isn't we first make it one. Afterwards we
6258 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6259 * submounts we can access, too. When mounts are stacked on
6260 * the same mount point we only care for each individual
6261 * "top-level" mount on each point, as we cannot
6262 * influence/access the underlying mounts anyway. We do not
6263 * have any effect on future submounts that might get
6264 * propagated, they migt be writable. This includes future
6265 * submounts that have been triggered via autofs. */
6267 cleaned = strdup(prefix);
6271 path_kill_slashes(cleaned);
6273 done = set_new(&string_hash_ops);
6278 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6279 _cleanup_set_free_free_ Set *todo = NULL;
6280 bool top_autofs = false;
6282 unsigned long orig_flags;
6284 todo = set_new(&string_hash_ops);
6288 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6289 if (!proc_self_mountinfo)
6293 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6296 k = fscanf(proc_self_mountinfo,
6297 "%*s " /* (1) mount id */
6298 "%*s " /* (2) parent id */
6299 "%*s " /* (3) major:minor */
6300 "%*s " /* (4) root */
6301 "%ms " /* (5) mount point */
6302 "%*s" /* (6) mount options (superblock) */
6303 "%*[^-]" /* (7) optional fields */
6304 "- " /* (8) separator */
6305 "%ms " /* (9) file system type */
6306 "%*s" /* (10) mount source */
6307 "%*s" /* (11) mount options (bind mount) */
6308 "%*[^\n]", /* some rubbish at the end */
6318 r = cunescape(path, UNESCAPE_RELAX, &p);
6322 /* Let's ignore autofs mounts. If they aren't
6323 * triggered yet, we want to avoid triggering
6324 * them, as we don't make any guarantees for
6325 * future submounts anyway. If they are
6326 * already triggered, then we will find
6327 * another entry for this. */
6328 if (streq(type, "autofs")) {
6329 top_autofs = top_autofs || path_equal(cleaned, p);
6333 if (path_startswith(p, cleaned) &&
6334 !set_contains(done, p)) {
6336 r = set_consume(todo, p);
6346 /* If we have no submounts to process anymore and if
6347 * the root is either already done, or an autofs, we
6349 if (set_isempty(todo) &&
6350 (top_autofs || set_contains(done, cleaned)))
6353 if (!set_contains(done, cleaned) &&
6354 !set_contains(todo, cleaned)) {
6355 /* The prefix directory itself is not yet a
6356 * mount, make it one. */
6357 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6361 (void) get_mount_flags(cleaned, &orig_flags);
6362 orig_flags &= ~MS_RDONLY;
6364 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6367 x = strdup(cleaned);
6371 r = set_consume(done, x);
6376 while ((x = set_steal_first(todo))) {
6378 r = set_consume(done, x);
6384 /* Try to reuse the original flag set, but
6385 * don't care for errors, in case of
6386 * obstructed mounts */
6388 (void) get_mount_flags(x, &orig_flags);
6389 orig_flags &= ~MS_RDONLY;
6391 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
6393 /* Deal with mount points that are
6394 * obstructed by a later mount */
6396 if (errno != ENOENT)
6404 int fflush_and_check(FILE *f) {
6411 return errno ? -errno : -EIO;
6416 int tempfn_xxxxxx(const char *p, char **ret) {
6428 * /foo/bar/.#waldoXXXXXX
6432 if (!filename_is_valid(fn))
6435 t = new(char, strlen(p) + 2 + 6 + 1);
6439 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
6441 *ret = path_kill_slashes(t);
6445 int tempfn_random(const char *p, char **ret) {
6459 * /foo/bar/.#waldobaa2a261115984a9
6463 if (!filename_is_valid(fn))
6466 t = new(char, strlen(p) + 2 + 16 + 1);
6470 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
6473 for (i = 0; i < 16; i++) {
6474 *(x++) = hexchar(u & 0xF);
6480 *ret = path_kill_slashes(t);
6484 int tempfn_random_child(const char *p, char **ret) {
6495 * /foo/bar/waldo/.#3c2b6219aa75d7d0
6498 t = new(char, strlen(p) + 3 + 16 + 1);
6502 x = stpcpy(stpcpy(t, p), "/.#");
6505 for (i = 0; i < 16; i++) {
6506 *(x++) = hexchar(u & 0xF);
6512 *ret = path_kill_slashes(t);
6516 /* make sure the hostname is not "localhost" */
6517 bool is_localhost(const char *hostname) {
6520 /* This tries to identify local host and domain names
6521 * described in RFC6761 plus the redhatism of .localdomain */
6523 return streq(hostname, "localhost") ||
6524 streq(hostname, "localhost.") ||
6525 streq(hostname, "localdomain.") ||
6526 streq(hostname, "localdomain") ||
6527 endswith(hostname, ".localhost") ||
6528 endswith(hostname, ".localhost.") ||
6529 endswith(hostname, ".localdomain") ||
6530 endswith(hostname, ".localdomain.");
6533 int take_password_lock(const char *root) {
6535 struct flock flock = {
6537 .l_whence = SEEK_SET,
6545 /* This is roughly the same as lckpwdf(), but not as awful. We
6546 * don't want to use alarm() and signals, hence we implement
6547 * our own trivial version of this.
6549 * Note that shadow-utils also takes per-database locks in
6550 * addition to lckpwdf(). However, we don't given that they
6551 * are redundant as they they invoke lckpwdf() first and keep
6552 * it during everything they do. The per-database locks are
6553 * awfully racy, and thus we just won't do them. */
6556 path = strjoina(root, "/etc/.pwd.lock");
6558 path = "/etc/.pwd.lock";
6560 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
6564 r = fcntl(fd, F_SETLKW, &flock);
6573 int is_symlink(const char *path) {
6576 if (lstat(path, &info) < 0)
6579 return !!S_ISLNK(info.st_mode);
6582 int is_dir(const char* path, bool follow) {
6587 r = stat(path, &st);
6589 r = lstat(path, &st);
6593 return !!S_ISDIR(st.st_mode);
6596 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
6597 _cleanup_free_ char *s = NULL;
6598 size_t allocated = 0, sz = 0;
6606 SINGLE_QUOTE_ESCAPE,
6608 DOUBLE_QUOTE_ESCAPE,
6616 /* Parses the first word of a string, and returns it in
6617 * *ret. Removes all quotes in the process. When parsing fails
6618 * (because of an uneven number of quotes or similar), leaves
6619 * the pointer *p at the first invalid character. */
6629 else if (strchr(WHITESPACE, c))
6639 state = SINGLE_QUOTE;
6641 state = VALUE_ESCAPE;
6643 state = DOUBLE_QUOTE;
6644 else if (strchr(WHITESPACE, c))
6647 if (!GREEDY_REALLOC(s, allocated, sz+2))
6657 if (flags & UNQUOTE_RELAX)
6662 if (!GREEDY_REALLOC(s, allocated, sz+7))
6665 if (flags & UNQUOTE_CUNESCAPE) {
6668 r = cunescape_one(*p, (size_t) -1, &c, &u);
6675 s[sz++] = c; /* normal explicit char */
6677 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
6686 if (flags & UNQUOTE_RELAX)
6689 } else if (c == '\'')
6692 state = SINGLE_QUOTE_ESCAPE;
6694 if (!GREEDY_REALLOC(s, allocated, sz+2))
6702 case SINGLE_QUOTE_ESCAPE:
6704 if (flags & UNQUOTE_RELAX)
6709 if (!GREEDY_REALLOC(s, allocated, sz+7))
6712 if (flags & UNQUOTE_CUNESCAPE) {
6715 r = cunescape_one(*p, (size_t) -1, &c, &u);
6724 sz += utf8_encode_unichar(s + sz, u);
6728 state = SINGLE_QUOTE;
6737 state = DOUBLE_QUOTE_ESCAPE;
6739 if (!GREEDY_REALLOC(s, allocated, sz+2))
6747 case DOUBLE_QUOTE_ESCAPE:
6749 if (flags & UNQUOTE_RELAX)
6754 if (!GREEDY_REALLOC(s, allocated, sz+7))
6757 if (flags & UNQUOTE_CUNESCAPE) {
6760 r = cunescape_one(*p, (size_t) -1, &c, &u);
6769 sz += utf8_encode_unichar(s + sz, u);
6773 state = DOUBLE_QUOTE;
6779 if (!strchr(WHITESPACE, c))
6801 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
6806 /* Parses a number of words from a string, stripping any
6807 * quotes if necessary. */
6811 /* Count how many words are expected */
6812 va_start(ap, flags);
6814 if (!va_arg(ap, char **))
6823 /* Read all words into a temporary array */
6824 l = newa0(char*, n);
6825 for (c = 0; c < n; c++) {
6827 r = unquote_first_word(p, &l[c], flags);
6831 for (j = 0; j < c; j++)
6841 /* If we managed to parse all words, return them in the passed
6843 va_start(ap, flags);
6844 for (i = 0; i < n; i++) {
6847 v = va_arg(ap, char **);
6857 int free_and_strdup(char **p, const char *s) {
6862 /* Replaces a string pointer with an strdup()ed new string,
6863 * possibly freeing the old one. */
6878 int sethostname_idempotent(const char *s) {
6880 char buf[HOST_NAME_MAX + 1] = {};
6884 r = gethostname(buf, sizeof(buf));
6891 r = sethostname(s, strlen(s));
6898 int ptsname_malloc(int fd, char **ret) {
6911 if (ptsname_r(fd, c, l) == 0) {
6915 if (errno != ERANGE) {
6925 int openpt_in_namespace(pid_t pid, int flags) {
6926 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
6927 _cleanup_close_pair_ int pair[2] = { -1, -1 };
6929 struct cmsghdr cmsghdr;
6930 uint8_t buf[CMSG_SPACE(sizeof(int))];
6932 struct msghdr mh = {
6933 .msg_control = &control,
6934 .msg_controllen = sizeof(control),
6936 struct cmsghdr *cmsg;
6943 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
6947 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
6957 pair[0] = safe_close(pair[0]);
6959 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
6961 _exit(EXIT_FAILURE);
6963 master = posix_openpt(flags);
6965 _exit(EXIT_FAILURE);
6967 cmsg = CMSG_FIRSTHDR(&mh);
6968 cmsg->cmsg_level = SOL_SOCKET;
6969 cmsg->cmsg_type = SCM_RIGHTS;
6970 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
6971 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
6973 mh.msg_controllen = cmsg->cmsg_len;
6975 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
6976 _exit(EXIT_FAILURE);
6978 _exit(EXIT_SUCCESS);
6981 pair[1] = safe_close(pair[1]);
6983 r = wait_for_terminate(child, &si);
6986 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
6989 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
6992 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
6993 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
6997 fds = (int*) CMSG_DATA(cmsg);
6998 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7001 close_many(fds, n_fds);
7011 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7012 _cleanup_close_ int fd = -1;
7015 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7017 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7021 l = fgetxattr(fd, attribute, value, size);
7028 static int parse_crtime(le64_t le, usec_t *usec) {
7034 if (u == 0 || u == (uint64_t) -1)
7041 int fd_getcrtime(int fd, usec_t *usec) {
7048 /* Until Linux gets a real concept of birthtime/creation time,
7049 * let's fake one with xattrs */
7051 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7054 if (n != sizeof(le))
7057 return parse_crtime(le, usec);
7060 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7064 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7067 if (n != sizeof(le))
7070 return parse_crtime(le, usec);
7073 int path_getcrtime(const char *p, usec_t *usec) {
7080 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7083 if (n != sizeof(le))
7086 return parse_crtime(le, usec);
7089 int fd_setcrtime(int fd, usec_t usec) {
7095 usec = now(CLOCK_REALTIME);
7097 le = htole64((uint64_t) usec);
7098 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7104 int chattr_fd(int fd, unsigned value, unsigned mask) {
7105 unsigned old_attr, new_attr;
7112 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7115 new_attr = (old_attr & ~mask) | (value & mask);
7116 if (new_attr == old_attr)
7119 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7125 int chattr_path(const char *p, unsigned value, unsigned mask) {
7126 _cleanup_close_ int fd = -1;
7133 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7137 return chattr_fd(fd, value, mask);
7140 int read_attr_fd(int fd, unsigned *ret) {
7143 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
7149 int read_attr_path(const char *p, unsigned *ret) {
7150 _cleanup_close_ int fd = -1;
7155 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7159 return read_attr_fd(fd, ret);
7162 int make_lock_file(const char *p, int operation, LockFile *ret) {
7163 _cleanup_close_ int fd = -1;
7164 _cleanup_free_ char *t = NULL;
7168 * We use UNPOSIX locks if they are available. They have nice
7169 * semantics, and are mostly compatible with NFS. However,
7170 * they are only available on new kernels. When we detect we
7171 * are running on an older kernel, then we fall back to good
7172 * old BSD locks. They also have nice semantics, but are
7173 * slightly problematic on NFS, where they are upgraded to
7174 * POSIX locks, even though locally they are orthogonal to
7184 .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
7185 .l_whence = SEEK_SET,
7189 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
7193 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
7196 /* If the kernel is too old, use good old BSD locks */
7197 if (errno == EINVAL)
7198 r = flock(fd, operation);
7201 return errno == EAGAIN ? -EBUSY : -errno;
7204 /* If we acquired the lock, let's check if the file
7205 * still exists in the file system. If not, then the
7206 * previous exclusive owner removed it and then closed
7207 * it. In such a case our acquired lock is worthless,
7208 * hence try again. */
7213 if (st.st_nlink > 0)
7216 fd = safe_close(fd);
7221 ret->operation = operation;
7229 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
7237 if (!filename_is_valid(fn))
7240 t = newa(char, strlen(p) + 2 + 4 + 1);
7241 stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
7243 return make_lock_file(t, operation, ret);
7246 void release_lock_file(LockFile *f) {
7254 /* If we are the exclusive owner we can safely delete
7255 * the lock file itself. If we are not the exclusive
7256 * owner, we can try becoming it. */
7259 (f->operation & ~LOCK_NB) == LOCK_SH) {
7260 static const struct flock fl = {
7262 .l_whence = SEEK_SET,
7265 r = fcntl(f->fd, F_OFD_SETLK, &fl);
7266 if (r < 0 && errno == EINVAL)
7267 r = flock(f->fd, LOCK_EX|LOCK_NB);
7270 f->operation = LOCK_EX|LOCK_NB;
7273 if ((f->operation & ~LOCK_NB) == LOCK_EX)
7274 unlink_noerrno(f->path);
7280 f->fd = safe_close(f->fd);
7284 static size_t nul_length(const uint8_t *p, size_t sz) {
7299 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
7300 const uint8_t *q, *w, *e;
7308 n = nul_length(q, e - q);
7310 /* If there are more than the specified run length of
7311 * NUL bytes, or if this is the beginning or the end
7312 * of the buffer, then seek instead of write */
7313 if ((n > run_length) ||
7314 (n > 0 && q == p) ||
7315 (n > 0 && q + n >= e)) {
7317 l = write(fd, w, q - w);
7324 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
7336 l = write(fd, w, q - w);
7343 return q - (const uint8_t*) p;
7346 void sigkill_wait(pid_t *pid) {
7352 if (kill(*pid, SIGKILL) > 0)
7353 (void) wait_for_terminate(*pid, NULL);
7356 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
7357 int a = 0, b = 0, c = 0;
7367 if (!strchr(*p, '>'))
7370 if ((*p)[2] == '>') {
7371 c = undecchar((*p)[1]);
7373 } else if ((*p)[3] == '>') {
7374 b = undecchar((*p)[1]);
7375 c = undecchar((*p)[2]);
7377 } else if ((*p)[4] == '>') {
7378 a = undecchar((*p)[1]);
7379 b = undecchar((*p)[2]);
7380 c = undecchar((*p)[3]);
7385 if (a < 0 || b < 0 || c < 0 ||
7386 (!with_facility && (a || b || c > 7)))
7390 *priority = a*100 + b*10 + c;
7392 *priority = (*priority & LOG_FACMASK) | c;
7398 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
7404 for (i = 0; i < len; ++i)
7405 if (streq_ptr(table[i], key))
7411 void cmsg_close_all(struct msghdr *mh) {
7412 struct cmsghdr *cmsg;
7416 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
7417 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
7418 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
7421 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
7425 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
7429 /* Even though renameat2() exists since Linux 3.15, btrfs added
7430 * support for it later. If it is not implemented, fallback to another
7432 if (errno != EINVAL)
7435 /* The link()/unlink() fallback does not work on directories. But
7436 * renameat() without RENAME_NOREPLACE gives the same semantics on
7437 * directories, except when newpath is an *empty* directory. This is
7439 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
7440 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
7441 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
7442 return ret >= 0 ? 0 : -errno;
7445 /* If it is not a directory, use the link()/unlink() fallback. */
7446 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
7450 ret = unlinkat(olddirfd, oldpath, 0);
7452 /* backup errno before the following unlinkat() alters it */
7454 (void) unlinkat(newdirfd, newpath, 0);
7462 char *shell_maybe_quote(const char *s) {
7468 /* Encloses a string in double quotes if necessary to make it
7469 * OK as shell string. */
7471 for (p = s; *p; p++)
7474 strchr(SHELL_NEED_QUOTES, *p))
7480 r = new(char, 1+strlen(s)*2+1+1);
7486 t = mempcpy(t, s, p - s);
7490 if (strchr(SHELL_NEED_ESCAPE, *p))
7502 int parse_mode(const char *s, mode_t *ret) {
7510 l = strtol(s, &x, 8);
7514 if (!x || x == s || *x)
7516 if (l < 0 || l > 07777)