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/>.
32 #include <sys/resource.h>
33 #include <linux/sched.h>
34 #include <sys/types.h>
38 #include <sys/ioctl.h>
40 #include <linux/tiocl.h>
45 #include <sys/prctl.h>
46 #include <sys/utsname.h>
48 #include <netinet/ip.h>
56 #include <sys/mount.h>
57 #include <linux/magic.h>
61 #include <sys/personality.h>
62 #include <sys/xattr.h>
63 #include <sys/statvfs.h>
67 /* When we include libgen.h because we need dirname() we immediately
68 * undefine basename() since libgen.h defines it as a macro to the XDG
69 * version which is really broken. */
73 #ifdef HAVE_SYS_AUXV_H
85 #include "path-util.h"
86 #include "exit-status.h"
90 #include "device-nodes.h"
95 #include "sparse-endian.h"
97 /* Put this test here for a lack of better place */
98 assert_cc(EAGAIN == EWOULDBLOCK);
101 char **saved_argv = NULL;
103 static volatile unsigned cached_columns = 0;
104 static volatile unsigned cached_lines = 0;
106 size_t page_size(void) {
107 static thread_local size_t pgsz = 0;
110 if (_likely_(pgsz > 0))
113 r = sysconf(_SC_PAGESIZE);
120 bool streq_ptr(const char *a, const char *b) {
122 /* Like streq(), but tries to make sense of NULL pointers */
133 char* endswith(const char *s, const char *postfix) {
140 pl = strlen(postfix);
143 return (char*) s + sl;
148 if (memcmp(s + sl - pl, postfix, pl) != 0)
151 return (char*) s + sl - pl;
154 char* first_word(const char *s, const char *word) {
161 /* Checks if the string starts with the specified word, either
162 * followed by NUL or by whitespace. Returns a pointer to the
163 * NUL or the first character after the whitespace. */
174 if (memcmp(s, word, wl) != 0)
181 if (!strchr(WHITESPACE, *p))
184 p += strspn(p, WHITESPACE);
188 static size_t cescape_char(char c, char *buf) {
189 char * buf_old = buf;
235 /* For special chars we prefer octal over
236 * hexadecimal encoding, simply because glib's
237 * g_strescape() does the same */
238 if ((c < ' ') || (c >= 127)) {
240 *(buf++) = octchar((unsigned char) c >> 6);
241 *(buf++) = octchar((unsigned char) c >> 3);
242 *(buf++) = octchar((unsigned char) c);
248 return buf - buf_old;
251 int close_nointr(int fd) {
258 * Just ignore EINTR; a retry loop is the wrong thing to do on
261 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
262 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
263 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
264 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
272 int safe_close(int fd) {
275 * Like close_nointr() but cannot fail. Guarantees errno is
276 * unchanged. Is a NOP with negative fds passed, and returns
277 * -1, so that it can be used in this syntax:
279 * fd = safe_close(fd);
285 /* The kernel might return pretty much any error code
286 * via close(), but the fd will be closed anyway. The
287 * only condition we want to check for here is whether
288 * the fd was invalid at all... */
290 assert_se(close_nointr(fd) != -EBADF);
296 void close_many(const int fds[], unsigned n_fd) {
299 assert(fds || n_fd <= 0);
301 for (i = 0; i < n_fd; i++)
305 int unlink_noerrno(const char *path) {
316 int parse_boolean(const char *v) {
319 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
321 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
327 int parse_pid(const char *s, pid_t* ret_pid) {
328 unsigned long ul = 0;
335 r = safe_atolu(s, &ul);
341 if ((unsigned long) pid != ul)
351 int parse_uid(const char *s, uid_t* ret_uid) {
352 unsigned long ul = 0;
359 r = safe_atolu(s, &ul);
365 if ((unsigned long) uid != ul)
368 /* Some libc APIs use UID_INVALID as special placeholder */
369 if (uid == (uid_t) 0xFFFFFFFF)
372 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
373 if (uid == (uid_t) 0xFFFF)
380 int safe_atou(const char *s, unsigned *ret_u) {
388 l = strtoul(s, &x, 0);
390 if (!x || x == s || *x || errno)
391 return errno > 0 ? -errno : -EINVAL;
393 if ((unsigned long) (unsigned) l != l)
396 *ret_u = (unsigned) l;
400 int safe_atoi(const char *s, int *ret_i) {
408 l = strtol(s, &x, 0);
410 if (!x || x == s || *x || errno)
411 return errno > 0 ? -errno : -EINVAL;
413 if ((long) (int) l != l)
420 int safe_atou8(const char *s, uint8_t *ret) {
428 l = strtoul(s, &x, 0);
430 if (!x || x == s || *x || errno)
431 return errno > 0 ? -errno : -EINVAL;
433 if ((unsigned long) (uint8_t) l != l)
440 int safe_atou16(const char *s, uint16_t *ret) {
448 l = strtoul(s, &x, 0);
450 if (!x || x == s || *x || errno)
451 return errno > 0 ? -errno : -EINVAL;
453 if ((unsigned long) (uint16_t) l != l)
460 int safe_atoi16(const char *s, int16_t *ret) {
468 l = strtol(s, &x, 0);
470 if (!x || x == s || *x || errno)
471 return errno > 0 ? -errno : -EINVAL;
473 if ((long) (int16_t) l != l)
480 int safe_atollu(const char *s, long long unsigned *ret_llu) {
482 unsigned long long l;
488 l = strtoull(s, &x, 0);
490 if (!x || x == s || *x || errno)
491 return errno ? -errno : -EINVAL;
497 int safe_atolli(const char *s, long long int *ret_lli) {
505 l = strtoll(s, &x, 0);
507 if (!x || x == s || *x || errno)
508 return errno ? -errno : -EINVAL;
514 int safe_atod(const char *s, double *ret_d) {
522 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
523 if (loc == (locale_t) 0)
527 d = strtod_l(s, &x, loc);
529 if (!x || x == s || *x || errno) {
531 return errno ? -errno : -EINVAL;
539 static size_t strcspn_escaped(const char *s, const char *reject) {
540 bool escaped = false;
543 for (n=0; s[n]; n++) {
546 else if (s[n] == '\\')
548 else if (strchr(reject, s[n]))
552 /* if s ends in \, return index of previous char */
556 /* Split a string into words. */
557 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
563 assert(**state == '\0');
567 current += strspn(current, separator);
573 if (quoted && strchr("\'\"", *current)) {
574 char quotechars[2] = {*current, '\0'};
576 *l = strcspn_escaped(current + 1, quotechars);
577 if (current[*l + 1] == '\0' ||
578 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
579 /* right quote missing or garbage at the end */
583 assert(current[*l + 1] == quotechars[0]);
584 *state = current++ + *l + 2;
586 *l = strcspn_escaped(current, separator);
587 if (current[*l] && !strchr(separator, current[*l])) {
588 /* unfinished escape */
592 *state = current + *l;
594 *l = strcspn(current, separator);
595 *state = current + *l;
601 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
603 _cleanup_free_ char *line = NULL;
615 p = procfs_file_alloca(pid, "stat");
616 r = read_one_line_file(p, &line);
620 /* Let's skip the pid and comm fields. The latter is enclosed
621 * in () but does not escape any () in its value, so let's
622 * skip over it manually */
624 p = strrchr(line, ')');
636 if ((long unsigned) (pid_t) ppid != ppid)
639 *_ppid = (pid_t) ppid;
644 int fchmod_umask(int fd, mode_t m) {
649 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
655 char *truncate_nl(char *s) {
658 s[strcspn(s, NEWLINE)] = 0;
662 int get_process_state(pid_t pid) {
666 _cleanup_free_ char *line = NULL;
670 p = procfs_file_alloca(pid, "stat");
671 r = read_one_line_file(p, &line);
675 p = strrchr(line, ')');
681 if (sscanf(p, " %c", &state) != 1)
684 return (unsigned char) state;
687 int get_process_comm(pid_t pid, char **name) {
694 p = procfs_file_alloca(pid, "comm");
696 r = read_one_line_file(p, name);
703 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
704 _cleanup_fclose_ FILE *f = NULL;
712 p = procfs_file_alloca(pid, "cmdline");
718 if (max_length == 0) {
719 size_t len = 0, allocated = 0;
721 while ((c = getc(f)) != EOF) {
723 if (!GREEDY_REALLOC(r, allocated, len+2)) {
728 r[len++] = isprint(c) ? c : ' ';
738 r = new(char, max_length);
744 while ((c = getc(f)) != EOF) {
766 size_t n = MIN(left-1, 3U);
773 /* Kernel threads have no argv[] */
775 _cleanup_free_ char *t = NULL;
783 h = get_process_comm(pid, &t);
787 r = strjoin("[", t, "]", NULL);
796 int is_kernel_thread(pid_t pid) {
808 p = procfs_file_alloca(pid, "cmdline");
813 count = fread(&c, 1, 1, f);
817 /* Kernel threads have an empty cmdline */
820 return eof ? 1 : -errno;
825 int get_process_capeff(pid_t pid, char **capeff) {
831 p = procfs_file_alloca(pid, "status");
833 return get_status_field(p, "\nCapEff:", capeff);
836 static int get_process_link_contents(const char *proc_file, char **name) {
842 r = readlink_malloc(proc_file, name);
844 return r == -ENOENT ? -ESRCH : r;
849 int get_process_exe(pid_t pid, char **name) {
856 p = procfs_file_alloca(pid, "exe");
857 r = get_process_link_contents(p, name);
861 d = endswith(*name, " (deleted)");
868 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
869 _cleanup_fclose_ FILE *f = NULL;
879 p = procfs_file_alloca(pid, "status");
884 FOREACH_LINE(line, f, return -errno) {
889 if (startswith(l, field)) {
891 l += strspn(l, WHITESPACE);
893 l[strcspn(l, WHITESPACE)] = 0;
895 return parse_uid(l, uid);
902 int get_process_uid(pid_t pid, uid_t *uid) {
903 return get_process_id(pid, "Uid:", uid);
906 int get_process_gid(pid_t pid, gid_t *gid) {
907 assert_cc(sizeof(uid_t) == sizeof(gid_t));
908 return get_process_id(pid, "Gid:", gid);
911 int get_process_cwd(pid_t pid, char **cwd) {
916 p = procfs_file_alloca(pid, "cwd");
918 return get_process_link_contents(p, cwd);
921 int get_process_root(pid_t pid, char **root) {
926 p = procfs_file_alloca(pid, "root");
928 return get_process_link_contents(p, root);
931 int get_process_environ(pid_t pid, char **env) {
932 _cleanup_fclose_ FILE *f = NULL;
933 _cleanup_free_ char *outcome = NULL;
936 size_t allocated = 0, sz = 0;
941 p = procfs_file_alloca(pid, "environ");
947 while ((c = fgetc(f)) != EOF) {
948 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
952 outcome[sz++] = '\n';
954 sz += cescape_char(c, outcome + sz);
964 char *strnappend(const char *s, const char *suffix, size_t b) {
972 return strndup(suffix, b);
981 if (b > ((size_t) -1) - a)
984 r = new(char, a+b+1);
989 memcpy(r+a, suffix, b);
995 char *strappend(const char *s, const char *suffix) {
996 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
999 int readlinkat_malloc(int fd, const char *p, char **ret) {
1014 n = readlinkat(fd, p, c, l-1);
1021 if ((size_t) n < l-1) {
1032 int readlink_malloc(const char *p, char **ret) {
1033 return readlinkat_malloc(AT_FDCWD, p, ret);
1036 int readlink_value(const char *p, char **ret) {
1037 _cleanup_free_ char *link = NULL;
1041 r = readlink_malloc(p, &link);
1045 value = basename(link);
1049 value = strdup(value);
1058 int readlink_and_make_absolute(const char *p, char **r) {
1059 _cleanup_free_ char *target = NULL;
1066 j = readlink_malloc(p, &target);
1070 k = file_in_same_dir(p, target);
1078 int readlink_and_canonicalize(const char *p, char **r) {
1085 j = readlink_and_make_absolute(p, &t);
1089 s = canonicalize_file_name(t);
1096 path_kill_slashes(*r);
1101 int reset_all_signal_handlers(void) {
1104 for (sig = 1; sig < _NSIG; sig++) {
1105 struct sigaction sa = {
1106 .sa_handler = SIG_DFL,
1107 .sa_flags = SA_RESTART,
1110 /* These two cannot be caught... */
1111 if (sig == SIGKILL || sig == SIGSTOP)
1114 /* On Linux the first two RT signals are reserved by
1115 * glibc, and sigaction() will return EINVAL for them. */
1116 if ((sigaction(sig, &sa, NULL) < 0))
1117 if (errno != EINVAL && r == 0)
1124 int reset_signal_mask(void) {
1127 if (sigemptyset(&ss) < 0)
1130 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
1136 char *strstrip(char *s) {
1139 /* Drops trailing whitespace. Modifies the string in
1140 * place. Returns pointer to first non-space character */
1142 s += strspn(s, WHITESPACE);
1144 for (e = strchr(s, 0); e > s; e --)
1145 if (!strchr(WHITESPACE, e[-1]))
1153 char *delete_chars(char *s, const char *bad) {
1156 /* Drops all whitespace, regardless where in the string */
1158 for (f = s, t = s; *f; f++) {
1159 if (strchr(bad, *f))
1170 char *file_in_same_dir(const char *path, const char *filename) {
1177 /* This removes the last component of path and appends
1178 * filename, unless the latter is absolute anyway or the
1181 if (path_is_absolute(filename))
1182 return strdup(filename);
1184 e = strrchr(path, '/');
1186 return strdup(filename);
1188 k = strlen(filename);
1189 ret = new(char, (e + 1 - path) + k + 1);
1193 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
1197 int rmdir_parents(const char *path, const char *stop) {
1206 /* Skip trailing slashes */
1207 while (l > 0 && path[l-1] == '/')
1213 /* Skip last component */
1214 while (l > 0 && path[l-1] != '/')
1217 /* Skip trailing slashes */
1218 while (l > 0 && path[l-1] == '/')
1224 if (!(t = strndup(path, l)))
1227 if (path_startswith(stop, t)) {
1236 if (errno != ENOENT)
1243 char hexchar(int x) {
1244 static const char table[16] = "0123456789abcdef";
1246 return table[x & 15];
1249 int unhexchar(char c) {
1251 if (c >= '0' && c <= '9')
1254 if (c >= 'a' && c <= 'f')
1255 return c - 'a' + 10;
1257 if (c >= 'A' && c <= 'F')
1258 return c - 'A' + 10;
1263 char *hexmem(const void *p, size_t l) {
1267 z = r = malloc(l * 2 + 1);
1271 for (x = p; x < (const uint8_t*) p + l; x++) {
1272 *(z++) = hexchar(*x >> 4);
1273 *(z++) = hexchar(*x & 15);
1280 void *unhexmem(const char *p, size_t l) {
1286 z = r = malloc((l + 1) / 2 + 1);
1290 for (x = p; x < p + l; x += 2) {
1293 a = unhexchar(x[0]);
1295 b = unhexchar(x[1]);
1299 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1306 char octchar(int x) {
1307 return '0' + (x & 7);
1310 int unoctchar(char c) {
1312 if (c >= '0' && c <= '7')
1318 char decchar(int x) {
1319 return '0' + (x % 10);
1322 int undecchar(char c) {
1324 if (c >= '0' && c <= '9')
1330 char *cescape(const char *s) {
1336 /* Does C style string escaping. */
1338 r = new(char, strlen(s)*4 + 1);
1342 for (f = s, t = r; *f; f++)
1343 t += cescape_char(*f, t);
1350 static int cunescape_one(const char *p, size_t length, char *ret) {
1357 if (length != (size_t) -1 && length < 1)
1394 /* This is an extension of the XDG syntax files */
1399 /* hexadecimal encoding */
1402 if (length != (size_t) -1 && length < 3)
1405 a = unhexchar(p[1]);
1409 b = unhexchar(p[2]);
1413 /* don't allow NUL bytes */
1414 if (a == 0 && b == 0)
1417 *ret = (char) ((a << 4) | b);
1430 /* octal encoding */
1433 if (length != (size_t) -1 && length < 4)
1436 a = unoctchar(p[0]);
1440 b = unoctchar(p[1]);
1444 c = unoctchar(p[2]);
1448 /* don't allow NUL bytes */
1449 if (a == 0 && b == 0 && c == 0)
1452 /* Don't allow bytes above 255 */
1453 m = (a << 6) | (b << 3) | c;
1469 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1476 /* Undoes C style string escaping, and optionally prefixes it. */
1478 pl = prefix ? strlen(prefix) : 0;
1480 r = new(char, pl+length+1);
1485 memcpy(r, prefix, pl);
1487 for (f = s, t = r + pl; f < s + length; f++) {
1491 remaining = s + length - f;
1492 assert(remaining > 0);
1494 if (*f != '\\' || remaining == 1) {
1495 /* a literal literal, or a trailing backslash, copy verbatim */
1500 k = cunescape_one(f + 1, remaining - 1, t);
1502 /* Invalid escape code, let's take it literal then */
1515 char *cunescape_length(const char *s, size_t length) {
1516 return cunescape_length_with_prefix(s, length, NULL);
1519 char *cunescape(const char *s) {
1522 return cunescape_length(s, strlen(s));
1525 char *xescape(const char *s, const char *bad) {
1529 /* Escapes all chars in bad, in addition to \ and all special
1530 * chars, in \xFF style escaping. May be reversed with
1533 r = new(char, strlen(s) * 4 + 1);
1537 for (f = s, t = r; *f; f++) {
1539 if ((*f < ' ') || (*f >= 127) ||
1540 (*f == '\\') || strchr(bad, *f)) {
1543 *(t++) = hexchar(*f >> 4);
1544 *(t++) = hexchar(*f);
1554 char *ascii_strlower(char *t) {
1559 for (p = t; *p; p++)
1560 if (*p >= 'A' && *p <= 'Z')
1561 *p = *p - 'A' + 'a';
1566 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1570 filename[0] == '.' ||
1571 streq(filename, "lost+found") ||
1572 streq(filename, "aquota.user") ||
1573 streq(filename, "aquota.group") ||
1574 endswith(filename, ".rpmnew") ||
1575 endswith(filename, ".rpmsave") ||
1576 endswith(filename, ".rpmorig") ||
1577 endswith(filename, ".dpkg-old") ||
1578 endswith(filename, ".dpkg-new") ||
1579 endswith(filename, ".dpkg-tmp") ||
1580 endswith(filename, ".dpkg-dist") ||
1581 endswith(filename, ".dpkg-bak") ||
1582 endswith(filename, ".dpkg-backup") ||
1583 endswith(filename, ".dpkg-remove") ||
1584 endswith(filename, ".swp");
1587 bool hidden_file(const char *filename) {
1590 if (endswith(filename, "~"))
1593 return hidden_file_allow_backup(filename);
1596 int fd_nonblock(int fd, bool nonblock) {
1601 flags = fcntl(fd, F_GETFL, 0);
1606 nflags = flags | O_NONBLOCK;
1608 nflags = flags & ~O_NONBLOCK;
1610 if (nflags == flags)
1613 if (fcntl(fd, F_SETFL, nflags) < 0)
1619 int fd_cloexec(int fd, bool cloexec) {
1624 flags = fcntl(fd, F_GETFD, 0);
1629 nflags = flags | FD_CLOEXEC;
1631 nflags = flags & ~FD_CLOEXEC;
1633 if (nflags == flags)
1636 if (fcntl(fd, F_SETFD, nflags) < 0)
1642 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1645 assert(n_fdset == 0 || fdset);
1647 for (i = 0; i < n_fdset; i++)
1654 int close_all_fds(const int except[], unsigned n_except) {
1655 _cleanup_closedir_ DIR *d = NULL;
1659 assert(n_except == 0 || except);
1661 d = opendir("/proc/self/fd");
1666 /* When /proc isn't available (for example in chroots)
1667 * the fallback is brute forcing through the fd
1670 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1671 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1673 if (fd_in_set(fd, except, n_except))
1676 if (close_nointr(fd) < 0)
1677 if (errno != EBADF && r == 0)
1684 while ((de = readdir(d))) {
1687 if (hidden_file(de->d_name))
1690 if (safe_atoi(de->d_name, &fd) < 0)
1691 /* Let's better ignore this, just in case */
1700 if (fd_in_set(fd, except, n_except))
1703 if (close_nointr(fd) < 0) {
1704 /* Valgrind has its own FD and doesn't want to have it closed */
1705 if (errno != EBADF && r == 0)
1713 bool chars_intersect(const char *a, const char *b) {
1716 /* Returns true if any of the chars in a are in b. */
1717 for (p = a; *p; p++)
1724 bool fstype_is_network(const char *fstype) {
1725 static const char table[] =
1740 x = startswith(fstype, "fuse.");
1744 return nulstr_contains(table, fstype);
1748 _cleanup_close_ int fd;
1750 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1756 TIOCL_GETKMSGREDIRECT,
1760 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1763 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1766 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1772 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1773 struct termios old_termios, new_termios;
1774 char c, line[LINE_MAX];
1779 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1780 new_termios = old_termios;
1782 new_termios.c_lflag &= ~ICANON;
1783 new_termios.c_cc[VMIN] = 1;
1784 new_termios.c_cc[VTIME] = 0;
1786 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1789 if (t != USEC_INFINITY) {
1790 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1791 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1796 k = fread(&c, 1, 1, f);
1798 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1804 *need_nl = c != '\n';
1811 if (t != USEC_INFINITY) {
1812 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1817 if (!fgets(line, sizeof(line), f))
1818 return errno ? -errno : -EIO;
1822 if (strlen(line) != 1)
1832 int ask_char(char *ret, const char *replies, const char *text, ...) {
1842 bool need_nl = true;
1845 fputs(ANSI_HIGHLIGHT_ON, stdout);
1852 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1856 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1859 if (r == -EBADMSG) {
1860 puts("Bad input, please try again.");
1871 if (strchr(replies, c)) {
1876 puts("Read unexpected character, please try again.");
1880 int ask_string(char **ret, const char *text, ...) {
1885 char line[LINE_MAX];
1889 fputs(ANSI_HIGHLIGHT_ON, stdout);
1896 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1901 if (!fgets(line, sizeof(line), stdin))
1902 return errno ? -errno : -EIO;
1904 if (!endswith(line, "\n"))
1923 int reset_terminal_fd(int fd, bool switch_to_text) {
1924 struct termios termios;
1927 /* Set terminal to some sane defaults */
1931 /* We leave locked terminal attributes untouched, so that
1932 * Plymouth may set whatever it wants to set, and we don't
1933 * interfere with that. */
1935 /* Disable exclusive mode, just in case */
1936 ioctl(fd, TIOCNXCL);
1938 /* Switch to text mode */
1940 ioctl(fd, KDSETMODE, KD_TEXT);
1942 /* Enable console unicode mode */
1943 ioctl(fd, KDSKBMODE, K_UNICODE);
1945 if (tcgetattr(fd, &termios) < 0) {
1950 /* We only reset the stuff that matters to the software. How
1951 * hardware is set up we don't touch assuming that somebody
1952 * else will do that for us */
1954 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1955 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1956 termios.c_oflag |= ONLCR;
1957 termios.c_cflag |= CREAD;
1958 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1960 termios.c_cc[VINTR] = 03; /* ^C */
1961 termios.c_cc[VQUIT] = 034; /* ^\ */
1962 termios.c_cc[VERASE] = 0177;
1963 termios.c_cc[VKILL] = 025; /* ^X */
1964 termios.c_cc[VEOF] = 04; /* ^D */
1965 termios.c_cc[VSTART] = 021; /* ^Q */
1966 termios.c_cc[VSTOP] = 023; /* ^S */
1967 termios.c_cc[VSUSP] = 032; /* ^Z */
1968 termios.c_cc[VLNEXT] = 026; /* ^V */
1969 termios.c_cc[VWERASE] = 027; /* ^W */
1970 termios.c_cc[VREPRINT] = 022; /* ^R */
1971 termios.c_cc[VEOL] = 0;
1972 termios.c_cc[VEOL2] = 0;
1974 termios.c_cc[VTIME] = 0;
1975 termios.c_cc[VMIN] = 1;
1977 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1981 /* Just in case, flush all crap out */
1982 tcflush(fd, TCIOFLUSH);
1987 int reset_terminal(const char *name) {
1988 _cleanup_close_ int fd = -1;
1990 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1994 return reset_terminal_fd(fd, true);
1997 int open_terminal(const char *name, int mode) {
2002 * If a TTY is in the process of being closed opening it might
2003 * cause EIO. This is horribly awful, but unlikely to be
2004 * changed in the kernel. Hence we work around this problem by
2005 * retrying a couple of times.
2007 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2010 assert(!(mode & O_CREAT));
2013 fd = open(name, mode, 0);
2020 /* Max 1s in total */
2024 usleep(50 * USEC_PER_MSEC);
2042 int flush_fd(int fd) {
2043 struct pollfd pollfd = {
2053 r = poll(&pollfd, 1, 0);
2063 l = read(fd, buf, sizeof(buf));
2069 if (errno == EAGAIN)
2078 int acquire_terminal(
2082 bool ignore_tiocstty_eperm,
2085 int fd = -1, notify = -1, r = 0, wd = -1;
2090 /* We use inotify to be notified when the tty is closed. We
2091 * create the watch before checking if we can actually acquire
2092 * it, so that we don't lose any event.
2094 * Note: strictly speaking this actually watches for the
2095 * device being closed, it does *not* really watch whether a
2096 * tty loses its controlling process. However, unless some
2097 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2098 * its tty otherwise this will not become a problem. As long
2099 * as the administrator makes sure not configure any service
2100 * on the same tty as an untrusted user this should not be a
2101 * problem. (Which he probably should not do anyway.) */
2103 if (timeout != USEC_INFINITY)
2104 ts = now(CLOCK_MONOTONIC);
2106 if (!fail && !force) {
2107 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
2113 wd = inotify_add_watch(notify, name, IN_CLOSE);
2121 struct sigaction sa_old, sa_new = {
2122 .sa_handler = SIG_IGN,
2123 .sa_flags = SA_RESTART,
2127 r = flush_fd(notify);
2132 /* We pass here O_NOCTTY only so that we can check the return
2133 * value TIOCSCTTY and have a reliable way to figure out if we
2134 * successfully became the controlling process of the tty */
2135 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2139 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2140 * if we already own the tty. */
2141 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2143 /* First, try to get the tty */
2144 if (ioctl(fd, TIOCSCTTY, force) < 0)
2147 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2149 /* Sometimes it makes sense to ignore TIOCSCTTY
2150 * returning EPERM, i.e. when very likely we already
2151 * are have this controlling terminal. */
2152 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2155 if (r < 0 && (force || fail || r != -EPERM)) {
2164 assert(notify >= 0);
2167 union inotify_event_buffer buffer;
2168 struct inotify_event *e;
2171 if (timeout != USEC_INFINITY) {
2174 n = now(CLOCK_MONOTONIC);
2175 if (ts + timeout < n) {
2180 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2190 l = read(notify, &buffer, sizeof(buffer));
2192 if (errno == EINTR || errno == EAGAIN)
2199 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2200 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2209 /* We close the tty fd here since if the old session
2210 * ended our handle will be dead. It's important that
2211 * we do this after sleeping, so that we don't enter
2212 * an endless loop. */
2213 fd = safe_close(fd);
2218 r = reset_terminal_fd(fd, true);
2220 log_warning_errno(r, "Failed to reset terminal: %m");
2231 int release_terminal(void) {
2232 static const struct sigaction sa_new = {
2233 .sa_handler = SIG_IGN,
2234 .sa_flags = SA_RESTART,
2237 _cleanup_close_ int fd = -1;
2238 struct sigaction sa_old;
2241 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2245 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2246 * by our own TIOCNOTTY */
2247 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2249 if (ioctl(fd, TIOCNOTTY) < 0)
2252 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2257 int sigaction_many(const struct sigaction *sa, ...) {
2262 while ((sig = va_arg(ap, int)) > 0)
2263 if (sigaction(sig, sa, NULL) < 0)
2270 int ignore_signals(int sig, ...) {
2271 struct sigaction sa = {
2272 .sa_handler = SIG_IGN,
2273 .sa_flags = SA_RESTART,
2278 if (sigaction(sig, &sa, NULL) < 0)
2282 while ((sig = va_arg(ap, int)) > 0)
2283 if (sigaction(sig, &sa, NULL) < 0)
2290 int default_signals(int sig, ...) {
2291 struct sigaction sa = {
2292 .sa_handler = SIG_DFL,
2293 .sa_flags = SA_RESTART,
2298 if (sigaction(sig, &sa, NULL) < 0)
2302 while ((sig = va_arg(ap, int)) > 0)
2303 if (sigaction(sig, &sa, NULL) < 0)
2310 void safe_close_pair(int p[]) {
2314 /* Special case pairs which use the same fd in both
2316 p[0] = p[1] = safe_close(p[0]);
2320 p[0] = safe_close(p[0]);
2321 p[1] = safe_close(p[1]);
2324 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2331 while (nbytes > 0) {
2334 k = read(fd, p, nbytes);
2339 if (errno == EAGAIN && do_poll) {
2341 /* We knowingly ignore any return value here,
2342 * and expect that any error/EOF is reported
2345 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2349 return n > 0 ? n : -errno;
2363 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
2366 n = loop_read(fd, buf, nbytes, do_poll);
2369 if ((size_t) n != nbytes)
2374 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2375 const uint8_t *p = buf;
2382 while (nbytes > 0) {
2385 k = write(fd, p, nbytes);
2390 if (errno == EAGAIN && do_poll) {
2391 /* We knowingly ignore any return value here,
2392 * and expect that any error/EOF is reported
2395 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2402 if (k == 0) /* Can't really happen */
2412 int parse_size(const char *t, off_t base, off_t *size) {
2414 /* Soo, sometimes we want to parse IEC binary suffxies, and
2415 * sometimes SI decimal suffixes. This function can parse
2416 * both. Which one is the right way depends on the
2417 * context. Wikipedia suggests that SI is customary for
2418 * hardrware metrics and network speeds, while IEC is
2419 * customary for most data sizes used by software and volatile
2420 * (RAM) memory. Hence be careful which one you pick!
2422 * In either case we use just K, M, G as suffix, and not Ki,
2423 * Mi, Gi or so (as IEC would suggest). That's because that's
2424 * frickin' ugly. But this means you really need to make sure
2425 * to document which base you are parsing when you use this
2430 unsigned long long factor;
2433 static const struct table iec[] = {
2434 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2435 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2436 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2437 { "G", 1024ULL*1024ULL*1024ULL },
2438 { "M", 1024ULL*1024ULL },
2444 static const struct table si[] = {
2445 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2446 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2447 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2448 { "G", 1000ULL*1000ULL*1000ULL },
2449 { "M", 1000ULL*1000ULL },
2455 const struct table *table;
2457 unsigned long long r = 0;
2458 unsigned n_entries, start_pos = 0;
2461 assert(base == 1000 || base == 1024);
2466 n_entries = ELEMENTSOF(si);
2469 n_entries = ELEMENTSOF(iec);
2475 unsigned long long l2;
2481 l = strtoll(p, &e, 10);
2494 if (*e >= '0' && *e <= '9') {
2497 /* strotoull itself would accept space/+/- */
2498 l2 = strtoull(e, &e2, 10);
2500 if (errno == ERANGE)
2503 /* Ignore failure. E.g. 10.M is valid */
2510 e += strspn(e, WHITESPACE);
2512 for (i = start_pos; i < n_entries; i++)
2513 if (startswith(e, table[i].suffix)) {
2514 unsigned long long tmp;
2515 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2517 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2518 if (tmp > ULLONG_MAX - r)
2522 if ((unsigned long long) (off_t) r != r)
2525 p = e + strlen(table[i].suffix);
2541 int make_stdio(int fd) {
2546 r = dup2(fd, STDIN_FILENO);
2547 s = dup2(fd, STDOUT_FILENO);
2548 t = dup2(fd, STDERR_FILENO);
2553 if (r < 0 || s < 0 || t < 0)
2556 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2557 * dup2() was a NOP and the bit hence possibly set. */
2558 fd_cloexec(STDIN_FILENO, false);
2559 fd_cloexec(STDOUT_FILENO, false);
2560 fd_cloexec(STDERR_FILENO, false);
2565 int make_null_stdio(void) {
2568 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2572 return make_stdio(null_fd);
2575 bool is_device_path(const char *path) {
2577 /* Returns true on paths that refer to a device, either in
2578 * sysfs or in /dev */
2581 path_startswith(path, "/dev/") ||
2582 path_startswith(path, "/sys/");
2585 int dir_is_empty(const char *path) {
2586 _cleanup_closedir_ DIR *d;
2597 if (!de && errno != 0)
2603 if (!hidden_file(de->d_name))
2608 char* dirname_malloc(const char *path) {
2609 char *d, *dir, *dir2;
2626 int dev_urandom(void *p, size_t n) {
2627 static int have_syscall = -1;
2629 _cleanup_close_ int fd = -1;
2632 /* Gathers some randomness from the kernel. This call will
2633 * never block, and will always return some data from the
2634 * kernel, regardless if the random pool is fully initialized
2635 * or not. It thus makes no guarantee for the quality of the
2636 * returned entropy, but is good enough for or usual usecases
2637 * of seeding the hash functions for hashtable */
2639 /* Use the getrandom() syscall unless we know we don't have
2640 * it, or when the requested size is too large for it. */
2641 if (have_syscall != 0 || (size_t) (int) n != n) {
2642 r = getrandom(p, n, GRND_NONBLOCK);
2644 have_syscall = true;
2649 if (errno == ENOSYS)
2650 /* we lack the syscall, continue with
2651 * reading from /dev/urandom */
2652 have_syscall = false;
2653 else if (errno == EAGAIN)
2654 /* not enough entropy for now. Let's
2655 * remember to use the syscall the
2656 * next time, again, but also read
2657 * from /dev/urandom for now, which
2658 * doesn't care about the current
2659 * amount of entropy. */
2660 have_syscall = true;
2664 /* too short read? */
2668 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2670 return errno == ENOENT ? -ENOSYS : -errno;
2672 return loop_read_exact(fd, p, n, true);
2675 void initialize_srand(void) {
2676 static bool srand_called = false;
2678 #ifdef HAVE_SYS_AUXV_H
2687 #ifdef HAVE_SYS_AUXV_H
2688 /* The kernel provides us with a bit of entropy in auxv, so
2689 * let's try to make use of that to seed the pseudo-random
2690 * generator. It's better than nothing... */
2692 auxv = (void*) getauxval(AT_RANDOM);
2694 x ^= *(unsigned*) auxv;
2697 x ^= (unsigned) now(CLOCK_REALTIME);
2698 x ^= (unsigned) gettid();
2701 srand_called = true;
2704 void random_bytes(void *p, size_t n) {
2708 r = dev_urandom(p, n);
2712 /* If some idiot made /dev/urandom unavailable to us, he'll
2713 * get a PRNG instead. */
2717 for (q = p; q < (uint8_t*) p + n; q ++)
2721 void rename_process(const char name[8]) {
2724 /* This is a like a poor man's setproctitle(). It changes the
2725 * comm field, argv[0], and also the glibc's internally used
2726 * name of the process. For the first one a limit of 16 chars
2727 * applies, to the second one usually one of 10 (i.e. length
2728 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2729 * "systemd"). If you pass a longer string it will be
2732 prctl(PR_SET_NAME, name);
2734 if (program_invocation_name)
2735 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2737 if (saved_argc > 0) {
2741 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2743 for (i = 1; i < saved_argc; i++) {
2747 memzero(saved_argv[i], strlen(saved_argv[i]));
2752 void sigset_add_many(sigset_t *ss, ...) {
2759 while ((sig = va_arg(ap, int)) > 0)
2760 assert_se(sigaddset(ss, sig) == 0);
2764 int sigprocmask_many(int how, ...) {
2769 assert_se(sigemptyset(&ss) == 0);
2772 while ((sig = va_arg(ap, int)) > 0)
2773 assert_se(sigaddset(&ss, sig) == 0);
2776 if (sigprocmask(how, &ss, NULL) < 0)
2782 char* gethostname_malloc(void) {
2785 assert_se(uname(&u) >= 0);
2787 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2788 return strdup(u.nodename);
2790 return strdup(u.sysname);
2793 bool hostname_is_set(void) {
2796 assert_se(uname(&u) >= 0);
2798 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2801 char *lookup_uid(uid_t uid) {
2804 _cleanup_free_ char *buf = NULL;
2805 struct passwd pwbuf, *pw = NULL;
2807 /* Shortcut things to avoid NSS lookups */
2809 return strdup("root");
2811 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2815 buf = malloc(bufsize);
2819 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2820 return strdup(pw->pw_name);
2822 if (asprintf(&name, UID_FMT, uid) < 0)
2828 char* getlogname_malloc(void) {
2832 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2837 return lookup_uid(uid);
2840 char *getusername_malloc(void) {
2847 return lookup_uid(getuid());
2850 int getttyname_malloc(int fd, char **ret) {
2860 r = ttyname_r(fd, path, sizeof(path));
2865 p = startswith(path, "/dev/");
2866 c = strdup(p ?: path);
2883 int getttyname_harder(int fd, char **r) {
2887 k = getttyname_malloc(fd, &s);
2891 if (streq(s, "tty")) {
2893 return get_ctty(0, NULL, r);
2900 int get_ctty_devnr(pid_t pid, dev_t *d) {
2902 _cleanup_free_ char *line = NULL;
2904 unsigned long ttynr;
2908 p = procfs_file_alloca(pid, "stat");
2909 r = read_one_line_file(p, &line);
2913 p = strrchr(line, ')');
2923 "%*d " /* session */
2928 if (major(ttynr) == 0 && minor(ttynr) == 0)
2937 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2938 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2939 _cleanup_free_ char *s = NULL;
2946 k = get_ctty_devnr(pid, &devnr);
2950 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2952 k = readlink_malloc(fn, &s);
2958 /* This is an ugly hack */
2959 if (major(devnr) == 136) {
2960 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
2963 /* Probably something like the ptys which have no
2964 * symlink in /dev/char. Let's return something
2965 * vaguely useful. */
2972 if (startswith(s, "/dev/"))
2974 else if (startswith(s, "../"))
2991 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2992 _cleanup_closedir_ DIR *d = NULL;
2997 /* This returns the first error we run into, but nevertheless
2998 * tries to go on. This closes the passed fd. */
3004 return errno == ENOENT ? 0 : -errno;
3009 bool is_dir, keep_around;
3016 if (errno != 0 && ret == 0)
3021 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3024 if (de->d_type == DT_UNKNOWN ||
3026 (de->d_type == DT_DIR && root_dev)) {
3027 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3028 if (ret == 0 && errno != ENOENT)
3033 is_dir = S_ISDIR(st.st_mode);
3036 (st.st_uid == 0 || st.st_uid == getuid()) &&
3037 (st.st_mode & S_ISVTX);
3039 is_dir = de->d_type == DT_DIR;
3040 keep_around = false;
3046 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3047 if (root_dev && st.st_dev != root_dev->st_dev)
3050 subdir_fd = openat(fd, de->d_name,
3051 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3052 if (subdir_fd < 0) {
3053 if (ret == 0 && errno != ENOENT)
3058 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3059 if (r < 0 && ret == 0)
3063 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3064 if (ret == 0 && errno != ENOENT)
3068 } else if (!only_dirs && !keep_around) {
3070 if (unlinkat(fd, de->d_name, 0) < 0) {
3071 if (ret == 0 && errno != ENOENT)
3078 _pure_ static int is_temporary_fs(struct statfs *s) {
3081 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
3082 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
3085 int is_fd_on_temporary_fs(int fd) {
3088 if (fstatfs(fd, &s) < 0)
3091 return is_temporary_fs(&s);
3094 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3099 if (fstatfs(fd, &s) < 0) {
3104 /* We refuse to clean disk file systems with this call. This
3105 * is extra paranoia just to be sure we never ever remove
3107 if (!is_temporary_fs(&s)) {
3108 log_error("Attempted to remove disk file system, and we can't allow that.");
3113 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3116 static int file_is_priv_sticky(const char *p) {
3121 if (lstat(p, &st) < 0)
3125 (st.st_uid == 0 || st.st_uid == getuid()) &&
3126 (st.st_mode & S_ISVTX);
3129 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3135 /* We refuse to clean the root file system with this
3136 * call. This is extra paranoia to never cause a really
3137 * seriously broken system. */
3138 if (path_equal(path, "/")) {
3139 log_error("Attempted to remove entire root file system, and we can't allow that.");
3143 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3146 if (errno != ENOTDIR && errno != ELOOP)
3150 if (statfs(path, &s) < 0)
3153 if (!is_temporary_fs(&s)) {
3154 log_error("Attempted to remove disk file system, and we can't allow that.");
3159 if (delete_root && !only_dirs)
3160 if (unlink(path) < 0 && errno != ENOENT)
3167 if (fstatfs(fd, &s) < 0) {
3172 if (!is_temporary_fs(&s)) {
3173 log_error("Attempted to remove disk file system, and we can't allow that.");
3179 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3182 if (honour_sticky && file_is_priv_sticky(path) > 0)
3185 if (rmdir(path) < 0 && errno != ENOENT) {
3194 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3195 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3198 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3199 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3202 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3205 /* Under the assumption that we are running privileged we
3206 * first change the access mode and only then hand out
3207 * ownership to avoid a window where access is too open. */
3209 if (mode != MODE_INVALID)
3210 if (chmod(path, mode) < 0)
3213 if (uid != UID_INVALID || gid != GID_INVALID)
3214 if (chown(path, uid, gid) < 0)
3220 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3223 /* Under the assumption that we are running privileged we
3224 * first change the access mode and only then hand out
3225 * ownership to avoid a window where access is too open. */
3227 if (mode != MODE_INVALID)
3228 if (fchmod(fd, mode) < 0)
3231 if (uid != UID_INVALID || gid != GID_INVALID)
3232 if (fchown(fd, uid, gid) < 0)
3238 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3242 /* Allocates the cpuset in the right size */
3245 if (!(r = CPU_ALLOC(n)))
3248 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3249 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3259 if (errno != EINVAL)
3266 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
3267 static const char status_indent[] = " "; /* "[" STATUS "] " */
3268 _cleanup_free_ char *s = NULL;
3269 _cleanup_close_ int fd = -1;
3270 struct iovec iovec[6] = {};
3272 static bool prev_ephemeral;
3276 /* This is independent of logging, as status messages are
3277 * optional and go exclusively to the console. */
3279 if (vasprintf(&s, format, ap) < 0)
3282 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3295 sl = status ? sizeof(status_indent)-1 : 0;
3301 e = ellipsize(s, emax, 50);
3309 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3310 prev_ephemeral = ephemeral;
3313 if (!isempty(status)) {
3314 IOVEC_SET_STRING(iovec[n++], "[");
3315 IOVEC_SET_STRING(iovec[n++], status);
3316 IOVEC_SET_STRING(iovec[n++], "] ");
3318 IOVEC_SET_STRING(iovec[n++], status_indent);
3321 IOVEC_SET_STRING(iovec[n++], s);
3323 IOVEC_SET_STRING(iovec[n++], "\n");
3325 if (writev(fd, iovec, n) < 0)
3331 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3337 va_start(ap, format);
3338 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3344 char *replace_env(const char *format, char **env) {
3351 const char *e, *word = format;
3356 for (e = format; *e; e ++) {
3367 k = strnappend(r, word, e-word-1);
3377 } else if (*e == '$') {
3378 k = strnappend(r, word, e-word);
3395 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3397 k = strappend(r, t);
3411 k = strnappend(r, word, e-word);
3423 char **replace_env_argv(char **argv, char **env) {
3425 unsigned k = 0, l = 0;
3427 l = strv_length(argv);
3429 ret = new(char*, l+1);
3433 STRV_FOREACH(i, argv) {
3435 /* If $FOO appears as single word, replace it by the split up variable */
3436 if ((*i)[0] == '$' && (*i)[1] != '{') {
3438 char **w, **m = NULL;
3441 e = strv_env_get(env, *i+1);
3445 r = strv_split_quoted(&m, e, UNQUOTE_RELAX);
3457 w = realloc(ret, sizeof(char*) * (l+1));
3467 memcpy(ret + k, m, q * sizeof(char*));
3475 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3476 ret[k] = replace_env(*i, env);
3488 int fd_columns(int fd) {
3489 struct winsize ws = {};
3491 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3500 unsigned columns(void) {
3504 if (_likely_(cached_columns > 0))
3505 return cached_columns;
3508 e = getenv("COLUMNS");
3510 (void) safe_atoi(e, &c);
3513 c = fd_columns(STDOUT_FILENO);
3519 return cached_columns;
3522 int fd_lines(int fd) {
3523 struct winsize ws = {};
3525 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3534 unsigned lines(void) {
3538 if (_likely_(cached_lines > 0))
3539 return cached_lines;
3542 e = getenv("LINES");
3544 (void) safe_atoi(e, &l);
3547 l = fd_lines(STDOUT_FILENO);
3553 return cached_lines;
3556 /* intended to be used as a SIGWINCH sighandler */
3557 void columns_lines_cache_reset(int signum) {
3563 static int cached_on_tty = -1;
3565 if (_unlikely_(cached_on_tty < 0))
3566 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3568 return cached_on_tty;
3571 int files_same(const char *filea, const char *fileb) {
3574 if (stat(filea, &a) < 0)
3577 if (stat(fileb, &b) < 0)
3580 return a.st_dev == b.st_dev &&
3581 a.st_ino == b.st_ino;
3584 int running_in_chroot(void) {
3587 ret = files_same("/proc/1/root", "/");
3594 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3599 assert(percent <= 100);
3600 assert(new_length >= 3);
3602 if (old_length <= 3 || old_length <= new_length)
3603 return strndup(s, old_length);
3605 r = new0(char, new_length+1);
3609 x = (new_length * percent) / 100;
3611 if (x > new_length - 3)
3619 s + old_length - (new_length - x - 3),
3620 new_length - x - 3);
3625 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3629 unsigned k, len, len2;
3632 assert(percent <= 100);
3633 assert(new_length >= 3);
3635 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3636 if (ascii_is_valid(s))
3637 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3639 if (old_length <= 3 || old_length <= new_length)
3640 return strndup(s, old_length);
3642 x = (new_length * percent) / 100;
3644 if (x > new_length - 3)
3648 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3651 c = utf8_encoded_to_unichar(i);
3654 k += unichar_iswide(c) ? 2 : 1;
3657 if (k > x) /* last character was wide and went over quota */
3660 for (j = s + old_length; k < new_length && j > i; ) {
3663 j = utf8_prev_char(j);
3664 c = utf8_encoded_to_unichar(j);
3667 k += unichar_iswide(c) ? 2 : 1;
3671 /* we don't actually need to ellipsize */
3673 return memdup(s, old_length + 1);
3675 /* make space for ellipsis */
3676 j = utf8_next_char(j);
3679 len2 = s + old_length - j;
3680 e = new(char, len + 3 + len2 + 1);
3685 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3686 old_length, new_length, x, len, len2, k);
3690 e[len] = 0xe2; /* tri-dot ellipsis: … */
3694 memcpy(e + len + 3, j, len2 + 1);
3699 char *ellipsize(const char *s, size_t length, unsigned percent) {
3700 return ellipsize_mem(s, strlen(s), length, percent);
3703 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3704 _cleanup_close_ int fd;
3710 mkdir_parents(path, 0755);
3712 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3717 r = fchmod(fd, mode);
3722 if (uid != UID_INVALID || gid != GID_INVALID) {
3723 r = fchown(fd, uid, gid);
3728 if (stamp != USEC_INFINITY) {
3729 struct timespec ts[2];
3731 timespec_store(&ts[0], stamp);
3733 r = futimens(fd, ts);
3735 r = futimens(fd, NULL);
3742 int touch(const char *path) {
3743 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3746 char *unquote(const char *s, const char* quotes) {
3750 /* This is rather stupid, simply removes the heading and
3751 * trailing quotes if there is one. Doesn't care about
3752 * escaping or anything. We should make this smarter one
3759 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3760 return strndup(s+1, l-2);
3765 char *normalize_env_assignment(const char *s) {
3766 _cleanup_free_ char *value = NULL;
3770 eq = strchr(s, '=');
3780 memmove(r, t, strlen(t) + 1);
3785 name = strndupa(s, eq - s);
3786 p = strdupa(eq + 1);
3788 value = unquote(strstrip(p), QUOTES);
3792 return strjoin(strstrip(name), "=", value, NULL);
3795 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3806 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3820 * < 0 : wait_for_terminate() failed to get the state of the
3821 * process, the process was terminated by a signal, or
3822 * failed for an unknown reason.
3823 * >=0 : The process terminated normally, and its exit code is
3826 * That is, success is indicated by a return value of zero, and an
3827 * error is indicated by a non-zero value.
3829 * A warning is emitted if the process terminates abnormally,
3830 * and also if it returns non-zero unless check_exit_code is true.
3832 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
3839 r = wait_for_terminate(pid, &status);
3841 return log_warning_errno(r, "Failed to wait for %s: %m", name);
3843 if (status.si_code == CLD_EXITED) {
3844 if (status.si_status != 0)
3845 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
3846 "%s failed with error code %i.", name, status.si_status);
3848 log_debug("%s succeeded.", name);
3850 return status.si_status;
3851 } else if (status.si_code == CLD_KILLED ||
3852 status.si_code == CLD_DUMPED) {
3854 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3858 log_warning("%s failed due to unknown reason.", name);
3862 noreturn void freeze(void) {
3864 /* Make sure nobody waits for us on a socket anymore */
3865 close_all_fds(NULL, 0);
3873 bool null_or_empty(struct stat *st) {
3876 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3879 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3885 int null_or_empty_path(const char *fn) {
3890 if (stat(fn, &st) < 0)
3893 return null_or_empty(&st);
3896 int null_or_empty_fd(int fd) {
3901 if (fstat(fd, &st) < 0)
3904 return null_or_empty(&st);
3907 DIR *xopendirat(int fd, const char *name, int flags) {
3911 assert(!(flags & O_CREAT));
3913 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3926 int signal_from_string_try_harder(const char *s) {
3930 signo = signal_from_string(s);
3932 if (startswith(s, "SIG"))
3933 return signal_from_string(s+3);
3938 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3939 _cleanup_free_ char *t = NULL, *u = NULL;
3942 u = unquote(tagvalue, "\"\'");
3946 enc_len = strlen(u) * 4 + 1;
3947 t = new(char, enc_len);
3951 if (encode_devnode_name(u, t, enc_len) < 0)
3954 return strjoin("/dev/disk/by-", by, "/", t, NULL);
3957 char *fstab_node_to_udev_node(const char *p) {
3960 if (startswith(p, "LABEL="))
3961 return tag_to_udev_node(p+6, "label");
3963 if (startswith(p, "UUID="))
3964 return tag_to_udev_node(p+5, "uuid");
3966 if (startswith(p, "PARTUUID="))
3967 return tag_to_udev_node(p+9, "partuuid");
3969 if (startswith(p, "PARTLABEL="))
3970 return tag_to_udev_node(p+10, "partlabel");
3975 bool tty_is_vc(const char *tty) {
3978 return vtnr_from_tty(tty) >= 0;
3981 bool tty_is_console(const char *tty) {
3984 if (startswith(tty, "/dev/"))
3987 return streq(tty, "console");
3990 int vtnr_from_tty(const char *tty) {
3995 if (startswith(tty, "/dev/"))
3998 if (!startswith(tty, "tty") )
4001 if (tty[3] < '0' || tty[3] > '9')
4004 r = safe_atoi(tty+3, &i);
4008 if (i < 0 || i > 63)
4014 char *resolve_dev_console(char **active) {
4017 /* Resolve where /dev/console is pointing to, if /sys is actually ours
4018 * (i.e. not read-only-mounted which is a sign for container setups) */
4020 if (path_is_read_only_fs("/sys") > 0)
4023 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
4026 /* If multiple log outputs are configured the last one is what
4027 * /dev/console points to */
4028 tty = strrchr(*active, ' ');
4034 if (streq(tty, "tty0")) {
4037 /* Get the active VC (e.g. tty1) */
4038 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
4040 tty = *active = tmp;
4047 bool tty_is_vc_resolve(const char *tty) {
4048 _cleanup_free_ char *active = NULL;
4052 if (startswith(tty, "/dev/"))
4055 if (streq(tty, "console")) {
4056 tty = resolve_dev_console(&active);
4061 return tty_is_vc(tty);
4064 const char *default_term_for_tty(const char *tty) {
4067 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
4070 bool dirent_is_file(const struct dirent *de) {
4073 if (hidden_file(de->d_name))
4076 if (de->d_type != DT_REG &&
4077 de->d_type != DT_LNK &&
4078 de->d_type != DT_UNKNOWN)
4084 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4087 if (de->d_type != DT_REG &&
4088 de->d_type != DT_LNK &&
4089 de->d_type != DT_UNKNOWN)
4092 if (hidden_file_allow_backup(de->d_name))
4095 return endswith(de->d_name, suffix);
4098 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
4099 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
4100 _cleanup_set_free_free_ Set *seen = NULL;
4103 /* We fork this all off from a child process so that we can
4104 * somewhat cleanly make use of SIGALRM to set a time limit */
4106 reset_all_signal_handlers();
4107 reset_signal_mask();
4109 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4111 pids = hashmap_new(NULL);
4115 seen = set_new(&string_hash_ops);
4119 STRV_FOREACH(directory, directories) {
4120 _cleanup_closedir_ DIR *d;
4123 d = opendir(*directory);
4125 if (errno == ENOENT)
4128 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
4131 FOREACH_DIRENT(de, d, break) {
4132 _cleanup_free_ char *path = NULL;
4136 if (!dirent_is_file(de))
4139 if (set_contains(seen, de->d_name)) {
4140 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
4144 r = set_put_strdup(seen, de->d_name);
4148 path = strjoin(*directory, "/", de->d_name, NULL);
4152 if (null_or_empty_path(path)) {
4153 log_debug("%s is empty (a mask).", path);
4159 log_error_errno(errno, "Failed to fork: %m");
4161 } else if (pid == 0) {
4164 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4174 return log_error_errno(errno, "Failed to execute %s: %m", path);
4177 log_debug("Spawned %s as " PID_FMT ".", path, pid);
4179 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
4186 /* Abort execution of this process after the timout. We simply
4187 * rely on SIGALRM as default action terminating the process,
4188 * and turn on alarm(). */
4190 if (timeout != USEC_INFINITY)
4191 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
4193 while (!hashmap_isempty(pids)) {
4194 _cleanup_free_ char *path = NULL;
4197 pid = PTR_TO_UINT(hashmap_first_key(pids));
4200 path = hashmap_remove(pids, UINT_TO_PTR(pid));
4203 wait_for_terminate_and_warn(path, pid, true);
4209 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
4213 char **dirs = (char**) directories;
4215 assert(!strv_isempty(dirs));
4217 name = basename(dirs[0]);
4218 assert(!isempty(name));
4220 /* Executes all binaries in the directories in parallel and waits
4221 * for them to finish. Optionally a timeout is applied. If a file
4222 * with the same name exists in more than one directory, the
4223 * earliest one wins. */
4225 executor_pid = fork();
4226 if (executor_pid < 0) {
4227 log_error_errno(errno, "Failed to fork: %m");
4230 } else if (executor_pid == 0) {
4231 r = do_execute(dirs, timeout, argv);
4232 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
4235 wait_for_terminate_and_warn(name, executor_pid, true);
4238 int kill_and_sigcont(pid_t pid, int sig) {
4241 r = kill(pid, sig) < 0 ? -errno : 0;
4249 bool nulstr_contains(const char*nulstr, const char *needle) {
4255 NULSTR_FOREACH(i, nulstr)
4256 if (streq(i, needle))
4262 bool plymouth_running(void) {
4263 return access("/run/plymouth/pid", F_OK) >= 0;
4266 char* strshorten(char *s, size_t l) {
4275 static bool hostname_valid_char(char c) {
4277 (c >= 'a' && c <= 'z') ||
4278 (c >= 'A' && c <= 'Z') ||
4279 (c >= '0' && c <= '9') ||
4285 bool hostname_is_valid(const char *s) {
4292 /* Doesn't accept empty hostnames, hostnames with trailing or
4293 * leading dots, and hostnames with multiple dots in a
4294 * sequence. Also ensures that the length stays below
4297 for (p = s, dot = true; *p; p++) {
4304 if (!hostname_valid_char(*p))
4314 if (p-s > HOST_NAME_MAX)
4320 char* hostname_cleanup(char *s, bool lowercase) {
4324 for (p = s, d = s, dot = true; *p; p++) {
4331 } else if (hostname_valid_char(*p)) {
4332 *(d++) = lowercase ? tolower(*p) : *p;
4343 strshorten(s, HOST_NAME_MAX);
4348 bool machine_name_is_valid(const char *s) {
4350 if (!hostname_is_valid(s))
4353 /* Machine names should be useful hostnames, but also be
4354 * useful in unit names, hence we enforce a stricter length
4363 int pipe_eof(int fd) {
4364 struct pollfd pollfd = {
4366 .events = POLLIN|POLLHUP,
4371 r = poll(&pollfd, 1, 0);
4378 return pollfd.revents & POLLHUP;
4381 int fd_wait_for_event(int fd, int event, usec_t t) {
4383 struct pollfd pollfd = {
4391 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
4398 return pollfd.revents;
4401 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4410 r = tempfn_xxxxxx(path, &t);
4414 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
4420 f = fdopen(fd, "we");
4433 int terminal_vhangup_fd(int fd) {
4436 if (ioctl(fd, TIOCVHANGUP) < 0)
4442 int terminal_vhangup(const char *name) {
4443 _cleanup_close_ int fd;
4445 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4449 return terminal_vhangup_fd(fd);
4452 int vt_disallocate(const char *name) {
4456 /* Deallocate the VT if possible. If not possible
4457 * (i.e. because it is the active one), at least clear it
4458 * entirely (including the scrollback buffer) */
4460 if (!startswith(name, "/dev/"))
4463 if (!tty_is_vc(name)) {
4464 /* So this is not a VT. I guess we cannot deallocate
4465 * it then. But let's at least clear the screen */
4467 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4472 "\033[r" /* clear scrolling region */
4473 "\033[H" /* move home */
4474 "\033[2J", /* clear screen */
4481 if (!startswith(name, "/dev/tty"))
4484 r = safe_atou(name+8, &u);
4491 /* Try to deallocate */
4492 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4496 r = ioctl(fd, VT_DISALLOCATE, u);
4505 /* Couldn't deallocate, so let's clear it fully with
4507 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4512 "\033[r" /* clear scrolling region */
4513 "\033[H" /* move home */
4514 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4521 int symlink_atomic(const char *from, const char *to) {
4522 _cleanup_free_ char *t = NULL;
4528 r = tempfn_random(to, &t);
4532 if (symlink(from, t) < 0)
4535 if (rename(t, to) < 0) {
4543 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4544 _cleanup_free_ char *t = NULL;
4549 r = tempfn_random(path, &t);
4553 if (mknod(t, mode, dev) < 0)
4556 if (rename(t, path) < 0) {
4564 int mkfifo_atomic(const char *path, mode_t mode) {
4565 _cleanup_free_ char *t = NULL;
4570 r = tempfn_random(path, &t);
4574 if (mkfifo(t, mode) < 0)
4577 if (rename(t, path) < 0) {
4585 bool display_is_local(const char *display) {
4589 display[0] == ':' &&
4590 display[1] >= '0' &&
4594 int socket_from_display(const char *display, char **path) {
4601 if (!display_is_local(display))
4604 k = strspn(display+1, "0123456789");
4606 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4610 c = stpcpy(f, "/tmp/.X11-unix/X");
4611 memcpy(c, display+1, k);
4620 const char **username,
4621 uid_t *uid, gid_t *gid,
4623 const char **shell) {
4631 /* We enforce some special rules for uid=0: in order to avoid
4632 * NSS lookups for root we hardcode its data. */
4634 if (streq(*username, "root") || streq(*username, "0")) {
4652 if (parse_uid(*username, &u) >= 0) {
4656 /* If there are multiple users with the same id, make
4657 * sure to leave $USER to the configured value instead
4658 * of the first occurrence in the database. However if
4659 * the uid was configured by a numeric uid, then let's
4660 * pick the real username from /etc/passwd. */
4662 *username = p->pw_name;
4665 p = getpwnam(*username);
4669 return errno > 0 ? -errno : -ESRCH;
4681 *shell = p->pw_shell;
4686 char* uid_to_name(uid_t uid) {
4691 return strdup("root");
4695 return strdup(p->pw_name);
4697 if (asprintf(&r, UID_FMT, uid) < 0)
4703 char* gid_to_name(gid_t gid) {
4708 return strdup("root");
4712 return strdup(p->gr_name);
4714 if (asprintf(&r, GID_FMT, gid) < 0)
4720 int get_group_creds(const char **groupname, gid_t *gid) {
4726 /* We enforce some special rules for gid=0: in order to avoid
4727 * NSS lookups for root we hardcode its data. */
4729 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4730 *groupname = "root";
4738 if (parse_gid(*groupname, &id) >= 0) {
4743 *groupname = g->gr_name;
4746 g = getgrnam(*groupname);
4750 return errno > 0 ? -errno : -ESRCH;
4758 int in_gid(gid_t gid) {
4760 int ngroups_max, r, i;
4762 if (getgid() == gid)
4765 if (getegid() == gid)
4768 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4769 assert(ngroups_max > 0);
4771 gids = alloca(sizeof(gid_t) * ngroups_max);
4773 r = getgroups(ngroups_max, gids);
4777 for (i = 0; i < r; i++)
4784 int in_group(const char *name) {
4788 r = get_group_creds(&name, &gid);
4795 int glob_exists(const char *path) {
4796 _cleanup_globfree_ glob_t g = {};
4802 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4804 if (k == GLOB_NOMATCH)
4806 else if (k == GLOB_NOSPACE)
4809 return !strv_isempty(g.gl_pathv);
4811 return errno ? -errno : -EIO;
4814 int glob_extend(char ***strv, const char *path) {
4815 _cleanup_globfree_ glob_t g = {};
4820 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4822 if (k == GLOB_NOMATCH)
4824 else if (k == GLOB_NOSPACE)
4826 else if (k != 0 || strv_isempty(g.gl_pathv))
4827 return errno ? -errno : -EIO;
4829 STRV_FOREACH(p, g.gl_pathv) {
4830 k = strv_extend(strv, *p);
4838 int dirent_ensure_type(DIR *d, struct dirent *de) {
4844 if (de->d_type != DT_UNKNOWN)
4847 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4851 S_ISREG(st.st_mode) ? DT_REG :
4852 S_ISDIR(st.st_mode) ? DT_DIR :
4853 S_ISLNK(st.st_mode) ? DT_LNK :
4854 S_ISFIFO(st.st_mode) ? DT_FIFO :
4855 S_ISSOCK(st.st_mode) ? DT_SOCK :
4856 S_ISCHR(st.st_mode) ? DT_CHR :
4857 S_ISBLK(st.st_mode) ? DT_BLK :
4863 int get_files_in_directory(const char *path, char ***list) {
4864 _cleanup_closedir_ DIR *d = NULL;
4865 size_t bufsize = 0, n = 0;
4866 _cleanup_strv_free_ char **l = NULL;
4870 /* Returns all files in a directory in *list, and the number
4871 * of files as return value. If list is NULL returns only the
4883 if (!de && errno != 0)
4888 dirent_ensure_type(d, de);
4890 if (!dirent_is_file(de))
4894 /* one extra slot is needed for the terminating NULL */
4895 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4898 l[n] = strdup(de->d_name);
4909 l = NULL; /* avoid freeing */
4915 char *strjoin(const char *x, ...) {
4929 t = va_arg(ap, const char *);
4934 if (n > ((size_t) -1) - l) {
4958 t = va_arg(ap, const char *);
4972 bool is_main_thread(void) {
4973 static thread_local int cached = 0;
4975 if (_unlikely_(cached == 0))
4976 cached = getpid() == gettid() ? 1 : -1;
4981 int block_get_whole_disk(dev_t d, dev_t *ret) {
4988 /* If it has a queue this is good enough for us */
4989 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4992 r = access(p, F_OK);
5000 /* If it is a partition find the originating device */
5001 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5004 r = access(p, F_OK);
5010 /* Get parent dev_t */
5011 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5014 r = read_one_line_file(p, &s);
5020 r = sscanf(s, "%u:%u", &m, &n);
5026 /* Only return this if it is really good enough for us. */
5027 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5030 r = access(p, F_OK);
5034 *ret = makedev(m, n);
5041 static const char *const ioprio_class_table[] = {
5042 [IOPRIO_CLASS_NONE] = "none",
5043 [IOPRIO_CLASS_RT] = "realtime",
5044 [IOPRIO_CLASS_BE] = "best-effort",
5045 [IOPRIO_CLASS_IDLE] = "idle"
5048 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
5050 static const char *const sigchld_code_table[] = {
5051 [CLD_EXITED] = "exited",
5052 [CLD_KILLED] = "killed",
5053 [CLD_DUMPED] = "dumped",
5054 [CLD_TRAPPED] = "trapped",
5055 [CLD_STOPPED] = "stopped",
5056 [CLD_CONTINUED] = "continued",
5059 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5061 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5062 [LOG_FAC(LOG_KERN)] = "kern",
5063 [LOG_FAC(LOG_USER)] = "user",
5064 [LOG_FAC(LOG_MAIL)] = "mail",
5065 [LOG_FAC(LOG_DAEMON)] = "daemon",
5066 [LOG_FAC(LOG_AUTH)] = "auth",
5067 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5068 [LOG_FAC(LOG_LPR)] = "lpr",
5069 [LOG_FAC(LOG_NEWS)] = "news",
5070 [LOG_FAC(LOG_UUCP)] = "uucp",
5071 [LOG_FAC(LOG_CRON)] = "cron",
5072 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5073 [LOG_FAC(LOG_FTP)] = "ftp",
5074 [LOG_FAC(LOG_LOCAL0)] = "local0",
5075 [LOG_FAC(LOG_LOCAL1)] = "local1",
5076 [LOG_FAC(LOG_LOCAL2)] = "local2",
5077 [LOG_FAC(LOG_LOCAL3)] = "local3",
5078 [LOG_FAC(LOG_LOCAL4)] = "local4",
5079 [LOG_FAC(LOG_LOCAL5)] = "local5",
5080 [LOG_FAC(LOG_LOCAL6)] = "local6",
5081 [LOG_FAC(LOG_LOCAL7)] = "local7"
5084 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5086 static const char *const log_level_table[] = {
5087 [LOG_EMERG] = "emerg",
5088 [LOG_ALERT] = "alert",
5089 [LOG_CRIT] = "crit",
5091 [LOG_WARNING] = "warning",
5092 [LOG_NOTICE] = "notice",
5093 [LOG_INFO] = "info",
5094 [LOG_DEBUG] = "debug"
5097 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5099 static const char* const sched_policy_table[] = {
5100 [SCHED_OTHER] = "other",
5101 [SCHED_BATCH] = "batch",
5102 [SCHED_IDLE] = "idle",
5103 [SCHED_FIFO] = "fifo",
5107 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5109 static const char* const rlimit_table[_RLIMIT_MAX] = {
5110 [RLIMIT_CPU] = "LimitCPU",
5111 [RLIMIT_FSIZE] = "LimitFSIZE",
5112 [RLIMIT_DATA] = "LimitDATA",
5113 [RLIMIT_STACK] = "LimitSTACK",
5114 [RLIMIT_CORE] = "LimitCORE",
5115 [RLIMIT_RSS] = "LimitRSS",
5116 [RLIMIT_NOFILE] = "LimitNOFILE",
5117 [RLIMIT_AS] = "LimitAS",
5118 [RLIMIT_NPROC] = "LimitNPROC",
5119 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5120 [RLIMIT_LOCKS] = "LimitLOCKS",
5121 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5122 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5123 [RLIMIT_NICE] = "LimitNICE",
5124 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5125 [RLIMIT_RTTIME] = "LimitRTTIME"
5128 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5130 static const char* const ip_tos_table[] = {
5131 [IPTOS_LOWDELAY] = "low-delay",
5132 [IPTOS_THROUGHPUT] = "throughput",
5133 [IPTOS_RELIABILITY] = "reliability",
5134 [IPTOS_LOWCOST] = "low-cost",
5137 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5139 static const char *const __signal_table[] = {
5156 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5167 [SIGVTALRM] = "VTALRM",
5169 [SIGWINCH] = "WINCH",
5175 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5177 const char *signal_to_string(int signo) {
5178 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
5181 name = __signal_to_string(signo);
5185 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5186 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
5188 snprintf(buf, sizeof(buf), "%d", signo);
5193 int signal_from_string(const char *s) {
5198 signo = __signal_from_string(s);
5202 if (startswith(s, "RTMIN+")) {
5206 if (safe_atou(s, &u) >= 0) {
5207 signo = (int) u + offset;
5208 if (signo > 0 && signo < _NSIG)
5214 bool kexec_loaded(void) {
5215 bool loaded = false;
5218 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5226 int prot_from_flags(int flags) {
5228 switch (flags & O_ACCMODE) {
5237 return PROT_READ|PROT_WRITE;
5244 char *format_bytes(char *buf, size_t l, off_t t) {
5247 static const struct {
5251 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5252 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5253 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5254 { "G", 1024ULL*1024ULL*1024ULL },
5255 { "M", 1024ULL*1024ULL },
5259 if (t == (off_t) -1)
5262 for (i = 0; i < ELEMENTSOF(table); i++) {
5264 if (t >= table[i].factor) {
5267 (unsigned long long) (t / table[i].factor),
5268 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5275 snprintf(buf, l, "%lluB", (unsigned long long) t);
5283 void* memdup(const void *p, size_t l) {
5296 int fd_inc_sndbuf(int fd, size_t n) {
5298 socklen_t l = sizeof(value);
5300 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5301 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5304 /* If we have the privileges we will ignore the kernel limit. */
5307 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5308 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5314 int fd_inc_rcvbuf(int fd, size_t n) {
5316 socklen_t l = sizeof(value);
5318 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5319 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5322 /* If we have the privileges we will ignore the kernel limit. */
5325 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5326 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5331 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5332 bool stdout_is_tty, stderr_is_tty;
5333 pid_t parent_pid, agent_pid;
5334 sigset_t ss, saved_ss;
5342 /* Spawns a temporary TTY agent, making sure it goes away when
5345 parent_pid = getpid();
5347 /* First we temporarily block all signals, so that the new
5348 * child has them blocked initially. This way, we can be sure
5349 * that SIGTERMs are not lost we might send to the agent. */
5350 assert_se(sigfillset(&ss) >= 0);
5351 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
5354 if (agent_pid < 0) {
5355 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5359 if (agent_pid != 0) {
5360 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5367 * Make sure the agent goes away when the parent dies */
5368 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5369 _exit(EXIT_FAILURE);
5371 /* Make sure we actually can kill the agent, if we need to, in
5372 * case somebody invoked us from a shell script that trapped
5373 * SIGTERM or so... */
5374 reset_all_signal_handlers();
5375 reset_signal_mask();
5377 /* Check whether our parent died before we were able
5378 * to set the death signal and unblock the signals */
5379 if (getppid() != parent_pid)
5380 _exit(EXIT_SUCCESS);
5382 /* Don't leak fds to the agent */
5383 close_all_fds(except, n_except);
5385 stdout_is_tty = isatty(STDOUT_FILENO);
5386 stderr_is_tty = isatty(STDERR_FILENO);
5388 if (!stdout_is_tty || !stderr_is_tty) {
5391 /* Detach from stdout/stderr. and reopen
5392 * /dev/tty for them. This is important to
5393 * ensure that when systemctl is started via
5394 * popen() or a similar call that expects to
5395 * read EOF we actually do generate EOF and
5396 * not delay this indefinitely by because we
5397 * keep an unused copy of stdin around. */
5398 fd = open("/dev/tty", O_WRONLY);
5400 log_error_errno(errno, "Failed to open /dev/tty: %m");
5401 _exit(EXIT_FAILURE);
5405 dup2(fd, STDOUT_FILENO);
5408 dup2(fd, STDERR_FILENO);
5414 /* Count arguments */
5416 for (n = 0; va_arg(ap, char*); n++)
5421 l = alloca(sizeof(char *) * (n + 1));
5423 /* Fill in arguments */
5425 for (i = 0; i <= n; i++)
5426 l[i] = va_arg(ap, char*);
5430 _exit(EXIT_FAILURE);
5433 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5434 struct rlimit highest, fixed;
5438 if (setrlimit(resource, rlim) >= 0)
5444 /* So we failed to set the desired setrlimit, then let's try
5445 * to get as close as we can */
5446 assert_se(getrlimit(resource, &highest) == 0);
5448 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5449 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5451 if (setrlimit(resource, &fixed) < 0)
5457 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5458 _cleanup_fclose_ FILE *f = NULL;
5469 path = procfs_file_alloca(pid, "environ");
5471 f = fopen(path, "re");
5479 char line[LINE_MAX];
5482 for (i = 0; i < sizeof(line)-1; i++) {
5486 if (_unlikely_(c == EOF)) {
5496 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5497 value = strdup(line + l + 1);
5511 bool http_etag_is_valid(const char *etag) {
5515 if (!endswith(etag, "\""))
5518 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
5524 bool http_url_is_valid(const char *url) {
5530 p = startswith(url, "http://");
5532 p = startswith(url, "https://");
5539 return ascii_is_valid(p);
5542 bool documentation_url_is_valid(const char *url) {
5548 if (http_url_is_valid(url))
5551 p = startswith(url, "file:/");
5553 p = startswith(url, "info:");
5555 p = startswith(url, "man:");
5560 return ascii_is_valid(p);
5563 bool in_initrd(void) {
5564 static int saved = -1;
5570 /* We make two checks here:
5572 * 1. the flag file /etc/initrd-release must exist
5573 * 2. the root file system must be a memory file system
5575 * The second check is extra paranoia, since misdetecting an
5576 * initrd can have bad bad consequences due the initrd
5577 * emptying when transititioning to the main systemd.
5580 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5581 statfs("/", &s) >= 0 &&
5582 is_temporary_fs(&s);
5587 void warn_melody(void) {
5588 _cleanup_close_ int fd = -1;
5590 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5594 /* Yeah, this is synchronous. Kinda sucks. But well... */
5596 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5597 usleep(125*USEC_PER_MSEC);
5599 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5600 usleep(125*USEC_PER_MSEC);
5602 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5603 usleep(125*USEC_PER_MSEC);
5605 ioctl(fd, KIOCSOUND, 0);
5608 int make_console_stdio(void) {
5611 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5613 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5615 return log_error_errno(fd, "Failed to acquire terminal: %m");
5619 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5624 int get_home_dir(char **_h) {
5632 /* Take the user specified one */
5633 e = secure_getenv("HOME");
5634 if (e && path_is_absolute(e)) {
5643 /* Hardcode home directory for root to avoid NSS */
5646 h = strdup("/root");
5654 /* Check the database... */
5658 return errno > 0 ? -errno : -ESRCH;
5660 if (!path_is_absolute(p->pw_dir))
5663 h = strdup(p->pw_dir);
5671 int get_shell(char **_s) {
5679 /* Take the user specified one */
5680 e = getenv("SHELL");
5690 /* Hardcode home directory for root to avoid NSS */
5693 s = strdup("/bin/sh");
5701 /* Check the database... */
5705 return errno > 0 ? -errno : -ESRCH;
5707 if (!path_is_absolute(p->pw_shell))
5710 s = strdup(p->pw_shell);
5718 bool filename_is_valid(const char *p) {
5732 if (strlen(p) > FILENAME_MAX)
5738 bool string_is_safe(const char *p) {
5744 for (t = p; *t; t++) {
5745 if (*t > 0 && *t < ' ')
5748 if (strchr("\\\"\'\0x7f", *t))
5756 * Check if a string contains control characters. If 'ok' is non-NULL
5757 * it may be a string containing additional CCs to be considered OK.
5759 bool string_has_cc(const char *p, const char *ok) {
5764 for (t = p; *t; t++) {
5765 if (ok && strchr(ok, *t))
5768 if (*t > 0 && *t < ' ')
5778 bool path_is_safe(const char *p) {
5783 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5786 if (strlen(p) > PATH_MAX)
5789 /* The following two checks are not really dangerous, but hey, they still are confusing */
5790 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5793 if (strstr(p, "//"))
5799 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5800 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5801 int (*compar) (const void *, const void *, void *), void *arg) {
5810 p = (void *)(((const char *) base) + (idx * size));
5811 comparison = compar(key, p, arg);
5814 else if (comparison > 0)
5822 void init_gettext(void) {
5823 setlocale(LC_ALL, "");
5824 textdomain(GETTEXT_PACKAGE);
5827 bool is_locale_utf8(void) {
5829 static int cached_answer = -1;
5831 if (cached_answer >= 0)
5834 if (!setlocale(LC_ALL, "")) {
5835 cached_answer = true;
5839 set = nl_langinfo(CODESET);
5841 cached_answer = true;
5845 if (streq(set, "UTF-8")) {
5846 cached_answer = true;
5850 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5851 * unset and everything can do to UTF-8 nowadays. */
5852 set = setlocale(LC_CTYPE, NULL);
5854 cached_answer = true;
5858 /* Check result, but ignore the result if C was set
5862 !getenv("LC_ALL") &&
5863 !getenv("LC_CTYPE") &&
5867 return (bool) cached_answer;
5870 const char *draw_special_char(DrawSpecialChar ch) {
5871 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5874 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
5875 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5876 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5877 [DRAW_TREE_SPACE] = " ", /* */
5878 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5879 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5880 [DRAW_ARROW] = "\342\206\222", /* → */
5881 [DRAW_DASH] = "\342\200\223", /* – */
5884 /* ASCII fallback */ {
5885 [DRAW_TREE_VERTICAL] = "| ",
5886 [DRAW_TREE_BRANCH] = "|-",
5887 [DRAW_TREE_RIGHT] = "`-",
5888 [DRAW_TREE_SPACE] = " ",
5889 [DRAW_TRIANGULAR_BULLET] = ">",
5890 [DRAW_BLACK_CIRCLE] = "*",
5891 [DRAW_ARROW] = "->",
5896 return draw_table[!is_locale_utf8()][ch];
5899 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5902 size_t l, old_len, new_len;
5908 old_len = strlen(old_string);
5909 new_len = strlen(new_string);
5922 if (!startswith(f, old_string)) {
5928 nl = l - old_len + new_len;
5929 a = realloc(r, nl + 1);
5937 t = stpcpy(t, new_string);
5949 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5950 const char *i, *begin = NULL;
5955 } state = STATE_OTHER;
5957 size_t osz = 0, isz;
5963 /* Strips ANSI color and replaces TABs by 8 spaces */
5965 isz = _isz ? *_isz : strlen(*ibuf);
5967 f = open_memstream(&obuf, &osz);
5971 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5976 if (i >= *ibuf + isz) /* EOT */
5978 else if (*i == '\x1B')
5979 state = STATE_ESCAPE;
5980 else if (*i == '\t')
5987 if (i >= *ibuf + isz) { /* EOT */
5990 } else if (*i == '[') {
5991 state = STATE_BRACKET;
5996 state = STATE_OTHER;
6003 if (i >= *ibuf + isz || /* EOT */
6004 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
6007 state = STATE_OTHER;
6009 } else if (*i == 'm')
6010 state = STATE_OTHER;
6032 int on_ac_power(void) {
6033 bool found_offline = false, found_online = false;
6034 _cleanup_closedir_ DIR *d = NULL;
6036 d = opendir("/sys/class/power_supply");
6038 return errno == ENOENT ? true : -errno;
6042 _cleanup_close_ int fd = -1, device = -1;
6048 if (!de && errno != 0)
6054 if (hidden_file(de->d_name))
6057 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
6059 if (errno == ENOENT || errno == ENOTDIR)
6065 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
6067 if (errno == ENOENT)
6073 n = read(fd, contents, sizeof(contents));
6077 if (n != 6 || memcmp(contents, "Mains\n", 6))
6081 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
6083 if (errno == ENOENT)
6089 n = read(fd, contents, sizeof(contents));
6093 if (n != 2 || contents[1] != '\n')
6096 if (contents[0] == '1') {
6097 found_online = true;
6099 } else if (contents[0] == '0')
6100 found_offline = true;
6105 return found_online || !found_offline;
6108 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
6115 if (!path_strv_resolve_uniq(search, root))
6118 STRV_FOREACH(i, search) {
6119 _cleanup_free_ char *p = NULL;
6123 p = strjoin(root, *i, "/", path, NULL);
6125 p = strjoin(*i, "/", path, NULL);
6135 if (errno != ENOENT)
6142 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
6143 _cleanup_strv_free_ char **copy = NULL;
6149 if (path_is_absolute(path)) {
6152 f = fopen(path, mode);
6161 copy = strv_copy((char**) search);
6165 return search_and_fopen_internal(path, mode, root, copy, _f);
6168 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
6169 _cleanup_strv_free_ char **s = NULL;
6171 if (path_is_absolute(path)) {
6174 f = fopen(path, mode);
6183 s = strv_split_nulstr(search);
6187 return search_and_fopen_internal(path, mode, root, s, _f);
6190 char *strextend(char **x, ...) {
6197 l = f = *x ? strlen(*x) : 0;
6204 t = va_arg(ap, const char *);
6209 if (n > ((size_t) -1) - l) {
6218 r = realloc(*x, l+1);
6228 t = va_arg(ap, const char *);
6242 char *strrep(const char *s, unsigned n) {
6250 p = r = malloc(l * n + 1);
6254 for (i = 0; i < n; i++)
6261 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
6268 if (*allocated >= need)
6271 newalloc = MAX(need * 2, 64u / size);
6272 a = newalloc * size;
6274 /* check for overflows */
6275 if (a < size * need)
6283 *allocated = newalloc;
6287 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
6296 q = greedy_realloc(p, allocated, need, size);
6300 if (*allocated > prev)
6301 memzero(q + prev * size, (*allocated - prev) * size);
6306 bool id128_is_valid(const char *s) {
6312 /* Simple formatted 128bit hex string */
6314 for (i = 0; i < l; i++) {
6317 if (!(c >= '0' && c <= '9') &&
6318 !(c >= 'a' && c <= 'z') &&
6319 !(c >= 'A' && c <= 'Z'))
6323 } else if (l == 36) {
6325 /* Formatted UUID */
6327 for (i = 0; i < l; i++) {
6330 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6334 if (!(c >= '0' && c <= '9') &&
6335 !(c >= 'a' && c <= 'z') &&
6336 !(c >= 'A' && c <= 'Z'))
6347 int split_pair(const char *s, const char *sep, char **l, char **r) {
6362 a = strndup(s, x - s);
6366 b = strdup(x + strlen(sep));
6378 int shall_restore_state(void) {
6379 _cleanup_free_ char *value = NULL;
6382 r = get_proc_cmdline_key("systemd.restore_state=", &value);
6388 return parse_boolean(value) != 0;
6391 int proc_cmdline(char **ret) {
6394 if (detect_container(NULL) > 0)
6395 return get_process_cmdline(1, 0, false, ret);
6397 return read_one_line_file("/proc/cmdline", ret);
6400 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6401 _cleanup_free_ char *line = NULL;
6407 r = proc_cmdline(&line);
6413 _cleanup_free_ char *word = NULL;
6416 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
6422 /* Filter out arguments that are intended only for the
6424 if (!in_initrd() && startswith(word, "rd."))
6427 value = strchr(word, '=');
6431 r = parse_item(word, value);
6439 int get_proc_cmdline_key(const char *key, char **value) {
6440 _cleanup_free_ char *line = NULL, *ret = NULL;
6447 r = proc_cmdline(&line);
6453 _cleanup_free_ char *word = NULL;
6456 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
6462 /* Filter out arguments that are intended only for the
6464 if (!in_initrd() && startswith(word, "rd."))
6468 e = startswith(word, key);
6472 r = free_and_strdup(&ret, e);
6478 if (streq(word, key))
6492 int container_get_leader(const char *machine, pid_t *pid) {
6493 _cleanup_free_ char *s = NULL, *class = NULL;
6501 p = strjoina("/run/systemd/machines/", machine);
6502 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6510 if (!streq_ptr(class, "container"))
6513 r = parse_pid(s, &leader);
6523 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6524 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
6532 mntns = procfs_file_alloca(pid, "ns/mnt");
6533 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6541 pidns = procfs_file_alloca(pid, "ns/pid");
6542 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6550 netns = procfs_file_alloca(pid, "ns/net");
6551 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6559 root = procfs_file_alloca(pid, "root");
6560 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6566 *pidns_fd = pidnsfd;
6569 *mntns_fd = mntnsfd;
6572 *netns_fd = netnsfd;
6577 pidnsfd = mntnsfd = netnsfd = -1;
6582 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
6585 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6589 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6593 if (setns(netns_fd, CLONE_NEWNET) < 0)
6597 if (fchdir(root_fd) < 0)
6600 if (chroot(".") < 0)
6604 if (setresgid(0, 0, 0) < 0)
6607 if (setgroups(0, NULL) < 0)
6610 if (setresuid(0, 0, 0) < 0)
6616 bool pid_is_unwaited(pid_t pid) {
6617 /* Checks whether a PID is still valid at all, including a zombie */
6622 if (kill(pid, 0) >= 0)
6625 return errno != ESRCH;
6628 bool pid_is_alive(pid_t pid) {
6631 /* Checks whether a PID is still valid and not a zombie */
6636 r = get_process_state(pid);
6637 if (r == -ENOENT || r == 'Z')
6643 int getpeercred(int fd, struct ucred *ucred) {
6644 socklen_t n = sizeof(struct ucred);
6651 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6655 if (n != sizeof(struct ucred))
6658 /* Check if the data is actually useful and not suppressed due
6659 * to namespacing issues */
6662 if (u.uid == UID_INVALID)
6664 if (u.gid == GID_INVALID)
6671 int getpeersec(int fd, char **ret) {
6683 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6687 if (errno != ERANGE)
6694 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6710 /* This is much like like mkostemp() but is subject to umask(). */
6711 int mkostemp_safe(char *pattern, int flags) {
6712 _cleanup_umask_ mode_t u;
6719 fd = mkostemp(pattern, flags);
6726 int open_tmpfile(const char *path, int flags) {
6733 /* Try O_TMPFILE first, if it is supported */
6734 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6739 /* Fall back to unguessable name + unlinking */
6740 p = strjoina(path, "/systemd-tmp-XXXXXX");
6742 fd = mkostemp_safe(p, flags);
6750 int fd_warn_permissions(const char *path, int fd) {
6753 if (fstat(fd, &st) < 0)
6756 if (st.st_mode & 0111)
6757 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6759 if (st.st_mode & 0002)
6760 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6762 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6763 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);
6768 unsigned long personality_from_string(const char *p) {
6770 /* Parse a personality specifier. We introduce our own
6771 * identifiers that indicate specific ABIs, rather than just
6772 * hints regarding the register size, since we want to keep
6773 * things open for multiple locally supported ABIs for the
6774 * same register size. We try to reuse the ABI identifiers
6775 * used by libseccomp. */
6777 #if defined(__x86_64__)
6779 if (streq(p, "x86"))
6782 if (streq(p, "x86-64"))
6785 #elif defined(__i386__)
6787 if (streq(p, "x86"))
6791 /* personality(7) documents that 0xffffffffUL is used for
6792 * querying the current personality, hence let's use that here
6793 * as error indicator. */
6794 return 0xffffffffUL;
6797 const char* personality_to_string(unsigned long p) {
6799 #if defined(__x86_64__)
6801 if (p == PER_LINUX32)
6807 #elif defined(__i386__)
6816 uint64_t physical_memory(void) {
6819 /* We return this as uint64_t in case we are running as 32bit
6820 * process on a 64bit kernel with huge amounts of memory */
6822 mem = sysconf(_SC_PHYS_PAGES);
6825 return (uint64_t) mem * (uint64_t) page_size();
6828 void hexdump(FILE *f, const void *p, size_t s) {
6829 const uint8_t *b = p;
6832 assert(s == 0 || b);
6837 fprintf(f, "%04x ", n);
6839 for (i = 0; i < 16; i++) {
6844 fprintf(f, "%02x ", b[i]);
6852 for (i = 0; i < 16; i++) {
6857 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6871 int update_reboot_param_file(const char *param) {
6876 r = write_string_file(REBOOT_PARAM_FILE, param);
6878 log_error("Failed to write reboot param to "
6879 REBOOT_PARAM_FILE": %s", strerror(-r));
6881 unlink(REBOOT_PARAM_FILE);
6886 int umount_recursive(const char *prefix, int flags) {
6890 /* Try to umount everything recursively below a
6891 * directory. Also, take care of stacked mounts, and keep
6892 * unmounting them until they are gone. */
6895 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6900 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6901 if (!proc_self_mountinfo)
6905 _cleanup_free_ char *path = NULL, *p = NULL;
6908 k = fscanf(proc_self_mountinfo,
6909 "%*s " /* (1) mount id */
6910 "%*s " /* (2) parent id */
6911 "%*s " /* (3) major:minor */
6912 "%*s " /* (4) root */
6913 "%ms " /* (5) mount point */
6914 "%*s" /* (6) mount options */
6915 "%*[^-]" /* (7) optional fields */
6916 "- " /* (8) separator */
6917 "%*s " /* (9) file system type */
6918 "%*s" /* (10) mount source */
6919 "%*s" /* (11) mount options 2 */
6920 "%*[^\n]", /* some rubbish at the end */
6929 p = cunescape(path);
6933 if (!path_startswith(p, prefix))
6936 if (umount2(p, flags) < 0) {
6952 static int get_mount_flags(const char *path, unsigned long *flags) {
6955 if (statvfs(path, &buf) < 0)
6957 *flags = buf.f_flag;
6961 int bind_remount_recursive(const char *prefix, bool ro) {
6962 _cleanup_set_free_free_ Set *done = NULL;
6963 _cleanup_free_ char *cleaned = NULL;
6966 /* Recursively remount a directory (and all its submounts)
6967 * read-only or read-write. If the directory is already
6968 * mounted, we reuse the mount and simply mark it
6969 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6970 * operation). If it isn't we first make it one. Afterwards we
6971 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6972 * submounts we can access, too. When mounts are stacked on
6973 * the same mount point we only care for each individual
6974 * "top-level" mount on each point, as we cannot
6975 * influence/access the underlying mounts anyway. We do not
6976 * have any effect on future submounts that might get
6977 * propagated, they migt be writable. This includes future
6978 * submounts that have been triggered via autofs. */
6980 cleaned = strdup(prefix);
6984 path_kill_slashes(cleaned);
6986 done = set_new(&string_hash_ops);
6991 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6992 _cleanup_set_free_free_ Set *todo = NULL;
6993 bool top_autofs = false;
6995 unsigned long orig_flags;
6997 todo = set_new(&string_hash_ops);
7001 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
7002 if (!proc_self_mountinfo)
7006 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
7009 k = fscanf(proc_self_mountinfo,
7010 "%*s " /* (1) mount id */
7011 "%*s " /* (2) parent id */
7012 "%*s " /* (3) major:minor */
7013 "%*s " /* (4) root */
7014 "%ms " /* (5) mount point */
7015 "%*s" /* (6) mount options (superblock) */
7016 "%*[^-]" /* (7) optional fields */
7017 "- " /* (8) separator */
7018 "%ms " /* (9) file system type */
7019 "%*s" /* (10) mount source */
7020 "%*s" /* (11) mount options (bind mount) */
7021 "%*[^\n]", /* some rubbish at the end */
7031 p = cunescape(path);
7035 /* Let's ignore autofs mounts. If they aren't
7036 * triggered yet, we want to avoid triggering
7037 * them, as we don't make any guarantees for
7038 * future submounts anyway. If they are
7039 * already triggered, then we will find
7040 * another entry for this. */
7041 if (streq(type, "autofs")) {
7042 top_autofs = top_autofs || path_equal(cleaned, p);
7046 if (path_startswith(p, cleaned) &&
7047 !set_contains(done, p)) {
7049 r = set_consume(todo, p);
7059 /* If we have no submounts to process anymore and if
7060 * the root is either already done, or an autofs, we
7062 if (set_isempty(todo) &&
7063 (top_autofs || set_contains(done, cleaned)))
7066 if (!set_contains(done, cleaned) &&
7067 !set_contains(todo, cleaned)) {
7068 /* The prefix directory itself is not yet a
7069 * mount, make it one. */
7070 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
7074 (void) get_mount_flags(cleaned, &orig_flags);
7075 orig_flags &= ~MS_RDONLY;
7077 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
7080 x = strdup(cleaned);
7084 r = set_consume(done, x);
7089 while ((x = set_steal_first(todo))) {
7091 r = set_consume(done, x);
7097 /* Try to reuse the original flag set, but
7098 * don't care for errors, in case of
7099 * obstructed mounts */
7101 (void) get_mount_flags(x, &orig_flags);
7102 orig_flags &= ~MS_RDONLY;
7104 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
7106 /* Deal with mount points that are
7107 * obstructed by a later mount */
7109 if (errno != ENOENT)
7117 int fflush_and_check(FILE *f) {
7124 return errno ? -errno : -EIO;
7129 int tempfn_xxxxxx(const char *p, char **ret) {
7141 * /foo/bar/.#waldoXXXXXX
7145 if (!filename_is_valid(fn))
7148 t = new(char, strlen(p) + 2 + 6 + 1);
7152 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
7154 *ret = path_kill_slashes(t);
7158 int tempfn_random(const char *p, char **ret) {
7172 * /foo/bar/.#waldobaa2a261115984a9
7176 if (!filename_is_valid(fn))
7179 t = new(char, strlen(p) + 2 + 16 + 1);
7183 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
7186 for (i = 0; i < 16; i++) {
7187 *(x++) = hexchar(u & 0xF);
7193 *ret = path_kill_slashes(t);
7197 int tempfn_random_child(const char *p, char **ret) {
7208 * /foo/bar/waldo/.#3c2b6219aa75d7d0
7211 t = new(char, strlen(p) + 3 + 16 + 1);
7215 x = stpcpy(stpcpy(t, p), "/.#");
7218 for (i = 0; i < 16; i++) {
7219 *(x++) = hexchar(u & 0xF);
7225 *ret = path_kill_slashes(t);
7229 /* make sure the hostname is not "localhost" */
7230 bool is_localhost(const char *hostname) {
7233 /* This tries to identify local host and domain names
7234 * described in RFC6761 plus the redhatism of .localdomain */
7236 return streq(hostname, "localhost") ||
7237 streq(hostname, "localhost.") ||
7238 streq(hostname, "localdomain.") ||
7239 streq(hostname, "localdomain") ||
7240 endswith(hostname, ".localhost") ||
7241 endswith(hostname, ".localhost.") ||
7242 endswith(hostname, ".localdomain") ||
7243 endswith(hostname, ".localdomain.");
7246 int take_password_lock(const char *root) {
7248 struct flock flock = {
7250 .l_whence = SEEK_SET,
7258 /* This is roughly the same as lckpwdf(), but not as awful. We
7259 * don't want to use alarm() and signals, hence we implement
7260 * our own trivial version of this.
7262 * Note that shadow-utils also takes per-database locks in
7263 * addition to lckpwdf(). However, we don't given that they
7264 * are redundant as they they invoke lckpwdf() first and keep
7265 * it during everything they do. The per-database locks are
7266 * awfully racy, and thus we just won't do them. */
7269 path = strjoina(root, "/etc/.pwd.lock");
7271 path = "/etc/.pwd.lock";
7273 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
7277 r = fcntl(fd, F_SETLKW, &flock);
7286 int is_symlink(const char *path) {
7289 if (lstat(path, &info) < 0)
7292 return !!S_ISLNK(info.st_mode);
7295 int is_dir(const char* path, bool follow) {
7300 r = stat(path, &st);
7302 r = lstat(path, &st);
7306 return !!S_ISDIR(st.st_mode);
7309 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
7310 _cleanup_free_ char *s = NULL;
7311 size_t allocated = 0, sz = 0;
7319 SINGLE_QUOTE_ESCAPE,
7321 DOUBLE_QUOTE_ESCAPE,
7329 /* Parses the first word of a string, and returns it in
7330 * *ret. Removes all quotes in the process. When parsing fails
7331 * (because of an uneven number of quotes or similar), leaves
7332 * the pointer *p at the first invalid character. */
7342 else if (strchr(WHITESPACE, c))
7352 state = SINGLE_QUOTE;
7354 state = VALUE_ESCAPE;
7356 state = DOUBLE_QUOTE;
7357 else if (strchr(WHITESPACE, c))
7360 if (!GREEDY_REALLOC(s, allocated, sz+2))
7370 if (flags & UNQUOTE_RELAX)
7375 if (!GREEDY_REALLOC(s, allocated, sz+2))
7378 if (flags & UNQUOTE_CUNESCAPE) {
7379 r = cunescape_one(*p, (size_t) -1, &c);
7393 if (flags & UNQUOTE_RELAX)
7396 } else if (c == '\'')
7399 state = SINGLE_QUOTE_ESCAPE;
7401 if (!GREEDY_REALLOC(s, allocated, sz+2))
7409 case SINGLE_QUOTE_ESCAPE:
7411 if (flags & UNQUOTE_RELAX)
7416 if (!GREEDY_REALLOC(s, allocated, sz+2))
7419 if (flags & UNQUOTE_CUNESCAPE) {
7420 r = cunescape_one(*p, (size_t) -1, &c);
7428 state = SINGLE_QUOTE;
7437 state = DOUBLE_QUOTE_ESCAPE;
7439 if (!GREEDY_REALLOC(s, allocated, sz+2))
7447 case DOUBLE_QUOTE_ESCAPE:
7449 if (flags & UNQUOTE_RELAX)
7454 if (!GREEDY_REALLOC(s, allocated, sz+2))
7457 if (flags & UNQUOTE_CUNESCAPE) {
7458 r = cunescape_one(*p, (size_t) -1, &c);
7466 state = DOUBLE_QUOTE;
7472 if (!strchr(WHITESPACE, c))
7494 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
7499 /* Parses a number of words from a string, stripping any
7500 * quotes if necessary. */
7504 /* Count how many words are expected */
7505 va_start(ap, flags);
7507 if (!va_arg(ap, char **))
7516 /* Read all words into a temporary array */
7517 l = newa0(char*, n);
7518 for (c = 0; c < n; c++) {
7520 r = unquote_first_word(p, &l[c], flags);
7524 for (j = 0; j < c; j++)
7534 /* If we managed to parse all words, return them in the passed
7536 va_start(ap, flags);
7537 for (i = 0; i < n; i++) {
7540 v = va_arg(ap, char **);
7550 int free_and_strdup(char **p, const char *s) {
7555 /* Replaces a string pointer with an strdup()ed new string,
7556 * possibly freeing the old one. */
7571 int sethostname_idempotent(const char *s) {
7573 char buf[HOST_NAME_MAX + 1] = {};
7577 r = gethostname(buf, sizeof(buf));
7584 r = sethostname(s, strlen(s));
7591 int ptsname_malloc(int fd, char **ret) {
7604 if (ptsname_r(fd, c, l) == 0) {
7608 if (errno != ERANGE) {
7618 int openpt_in_namespace(pid_t pid, int flags) {
7619 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7620 _cleanup_close_pair_ int pair[2] = { -1, -1 };
7622 struct cmsghdr cmsghdr;
7623 uint8_t buf[CMSG_SPACE(sizeof(int))];
7625 struct msghdr mh = {
7626 .msg_control = &control,
7627 .msg_controllen = sizeof(control),
7629 struct cmsghdr *cmsg;
7636 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7640 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7650 pair[0] = safe_close(pair[0]);
7652 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7654 _exit(EXIT_FAILURE);
7656 master = posix_openpt(flags);
7658 _exit(EXIT_FAILURE);
7660 cmsg = CMSG_FIRSTHDR(&mh);
7661 cmsg->cmsg_level = SOL_SOCKET;
7662 cmsg->cmsg_type = SCM_RIGHTS;
7663 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7664 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7666 mh.msg_controllen = cmsg->cmsg_len;
7668 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7669 _exit(EXIT_FAILURE);
7671 _exit(EXIT_SUCCESS);
7674 pair[1] = safe_close(pair[1]);
7676 r = wait_for_terminate(child, &si);
7679 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7682 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7685 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7686 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7690 fds = (int*) CMSG_DATA(cmsg);
7691 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7694 close_many(fds, n_fds);
7704 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7705 _cleanup_close_ int fd = -1;
7708 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7710 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7714 l = fgetxattr(fd, attribute, value, size);
7721 static int parse_crtime(le64_t le, usec_t *usec) {
7727 if (u == 0 || u == (uint64_t) -1)
7734 int fd_getcrtime(int fd, usec_t *usec) {
7741 /* Until Linux gets a real concept of birthtime/creation time,
7742 * let's fake one with xattrs */
7744 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7747 if (n != sizeof(le))
7750 return parse_crtime(le, usec);
7753 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7757 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7760 if (n != sizeof(le))
7763 return parse_crtime(le, usec);
7766 int path_getcrtime(const char *p, usec_t *usec) {
7773 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7776 if (n != sizeof(le))
7779 return parse_crtime(le, usec);
7782 int fd_setcrtime(int fd, usec_t usec) {
7788 usec = now(CLOCK_REALTIME);
7790 le = htole64((uint64_t) usec);
7791 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7797 int chattr_fd(int fd, bool b, unsigned mask) {
7798 unsigned old_attr, new_attr;
7805 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7809 new_attr = old_attr | mask;
7811 new_attr = old_attr & ~mask;
7813 if (new_attr == old_attr)
7816 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7822 int chattr_path(const char *p, bool b, unsigned mask) {
7823 _cleanup_close_ int fd = -1;
7830 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7834 return chattr_fd(fd, b, mask);
7837 int change_attr_fd(int fd, unsigned value, unsigned mask) {
7838 unsigned old_attr, new_attr;
7845 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7848 new_attr = (old_attr & ~mask) |(value & mask);
7850 if (new_attr == old_attr)
7853 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7859 int read_attr_fd(int fd, unsigned *ret) {
7862 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
7868 int read_attr_path(const char *p, unsigned *ret) {
7869 _cleanup_close_ int fd = -1;
7874 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7878 return read_attr_fd(fd, ret);
7881 int make_lock_file(const char *p, int operation, LockFile *ret) {
7882 _cleanup_close_ int fd = -1;
7883 _cleanup_free_ char *t = NULL;
7887 * We use UNPOSIX locks if they are available. They have nice
7888 * semantics, and are mostly compatible with NFS. However,
7889 * they are only available on new kernels. When we detect we
7890 * are running on an older kernel, then we fall back to good
7891 * old BSD locks. They also have nice semantics, but are
7892 * slightly problematic on NFS, where they are upgraded to
7893 * POSIX locks, even though locally they are orthogonal to
7903 .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
7904 .l_whence = SEEK_SET,
7908 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
7912 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
7915 /* If the kernel is too old, use good old BSD locks */
7916 if (errno == EINVAL)
7917 r = flock(fd, operation);
7920 return errno == EAGAIN ? -EBUSY : -errno;
7923 /* If we acquired the lock, let's check if the file
7924 * still exists in the file system. If not, then the
7925 * previous exclusive owner removed it and then closed
7926 * it. In such a case our acquired lock is worthless,
7927 * hence try again. */
7932 if (st.st_nlink > 0)
7935 fd = safe_close(fd);
7940 ret->operation = operation;
7948 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
7956 if (!filename_is_valid(fn))
7959 t = newa(char, strlen(p) + 2 + 4 + 1);
7960 stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
7962 return make_lock_file(t, operation, ret);
7965 void release_lock_file(LockFile *f) {
7973 /* If we are the exclusive owner we can safely delete
7974 * the lock file itself. If we are not the exclusive
7975 * owner, we can try becoming it. */
7978 (f->operation & ~LOCK_NB) == LOCK_SH) {
7979 static const struct flock fl = {
7981 .l_whence = SEEK_SET,
7984 r = fcntl(f->fd, F_OFD_SETLK, &fl);
7985 if (r < 0 && errno == EINVAL)
7986 r = flock(f->fd, LOCK_EX|LOCK_NB);
7989 f->operation = LOCK_EX|LOCK_NB;
7992 if ((f->operation & ~LOCK_NB) == LOCK_EX)
7993 unlink_noerrno(f->path);
7999 f->fd = safe_close(f->fd);
8003 static size_t nul_length(const uint8_t *p, size_t sz) {
8018 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
8019 const uint8_t *q, *w, *e;
8027 n = nul_length(q, e - q);
8029 /* If there are more than the specified run length of
8030 * NUL bytes, or if this is the beginning or the end
8031 * of the buffer, then seek instead of write */
8032 if ((n > run_length) ||
8033 (n > 0 && q == p) ||
8034 (n > 0 && q + n >= e)) {
8036 l = write(fd, w, q - w);
8043 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
8055 l = write(fd, w, q - w);
8062 return q - (const uint8_t*) p;
8065 void sigkill_wait(pid_t *pid) {
8071 if (kill(*pid, SIGKILL) > 0)
8072 (void) wait_for_terminate(*pid, NULL);
8075 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
8076 int a = 0, b = 0, c = 0;
8086 if (!strchr(*p, '>'))
8089 if ((*p)[2] == '>') {
8090 c = undecchar((*p)[1]);
8092 } else if ((*p)[3] == '>') {
8093 b = undecchar((*p)[1]);
8094 c = undecchar((*p)[2]);
8096 } else if ((*p)[4] == '>') {
8097 a = undecchar((*p)[1]);
8098 b = undecchar((*p)[2]);
8099 c = undecchar((*p)[3]);
8104 if (a < 0 || b < 0 || c < 0 ||
8105 (!with_facility && (a || b || c > 7)))
8109 *priority = a*100 + b*10 + c;
8111 *priority = (*priority & LOG_FACMASK) | c;
8117 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
8123 for (i = 0; i < len; ++i)
8124 if (streq_ptr(table[i], key))
8130 void cmsg_close_all(struct msghdr *mh) {
8131 struct cmsghdr *cmsg;
8135 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
8136 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
8137 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
8140 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
8144 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
8148 /* Even though renameat2() exists since Linux 3.15, btrfs added
8149 * support for it later. If it is not implemented, fallback to another
8151 if (errno != EINVAL)
8154 /* The link()/unlink() fallback does not work on directories. But
8155 * renameat() without RENAME_NOREPLACE gives the same semantics on
8156 * directories, except when newpath is an *empty* directory. This is
8158 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
8159 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
8160 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
8161 return ret >= 0 ? 0 : -errno;
8164 /* If it is not a directory, use the link()/unlink() fallback. */
8165 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
8169 ret = unlinkat(olddirfd, oldpath, 0);
8171 /* backup errno before the following unlinkat() alters it */
8173 (void) unlinkat(newdirfd, newpath, 0);