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>
56 #include <sys/mount.h>
57 #include <linux/magic.h>
61 #include <sys/personality.h>
62 #include <sys/xattr.h>
64 #include <sys/statvfs.h>
67 #ifdef HAVE_SYS_AUXV_H
79 #include "path-util.h"
80 #include "exit-status.h"
84 #include "device-nodes.h"
89 #include "sparse-endian.h"
92 char **saved_argv = NULL;
94 static volatile unsigned cached_columns = 0;
95 static volatile unsigned cached_lines = 0;
97 size_t page_size(void) {
98 static thread_local size_t pgsz = 0;
101 if (_likely_(pgsz > 0))
104 r = sysconf(_SC_PAGESIZE);
111 bool streq_ptr(const char *a, const char *b) {
113 /* Like streq(), but tries to make sense of NULL pointers */
124 char* endswith(const char *s, const char *postfix) {
131 pl = strlen(postfix);
134 return (char*) s + sl;
139 if (memcmp(s + sl - pl, postfix, pl) != 0)
142 return (char*) s + sl - pl;
145 char* first_word(const char *s, const char *word) {
152 /* Checks if the string starts with the specified word, either
153 * followed by NUL or by whitespace. Returns a pointer to the
154 * NUL or the first character after the whitespace. */
165 if (memcmp(s, word, wl) != 0)
172 if (!strchr(WHITESPACE, *p))
175 p += strspn(p, WHITESPACE);
179 static size_t cescape_char(char c, char *buf) {
180 char * buf_old = buf;
226 /* For special chars we prefer octal over
227 * hexadecimal encoding, simply because glib's
228 * g_strescape() does the same */
229 if ((c < ' ') || (c >= 127)) {
231 *(buf++) = octchar((unsigned char) c >> 6);
232 *(buf++) = octchar((unsigned char) c >> 3);
233 *(buf++) = octchar((unsigned char) c);
239 return buf - buf_old;
242 int close_nointr(int fd) {
249 * Just ignore EINTR; a retry loop is the wrong thing to do on
252 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
253 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
254 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
255 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
263 int safe_close(int fd) {
266 * Like close_nointr() but cannot fail. Guarantees errno is
267 * unchanged. Is a NOP with negative fds passed, and returns
268 * -1, so that it can be used in this syntax:
270 * fd = safe_close(fd);
276 /* The kernel might return pretty much any error code
277 * via close(), but the fd will be closed anyway. The
278 * only condition we want to check for here is whether
279 * the fd was invalid at all... */
281 assert_se(close_nointr(fd) != -EBADF);
287 void close_many(const int fds[], unsigned n_fd) {
290 assert(fds || n_fd <= 0);
292 for (i = 0; i < n_fd; i++)
296 int unlink_noerrno(const char *path) {
307 int parse_boolean(const char *v) {
310 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
312 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
318 int parse_pid(const char *s, pid_t* ret_pid) {
319 unsigned long ul = 0;
326 r = safe_atolu(s, &ul);
332 if ((unsigned long) pid != ul)
342 int parse_uid(const char *s, uid_t* ret_uid) {
343 unsigned long ul = 0;
350 r = safe_atolu(s, &ul);
356 if ((unsigned long) uid != ul)
359 /* Some libc APIs use UID_INVALID as special placeholder */
360 if (uid == (uid_t) 0xFFFFFFFF)
363 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
364 if (uid == (uid_t) 0xFFFF)
371 int safe_atou(const char *s, unsigned *ret_u) {
379 l = strtoul(s, &x, 0);
381 if (!x || x == s || *x || errno)
382 return errno > 0 ? -errno : -EINVAL;
384 if ((unsigned long) (unsigned) l != l)
387 *ret_u = (unsigned) l;
391 int safe_atoi(const char *s, int *ret_i) {
399 l = strtol(s, &x, 0);
401 if (!x || x == s || *x || errno)
402 return errno > 0 ? -errno : -EINVAL;
404 if ((long) (int) l != l)
411 int safe_atou8(const char *s, uint8_t *ret) {
419 l = strtoul(s, &x, 0);
421 if (!x || x == s || *x || errno)
422 return errno > 0 ? -errno : -EINVAL;
424 if ((unsigned long) (uint8_t) l != l)
431 int safe_atou16(const char *s, uint16_t *ret) {
439 l = strtoul(s, &x, 0);
441 if (!x || x == s || *x || errno)
442 return errno > 0 ? -errno : -EINVAL;
444 if ((unsigned long) (uint16_t) l != l)
451 int safe_atoi16(const char *s, int16_t *ret) {
459 l = strtol(s, &x, 0);
461 if (!x || x == s || *x || errno)
462 return errno > 0 ? -errno : -EINVAL;
464 if ((long) (int16_t) l != l)
471 int safe_atollu(const char *s, long long unsigned *ret_llu) {
473 unsigned long long l;
479 l = strtoull(s, &x, 0);
481 if (!x || x == s || *x || errno)
482 return errno ? -errno : -EINVAL;
488 int safe_atolli(const char *s, long long int *ret_lli) {
496 l = strtoll(s, &x, 0);
498 if (!x || x == s || *x || errno)
499 return errno ? -errno : -EINVAL;
505 int safe_atod(const char *s, double *ret_d) {
512 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
517 if (!x || x == s || *x || errno)
518 return errno ? -errno : -EINVAL;
524 static size_t strcspn_escaped(const char *s, const char *reject) {
525 bool escaped = false;
528 for (n=0; s[n]; n++) {
531 else if (s[n] == '\\')
533 else if (strchr(reject, s[n]))
537 /* if s ends in \, return index of previous char */
541 /* Split a string into words. */
542 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
548 assert(**state == '\0');
552 current += strspn(current, separator);
558 if (quoted && strchr("\'\"", *current)) {
559 char quotechars[2] = {*current, '\0'};
561 *l = strcspn_escaped(current + 1, quotechars);
562 if (current[*l + 1] == '\0' ||
563 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
564 /* right quote missing or garbage at the end */
568 assert(current[*l + 1] == quotechars[0]);
569 *state = current++ + *l + 2;
571 *l = strcspn_escaped(current, separator);
572 if (current[*l] && !strchr(separator, current[*l])) {
573 /* unfinished escape */
577 *state = current + *l;
579 *l = strcspn(current, separator);
580 *state = current + *l;
586 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
588 _cleanup_free_ char *line = NULL;
600 p = procfs_file_alloca(pid, "stat");
601 r = read_one_line_file(p, &line);
605 /* Let's skip the pid and comm fields. The latter is enclosed
606 * in () but does not escape any () in its value, so let's
607 * skip over it manually */
609 p = strrchr(line, ')');
621 if ((long unsigned) (pid_t) ppid != ppid)
624 *_ppid = (pid_t) ppid;
629 int fchmod_umask(int fd, mode_t m) {
634 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
640 char *truncate_nl(char *s) {
643 s[strcspn(s, NEWLINE)] = 0;
647 int get_process_state(pid_t pid) {
651 _cleanup_free_ char *line = NULL;
655 p = procfs_file_alloca(pid, "stat");
656 r = read_one_line_file(p, &line);
660 p = strrchr(line, ')');
666 if (sscanf(p, " %c", &state) != 1)
669 return (unsigned char) state;
672 int get_process_comm(pid_t pid, char **name) {
679 p = procfs_file_alloca(pid, "comm");
681 r = read_one_line_file(p, name);
688 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
689 _cleanup_fclose_ FILE *f = NULL;
697 p = procfs_file_alloca(pid, "cmdline");
703 if (max_length == 0) {
704 size_t len = 0, allocated = 0;
706 while ((c = getc(f)) != EOF) {
708 if (!GREEDY_REALLOC(r, allocated, len+2)) {
713 r[len++] = isprint(c) ? c : ' ';
723 r = new(char, max_length);
729 while ((c = getc(f)) != EOF) {
751 size_t n = MIN(left-1, 3U);
758 /* Kernel threads have no argv[] */
760 _cleanup_free_ char *t = NULL;
768 h = get_process_comm(pid, &t);
772 r = strjoin("[", t, "]", NULL);
781 int is_kernel_thread(pid_t pid) {
793 p = procfs_file_alloca(pid, "cmdline");
798 count = fread(&c, 1, 1, f);
802 /* Kernel threads have an empty cmdline */
805 return eof ? 1 : -errno;
810 int get_process_capeff(pid_t pid, char **capeff) {
816 p = procfs_file_alloca(pid, "status");
818 return get_status_field(p, "\nCapEff:", capeff);
821 static int get_process_link_contents(const char *proc_file, char **name) {
827 r = readlink_malloc(proc_file, name);
829 return r == -ENOENT ? -ESRCH : r;
834 int get_process_exe(pid_t pid, char **name) {
841 p = procfs_file_alloca(pid, "exe");
842 r = get_process_link_contents(p, name);
846 d = endswith(*name, " (deleted)");
853 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
854 _cleanup_fclose_ FILE *f = NULL;
864 p = procfs_file_alloca(pid, "status");
869 FOREACH_LINE(line, f, return -errno) {
874 if (startswith(l, field)) {
876 l += strspn(l, WHITESPACE);
878 l[strcspn(l, WHITESPACE)] = 0;
880 return parse_uid(l, uid);
887 int get_process_uid(pid_t pid, uid_t *uid) {
888 return get_process_id(pid, "Uid:", uid);
891 int get_process_gid(pid_t pid, gid_t *gid) {
892 assert_cc(sizeof(uid_t) == sizeof(gid_t));
893 return get_process_id(pid, "Gid:", gid);
896 int get_process_cwd(pid_t pid, char **cwd) {
901 p = procfs_file_alloca(pid, "cwd");
903 return get_process_link_contents(p, cwd);
906 int get_process_root(pid_t pid, char **root) {
911 p = procfs_file_alloca(pid, "root");
913 return get_process_link_contents(p, root);
916 int get_process_environ(pid_t pid, char **env) {
917 _cleanup_fclose_ FILE *f = NULL;
918 _cleanup_free_ char *outcome = NULL;
921 size_t allocated = 0, sz = 0;
926 p = procfs_file_alloca(pid, "environ");
932 while ((c = fgetc(f)) != EOF) {
933 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
937 outcome[sz++] = '\n';
939 sz += cescape_char(c, outcome + sz);
949 char *strnappend(const char *s, const char *suffix, size_t b) {
957 return strndup(suffix, b);
966 if (b > ((size_t) -1) - a)
969 r = new(char, a+b+1);
974 memcpy(r+a, suffix, b);
980 char *strappend(const char *s, const char *suffix) {
981 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
984 int readlinkat_malloc(int fd, const char *p, char **ret) {
999 n = readlinkat(fd, p, c, l-1);
1006 if ((size_t) n < l-1) {
1017 int readlink_malloc(const char *p, char **ret) {
1018 return readlinkat_malloc(AT_FDCWD, p, ret);
1021 int readlink_value(const char *p, char **ret) {
1022 _cleanup_free_ char *link = NULL;
1026 r = readlink_malloc(p, &link);
1030 value = basename(link);
1034 value = strdup(value);
1043 int readlink_and_make_absolute(const char *p, char **r) {
1044 _cleanup_free_ char *target = NULL;
1051 j = readlink_malloc(p, &target);
1055 k = file_in_same_dir(p, target);
1063 int readlink_and_canonicalize(const char *p, char **r) {
1070 j = readlink_and_make_absolute(p, &t);
1074 s = canonicalize_file_name(t);
1081 path_kill_slashes(*r);
1086 int reset_all_signal_handlers(void) {
1089 for (sig = 1; sig < _NSIG; sig++) {
1090 struct sigaction sa = {
1091 .sa_handler = SIG_DFL,
1092 .sa_flags = SA_RESTART,
1095 /* These two cannot be caught... */
1096 if (sig == SIGKILL || sig == SIGSTOP)
1099 /* On Linux the first two RT signals are reserved by
1100 * glibc, and sigaction() will return EINVAL for them. */
1101 if ((sigaction(sig, &sa, NULL) < 0))
1102 if (errno != EINVAL && r == 0)
1109 int reset_signal_mask(void) {
1112 if (sigemptyset(&ss) < 0)
1115 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
1121 char *strstrip(char *s) {
1124 /* Drops trailing whitespace. Modifies the string in
1125 * place. Returns pointer to first non-space character */
1127 s += strspn(s, WHITESPACE);
1129 for (e = strchr(s, 0); e > s; e --)
1130 if (!strchr(WHITESPACE, e[-1]))
1138 char *delete_chars(char *s, const char *bad) {
1141 /* Drops all whitespace, regardless where in the string */
1143 for (f = s, t = s; *f; f++) {
1144 if (strchr(bad, *f))
1155 char *file_in_same_dir(const char *path, const char *filename) {
1162 /* This removes the last component of path and appends
1163 * filename, unless the latter is absolute anyway or the
1166 if (path_is_absolute(filename))
1167 return strdup(filename);
1169 e = strrchr(path, '/');
1171 return strdup(filename);
1173 k = strlen(filename);
1174 ret = new(char, (e + 1 - path) + k + 1);
1178 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
1182 int rmdir_parents(const char *path, const char *stop) {
1191 /* Skip trailing slashes */
1192 while (l > 0 && path[l-1] == '/')
1198 /* Skip last component */
1199 while (l > 0 && path[l-1] != '/')
1202 /* Skip trailing slashes */
1203 while (l > 0 && path[l-1] == '/')
1209 if (!(t = strndup(path, l)))
1212 if (path_startswith(stop, t)) {
1221 if (errno != ENOENT)
1228 char hexchar(int x) {
1229 static const char table[16] = "0123456789abcdef";
1231 return table[x & 15];
1234 int unhexchar(char c) {
1236 if (c >= '0' && c <= '9')
1239 if (c >= 'a' && c <= 'f')
1240 return c - 'a' + 10;
1242 if (c >= 'A' && c <= 'F')
1243 return c - 'A' + 10;
1248 char *hexmem(const void *p, size_t l) {
1252 z = r = malloc(l * 2 + 1);
1256 for (x = p; x < (const uint8_t*) p + l; x++) {
1257 *(z++) = hexchar(*x >> 4);
1258 *(z++) = hexchar(*x & 15);
1265 void *unhexmem(const char *p, size_t l) {
1271 z = r = malloc((l + 1) / 2 + 1);
1275 for (x = p; x < p + l; x += 2) {
1278 a = unhexchar(x[0]);
1280 b = unhexchar(x[1]);
1284 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1291 char octchar(int x) {
1292 return '0' + (x & 7);
1295 int unoctchar(char c) {
1297 if (c >= '0' && c <= '7')
1303 char decchar(int x) {
1304 return '0' + (x % 10);
1307 int undecchar(char c) {
1309 if (c >= '0' && c <= '9')
1315 char *cescape(const char *s) {
1321 /* Does C style string escaping. */
1323 r = new(char, strlen(s)*4 + 1);
1327 for (f = s, t = r; *f; f++)
1328 t += cescape_char(*f, t);
1335 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1342 /* Undoes C style string escaping, and optionally prefixes it. */
1344 pl = prefix ? strlen(prefix) : 0;
1346 r = new(char, pl+length+1);
1351 memcpy(r, prefix, pl);
1353 for (f = s, t = r + pl; f < s + length; f++) {
1396 /* This is an extension of the XDG syntax files */
1401 /* hexadecimal encoding */
1404 a = unhexchar(f[1]);
1405 b = unhexchar(f[2]);
1407 if (a < 0 || b < 0 || (a == 0 && b == 0)) {
1408 /* Invalid escape code, let's take it literal then */
1412 *(t++) = (char) ((a << 4) | b);
1427 /* octal encoding */
1430 a = unoctchar(f[0]);
1431 b = unoctchar(f[1]);
1432 c = unoctchar(f[2]);
1434 if (a < 0 || b < 0 || c < 0 || (a == 0 && b == 0 && c == 0)) {
1435 /* Invalid escape code, let's take it literal then */
1439 *(t++) = (char) ((a << 6) | (b << 3) | c);
1447 /* premature end of string. */
1452 /* Invalid escape code, let's take it literal then */
1464 char *cunescape_length(const char *s, size_t length) {
1465 return cunescape_length_with_prefix(s, length, NULL);
1468 char *cunescape(const char *s) {
1471 return cunescape_length(s, strlen(s));
1474 char *xescape(const char *s, const char *bad) {
1478 /* Escapes all chars in bad, in addition to \ and all special
1479 * chars, in \xFF style escaping. May be reversed with
1482 r = new(char, strlen(s) * 4 + 1);
1486 for (f = s, t = r; *f; f++) {
1488 if ((*f < ' ') || (*f >= 127) ||
1489 (*f == '\\') || strchr(bad, *f)) {
1492 *(t++) = hexchar(*f >> 4);
1493 *(t++) = hexchar(*f);
1503 char *ascii_strlower(char *t) {
1508 for (p = t; *p; p++)
1509 if (*p >= 'A' && *p <= 'Z')
1510 *p = *p - 'A' + 'a';
1515 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1519 filename[0] == '.' ||
1520 streq(filename, "lost+found") ||
1521 streq(filename, "aquota.user") ||
1522 streq(filename, "aquota.group") ||
1523 endswith(filename, ".rpmnew") ||
1524 endswith(filename, ".rpmsave") ||
1525 endswith(filename, ".rpmorig") ||
1526 endswith(filename, ".dpkg-old") ||
1527 endswith(filename, ".dpkg-new") ||
1528 endswith(filename, ".dpkg-tmp") ||
1529 endswith(filename, ".swp");
1532 bool hidden_file(const char *filename) {
1535 if (endswith(filename, "~"))
1538 return hidden_file_allow_backup(filename);
1541 int fd_nonblock(int fd, bool nonblock) {
1546 flags = fcntl(fd, F_GETFL, 0);
1551 nflags = flags | O_NONBLOCK;
1553 nflags = flags & ~O_NONBLOCK;
1555 if (nflags == flags)
1558 if (fcntl(fd, F_SETFL, nflags) < 0)
1564 int fd_cloexec(int fd, bool cloexec) {
1569 flags = fcntl(fd, F_GETFD, 0);
1574 nflags = flags | FD_CLOEXEC;
1576 nflags = flags & ~FD_CLOEXEC;
1578 if (nflags == flags)
1581 if (fcntl(fd, F_SETFD, nflags) < 0)
1587 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1590 assert(n_fdset == 0 || fdset);
1592 for (i = 0; i < n_fdset; i++)
1599 int close_all_fds(const int except[], unsigned n_except) {
1600 _cleanup_closedir_ DIR *d = NULL;
1604 assert(n_except == 0 || except);
1606 d = opendir("/proc/self/fd");
1611 /* When /proc isn't available (for example in chroots)
1612 * the fallback is brute forcing through the fd
1615 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1616 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1618 if (fd_in_set(fd, except, n_except))
1621 if (close_nointr(fd) < 0)
1622 if (errno != EBADF && r == 0)
1629 while ((de = readdir(d))) {
1632 if (hidden_file(de->d_name))
1635 if (safe_atoi(de->d_name, &fd) < 0)
1636 /* Let's better ignore this, just in case */
1645 if (fd_in_set(fd, except, n_except))
1648 if (close_nointr(fd) < 0) {
1649 /* Valgrind has its own FD and doesn't want to have it closed */
1650 if (errno != EBADF && r == 0)
1658 bool chars_intersect(const char *a, const char *b) {
1661 /* Returns true if any of the chars in a are in b. */
1662 for (p = a; *p; p++)
1669 bool fstype_is_network(const char *fstype) {
1670 static const char table[] =
1684 x = startswith(fstype, "fuse.");
1688 return nulstr_contains(table, fstype);
1692 _cleanup_close_ int fd;
1694 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1700 TIOCL_GETKMSGREDIRECT,
1704 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1707 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1710 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1716 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1717 struct termios old_termios, new_termios;
1718 char c, line[LINE_MAX];
1723 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1724 new_termios = old_termios;
1726 new_termios.c_lflag &= ~ICANON;
1727 new_termios.c_cc[VMIN] = 1;
1728 new_termios.c_cc[VTIME] = 0;
1730 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1733 if (t != USEC_INFINITY) {
1734 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1735 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1740 k = fread(&c, 1, 1, f);
1742 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1748 *need_nl = c != '\n';
1755 if (t != USEC_INFINITY) {
1756 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1761 if (!fgets(line, sizeof(line), f))
1762 return errno ? -errno : -EIO;
1766 if (strlen(line) != 1)
1776 int ask_char(char *ret, const char *replies, const char *text, ...) {
1786 bool need_nl = true;
1789 fputs(ANSI_HIGHLIGHT_ON, stdout);
1796 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1800 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1803 if (r == -EBADMSG) {
1804 puts("Bad input, please try again.");
1815 if (strchr(replies, c)) {
1820 puts("Read unexpected character, please try again.");
1824 int ask_string(char **ret, const char *text, ...) {
1829 char line[LINE_MAX];
1833 fputs(ANSI_HIGHLIGHT_ON, stdout);
1840 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1845 if (!fgets(line, sizeof(line), stdin))
1846 return errno ? -errno : -EIO;
1848 if (!endswith(line, "\n"))
1867 int reset_terminal_fd(int fd, bool switch_to_text) {
1868 struct termios termios;
1871 /* Set terminal to some sane defaults */
1875 /* We leave locked terminal attributes untouched, so that
1876 * Plymouth may set whatever it wants to set, and we don't
1877 * interfere with that. */
1879 /* Disable exclusive mode, just in case */
1880 ioctl(fd, TIOCNXCL);
1882 /* Switch to text mode */
1884 ioctl(fd, KDSETMODE, KD_TEXT);
1886 /* Enable console unicode mode */
1887 ioctl(fd, KDSKBMODE, K_UNICODE);
1889 if (tcgetattr(fd, &termios) < 0) {
1894 /* We only reset the stuff that matters to the software. How
1895 * hardware is set up we don't touch assuming that somebody
1896 * else will do that for us */
1898 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1899 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1900 termios.c_oflag |= ONLCR;
1901 termios.c_cflag |= CREAD;
1902 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1904 termios.c_cc[VINTR] = 03; /* ^C */
1905 termios.c_cc[VQUIT] = 034; /* ^\ */
1906 termios.c_cc[VERASE] = 0177;
1907 termios.c_cc[VKILL] = 025; /* ^X */
1908 termios.c_cc[VEOF] = 04; /* ^D */
1909 termios.c_cc[VSTART] = 021; /* ^Q */
1910 termios.c_cc[VSTOP] = 023; /* ^S */
1911 termios.c_cc[VSUSP] = 032; /* ^Z */
1912 termios.c_cc[VLNEXT] = 026; /* ^V */
1913 termios.c_cc[VWERASE] = 027; /* ^W */
1914 termios.c_cc[VREPRINT] = 022; /* ^R */
1915 termios.c_cc[VEOL] = 0;
1916 termios.c_cc[VEOL2] = 0;
1918 termios.c_cc[VTIME] = 0;
1919 termios.c_cc[VMIN] = 1;
1921 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1925 /* Just in case, flush all crap out */
1926 tcflush(fd, TCIOFLUSH);
1931 int reset_terminal(const char *name) {
1932 _cleanup_close_ int fd = -1;
1934 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1938 return reset_terminal_fd(fd, true);
1941 int open_terminal(const char *name, int mode) {
1946 * If a TTY is in the process of being closed opening it might
1947 * cause EIO. This is horribly awful, but unlikely to be
1948 * changed in the kernel. Hence we work around this problem by
1949 * retrying a couple of times.
1951 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1954 assert(!(mode & O_CREAT));
1957 fd = open(name, mode, 0);
1964 /* Max 1s in total */
1968 usleep(50 * USEC_PER_MSEC);
1986 int flush_fd(int fd) {
1987 struct pollfd pollfd = {
1997 r = poll(&pollfd, 1, 0);
2007 l = read(fd, buf, sizeof(buf));
2013 if (errno == EAGAIN)
2022 int acquire_terminal(
2026 bool ignore_tiocstty_eperm,
2029 int fd = -1, notify = -1, r = 0, wd = -1;
2034 /* We use inotify to be notified when the tty is closed. We
2035 * create the watch before checking if we can actually acquire
2036 * it, so that we don't lose any event.
2038 * Note: strictly speaking this actually watches for the
2039 * device being closed, it does *not* really watch whether a
2040 * tty loses its controlling process. However, unless some
2041 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2042 * its tty otherwise this will not become a problem. As long
2043 * as the administrator makes sure not configure any service
2044 * on the same tty as an untrusted user this should not be a
2045 * problem. (Which he probably should not do anyway.) */
2047 if (timeout != USEC_INFINITY)
2048 ts = now(CLOCK_MONOTONIC);
2050 if (!fail && !force) {
2051 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
2057 wd = inotify_add_watch(notify, name, IN_CLOSE);
2065 struct sigaction sa_old, sa_new = {
2066 .sa_handler = SIG_IGN,
2067 .sa_flags = SA_RESTART,
2071 r = flush_fd(notify);
2076 /* We pass here O_NOCTTY only so that we can check the return
2077 * value TIOCSCTTY and have a reliable way to figure out if we
2078 * successfully became the controlling process of the tty */
2079 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2083 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2084 * if we already own the tty. */
2085 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2087 /* First, try to get the tty */
2088 if (ioctl(fd, TIOCSCTTY, force) < 0)
2091 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2093 /* Sometimes it makes sense to ignore TIOCSCTTY
2094 * returning EPERM, i.e. when very likely we already
2095 * are have this controlling terminal. */
2096 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2099 if (r < 0 && (force || fail || r != -EPERM)) {
2108 assert(notify >= 0);
2111 union inotify_event_buffer buffer;
2112 struct inotify_event *e;
2115 if (timeout != USEC_INFINITY) {
2118 n = now(CLOCK_MONOTONIC);
2119 if (ts + timeout < n) {
2124 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2134 l = read(notify, &buffer, sizeof(buffer));
2136 if (errno == EINTR || errno == EAGAIN)
2143 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2144 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2153 /* We close the tty fd here since if the old session
2154 * ended our handle will be dead. It's important that
2155 * we do this after sleeping, so that we don't enter
2156 * an endless loop. */
2157 fd = safe_close(fd);
2162 r = reset_terminal_fd(fd, true);
2164 log_warning_errno(r, "Failed to reset terminal: %m");
2175 int release_terminal(void) {
2176 static const struct sigaction sa_new = {
2177 .sa_handler = SIG_IGN,
2178 .sa_flags = SA_RESTART,
2181 _cleanup_close_ int fd = -1;
2182 struct sigaction sa_old;
2185 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2189 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2190 * by our own TIOCNOTTY */
2191 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2193 if (ioctl(fd, TIOCNOTTY) < 0)
2196 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2201 int sigaction_many(const struct sigaction *sa, ...) {
2206 while ((sig = va_arg(ap, int)) > 0)
2207 if (sigaction(sig, sa, NULL) < 0)
2214 int ignore_signals(int sig, ...) {
2215 struct sigaction sa = {
2216 .sa_handler = SIG_IGN,
2217 .sa_flags = SA_RESTART,
2222 if (sigaction(sig, &sa, NULL) < 0)
2226 while ((sig = va_arg(ap, int)) > 0)
2227 if (sigaction(sig, &sa, NULL) < 0)
2234 int default_signals(int sig, ...) {
2235 struct sigaction sa = {
2236 .sa_handler = SIG_DFL,
2237 .sa_flags = SA_RESTART,
2242 if (sigaction(sig, &sa, NULL) < 0)
2246 while ((sig = va_arg(ap, int)) > 0)
2247 if (sigaction(sig, &sa, NULL) < 0)
2254 void safe_close_pair(int p[]) {
2258 /* Special case pairs which use the same fd in both
2260 p[0] = p[1] = safe_close(p[0]);
2264 p[0] = safe_close(p[0]);
2265 p[1] = safe_close(p[1]);
2268 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2275 while (nbytes > 0) {
2278 k = read(fd, p, nbytes);
2283 if (errno == EAGAIN && do_poll) {
2285 /* We knowingly ignore any return value here,
2286 * and expect that any error/EOF is reported
2289 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2293 return n > 0 ? n : -errno;
2307 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2308 const uint8_t *p = buf;
2315 while (nbytes > 0) {
2318 k = write(fd, p, nbytes);
2323 if (errno == EAGAIN && do_poll) {
2324 /* We knowingly ignore any return value here,
2325 * and expect that any error/EOF is reported
2328 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2335 if (k == 0) /* Can't really happen */
2345 int parse_size(const char *t, off_t base, off_t *size) {
2347 /* Soo, sometimes we want to parse IEC binary suffxies, and
2348 * sometimes SI decimal suffixes. This function can parse
2349 * both. Which one is the right way depends on the
2350 * context. Wikipedia suggests that SI is customary for
2351 * hardrware metrics and network speeds, while IEC is
2352 * customary for most data sizes used by software and volatile
2353 * (RAM) memory. Hence be careful which one you pick!
2355 * In either case we use just K, M, G as suffix, and not Ki,
2356 * Mi, Gi or so (as IEC would suggest). That's because that's
2357 * frickin' ugly. But this means you really need to make sure
2358 * to document which base you are parsing when you use this
2363 unsigned long long factor;
2366 static const struct table iec[] = {
2367 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2368 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2369 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2370 { "G", 1024ULL*1024ULL*1024ULL },
2371 { "M", 1024ULL*1024ULL },
2377 static const struct table si[] = {
2378 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2379 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2380 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2381 { "G", 1000ULL*1000ULL*1000ULL },
2382 { "M", 1000ULL*1000ULL },
2388 const struct table *table;
2390 unsigned long long r = 0;
2391 unsigned n_entries, start_pos = 0;
2394 assert(base == 1000 || base == 1024);
2399 n_entries = ELEMENTSOF(si);
2402 n_entries = ELEMENTSOF(iec);
2408 unsigned long long l2;
2414 l = strtoll(p, &e, 10);
2427 if (*e >= '0' && *e <= '9') {
2430 /* strotoull itself would accept space/+/- */
2431 l2 = strtoull(e, &e2, 10);
2433 if (errno == ERANGE)
2436 /* Ignore failure. E.g. 10.M is valid */
2443 e += strspn(e, WHITESPACE);
2445 for (i = start_pos; i < n_entries; i++)
2446 if (startswith(e, table[i].suffix)) {
2447 unsigned long long tmp;
2448 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2450 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2451 if (tmp > ULLONG_MAX - r)
2455 if ((unsigned long long) (off_t) r != r)
2458 p = e + strlen(table[i].suffix);
2474 int make_stdio(int fd) {
2479 r = dup2(fd, STDIN_FILENO);
2480 s = dup2(fd, STDOUT_FILENO);
2481 t = dup2(fd, STDERR_FILENO);
2486 if (r < 0 || s < 0 || t < 0)
2489 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2490 * dup2() was a NOP and the bit hence possibly set. */
2491 fd_cloexec(STDIN_FILENO, false);
2492 fd_cloexec(STDOUT_FILENO, false);
2493 fd_cloexec(STDERR_FILENO, false);
2498 int make_null_stdio(void) {
2501 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2505 return make_stdio(null_fd);
2508 bool is_device_path(const char *path) {
2510 /* Returns true on paths that refer to a device, either in
2511 * sysfs or in /dev */
2514 path_startswith(path, "/dev/") ||
2515 path_startswith(path, "/sys/");
2518 int dir_is_empty(const char *path) {
2519 _cleanup_closedir_ DIR *d;
2530 if (!de && errno != 0)
2536 if (!hidden_file(de->d_name))
2541 char* dirname_malloc(const char *path) {
2542 char *d, *dir, *dir2;
2559 int dev_urandom(void *p, size_t n) {
2560 static int have_syscall = -1;
2564 /* Gathers some randomness from the kernel. This call will
2565 * never block, and will always return some data from the
2566 * kernel, regardless if the random pool is fully initialized
2567 * or not. It thus makes no guarantee for the quality of the
2568 * returned entropy, but is good enough for or usual usecases
2569 * of seeding the hash functions for hashtable */
2571 /* Use the getrandom() syscall unless we know we don't have
2572 * it, or when the requested size is too large for it. */
2573 if (have_syscall != 0 || (size_t) (int) n != n) {
2574 r = getrandom(p, n, GRND_NONBLOCK);
2576 have_syscall = true;
2581 if (errno == ENOSYS)
2582 /* we lack the syscall, continue with
2583 * reading from /dev/urandom */
2584 have_syscall = false;
2585 else if (errno == EAGAIN)
2586 /* not enough entropy for now. Let's
2587 * remember to use the syscall the
2588 * next time, again, but also read
2589 * from /dev/urandom for now, which
2590 * doesn't care about the current
2591 * amount of entropy. */
2592 have_syscall = true;
2596 /* too short read? */
2600 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2602 return errno == ENOENT ? -ENOSYS : -errno;
2604 k = loop_read(fd, p, n, true);
2609 if ((size_t) k != n)
2615 void initialize_srand(void) {
2616 static bool srand_called = false;
2618 #ifdef HAVE_SYS_AUXV_H
2627 #ifdef HAVE_SYS_AUXV_H
2628 /* The kernel provides us with a bit of entropy in auxv, so
2629 * let's try to make use of that to seed the pseudo-random
2630 * generator. It's better than nothing... */
2632 auxv = (void*) getauxval(AT_RANDOM);
2634 x ^= *(unsigned*) auxv;
2637 x ^= (unsigned) now(CLOCK_REALTIME);
2638 x ^= (unsigned) gettid();
2641 srand_called = true;
2644 void random_bytes(void *p, size_t n) {
2648 r = dev_urandom(p, n);
2652 /* If some idiot made /dev/urandom unavailable to us, he'll
2653 * get a PRNG instead. */
2657 for (q = p; q < (uint8_t*) p + n; q ++)
2661 void rename_process(const char name[8]) {
2664 /* This is a like a poor man's setproctitle(). It changes the
2665 * comm field, argv[0], and also the glibc's internally used
2666 * name of the process. For the first one a limit of 16 chars
2667 * applies, to the second one usually one of 10 (i.e. length
2668 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2669 * "systemd"). If you pass a longer string it will be
2672 prctl(PR_SET_NAME, name);
2674 if (program_invocation_name)
2675 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2677 if (saved_argc > 0) {
2681 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2683 for (i = 1; i < saved_argc; i++) {
2687 memzero(saved_argv[i], strlen(saved_argv[i]));
2692 void sigset_add_many(sigset_t *ss, ...) {
2699 while ((sig = va_arg(ap, int)) > 0)
2700 assert_se(sigaddset(ss, sig) == 0);
2704 int sigprocmask_many(int how, ...) {
2709 assert_se(sigemptyset(&ss) == 0);
2712 while ((sig = va_arg(ap, int)) > 0)
2713 assert_se(sigaddset(&ss, sig) == 0);
2716 if (sigprocmask(how, &ss, NULL) < 0)
2722 char* gethostname_malloc(void) {
2725 assert_se(uname(&u) >= 0);
2727 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2728 return strdup(u.nodename);
2730 return strdup(u.sysname);
2733 bool hostname_is_set(void) {
2736 assert_se(uname(&u) >= 0);
2738 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2741 char *lookup_uid(uid_t uid) {
2744 _cleanup_free_ char *buf = NULL;
2745 struct passwd pwbuf, *pw = NULL;
2747 /* Shortcut things to avoid NSS lookups */
2749 return strdup("root");
2751 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2755 buf = malloc(bufsize);
2759 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2760 return strdup(pw->pw_name);
2762 if (asprintf(&name, UID_FMT, uid) < 0)
2768 char* getlogname_malloc(void) {
2772 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2777 return lookup_uid(uid);
2780 char *getusername_malloc(void) {
2787 return lookup_uid(getuid());
2790 int getttyname_malloc(int fd, char **ret) {
2800 r = ttyname_r(fd, path, sizeof(path));
2805 p = startswith(path, "/dev/");
2806 c = strdup(p ?: path);
2823 int getttyname_harder(int fd, char **r) {
2827 k = getttyname_malloc(fd, &s);
2831 if (streq(s, "tty")) {
2833 return get_ctty(0, NULL, r);
2840 int get_ctty_devnr(pid_t pid, dev_t *d) {
2842 _cleanup_free_ char *line = NULL;
2844 unsigned long ttynr;
2848 p = procfs_file_alloca(pid, "stat");
2849 r = read_one_line_file(p, &line);
2853 p = strrchr(line, ')');
2863 "%*d " /* session */
2868 if (major(ttynr) == 0 && minor(ttynr) == 0)
2877 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2878 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2879 _cleanup_free_ char *s = NULL;
2886 k = get_ctty_devnr(pid, &devnr);
2890 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2892 k = readlink_malloc(fn, &s);
2898 /* This is an ugly hack */
2899 if (major(devnr) == 136) {
2900 asprintf(&b, "pts/%u", minor(devnr));
2904 /* Probably something like the ptys which have no
2905 * symlink in /dev/char. Let's return something
2906 * vaguely useful. */
2912 if (startswith(s, "/dev/"))
2914 else if (startswith(s, "../"))
2932 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2933 _cleanup_closedir_ DIR *d = NULL;
2938 /* This returns the first error we run into, but nevertheless
2939 * tries to go on. This closes the passed fd. */
2945 return errno == ENOENT ? 0 : -errno;
2950 bool is_dir, keep_around;
2957 if (errno != 0 && ret == 0)
2962 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2965 if (de->d_type == DT_UNKNOWN ||
2967 (de->d_type == DT_DIR && root_dev)) {
2968 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2969 if (ret == 0 && errno != ENOENT)
2974 is_dir = S_ISDIR(st.st_mode);
2977 (st.st_uid == 0 || st.st_uid == getuid()) &&
2978 (st.st_mode & S_ISVTX);
2980 is_dir = de->d_type == DT_DIR;
2981 keep_around = false;
2987 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2988 if (root_dev && st.st_dev != root_dev->st_dev)
2991 subdir_fd = openat(fd, de->d_name,
2992 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2993 if (subdir_fd < 0) {
2994 if (ret == 0 && errno != ENOENT)
2999 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3000 if (r < 0 && ret == 0)
3004 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3005 if (ret == 0 && errno != ENOENT)
3009 } else if (!only_dirs && !keep_around) {
3011 if (unlinkat(fd, de->d_name, 0) < 0) {
3012 if (ret == 0 && errno != ENOENT)
3019 _pure_ static int is_temporary_fs(struct statfs *s) {
3022 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
3023 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
3026 int is_fd_on_temporary_fs(int fd) {
3029 if (fstatfs(fd, &s) < 0)
3032 return is_temporary_fs(&s);
3035 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3040 if (fstatfs(fd, &s) < 0) {
3045 /* We refuse to clean disk file systems with this call. This
3046 * is extra paranoia just to be sure we never ever remove
3048 if (!is_temporary_fs(&s)) {
3049 log_error("Attempted to remove disk file system, and we can't allow that.");
3054 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3057 static int file_is_priv_sticky(const char *p) {
3062 if (lstat(p, &st) < 0)
3066 (st.st_uid == 0 || st.st_uid == getuid()) &&
3067 (st.st_mode & S_ISVTX);
3070 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3076 /* We refuse to clean the root file system with this
3077 * call. This is extra paranoia to never cause a really
3078 * seriously broken system. */
3079 if (path_equal(path, "/")) {
3080 log_error("Attempted to remove entire root file system, and we can't allow that.");
3084 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3087 if (errno != ENOTDIR && errno != ELOOP)
3091 if (statfs(path, &s) < 0)
3094 if (!is_temporary_fs(&s)) {
3095 log_error("Attempted to remove disk file system, and we can't allow that.");
3100 if (delete_root && !only_dirs)
3101 if (unlink(path) < 0 && errno != ENOENT)
3108 if (fstatfs(fd, &s) < 0) {
3113 if (!is_temporary_fs(&s)) {
3114 log_error("Attempted to remove disk file system, and we can't allow that.");
3120 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3123 if (honour_sticky && file_is_priv_sticky(path) > 0)
3126 if (rmdir(path) < 0 && errno != ENOENT) {
3135 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3136 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3139 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3140 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3143 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3146 /* Under the assumption that we are running privileged we
3147 * first change the access mode and only then hand out
3148 * ownership to avoid a window where access is too open. */
3150 if (mode != MODE_INVALID)
3151 if (chmod(path, mode) < 0)
3154 if (uid != UID_INVALID || gid != GID_INVALID)
3155 if (chown(path, uid, gid) < 0)
3161 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3164 /* Under the assumption that we are running privileged we
3165 * first change the access mode and only then hand out
3166 * ownership to avoid a window where access is too open. */
3168 if (mode != MODE_INVALID)
3169 if (fchmod(fd, mode) < 0)
3172 if (uid != UID_INVALID || gid != GID_INVALID)
3173 if (fchown(fd, uid, gid) < 0)
3179 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3183 /* Allocates the cpuset in the right size */
3186 if (!(r = CPU_ALLOC(n)))
3189 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3190 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3200 if (errno != EINVAL)
3207 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
3208 static const char status_indent[] = " "; /* "[" STATUS "] " */
3209 _cleanup_free_ char *s = NULL;
3210 _cleanup_close_ int fd = -1;
3211 struct iovec iovec[6] = {};
3213 static bool prev_ephemeral;
3217 /* This is independent of logging, as status messages are
3218 * optional and go exclusively to the console. */
3220 if (vasprintf(&s, format, ap) < 0)
3223 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3236 sl = status ? sizeof(status_indent)-1 : 0;
3242 e = ellipsize(s, emax, 50);
3250 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3251 prev_ephemeral = ephemeral;
3254 if (!isempty(status)) {
3255 IOVEC_SET_STRING(iovec[n++], "[");
3256 IOVEC_SET_STRING(iovec[n++], status);
3257 IOVEC_SET_STRING(iovec[n++], "] ");
3259 IOVEC_SET_STRING(iovec[n++], status_indent);
3262 IOVEC_SET_STRING(iovec[n++], s);
3264 IOVEC_SET_STRING(iovec[n++], "\n");
3266 if (writev(fd, iovec, n) < 0)
3272 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3278 va_start(ap, format);
3279 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3285 char *replace_env(const char *format, char **env) {
3292 const char *e, *word = format;
3297 for (e = format; *e; e ++) {
3308 k = strnappend(r, word, e-word-1);
3318 } else if (*e == '$') {
3319 k = strnappend(r, word, e-word);
3336 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3338 k = strappend(r, t);
3352 k = strnappend(r, word, e-word);
3364 char **replace_env_argv(char **argv, char **env) {
3366 unsigned k = 0, l = 0;
3368 l = strv_length(argv);
3370 ret = new(char*, l+1);
3374 STRV_FOREACH(i, argv) {
3376 /* If $FOO appears as single word, replace it by the split up variable */
3377 if ((*i)[0] == '$' && (*i)[1] != '{') {
3382 e = strv_env_get(env, *i+1);
3386 r = strv_split_quoted(&m, e, true);
3398 w = realloc(ret, sizeof(char*) * (l+1));
3408 memcpy(ret + k, m, q * sizeof(char*));
3416 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3417 ret[k] = replace_env(*i, env);
3429 int fd_columns(int fd) {
3430 struct winsize ws = {};
3432 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3441 unsigned columns(void) {
3445 if (_likely_(cached_columns > 0))
3446 return cached_columns;
3449 e = getenv("COLUMNS");
3451 (void) safe_atoi(e, &c);
3454 c = fd_columns(STDOUT_FILENO);
3460 return cached_columns;
3463 int fd_lines(int fd) {
3464 struct winsize ws = {};
3466 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3475 unsigned lines(void) {
3479 if (_likely_(cached_lines > 0))
3480 return cached_lines;
3483 e = getenv("LINES");
3485 (void) safe_atoi(e, &l);
3488 l = fd_lines(STDOUT_FILENO);
3494 return cached_lines;
3497 /* intended to be used as a SIGWINCH sighandler */
3498 void columns_lines_cache_reset(int signum) {
3504 static int cached_on_tty = -1;
3506 if (_unlikely_(cached_on_tty < 0))
3507 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3509 return cached_on_tty;
3512 int files_same(const char *filea, const char *fileb) {
3515 if (stat(filea, &a) < 0)
3518 if (stat(fileb, &b) < 0)
3521 return a.st_dev == b.st_dev &&
3522 a.st_ino == b.st_ino;
3525 int running_in_chroot(void) {
3528 ret = files_same("/proc/1/root", "/");
3535 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3540 assert(percent <= 100);
3541 assert(new_length >= 3);
3543 if (old_length <= 3 || old_length <= new_length)
3544 return strndup(s, old_length);
3546 r = new0(char, new_length+1);
3550 x = (new_length * percent) / 100;
3552 if (x > new_length - 3)
3560 s + old_length - (new_length - x - 3),
3561 new_length - x - 3);
3566 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3570 unsigned k, len, len2;
3573 assert(percent <= 100);
3574 assert(new_length >= 3);
3576 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3577 if (ascii_is_valid(s))
3578 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3580 if (old_length <= 3 || old_length <= new_length)
3581 return strndup(s, old_length);
3583 x = (new_length * percent) / 100;
3585 if (x > new_length - 3)
3589 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3592 c = utf8_encoded_to_unichar(i);
3595 k += unichar_iswide(c) ? 2 : 1;
3598 if (k > x) /* last character was wide and went over quota */
3601 for (j = s + old_length; k < new_length && j > i; ) {
3604 j = utf8_prev_char(j);
3605 c = utf8_encoded_to_unichar(j);
3608 k += unichar_iswide(c) ? 2 : 1;
3612 /* we don't actually need to ellipsize */
3614 return memdup(s, old_length + 1);
3616 /* make space for ellipsis */
3617 j = utf8_next_char(j);
3620 len2 = s + old_length - j;
3621 e = new(char, len + 3 + len2 + 1);
3626 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3627 old_length, new_length, x, len, len2, k);
3631 e[len] = 0xe2; /* tri-dot ellipsis: … */
3635 memcpy(e + len + 3, j, len2 + 1);
3640 char *ellipsize(const char *s, size_t length, unsigned percent) {
3641 return ellipsize_mem(s, strlen(s), length, percent);
3644 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3645 _cleanup_close_ int fd;
3651 mkdir_parents(path, 0755);
3653 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3658 r = fchmod(fd, mode);
3663 if (uid != UID_INVALID || gid != GID_INVALID) {
3664 r = fchown(fd, uid, gid);
3669 if (stamp != USEC_INFINITY) {
3670 struct timespec ts[2];
3672 timespec_store(&ts[0], stamp);
3674 r = futimens(fd, ts);
3676 r = futimens(fd, NULL);
3683 int touch(const char *path) {
3684 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3687 char *unquote(const char *s, const char* quotes) {
3691 /* This is rather stupid, simply removes the heading and
3692 * trailing quotes if there is one. Doesn't care about
3693 * escaping or anything. We should make this smarter one
3700 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3701 return strndup(s+1, l-2);
3706 char *normalize_env_assignment(const char *s) {
3707 _cleanup_free_ char *value = NULL;
3711 eq = strchr(s, '=');
3721 memmove(r, t, strlen(t) + 1);
3726 name = strndupa(s, eq - s);
3727 p = strdupa(eq + 1);
3729 value = unquote(strstrip(p), QUOTES);
3733 return strjoin(strstrip(name), "=", value, NULL);
3736 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3747 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3761 * < 0 : wait_for_terminate() failed to get the state of the
3762 * process, the process was terminated by a signal, or
3763 * failed for an unknown reason.
3764 * >=0 : The process terminated normally, and its exit code is
3767 * That is, success is indicated by a return value of zero, and an
3768 * error is indicated by a non-zero value.
3770 * A warning is emitted if the process terminates abnormally,
3771 * and also if it returns non-zero unless check_exit_code is true.
3773 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
3780 r = wait_for_terminate(pid, &status);
3782 return log_warning_errno(r, "Failed to wait for %s: %m", name);
3784 if (status.si_code == CLD_EXITED) {
3785 if (status.si_status != 0)
3786 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
3787 "%s failed with error code %i.", name, status.si_status);
3789 log_debug("%s succeeded.", name);
3791 return status.si_status;
3792 } else if (status.si_code == CLD_KILLED ||
3793 status.si_code == CLD_DUMPED) {
3795 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3799 log_warning("%s failed due to unknown reason.", name);
3803 noreturn void freeze(void) {
3805 /* Make sure nobody waits for us on a socket anymore */
3806 close_all_fds(NULL, 0);
3814 bool null_or_empty(struct stat *st) {
3817 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3820 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3826 int null_or_empty_path(const char *fn) {
3831 if (stat(fn, &st) < 0)
3834 return null_or_empty(&st);
3837 int null_or_empty_fd(int fd) {
3842 if (fstat(fd, &st) < 0)
3845 return null_or_empty(&st);
3848 DIR *xopendirat(int fd, const char *name, int flags) {
3852 assert(!(flags & O_CREAT));
3854 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3867 int signal_from_string_try_harder(const char *s) {
3871 signo = signal_from_string(s);
3873 if (startswith(s, "SIG"))
3874 return signal_from_string(s+3);
3879 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3880 _cleanup_free_ char *t = NULL, *u = NULL;
3883 u = unquote(tagvalue, "\"\'");
3887 enc_len = strlen(u) * 4 + 1;
3888 t = new(char, enc_len);
3892 if (encode_devnode_name(u, t, enc_len) < 0)
3895 return strjoin("/dev/disk/by-", by, "/", t, NULL);
3898 char *fstab_node_to_udev_node(const char *p) {
3901 if (startswith(p, "LABEL="))
3902 return tag_to_udev_node(p+6, "label");
3904 if (startswith(p, "UUID="))
3905 return tag_to_udev_node(p+5, "uuid");
3907 if (startswith(p, "PARTUUID="))
3908 return tag_to_udev_node(p+9, "partuuid");
3910 if (startswith(p, "PARTLABEL="))
3911 return tag_to_udev_node(p+10, "partlabel");
3916 bool tty_is_vc(const char *tty) {
3919 return vtnr_from_tty(tty) >= 0;
3922 bool tty_is_console(const char *tty) {
3925 if (startswith(tty, "/dev/"))
3928 return streq(tty, "console");
3931 int vtnr_from_tty(const char *tty) {
3936 if (startswith(tty, "/dev/"))
3939 if (!startswith(tty, "tty") )
3942 if (tty[3] < '0' || tty[3] > '9')
3945 r = safe_atoi(tty+3, &i);
3949 if (i < 0 || i > 63)
3955 char *resolve_dev_console(char **active) {
3958 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3959 * (i.e. not read-only-mounted which is a sign for container setups) */
3961 if (path_is_read_only_fs("/sys") > 0)
3964 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3967 /* If multiple log outputs are configured the last one is what
3968 * /dev/console points to */
3969 tty = strrchr(*active, ' ');
3975 if (streq(tty, "tty0")) {
3978 /* Get the active VC (e.g. tty1) */
3979 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3981 tty = *active = tmp;
3988 bool tty_is_vc_resolve(const char *tty) {
3989 _cleanup_free_ char *active = NULL;
3993 if (startswith(tty, "/dev/"))
3996 if (streq(tty, "console")) {
3997 tty = resolve_dev_console(&active);
4002 return tty_is_vc(tty);
4005 const char *default_term_for_tty(const char *tty) {
4008 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4011 bool dirent_is_file(const struct dirent *de) {
4014 if (hidden_file(de->d_name))
4017 if (de->d_type != DT_REG &&
4018 de->d_type != DT_LNK &&
4019 de->d_type != DT_UNKNOWN)
4025 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4028 if (de->d_type != DT_REG &&
4029 de->d_type != DT_LNK &&
4030 de->d_type != DT_UNKNOWN)
4033 if (hidden_file_allow_backup(de->d_name))
4036 return endswith(de->d_name, suffix);
4039 void execute_directory(const char *directory, DIR *d, usec_t timeout, char *argv[]) {
4045 /* Executes all binaries in a directory in parallel and waits
4046 * for them to finish. Optionally a timeout is applied. */
4048 executor_pid = fork();
4049 if (executor_pid < 0) {
4050 log_error_errno(errno, "Failed to fork: %m");
4053 } else if (executor_pid == 0) {
4054 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
4055 _cleanup_closedir_ DIR *_d = NULL;
4058 /* We fork this all off from a child process so that
4059 * we can somewhat cleanly make use of SIGALRM to set
4062 reset_all_signal_handlers();
4063 reset_signal_mask();
4065 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4068 d = _d = opendir(directory);
4070 if (errno == ENOENT)
4071 _exit(EXIT_SUCCESS);
4073 log_error_errno(errno, "Failed to enumerate directory %s: %m", directory);
4074 _exit(EXIT_FAILURE);
4078 pids = hashmap_new(NULL);
4081 _exit(EXIT_FAILURE);
4084 FOREACH_DIRENT(de, d, break) {
4085 _cleanup_free_ char *path = NULL;
4088 if (!dirent_is_file(de))
4091 path = strjoin(directory, "/", de->d_name, NULL);
4094 _exit(EXIT_FAILURE);
4099 log_error_errno(errno, "Failed to fork: %m");
4101 } else if (pid == 0) {
4104 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4114 log_error_errno(errno, "Failed to execute %s: %m", path);
4115 _exit(EXIT_FAILURE);
4118 log_debug("Spawned %s as " PID_FMT ".", path, pid);
4120 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
4123 _exit(EXIT_FAILURE);
4129 /* Abort execution of this process after the
4130 * timout. We simply rely on SIGALRM as default action
4131 * terminating the process, and turn on alarm(). */
4133 if (timeout != USEC_INFINITY)
4134 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
4136 while (!hashmap_isempty(pids)) {
4137 _cleanup_free_ char *path = NULL;
4140 pid = PTR_TO_UINT(hashmap_first_key(pids));
4143 path = hashmap_remove(pids, UINT_TO_PTR(pid));
4146 wait_for_terminate_and_warn(path, pid, true);
4149 _exit(EXIT_SUCCESS);
4152 wait_for_terminate_and_warn(directory, executor_pid, true);
4155 int kill_and_sigcont(pid_t pid, int sig) {
4158 r = kill(pid, sig) < 0 ? -errno : 0;
4166 bool nulstr_contains(const char*nulstr, const char *needle) {
4172 NULSTR_FOREACH(i, nulstr)
4173 if (streq(i, needle))
4179 bool plymouth_running(void) {
4180 return access("/run/plymouth/pid", F_OK) >= 0;
4183 char* strshorten(char *s, size_t l) {
4192 static bool hostname_valid_char(char c) {
4194 (c >= 'a' && c <= 'z') ||
4195 (c >= 'A' && c <= 'Z') ||
4196 (c >= '0' && c <= '9') ||
4202 bool hostname_is_valid(const char *s) {
4209 for (p = s, dot = true; *p; p++) {
4216 if (!hostname_valid_char(*p))
4226 if (p-s > HOST_NAME_MAX)
4232 char* hostname_cleanup(char *s, bool lowercase) {
4236 for (p = s, d = s, dot = true; *p; p++) {
4243 } else if (hostname_valid_char(*p)) {
4244 *(d++) = lowercase ? tolower(*p) : *p;
4255 strshorten(s, HOST_NAME_MAX);
4260 bool machine_name_is_valid(const char *s) {
4262 if (!hostname_is_valid(s))
4265 /* Machine names should be useful hostnames, but also be
4266 * useful in unit names, hence we enforce a stricter length
4275 bool image_name_is_valid(const char *s) {
4276 if (!filename_is_valid(s))
4279 if (string_has_cc(s, NULL))
4282 if (!utf8_is_valid(s))
4285 /* Temporary files for atomically creating new files */
4286 if (startswith(s, ".#"))
4292 int pipe_eof(int fd) {
4293 struct pollfd pollfd = {
4295 .events = POLLIN|POLLHUP,
4300 r = poll(&pollfd, 1, 0);
4307 return pollfd.revents & POLLHUP;
4310 int fd_wait_for_event(int fd, int event, usec_t t) {
4312 struct pollfd pollfd = {
4320 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
4327 return pollfd.revents;
4330 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4339 r = tempfn_xxxxxx(path, &t);
4343 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
4349 f = fdopen(fd, "we");
4362 int terminal_vhangup_fd(int fd) {
4365 if (ioctl(fd, TIOCVHANGUP) < 0)
4371 int terminal_vhangup(const char *name) {
4372 _cleanup_close_ int fd;
4374 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4378 return terminal_vhangup_fd(fd);
4381 int vt_disallocate(const char *name) {
4385 /* Deallocate the VT if possible. If not possible
4386 * (i.e. because it is the active one), at least clear it
4387 * entirely (including the scrollback buffer) */
4389 if (!startswith(name, "/dev/"))
4392 if (!tty_is_vc(name)) {
4393 /* So this is not a VT. I guess we cannot deallocate
4394 * it then. But let's at least clear the screen */
4396 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4401 "\033[r" /* clear scrolling region */
4402 "\033[H" /* move home */
4403 "\033[2J", /* clear screen */
4410 if (!startswith(name, "/dev/tty"))
4413 r = safe_atou(name+8, &u);
4420 /* Try to deallocate */
4421 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4425 r = ioctl(fd, VT_DISALLOCATE, u);
4434 /* Couldn't deallocate, so let's clear it fully with
4436 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4441 "\033[r" /* clear scrolling region */
4442 "\033[H" /* move home */
4443 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4450 int symlink_atomic(const char *from, const char *to) {
4451 _cleanup_free_ char *t = NULL;
4457 r = tempfn_random(to, &t);
4461 if (symlink(from, t) < 0)
4464 if (rename(t, to) < 0) {
4472 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4473 _cleanup_free_ char *t = NULL;
4478 r = tempfn_random(path, &t);
4482 if (mknod(t, mode, dev) < 0)
4485 if (rename(t, path) < 0) {
4493 int mkfifo_atomic(const char *path, mode_t mode) {
4494 _cleanup_free_ char *t = NULL;
4499 r = tempfn_random(path, &t);
4503 if (mkfifo(t, mode) < 0)
4506 if (rename(t, path) < 0) {
4514 bool display_is_local(const char *display) {
4518 display[0] == ':' &&
4519 display[1] >= '0' &&
4523 int socket_from_display(const char *display, char **path) {
4530 if (!display_is_local(display))
4533 k = strspn(display+1, "0123456789");
4535 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4539 c = stpcpy(f, "/tmp/.X11-unix/X");
4540 memcpy(c, display+1, k);
4549 const char **username,
4550 uid_t *uid, gid_t *gid,
4552 const char **shell) {
4560 /* We enforce some special rules for uid=0: in order to avoid
4561 * NSS lookups for root we hardcode its data. */
4563 if (streq(*username, "root") || streq(*username, "0")) {
4581 if (parse_uid(*username, &u) >= 0) {
4585 /* If there are multiple users with the same id, make
4586 * sure to leave $USER to the configured value instead
4587 * of the first occurrence in the database. However if
4588 * the uid was configured by a numeric uid, then let's
4589 * pick the real username from /etc/passwd. */
4591 *username = p->pw_name;
4594 p = getpwnam(*username);
4598 return errno > 0 ? -errno : -ESRCH;
4610 *shell = p->pw_shell;
4615 char* uid_to_name(uid_t uid) {
4620 return strdup("root");
4624 return strdup(p->pw_name);
4626 if (asprintf(&r, UID_FMT, uid) < 0)
4632 char* gid_to_name(gid_t gid) {
4637 return strdup("root");
4641 return strdup(p->gr_name);
4643 if (asprintf(&r, GID_FMT, gid) < 0)
4649 int get_group_creds(const char **groupname, gid_t *gid) {
4655 /* We enforce some special rules for gid=0: in order to avoid
4656 * NSS lookups for root we hardcode its data. */
4658 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4659 *groupname = "root";
4667 if (parse_gid(*groupname, &id) >= 0) {
4672 *groupname = g->gr_name;
4675 g = getgrnam(*groupname);
4679 return errno > 0 ? -errno : -ESRCH;
4687 int in_gid(gid_t gid) {
4689 int ngroups_max, r, i;
4691 if (getgid() == gid)
4694 if (getegid() == gid)
4697 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4698 assert(ngroups_max > 0);
4700 gids = alloca(sizeof(gid_t) * ngroups_max);
4702 r = getgroups(ngroups_max, gids);
4706 for (i = 0; i < r; i++)
4713 int in_group(const char *name) {
4717 r = get_group_creds(&name, &gid);
4724 int glob_exists(const char *path) {
4725 _cleanup_globfree_ glob_t g = {};
4731 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4733 if (k == GLOB_NOMATCH)
4735 else if (k == GLOB_NOSPACE)
4738 return !strv_isempty(g.gl_pathv);
4740 return errno ? -errno : -EIO;
4743 int glob_extend(char ***strv, const char *path) {
4744 _cleanup_globfree_ glob_t g = {};
4749 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4751 if (k == GLOB_NOMATCH)
4753 else if (k == GLOB_NOSPACE)
4755 else if (k != 0 || strv_isempty(g.gl_pathv))
4756 return errno ? -errno : -EIO;
4758 STRV_FOREACH(p, g.gl_pathv) {
4759 k = strv_extend(strv, *p);
4767 int dirent_ensure_type(DIR *d, struct dirent *de) {
4773 if (de->d_type != DT_UNKNOWN)
4776 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4780 S_ISREG(st.st_mode) ? DT_REG :
4781 S_ISDIR(st.st_mode) ? DT_DIR :
4782 S_ISLNK(st.st_mode) ? DT_LNK :
4783 S_ISFIFO(st.st_mode) ? DT_FIFO :
4784 S_ISSOCK(st.st_mode) ? DT_SOCK :
4785 S_ISCHR(st.st_mode) ? DT_CHR :
4786 S_ISBLK(st.st_mode) ? DT_BLK :
4792 int get_files_in_directory(const char *path, char ***list) {
4793 _cleanup_closedir_ DIR *d = NULL;
4794 size_t bufsize = 0, n = 0;
4795 _cleanup_strv_free_ char **l = NULL;
4799 /* Returns all files in a directory in *list, and the number
4800 * of files as return value. If list is NULL returns only the
4812 if (!de && errno != 0)
4817 dirent_ensure_type(d, de);
4819 if (!dirent_is_file(de))
4823 /* one extra slot is needed for the terminating NULL */
4824 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4827 l[n] = strdup(de->d_name);
4838 l = NULL; /* avoid freeing */
4844 char *strjoin(const char *x, ...) {
4858 t = va_arg(ap, const char *);
4863 if (n > ((size_t) -1) - l) {
4887 t = va_arg(ap, const char *);
4901 bool is_main_thread(void) {
4902 static thread_local int cached = 0;
4904 if (_unlikely_(cached == 0))
4905 cached = getpid() == gettid() ? 1 : -1;
4910 int block_get_whole_disk(dev_t d, dev_t *ret) {
4917 /* If it has a queue this is good enough for us */
4918 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4921 r = access(p, F_OK);
4929 /* If it is a partition find the originating device */
4930 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4933 r = access(p, F_OK);
4939 /* Get parent dev_t */
4940 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4943 r = read_one_line_file(p, &s);
4949 r = sscanf(s, "%u:%u", &m, &n);
4955 /* Only return this if it is really good enough for us. */
4956 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4959 r = access(p, F_OK);
4963 *ret = makedev(m, n);
4970 static const char *const ioprio_class_table[] = {
4971 [IOPRIO_CLASS_NONE] = "none",
4972 [IOPRIO_CLASS_RT] = "realtime",
4973 [IOPRIO_CLASS_BE] = "best-effort",
4974 [IOPRIO_CLASS_IDLE] = "idle"
4977 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4979 static const char *const sigchld_code_table[] = {
4980 [CLD_EXITED] = "exited",
4981 [CLD_KILLED] = "killed",
4982 [CLD_DUMPED] = "dumped",
4983 [CLD_TRAPPED] = "trapped",
4984 [CLD_STOPPED] = "stopped",
4985 [CLD_CONTINUED] = "continued",
4988 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4990 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4991 [LOG_FAC(LOG_KERN)] = "kern",
4992 [LOG_FAC(LOG_USER)] = "user",
4993 [LOG_FAC(LOG_MAIL)] = "mail",
4994 [LOG_FAC(LOG_DAEMON)] = "daemon",
4995 [LOG_FAC(LOG_AUTH)] = "auth",
4996 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4997 [LOG_FAC(LOG_LPR)] = "lpr",
4998 [LOG_FAC(LOG_NEWS)] = "news",
4999 [LOG_FAC(LOG_UUCP)] = "uucp",
5000 [LOG_FAC(LOG_CRON)] = "cron",
5001 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5002 [LOG_FAC(LOG_FTP)] = "ftp",
5003 [LOG_FAC(LOG_LOCAL0)] = "local0",
5004 [LOG_FAC(LOG_LOCAL1)] = "local1",
5005 [LOG_FAC(LOG_LOCAL2)] = "local2",
5006 [LOG_FAC(LOG_LOCAL3)] = "local3",
5007 [LOG_FAC(LOG_LOCAL4)] = "local4",
5008 [LOG_FAC(LOG_LOCAL5)] = "local5",
5009 [LOG_FAC(LOG_LOCAL6)] = "local6",
5010 [LOG_FAC(LOG_LOCAL7)] = "local7"
5013 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5015 static const char *const log_level_table[] = {
5016 [LOG_EMERG] = "emerg",
5017 [LOG_ALERT] = "alert",
5018 [LOG_CRIT] = "crit",
5020 [LOG_WARNING] = "warning",
5021 [LOG_NOTICE] = "notice",
5022 [LOG_INFO] = "info",
5023 [LOG_DEBUG] = "debug"
5026 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5028 static const char* const sched_policy_table[] = {
5029 [SCHED_OTHER] = "other",
5030 [SCHED_BATCH] = "batch",
5031 [SCHED_IDLE] = "idle",
5032 [SCHED_FIFO] = "fifo",
5036 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5038 static const char* const rlimit_table[_RLIMIT_MAX] = {
5039 [RLIMIT_CPU] = "LimitCPU",
5040 [RLIMIT_FSIZE] = "LimitFSIZE",
5041 [RLIMIT_DATA] = "LimitDATA",
5042 [RLIMIT_STACK] = "LimitSTACK",
5043 [RLIMIT_CORE] = "LimitCORE",
5044 [RLIMIT_RSS] = "LimitRSS",
5045 [RLIMIT_NOFILE] = "LimitNOFILE",
5046 [RLIMIT_AS] = "LimitAS",
5047 [RLIMIT_NPROC] = "LimitNPROC",
5048 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5049 [RLIMIT_LOCKS] = "LimitLOCKS",
5050 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5051 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5052 [RLIMIT_NICE] = "LimitNICE",
5053 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5054 [RLIMIT_RTTIME] = "LimitRTTIME"
5057 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5059 static const char* const ip_tos_table[] = {
5060 [IPTOS_LOWDELAY] = "low-delay",
5061 [IPTOS_THROUGHPUT] = "throughput",
5062 [IPTOS_RELIABILITY] = "reliability",
5063 [IPTOS_LOWCOST] = "low-cost",
5066 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5068 static const char *const __signal_table[] = {
5085 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5096 [SIGVTALRM] = "VTALRM",
5098 [SIGWINCH] = "WINCH",
5104 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5106 const char *signal_to_string(int signo) {
5107 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
5110 name = __signal_to_string(signo);
5114 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5115 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
5117 snprintf(buf, sizeof(buf), "%d", signo);
5122 int signal_from_string(const char *s) {
5127 signo = __signal_from_string(s);
5131 if (startswith(s, "RTMIN+")) {
5135 if (safe_atou(s, &u) >= 0) {
5136 signo = (int) u + offset;
5137 if (signo > 0 && signo < _NSIG)
5143 bool kexec_loaded(void) {
5144 bool loaded = false;
5147 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5155 int prot_from_flags(int flags) {
5157 switch (flags & O_ACCMODE) {
5166 return PROT_READ|PROT_WRITE;
5173 char *format_bytes(char *buf, size_t l, off_t t) {
5176 static const struct {
5180 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5181 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5182 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5183 { "G", 1024ULL*1024ULL*1024ULL },
5184 { "M", 1024ULL*1024ULL },
5188 if (t == (off_t) -1)
5191 for (i = 0; i < ELEMENTSOF(table); i++) {
5193 if (t >= table[i].factor) {
5196 (unsigned long long) (t / table[i].factor),
5197 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5204 snprintf(buf, l, "%lluB", (unsigned long long) t);
5212 void* memdup(const void *p, size_t l) {
5225 int fd_inc_sndbuf(int fd, size_t n) {
5227 socklen_t l = sizeof(value);
5229 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5230 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5233 /* If we have the privileges we will ignore the kernel limit. */
5236 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5237 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5243 int fd_inc_rcvbuf(int fd, size_t n) {
5245 socklen_t l = sizeof(value);
5247 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5248 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5251 /* If we have the privileges we will ignore the kernel limit. */
5254 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5255 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5260 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5261 bool stdout_is_tty, stderr_is_tty;
5262 pid_t parent_pid, agent_pid;
5263 sigset_t ss, saved_ss;
5271 /* Spawns a temporary TTY agent, making sure it goes away when
5274 parent_pid = getpid();
5276 /* First we temporarily block all signals, so that the new
5277 * child has them blocked initially. This way, we can be sure
5278 * that SIGTERMs are not lost we might send to the agent. */
5279 assert_se(sigfillset(&ss) >= 0);
5280 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
5283 if (agent_pid < 0) {
5284 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5288 if (agent_pid != 0) {
5289 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5296 * Make sure the agent goes away when the parent dies */
5297 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5298 _exit(EXIT_FAILURE);
5300 /* Make sure we actually can kill the agent, if we need to, in
5301 * case somebody invoked us from a shell script that trapped
5302 * SIGTERM or so... */
5303 reset_all_signal_handlers();
5304 reset_signal_mask();
5306 /* Check whether our parent died before we were able
5307 * to set the death signal and unblock the signals */
5308 if (getppid() != parent_pid)
5309 _exit(EXIT_SUCCESS);
5311 /* Don't leak fds to the agent */
5312 close_all_fds(except, n_except);
5314 stdout_is_tty = isatty(STDOUT_FILENO);
5315 stderr_is_tty = isatty(STDERR_FILENO);
5317 if (!stdout_is_tty || !stderr_is_tty) {
5320 /* Detach from stdout/stderr. and reopen
5321 * /dev/tty for them. This is important to
5322 * ensure that when systemctl is started via
5323 * popen() or a similar call that expects to
5324 * read EOF we actually do generate EOF and
5325 * not delay this indefinitely by because we
5326 * keep an unused copy of stdin around. */
5327 fd = open("/dev/tty", O_WRONLY);
5329 log_error_errno(errno, "Failed to open /dev/tty: %m");
5330 _exit(EXIT_FAILURE);
5334 dup2(fd, STDOUT_FILENO);
5337 dup2(fd, STDERR_FILENO);
5343 /* Count arguments */
5345 for (n = 0; va_arg(ap, char*); n++)
5350 l = alloca(sizeof(char *) * (n + 1));
5352 /* Fill in arguments */
5354 for (i = 0; i <= n; i++)
5355 l[i] = va_arg(ap, char*);
5359 _exit(EXIT_FAILURE);
5362 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5363 struct rlimit highest, fixed;
5367 if (setrlimit(resource, rlim) >= 0)
5373 /* So we failed to set the desired setrlimit, then let's try
5374 * to get as close as we can */
5375 assert_se(getrlimit(resource, &highest) == 0);
5377 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5378 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5380 if (setrlimit(resource, &fixed) < 0)
5386 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5387 _cleanup_fclose_ FILE *f = NULL;
5398 path = procfs_file_alloca(pid, "environ");
5400 f = fopen(path, "re");
5408 char line[LINE_MAX];
5411 for (i = 0; i < sizeof(line)-1; i++) {
5415 if (_unlikely_(c == EOF)) {
5425 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5426 value = strdup(line + l + 1);
5440 bool is_valid_documentation_url(const char *url) {
5443 if (startswith(url, "http://") && url[7])
5446 if (startswith(url, "https://") && url[8])
5449 if (startswith(url, "file:") && url[5])
5452 if (startswith(url, "info:") && url[5])
5455 if (startswith(url, "man:") && url[4])
5461 bool in_initrd(void) {
5462 static int saved = -1;
5468 /* We make two checks here:
5470 * 1. the flag file /etc/initrd-release must exist
5471 * 2. the root file system must be a memory file system
5473 * The second check is extra paranoia, since misdetecting an
5474 * initrd can have bad bad consequences due the initrd
5475 * emptying when transititioning to the main systemd.
5478 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5479 statfs("/", &s) >= 0 &&
5480 is_temporary_fs(&s);
5485 void warn_melody(void) {
5486 _cleanup_close_ int fd = -1;
5488 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5492 /* Yeah, this is synchronous. Kinda sucks. But well... */
5494 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5495 usleep(125*USEC_PER_MSEC);
5497 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5498 usleep(125*USEC_PER_MSEC);
5500 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5501 usleep(125*USEC_PER_MSEC);
5503 ioctl(fd, KIOCSOUND, 0);
5506 int make_console_stdio(void) {
5509 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5511 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5513 return log_error_errno(fd, "Failed to acquire terminal: %m");
5517 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5522 int get_home_dir(char **_h) {
5530 /* Take the user specified one */
5531 e = secure_getenv("HOME");
5532 if (e && path_is_absolute(e)) {
5541 /* Hardcode home directory for root to avoid NSS */
5544 h = strdup("/root");
5552 /* Check the database... */
5556 return errno > 0 ? -errno : -ESRCH;
5558 if (!path_is_absolute(p->pw_dir))
5561 h = strdup(p->pw_dir);
5569 int get_shell(char **_s) {
5577 /* Take the user specified one */
5578 e = getenv("SHELL");
5588 /* Hardcode home directory for root to avoid NSS */
5591 s = strdup("/bin/sh");
5599 /* Check the database... */
5603 return errno > 0 ? -errno : -ESRCH;
5605 if (!path_is_absolute(p->pw_shell))
5608 s = strdup(p->pw_shell);
5616 bool filename_is_valid(const char *p) {
5630 if (strlen(p) > FILENAME_MAX)
5636 bool string_is_safe(const char *p) {
5642 for (t = p; *t; t++) {
5643 if (*t > 0 && *t < ' ')
5646 if (strchr("\\\"\'\0x7f", *t))
5654 * Check if a string contains control characters. If 'ok' is non-NULL
5655 * it may be a string containing additional CCs to be considered OK.
5657 bool string_has_cc(const char *p, const char *ok) {
5662 for (t = p; *t; t++) {
5663 if (ok && strchr(ok, *t))
5666 if (*t > 0 && *t < ' ')
5676 bool path_is_safe(const char *p) {
5681 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5684 if (strlen(p) > PATH_MAX)
5687 /* The following two checks are not really dangerous, but hey, they still are confusing */
5688 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5691 if (strstr(p, "//"))
5697 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5698 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5699 int (*compar) (const void *, const void *, void *), void *arg) {
5708 p = (void *)(((const char *) base) + (idx * size));
5709 comparison = compar(key, p, arg);
5712 else if (comparison > 0)
5720 bool is_locale_utf8(void) {
5722 static int cached_answer = -1;
5724 if (cached_answer >= 0)
5727 if (!setlocale(LC_ALL, "")) {
5728 cached_answer = true;
5732 set = nl_langinfo(CODESET);
5734 cached_answer = true;
5738 if (streq(set, "UTF-8")) {
5739 cached_answer = true;
5743 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5744 * unset and everything can do to UTF-8 nowadays. */
5745 set = setlocale(LC_CTYPE, NULL);
5747 cached_answer = true;
5751 /* Check result, but ignore the result if C was set
5755 !getenv("LC_ALL") &&
5756 !getenv("LC_CTYPE") &&
5760 return (bool) cached_answer;
5763 const char *draw_special_char(DrawSpecialChar ch) {
5764 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5767 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
5768 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5769 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5770 [DRAW_TREE_SPACE] = " ", /* */
5771 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5772 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5773 [DRAW_ARROW] = "\342\206\222", /* → */
5774 [DRAW_DASH] = "\342\200\223", /* – */
5777 /* ASCII fallback */ {
5778 [DRAW_TREE_VERTICAL] = "| ",
5779 [DRAW_TREE_BRANCH] = "|-",
5780 [DRAW_TREE_RIGHT] = "`-",
5781 [DRAW_TREE_SPACE] = " ",
5782 [DRAW_TRIANGULAR_BULLET] = ">",
5783 [DRAW_BLACK_CIRCLE] = "*",
5784 [DRAW_ARROW] = "->",
5789 return draw_table[!is_locale_utf8()][ch];
5792 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5795 size_t l, old_len, new_len;
5801 old_len = strlen(old_string);
5802 new_len = strlen(new_string);
5815 if (!startswith(f, old_string)) {
5821 nl = l - old_len + new_len;
5822 a = realloc(r, nl + 1);
5830 t = stpcpy(t, new_string);
5842 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5843 const char *i, *begin = NULL;
5848 } state = STATE_OTHER;
5850 size_t osz = 0, isz;
5856 /* Strips ANSI color and replaces TABs by 8 spaces */
5858 isz = _isz ? *_isz : strlen(*ibuf);
5860 f = open_memstream(&obuf, &osz);
5864 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5869 if (i >= *ibuf + isz) /* EOT */
5871 else if (*i == '\x1B')
5872 state = STATE_ESCAPE;
5873 else if (*i == '\t')
5880 if (i >= *ibuf + isz) { /* EOT */
5883 } else if (*i == '[') {
5884 state = STATE_BRACKET;
5889 state = STATE_OTHER;
5896 if (i >= *ibuf + isz || /* EOT */
5897 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5900 state = STATE_OTHER;
5902 } else if (*i == 'm')
5903 state = STATE_OTHER;
5925 int on_ac_power(void) {
5926 bool found_offline = false, found_online = false;
5927 _cleanup_closedir_ DIR *d = NULL;
5929 d = opendir("/sys/class/power_supply");
5935 _cleanup_close_ int fd = -1, device = -1;
5941 if (!de && errno != 0)
5947 if (hidden_file(de->d_name))
5950 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5952 if (errno == ENOENT || errno == ENOTDIR)
5958 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5960 if (errno == ENOENT)
5966 n = read(fd, contents, sizeof(contents));
5970 if (n != 6 || memcmp(contents, "Mains\n", 6))
5974 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5976 if (errno == ENOENT)
5982 n = read(fd, contents, sizeof(contents));
5986 if (n != 2 || contents[1] != '\n')
5989 if (contents[0] == '1') {
5990 found_online = true;
5992 } else if (contents[0] == '0')
5993 found_offline = true;
5998 return found_online || !found_offline;
6001 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
6008 if (!path_strv_resolve_uniq(search, root))
6011 STRV_FOREACH(i, search) {
6012 _cleanup_free_ char *p = NULL;
6016 p = strjoin(root, *i, "/", path, NULL);
6018 p = strjoin(*i, "/", path, NULL);
6028 if (errno != ENOENT)
6035 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
6036 _cleanup_strv_free_ char **copy = NULL;
6042 if (path_is_absolute(path)) {
6045 f = fopen(path, mode);
6054 copy = strv_copy((char**) search);
6058 return search_and_fopen_internal(path, mode, root, copy, _f);
6061 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
6062 _cleanup_strv_free_ char **s = NULL;
6064 if (path_is_absolute(path)) {
6067 f = fopen(path, mode);
6076 s = strv_split_nulstr(search);
6080 return search_and_fopen_internal(path, mode, root, s, _f);
6083 char *strextend(char **x, ...) {
6090 l = f = *x ? strlen(*x) : 0;
6097 t = va_arg(ap, const char *);
6102 if (n > ((size_t) -1) - l) {
6111 r = realloc(*x, l+1);
6121 t = va_arg(ap, const char *);
6135 char *strrep(const char *s, unsigned n) {
6143 p = r = malloc(l * n + 1);
6147 for (i = 0; i < n; i++)
6154 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
6161 if (*allocated >= need)
6164 newalloc = MAX(need * 2, 64u / size);
6165 a = newalloc * size;
6167 /* check for overflows */
6168 if (a < size * need)
6176 *allocated = newalloc;
6180 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
6189 q = greedy_realloc(p, allocated, need, size);
6193 if (*allocated > prev)
6194 memzero(q + prev * size, (*allocated - prev) * size);
6199 bool id128_is_valid(const char *s) {
6205 /* Simple formatted 128bit hex string */
6207 for (i = 0; i < l; i++) {
6210 if (!(c >= '0' && c <= '9') &&
6211 !(c >= 'a' && c <= 'z') &&
6212 !(c >= 'A' && c <= 'Z'))
6216 } else if (l == 36) {
6218 /* Formatted UUID */
6220 for (i = 0; i < l; i++) {
6223 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6227 if (!(c >= '0' && c <= '9') &&
6228 !(c >= 'a' && c <= 'z') &&
6229 !(c >= 'A' && c <= 'Z'))
6240 int split_pair(const char *s, const char *sep, char **l, char **r) {
6255 a = strndup(s, x - s);
6259 b = strdup(x + strlen(sep));
6271 int shall_restore_state(void) {
6272 _cleanup_free_ char *value = NULL;
6275 r = get_proc_cmdline_key("systemd.restore_state=", &value);
6281 return parse_boolean(value) != 0;
6284 int proc_cmdline(char **ret) {
6287 if (detect_container(NULL) > 0)
6288 return get_process_cmdline(1, 0, false, ret);
6290 return read_one_line_file("/proc/cmdline", ret);
6293 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6294 _cleanup_free_ char *line = NULL;
6300 r = proc_cmdline(&line);
6306 _cleanup_free_ char *word = NULL;
6309 r = unquote_first_word(&p, &word, true);
6315 /* Filter out arguments that are intended only for the
6317 if (!in_initrd() && startswith(word, "rd."))
6320 value = strchr(word, '=');
6324 r = parse_item(word, value);
6332 int get_proc_cmdline_key(const char *key, char **value) {
6333 _cleanup_free_ char *line = NULL, *ret = NULL;
6340 r = proc_cmdline(&line);
6346 _cleanup_free_ char *word = NULL;
6349 r = unquote_first_word(&p, &word, true);
6355 /* Filter out arguments that are intended only for the
6357 if (!in_initrd() && startswith(word, "rd."))
6361 e = startswith(word, key);
6365 r = free_and_strdup(&ret, e);
6371 if (streq(word, key))
6385 int container_get_leader(const char *machine, pid_t *pid) {
6386 _cleanup_free_ char *s = NULL, *class = NULL;
6394 p = strappenda("/run/systemd/machines/", machine);
6395 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6403 if (!streq_ptr(class, "container"))
6406 r = parse_pid(s, &leader);
6416 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6417 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
6425 mntns = procfs_file_alloca(pid, "ns/mnt");
6426 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6434 pidns = procfs_file_alloca(pid, "ns/pid");
6435 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6443 netns = procfs_file_alloca(pid, "ns/net");
6444 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6452 root = procfs_file_alloca(pid, "root");
6453 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6459 *pidns_fd = pidnsfd;
6462 *mntns_fd = mntnsfd;
6465 *netns_fd = netnsfd;
6470 pidnsfd = mntnsfd = netnsfd = -1;
6475 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
6478 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6482 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6486 if (setns(netns_fd, CLONE_NEWNET) < 0)
6490 if (fchdir(root_fd) < 0)
6493 if (chroot(".") < 0)
6497 if (setresgid(0, 0, 0) < 0)
6500 if (setgroups(0, NULL) < 0)
6503 if (setresuid(0, 0, 0) < 0)
6509 bool pid_is_unwaited(pid_t pid) {
6510 /* Checks whether a PID is still valid at all, including a zombie */
6515 if (kill(pid, 0) >= 0)
6518 return errno != ESRCH;
6521 bool pid_is_alive(pid_t pid) {
6524 /* Checks whether a PID is still valid and not a zombie */
6529 r = get_process_state(pid);
6530 if (r == -ENOENT || r == 'Z')
6536 int getpeercred(int fd, struct ucred *ucred) {
6537 socklen_t n = sizeof(struct ucred);
6544 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6548 if (n != sizeof(struct ucred))
6551 /* Check if the data is actually useful and not suppressed due
6552 * to namespacing issues */
6555 if (u.uid == UID_INVALID)
6557 if (u.gid == GID_INVALID)
6564 int getpeersec(int fd, char **ret) {
6576 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6580 if (errno != ERANGE)
6587 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6603 /* This is much like like mkostemp() but is subject to umask(). */
6604 int mkostemp_safe(char *pattern, int flags) {
6605 _cleanup_umask_ mode_t u;
6612 fd = mkostemp(pattern, flags);
6619 int open_tmpfile(const char *path, int flags) {
6626 /* Try O_TMPFILE first, if it is supported */
6627 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6632 /* Fall back to unguessable name + unlinking */
6633 p = strappenda(path, "/systemd-tmp-XXXXXX");
6635 fd = mkostemp_safe(p, flags);
6643 int fd_warn_permissions(const char *path, int fd) {
6646 if (fstat(fd, &st) < 0)
6649 if (st.st_mode & 0111)
6650 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6652 if (st.st_mode & 0002)
6653 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6655 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6656 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);
6661 unsigned long personality_from_string(const char *p) {
6663 /* Parse a personality specifier. We introduce our own
6664 * identifiers that indicate specific ABIs, rather than just
6665 * hints regarding the register size, since we want to keep
6666 * things open for multiple locally supported ABIs for the
6667 * same register size. We try to reuse the ABI identifiers
6668 * used by libseccomp. */
6670 #if defined(__x86_64__)
6672 if (streq(p, "x86"))
6675 if (streq(p, "x86-64"))
6678 #elif defined(__i386__)
6680 if (streq(p, "x86"))
6684 /* personality(7) documents that 0xffffffffUL is used for
6685 * querying the current personality, hence let's use that here
6686 * as error indicator. */
6687 return 0xffffffffUL;
6690 const char* personality_to_string(unsigned long p) {
6692 #if defined(__x86_64__)
6694 if (p == PER_LINUX32)
6700 #elif defined(__i386__)
6709 uint64_t physical_memory(void) {
6712 /* We return this as uint64_t in case we are running as 32bit
6713 * process on a 64bit kernel with huge amounts of memory */
6715 mem = sysconf(_SC_PHYS_PAGES);
6718 return (uint64_t) mem * (uint64_t) page_size();
6721 char* mount_test_option(const char *haystack, const char *needle) {
6723 struct mntent me = {
6724 .mnt_opts = (char*) haystack
6729 /* Like glibc's hasmntopt(), but works on a string, not a
6735 return hasmntopt(&me, needle);
6738 void hexdump(FILE *f, const void *p, size_t s) {
6739 const uint8_t *b = p;
6742 assert(s == 0 || b);
6747 fprintf(f, "%04x ", n);
6749 for (i = 0; i < 16; i++) {
6754 fprintf(f, "%02x ", b[i]);
6762 for (i = 0; i < 16; i++) {
6767 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6781 int update_reboot_param_file(const char *param) {
6786 r = write_string_file(REBOOT_PARAM_FILE, param);
6788 log_error("Failed to write reboot param to "
6789 REBOOT_PARAM_FILE": %s", strerror(-r));
6791 unlink(REBOOT_PARAM_FILE);
6796 int umount_recursive(const char *prefix, int flags) {
6800 /* Try to umount everything recursively below a
6801 * directory. Also, take care of stacked mounts, and keep
6802 * unmounting them until they are gone. */
6805 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6810 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6811 if (!proc_self_mountinfo)
6815 _cleanup_free_ char *path = NULL, *p = NULL;
6818 k = fscanf(proc_self_mountinfo,
6819 "%*s " /* (1) mount id */
6820 "%*s " /* (2) parent id */
6821 "%*s " /* (3) major:minor */
6822 "%*s " /* (4) root */
6823 "%ms " /* (5) mount point */
6824 "%*s" /* (6) mount options */
6825 "%*[^-]" /* (7) optional fields */
6826 "- " /* (8) separator */
6827 "%*s " /* (9) file system type */
6828 "%*s" /* (10) mount source */
6829 "%*s" /* (11) mount options 2 */
6830 "%*[^\n]", /* some rubbish at the end */
6839 p = cunescape(path);
6843 if (!path_startswith(p, prefix))
6846 if (umount2(p, flags) < 0) {
6862 static int get_mount_flags(const char *path, unsigned long *flags) {
6865 if (statvfs(path, &buf) < 0)
6867 *flags = buf.f_flag;
6871 int bind_remount_recursive(const char *prefix, bool ro) {
6872 _cleanup_set_free_free_ Set *done = NULL;
6873 _cleanup_free_ char *cleaned = NULL;
6876 /* Recursively remount a directory (and all its submounts)
6877 * read-only or read-write. If the directory is already
6878 * mounted, we reuse the mount and simply mark it
6879 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6880 * operation). If it isn't we first make it one. Afterwards we
6881 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6882 * submounts we can access, too. When mounts are stacked on
6883 * the same mount point we only care for each individual
6884 * "top-level" mount on each point, as we cannot
6885 * influence/access the underlying mounts anyway. We do not
6886 * have any effect on future submounts that might get
6887 * propagated, they migt be writable. This includes future
6888 * submounts that have been triggered via autofs. */
6890 cleaned = strdup(prefix);
6894 path_kill_slashes(cleaned);
6896 done = set_new(&string_hash_ops);
6901 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6902 _cleanup_set_free_free_ Set *todo = NULL;
6903 bool top_autofs = false;
6905 unsigned long orig_flags;
6907 todo = set_new(&string_hash_ops);
6911 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6912 if (!proc_self_mountinfo)
6916 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6919 k = fscanf(proc_self_mountinfo,
6920 "%*s " /* (1) mount id */
6921 "%*s " /* (2) parent id */
6922 "%*s " /* (3) major:minor */
6923 "%*s " /* (4) root */
6924 "%ms " /* (5) mount point */
6925 "%*s" /* (6) mount options (superblock) */
6926 "%*[^-]" /* (7) optional fields */
6927 "- " /* (8) separator */
6928 "%ms " /* (9) file system type */
6929 "%*s" /* (10) mount source */
6930 "%*s" /* (11) mount options (bind mount) */
6931 "%*[^\n]", /* some rubbish at the end */
6941 p = cunescape(path);
6945 /* Let's ignore autofs mounts. If they aren't
6946 * triggered yet, we want to avoid triggering
6947 * them, as we don't make any guarantees for
6948 * future submounts anyway. If they are
6949 * already triggered, then we will find
6950 * another entry for this. */
6951 if (streq(type, "autofs")) {
6952 top_autofs = top_autofs || path_equal(cleaned, p);
6956 if (path_startswith(p, cleaned) &&
6957 !set_contains(done, p)) {
6959 r = set_consume(todo, p);
6969 /* If we have no submounts to process anymore and if
6970 * the root is either already done, or an autofs, we
6972 if (set_isempty(todo) &&
6973 (top_autofs || set_contains(done, cleaned)))
6976 if (!set_contains(done, cleaned) &&
6977 !set_contains(todo, cleaned)) {
6978 /* The prefix directory itself is not yet a
6979 * mount, make it one. */
6980 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6984 (void) get_mount_flags(cleaned, &orig_flags);
6985 orig_flags &= ~MS_RDONLY;
6987 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6990 x = strdup(cleaned);
6994 r = set_consume(done, x);
6999 while ((x = set_steal_first(todo))) {
7001 r = set_consume(done, x);
7007 /* Try to reuse the original flag set, but
7008 * don't care for errors, in case of
7009 * obstructed mounts */
7011 (void) get_mount_flags(x, &orig_flags);
7012 orig_flags &= ~MS_RDONLY;
7014 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
7016 /* Deal with mount points that are
7017 * obstructed by a later mount */
7019 if (errno != ENOENT)
7027 int fflush_and_check(FILE *f) {
7034 return errno ? -errno : -EIO;
7039 int tempfn_xxxxxx(const char *p, char **ret) {
7051 * /foo/bar/.#waldoXXXXXX
7055 if (!filename_is_valid(fn))
7058 t = new(char, strlen(p) + 2 + 6 + 1);
7062 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
7064 *ret = path_kill_slashes(t);
7068 int tempfn_random(const char *p, char **ret) {
7082 * /foo/bar/.#waldobaa2a261115984a9
7086 if (!filename_is_valid(fn))
7089 t = new(char, strlen(p) + 2 + 16 + 1);
7093 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
7096 for (i = 0; i < 16; i++) {
7097 *(x++) = hexchar(u & 0xF);
7103 *ret = path_kill_slashes(t);
7107 int tempfn_random_child(const char *p, char **ret) {
7118 * /foo/bar/waldo/.#3c2b6219aa75d7d0
7121 t = new(char, strlen(p) + 3 + 16 + 1);
7125 x = stpcpy(stpcpy(t, p), "/.#");
7128 for (i = 0; i < 16; i++) {
7129 *(x++) = hexchar(u & 0xF);
7135 *ret = path_kill_slashes(t);
7139 /* make sure the hostname is not "localhost" */
7140 bool is_localhost(const char *hostname) {
7143 /* This tries to identify local host and domain names
7144 * described in RFC6761 plus the redhatism of .localdomain */
7146 return streq(hostname, "localhost") ||
7147 streq(hostname, "localhost.") ||
7148 streq(hostname, "localdomain.") ||
7149 streq(hostname, "localdomain") ||
7150 endswith(hostname, ".localhost") ||
7151 endswith(hostname, ".localhost.") ||
7152 endswith(hostname, ".localdomain") ||
7153 endswith(hostname, ".localdomain.");
7156 int take_password_lock(const char *root) {
7158 struct flock flock = {
7160 .l_whence = SEEK_SET,
7168 /* This is roughly the same as lckpwdf(), but not as awful. We
7169 * don't want to use alarm() and signals, hence we implement
7170 * our own trivial version of this.
7172 * Note that shadow-utils also takes per-database locks in
7173 * addition to lckpwdf(). However, we don't given that they
7174 * are redundant as they they invoke lckpwdf() first and keep
7175 * it during everything they do. The per-database locks are
7176 * awfully racy, and thus we just won't do them. */
7179 path = strappenda(root, "/etc/.pwd.lock");
7181 path = "/etc/.pwd.lock";
7183 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
7187 r = fcntl(fd, F_SETLKW, &flock);
7196 int is_symlink(const char *path) {
7199 if (lstat(path, &info) < 0)
7202 return !!S_ISLNK(info.st_mode);
7205 int is_dir(const char* path, bool follow) {
7210 r = stat(path, &st);
7212 r = lstat(path, &st);
7216 return !!S_ISDIR(st.st_mode);
7219 int unquote_first_word(const char **p, char **ret, bool relax) {
7220 _cleanup_free_ char *s = NULL;
7221 size_t allocated = 0, sz = 0;
7228 SINGLE_QUOTE_ESCAPE,
7230 DOUBLE_QUOTE_ESCAPE,
7238 /* Parses the first word of a string, and returns it in
7239 * *ret. Removes all quotes in the process. When parsing fails
7240 * (because of an uneven number of quotes or similar), leaves
7241 * the pointer *p at the first invalid character. */
7251 else if (strchr(WHITESPACE, c))
7261 state = SINGLE_QUOTE;
7263 state = VALUE_ESCAPE;
7265 state = DOUBLE_QUOTE;
7266 else if (strchr(WHITESPACE, c))
7269 if (!GREEDY_REALLOC(s, allocated, sz+2))
7284 if (!GREEDY_REALLOC(s, allocated, sz+2))
7297 } else if (c == '\'')
7300 state = SINGLE_QUOTE_ESCAPE;
7302 if (!GREEDY_REALLOC(s, allocated, sz+2))
7310 case SINGLE_QUOTE_ESCAPE:
7317 if (!GREEDY_REALLOC(s, allocated, sz+2))
7321 state = SINGLE_QUOTE;
7330 state = DOUBLE_QUOTE_ESCAPE;
7332 if (!GREEDY_REALLOC(s, allocated, sz+2))
7340 case DOUBLE_QUOTE_ESCAPE:
7347 if (!GREEDY_REALLOC(s, allocated, sz+2))
7351 state = DOUBLE_QUOTE;
7357 if (!strchr(WHITESPACE, c))
7379 int unquote_many_words(const char **p, ...) {
7384 /* Parses a number of words from a string, stripping any
7385 * quotes if necessary. */
7389 /* Count how many words are expected */
7392 if (!va_arg(ap, char **))
7401 /* Read all words into a temporary array */
7402 l = newa0(char*, n);
7403 for (c = 0; c < n; c++) {
7405 r = unquote_first_word(p, &l[c], false);
7409 for (j = 0; j < c; j++)
7419 /* If we managed to parse all words, return them in the passed
7422 for (i = 0; i < n; i++) {
7425 v = va_arg(ap, char **);
7435 int free_and_strdup(char **p, const char *s) {
7440 /* Replaces a string pointer with an strdup()ed new string,
7441 * possibly freeing the old one. */
7456 int sethostname_idempotent(const char *s) {
7458 char buf[HOST_NAME_MAX + 1] = {};
7462 r = gethostname(buf, sizeof(buf));
7469 r = sethostname(s, strlen(s));
7476 int ptsname_malloc(int fd, char **ret) {
7489 if (ptsname_r(fd, c, l) == 0) {
7493 if (errno != ERANGE) {
7503 int openpt_in_namespace(pid_t pid, int flags) {
7504 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7505 _cleanup_close_pair_ int pair[2] = { -1, -1 };
7507 struct cmsghdr cmsghdr;
7508 uint8_t buf[CMSG_SPACE(sizeof(int))];
7510 struct msghdr mh = {
7511 .msg_control = &control,
7512 .msg_controllen = sizeof(control),
7514 struct cmsghdr *cmsg;
7521 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7525 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7535 pair[0] = safe_close(pair[0]);
7537 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7539 _exit(EXIT_FAILURE);
7541 master = posix_openpt(flags);
7543 _exit(EXIT_FAILURE);
7545 cmsg = CMSG_FIRSTHDR(&mh);
7546 cmsg->cmsg_level = SOL_SOCKET;
7547 cmsg->cmsg_type = SCM_RIGHTS;
7548 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7549 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7551 mh.msg_controllen = cmsg->cmsg_len;
7553 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7554 _exit(EXIT_FAILURE);
7556 _exit(EXIT_SUCCESS);
7559 pair[1] = safe_close(pair[1]);
7561 r = wait_for_terminate(child, &si);
7564 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7567 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7570 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7571 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7575 fds = (int*) CMSG_DATA(cmsg);
7576 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7579 close_many(fds, n_fds);
7589 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7590 _cleanup_close_ int fd = -1;
7593 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7595 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7599 l = fgetxattr(fd, attribute, value, size);
7606 static int parse_crtime(le64_t le, usec_t *usec) {
7612 if (u == 0 || u == (uint64_t) -1)
7619 int fd_getcrtime(int fd, usec_t *usec) {
7626 /* Until Linux gets a real concept of birthtime/creation time,
7627 * let's fake one with xattrs */
7629 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7632 if (n != sizeof(le))
7635 return parse_crtime(le, usec);
7638 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7642 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7645 if (n != sizeof(le))
7648 return parse_crtime(le, usec);
7651 int path_getcrtime(const char *p, usec_t *usec) {
7658 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7661 if (n != sizeof(le))
7664 return parse_crtime(le, usec);
7667 int fd_setcrtime(int fd, usec_t usec) {
7672 le = htole64((uint64_t) usec);
7673 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7679 int same_fd(int a, int b) {
7680 struct stat sta, stb;
7688 if (fstat(a, &sta) < 0)
7691 if (fstat(b, &stb) < 0)
7694 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
7697 if (S_ISREG(sta.st_mode) || S_ISDIR(sta.st_mode) || S_ISFIFO(sta.st_mode) || S_ISSOCK(sta.st_mode) || S_ISLNK(sta.st_mode))
7698 return (sta.st_dev == stb.st_dev) && (sta.st_ino == stb.st_ino);
7700 /* We consider all device fds different... */