1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
53 #include <sys/capability.h>
55 #include <linux/rtc.h>
59 #include <sys/statvfs.h>
68 #include "exit-status.h"
72 char **saved_argv = NULL;
74 size_t page_size(void) {
75 static __thread size_t pgsz = 0;
78 if (_likely_(pgsz > 0))
81 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
88 bool streq_ptr(const char *a, const char *b) {
90 /* Like streq(), but tries to make sense of NULL pointers */
101 usec_t now(clockid_t clock_id) {
104 assert_se(clock_gettime(clock_id, &ts) == 0);
106 return timespec_load(&ts);
109 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
112 ts->realtime = now(CLOCK_REALTIME);
113 ts->monotonic = now(CLOCK_MONOTONIC);
118 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
127 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
129 ts->monotonic = now(CLOCK_MONOTONIC);
131 if ((int64_t) ts->monotonic > delta)
132 ts->monotonic -= delta;
140 usec_t timespec_load(const struct timespec *ts) {
144 (usec_t) ts->tv_sec * USEC_PER_SEC +
145 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
148 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
151 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
152 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
157 usec_t timeval_load(const struct timeval *tv) {
161 (usec_t) tv->tv_sec * USEC_PER_SEC +
162 (usec_t) tv->tv_usec;
165 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
168 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
169 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
174 bool endswith(const char *s, const char *postfix) {
181 pl = strlen(postfix);
189 return memcmp(s + sl - pl, postfix, pl) == 0;
192 bool startswith(const char *s, const char *prefix) {
207 return memcmp(s, prefix, pl) == 0;
210 bool startswith_no_case(const char *s, const char *prefix) {
226 for(i = 0; i < pl; ++i) {
227 if (tolower(s[i]) != tolower(prefix[i]))
234 bool first_word(const char *s, const char *word) {
249 if (memcmp(s, word, wl) != 0)
253 strchr(WHITESPACE, s[wl]);
256 int close_nointr(int fd) {
271 void close_nointr_nofail(int fd) {
272 int saved_errno = errno;
274 /* like close_nointr() but cannot fail, and guarantees errno
277 assert_se(close_nointr(fd) == 0);
282 void close_many(const int fds[], unsigned n_fd) {
285 for (i = 0; i < n_fd; i++)
286 close_nointr_nofail(fds[i]);
289 int parse_boolean(const char *v) {
292 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
294 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
300 int parse_pid(const char *s, pid_t* ret_pid) {
301 unsigned long ul = 0;
308 if ((r = safe_atolu(s, &ul)) < 0)
313 if ((unsigned long) pid != ul)
323 int parse_uid(const char *s, uid_t* ret_uid) {
324 unsigned long ul = 0;
331 if ((r = safe_atolu(s, &ul)) < 0)
336 if ((unsigned long) uid != ul)
343 int safe_atou(const char *s, unsigned *ret_u) {
351 l = strtoul(s, &x, 0);
353 if (!x || *x || errno)
354 return errno ? -errno : -EINVAL;
356 if ((unsigned long) (unsigned) l != l)
359 *ret_u = (unsigned) l;
363 int safe_atoi(const char *s, int *ret_i) {
371 l = strtol(s, &x, 0);
373 if (!x || *x || errno)
374 return errno ? -errno : -EINVAL;
376 if ((long) (int) l != l)
383 int safe_atollu(const char *s, long long unsigned *ret_llu) {
385 unsigned long long l;
391 l = strtoull(s, &x, 0);
393 if (!x || *x || errno)
394 return errno ? -errno : -EINVAL;
400 int safe_atolli(const char *s, long long int *ret_lli) {
408 l = strtoll(s, &x, 0);
410 if (!x || *x || errno)
411 return errno ? -errno : -EINVAL;
417 /* Split a string into words. */
418 char *split(const char *c, size_t *l, const char *separator, char **state) {
421 current = *state ? *state : (char*) c;
423 if (!*current || *c == 0)
426 current += strspn(current, separator);
427 *l = strcspn(current, separator);
430 return (char*) current;
433 /* Split a string into words, but consider strings enclosed in '' and
434 * "" as words even if they include spaces. */
435 char *split_quoted(const char *c, size_t *l, char **state) {
437 bool escaped = false;
439 current = *state ? *state : (char*) c;
441 if (!*current || *c == 0)
444 current += strspn(current, WHITESPACE);
446 if (*current == '\'') {
449 for (e = current; *e; e++) {
459 *state = *e == 0 ? e : e+1;
460 } else if (*current == '\"') {
463 for (e = current; *e; e++) {
473 *state = *e == 0 ? e : e+1;
475 for (e = current; *e; e++) {
480 else if (strchr(WHITESPACE, *e))
487 return (char*) current;
490 char **split_path_and_make_absolute(const char *p) {
494 if (!(l = strv_split(p, ":")))
497 if (!strv_path_make_absolute_cwd(l)) {
505 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
508 char fn[PATH_MAX], line[LINE_MAX], *p;
514 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
517 if (!(f = fopen(fn, "re")))
520 if (!(fgets(line, sizeof(line), f))) {
521 r = feof(f) ? -EIO : -errno;
528 /* Let's skip the pid and comm fields. The latter is enclosed
529 * in () but does not escape any () in its value, so let's
530 * skip over it manually */
532 if (!(p = strrchr(line, ')')))
543 if ((long unsigned) (pid_t) ppid != ppid)
546 *_ppid = (pid_t) ppid;
551 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
554 char fn[PATH_MAX], line[LINE_MAX], *p;
559 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
562 if (!(f = fopen(fn, "re")))
565 if (!(fgets(line, sizeof(line), f))) {
566 r = feof(f) ? -EIO : -errno;
573 /* Let's skip the pid and comm fields. The latter is enclosed
574 * in () but does not escape any () in its value, so let's
575 * skip over it manually */
577 if (!(p = strrchr(line, ')')))
598 "%*d " /* priority */
600 "%*d " /* num_threads */
601 "%*d " /* itrealvalue */
602 "%llu " /* starttime */,
609 int write_one_line_file(const char *fn, const char *line) {
616 if (!(f = fopen(fn, "we")))
620 if (fputs(line, f) < 0) {
625 if (!endswith(line, "\n"))
643 int fchmod_umask(int fd, mode_t m) {
648 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
654 int write_one_line_file_atomic(const char *fn, const char *line) {
662 r = fopen_temporary(fn, &f, &p);
666 fchmod_umask(fileno(f), 0644);
669 if (fputs(line, f) < 0) {
674 if (!endswith(line, "\n"))
685 if (rename(p, fn) < 0)
701 int read_one_line_file(const char *fn, char **line) {
704 char t[LINE_MAX], *c;
713 if (!fgets(t, sizeof(t), f)) {
739 int read_full_file(const char *fn, char **contents, size_t *size) {
746 if (!(f = fopen(fn, "re")))
749 if (fstat(fileno(f), &st) < 0) {
755 if (st.st_size > 4*1024*1024) {
760 n = st.st_size > 0 ? st.st_size : LINE_MAX;
767 if (!(t = realloc(buf, n+1))) {
773 k = fread(buf + l, 1, n - l, f);
788 if (n > 4*1024*1024) {
812 const char *separator, ...) {
815 char *contents = NULL, *p;
820 if ((r = read_full_file(fname, &contents, NULL)) < 0)
825 const char *key = NULL;
827 p += strspn(p, separator);
828 p += strspn(p, WHITESPACE);
833 if (!strchr(COMMENTS, *p)) {
837 va_start(ap, separator);
838 while ((key = va_arg(ap, char *))) {
842 value = va_arg(ap, char **);
845 if (strncmp(p, key, n) != 0 ||
850 n = strcspn(p, separator);
853 strchr(QUOTES, p[0]) &&
855 v = strndup(p+1, n-2);
866 /* return empty value strings as NULL */
883 p += strcspn(p, separator);
902 if (!(f = fopen(fname, "re")))
906 char l[LINE_MAX], *p, *u;
909 if (!fgets(l, sizeof(l), f)) {
922 if (strchr(COMMENTS, *p))
925 if (!(u = normalize_env_assignment(p))) {
926 log_error("Out of memory");
931 t = strv_append(m, u);
935 log_error("Out of memory");
958 int write_env_file(const char *fname, char **l) {
963 r = fopen_temporary(fname, &f, &p);
967 fchmod_umask(fileno(f), 0644);
983 if (rename(p, fname) < 0)
998 char *truncate_nl(char *s) {
1001 s[strcspn(s, NEWLINE)] = 0;
1005 int get_process_comm(pid_t pid, char **name) {
1011 r = read_one_line_file("/proc/self/comm", name);
1014 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1017 r = read_one_line_file(p, name);
1024 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1031 assert(max_length > 0);
1035 f = fopen("/proc/self/cmdline", "re");
1038 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1048 r = new(char, max_length);
1056 while ((c = getc(f)) != EOF) {
1078 size_t n = MIN(left-1, 3U);
1079 memcpy(k, "...", n);
1086 /* Kernel threads have no argv[] */
1096 h = get_process_comm(pid, &t);
1100 r = join("[", t, "]", NULL);
1111 int is_kernel_thread(pid_t pid) {
1121 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1130 count = fread(&c, 1, 1, f);
1134 /* Kernel threads have an empty cmdline */
1137 return eof ? 1 : -errno;
1142 int get_process_exe(pid_t pid, char **name) {
1148 r = readlink_malloc("/proc/self/exe", name);
1151 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1154 r = readlink_malloc(p, name);
1161 int get_process_uid(pid_t pid, uid_t *uid) {
1171 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1181 char line[LINE_MAX], *l;
1183 if (!fgets(line, sizeof(line), f)) {
1193 if (startswith(l, "Uid:")) {
1195 l += strspn(l, WHITESPACE);
1197 l[strcspn(l, WHITESPACE)] = 0;
1199 r = parse_uid(l, uid);
1212 char *strnappend(const char *s, const char *suffix, size_t b) {
1220 return strndup(suffix, b);
1230 if (!(r = new(char, a+b+1)))
1234 memcpy(r+a, suffix, b);
1240 char *strappend(const char *s, const char *suffix) {
1241 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1244 int readlink_malloc(const char *p, char **r) {
1254 if (!(c = new(char, l)))
1257 if ((n = readlink(p, c, l-1)) < 0) {
1263 if ((size_t) n < l-1) {
1274 int readlink_and_make_absolute(const char *p, char **r) {
1281 if ((j = readlink_malloc(p, &target)) < 0)
1284 k = file_in_same_dir(p, target);
1294 int readlink_and_canonicalize(const char *p, char **r) {
1301 j = readlink_and_make_absolute(p, &t);
1305 s = canonicalize_file_name(t);
1312 path_kill_slashes(*r);
1317 int parent_of_path(const char *path, char **_r) {
1318 const char *e, *a = NULL, *b = NULL, *p;
1328 for (e = path; *e; e++) {
1330 if (!slash && *e == '/') {
1334 } else if (slash && *e != '/')
1349 r = strndup(path, p-path);
1359 char *file_name_from_path(const char *p) {
1364 if ((r = strrchr(p, '/')))
1370 bool path_is_absolute(const char *p) {
1376 bool is_path(const char *p) {
1378 return !!strchr(p, '/');
1381 char *path_make_absolute(const char *p, const char *prefix) {
1384 /* Makes every item in the list an absolute path by prepending
1385 * the prefix, if specified and necessary */
1387 if (path_is_absolute(p) || !prefix)
1390 return join(prefix, "/", p, NULL);
1393 char *path_make_absolute_cwd(const char *p) {
1398 /* Similar to path_make_absolute(), but prefixes with the
1399 * current working directory. */
1401 if (path_is_absolute(p))
1404 if (!(cwd = get_current_dir_name()))
1407 r = path_make_absolute(p, cwd);
1413 char **strv_path_make_absolute_cwd(char **l) {
1416 /* Goes through every item in the string list and makes it
1417 * absolute. This works in place and won't rollback any
1418 * changes on failure. */
1420 STRV_FOREACH(s, l) {
1423 if (!(t = path_make_absolute_cwd(*s)))
1433 char **strv_path_canonicalize(char **l) {
1436 bool enomem = false;
1438 if (strv_isempty(l))
1441 /* Goes through every item in the string list and canonicalize
1442 * the path. This works in place and won't rollback any
1443 * changes on failure. */
1445 STRV_FOREACH(s, l) {
1448 t = path_make_absolute_cwd(*s);
1457 u = canonicalize_file_name(t);
1461 if (errno == ENOMEM || !errno)
1478 char **strv_path_remove_empty(char **l) {
1484 for (f = t = l; *f; f++) {
1486 if (dir_is_empty(*f) > 0) {
1498 int reset_all_signal_handlers(void) {
1501 for (sig = 1; sig < _NSIG; sig++) {
1502 struct sigaction sa;
1504 if (sig == SIGKILL || sig == SIGSTOP)
1508 sa.sa_handler = SIG_DFL;
1509 sa.sa_flags = SA_RESTART;
1511 /* On Linux the first two RT signals are reserved by
1512 * glibc, and sigaction() will return EINVAL for them. */
1513 if ((sigaction(sig, &sa, NULL) < 0))
1514 if (errno != EINVAL)
1521 char *strstrip(char *s) {
1524 /* Drops trailing whitespace. Modifies the string in
1525 * place. Returns pointer to first non-space character */
1527 s += strspn(s, WHITESPACE);
1529 for (e = strchr(s, 0); e > s; e --)
1530 if (!strchr(WHITESPACE, e[-1]))
1538 char *delete_chars(char *s, const char *bad) {
1541 /* Drops all whitespace, regardless where in the string */
1543 for (f = s, t = s; *f; f++) {
1544 if (strchr(bad, *f))
1555 bool in_charset(const char *s, const char* charset) {
1561 for (i = s; *i; i++)
1562 if (!strchr(charset, *i))
1568 char *file_in_same_dir(const char *path, const char *filename) {
1575 /* This removes the last component of path and appends
1576 * filename, unless the latter is absolute anyway or the
1579 if (path_is_absolute(filename))
1580 return strdup(filename);
1582 if (!(e = strrchr(path, '/')))
1583 return strdup(filename);
1585 k = strlen(filename);
1586 if (!(r = new(char, e-path+1+k+1)))
1589 memcpy(r, path, e-path+1);
1590 memcpy(r+(e-path)+1, filename, k+1);
1595 int rmdir_parents(const char *path, const char *stop) {
1604 /* Skip trailing slashes */
1605 while (l > 0 && path[l-1] == '/')
1611 /* Skip last component */
1612 while (l > 0 && path[l-1] != '/')
1615 /* Skip trailing slashes */
1616 while (l > 0 && path[l-1] == '/')
1622 if (!(t = strndup(path, l)))
1625 if (path_startswith(stop, t)) {
1634 if (errno != ENOENT)
1642 char hexchar(int x) {
1643 static const char table[16] = "0123456789abcdef";
1645 return table[x & 15];
1648 int unhexchar(char c) {
1650 if (c >= '0' && c <= '9')
1653 if (c >= 'a' && c <= 'f')
1654 return c - 'a' + 10;
1656 if (c >= 'A' && c <= 'F')
1657 return c - 'A' + 10;
1662 char octchar(int x) {
1663 return '0' + (x & 7);
1666 int unoctchar(char c) {
1668 if (c >= '0' && c <= '7')
1674 char decchar(int x) {
1675 return '0' + (x % 10);
1678 int undecchar(char c) {
1680 if (c >= '0' && c <= '9')
1686 char *cescape(const char *s) {
1692 /* Does C style string escaping. */
1694 r = new(char, strlen(s)*4 + 1);
1698 for (f = s, t = r; *f; f++)
1744 /* For special chars we prefer octal over
1745 * hexadecimal encoding, simply because glib's
1746 * g_strescape() does the same */
1747 if ((*f < ' ') || (*f >= 127)) {
1749 *(t++) = octchar((unsigned char) *f >> 6);
1750 *(t++) = octchar((unsigned char) *f >> 3);
1751 *(t++) = octchar((unsigned char) *f);
1762 char *cunescape_length(const char *s, size_t length) {
1768 /* Undoes C style string escaping */
1770 r = new(char, length+1);
1774 for (f = s, t = r; f < s + length; f++) {
1817 /* This is an extension of the XDG syntax files */
1822 /* hexadecimal encoding */
1825 a = unhexchar(f[1]);
1826 b = unhexchar(f[2]);
1828 if (a < 0 || b < 0) {
1829 /* Invalid escape code, let's take it literal then */
1833 *(t++) = (char) ((a << 4) | b);
1848 /* octal encoding */
1851 a = unoctchar(f[0]);
1852 b = unoctchar(f[1]);
1853 c = unoctchar(f[2]);
1855 if (a < 0 || b < 0 || c < 0) {
1856 /* Invalid escape code, let's take it literal then */
1860 *(t++) = (char) ((a << 6) | (b << 3) | c);
1868 /* premature end of string.*/
1873 /* Invalid escape code, let's take it literal then */
1885 char *cunescape(const char *s) {
1886 return cunescape_length(s, strlen(s));
1889 char *xescape(const char *s, const char *bad) {
1893 /* Escapes all chars in bad, in addition to \ and all special
1894 * chars, in \xFF style escaping. May be reversed with
1897 if (!(r = new(char, strlen(s)*4+1)))
1900 for (f = s, t = r; *f; f++) {
1902 if ((*f < ' ') || (*f >= 127) ||
1903 (*f == '\\') || strchr(bad, *f)) {
1906 *(t++) = hexchar(*f >> 4);
1907 *(t++) = hexchar(*f);
1917 char *bus_path_escape(const char *s) {
1923 /* Escapes all chars that D-Bus' object path cannot deal
1924 * with. Can be reverse with bus_path_unescape() */
1926 if (!(r = new(char, strlen(s)*3+1)))
1929 for (f = s, t = r; *f; f++) {
1931 if (!(*f >= 'A' && *f <= 'Z') &&
1932 !(*f >= 'a' && *f <= 'z') &&
1933 !(*f >= '0' && *f <= '9')) {
1935 *(t++) = hexchar(*f >> 4);
1936 *(t++) = hexchar(*f);
1946 char *bus_path_unescape(const char *f) {
1951 if (!(r = strdup(f)))
1954 for (t = r; *f; f++) {
1959 if ((a = unhexchar(f[1])) < 0 ||
1960 (b = unhexchar(f[2])) < 0) {
1961 /* Invalid escape code, let's take it literal then */
1964 *(t++) = (char) ((a << 4) | b);
1976 char *path_kill_slashes(char *path) {
1980 /* Removes redundant inner and trailing slashes. Modifies the
1981 * passed string in-place.
1983 * ///foo///bar/ becomes /foo/bar
1986 for (f = path, t = path; *f; f++) {
2001 /* Special rule, if we are talking of the root directory, a
2002 trailing slash is good */
2004 if (t == path && slash)
2011 bool path_startswith(const char *path, const char *prefix) {
2015 if ((path[0] == '/') != (prefix[0] == '/'))
2021 path += strspn(path, "/");
2022 prefix += strspn(prefix, "/");
2030 a = strcspn(path, "/");
2031 b = strcspn(prefix, "/");
2036 if (memcmp(path, prefix, a) != 0)
2044 bool path_equal(const char *a, const char *b) {
2048 if ((a[0] == '/') != (b[0] == '/'))
2054 a += strspn(a, "/");
2055 b += strspn(b, "/");
2057 if (*a == 0 && *b == 0)
2060 if (*a == 0 || *b == 0)
2063 j = strcspn(a, "/");
2064 k = strcspn(b, "/");
2069 if (memcmp(a, b, j) != 0)
2077 char *ascii_strlower(char *t) {
2082 for (p = t; *p; p++)
2083 if (*p >= 'A' && *p <= 'Z')
2084 *p = *p - 'A' + 'a';
2089 bool ignore_file(const char *filename) {
2093 filename[0] == '.' ||
2094 streq(filename, "lost+found") ||
2095 streq(filename, "aquota.user") ||
2096 streq(filename, "aquota.group") ||
2097 endswith(filename, "~") ||
2098 endswith(filename, ".rpmnew") ||
2099 endswith(filename, ".rpmsave") ||
2100 endswith(filename, ".rpmorig") ||
2101 endswith(filename, ".dpkg-old") ||
2102 endswith(filename, ".dpkg-new") ||
2103 endswith(filename, ".swp");
2106 int fd_nonblock(int fd, bool nonblock) {
2111 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2115 flags |= O_NONBLOCK;
2117 flags &= ~O_NONBLOCK;
2119 if (fcntl(fd, F_SETFL, flags) < 0)
2125 int fd_cloexec(int fd, bool cloexec) {
2130 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2134 flags |= FD_CLOEXEC;
2136 flags &= ~FD_CLOEXEC;
2138 if (fcntl(fd, F_SETFD, flags) < 0)
2144 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
2147 assert(n_fdset == 0 || fdset);
2149 for (i = 0; i < n_fdset; i++)
2156 int close_all_fds(const int except[], unsigned n_except) {
2161 assert(n_except == 0 || except);
2163 d = opendir("/proc/self/fd");
2168 /* When /proc isn't available (for example in chroots)
2169 * the fallback is brute forcing through the fd
2172 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
2173 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
2175 if (fd_in_set(fd, except, n_except))
2178 if (close_nointr(fd) < 0)
2179 if (errno != EBADF && r == 0)
2186 while ((de = readdir(d))) {
2189 if (ignore_file(de->d_name))
2192 if (safe_atoi(de->d_name, &fd) < 0)
2193 /* Let's better ignore this, just in case */
2202 if (fd_in_set(fd, except, n_except))
2205 if (close_nointr(fd) < 0) {
2206 /* Valgrind has its own FD and doesn't want to have it closed */
2207 if (errno != EBADF && r == 0)
2216 bool chars_intersect(const char *a, const char *b) {
2219 /* Returns true if any of the chars in a are in b. */
2220 for (p = a; *p; p++)
2227 char *format_timestamp(char *buf, size_t l, usec_t t) {
2237 sec = (time_t) (t / USEC_PER_SEC);
2239 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2245 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2248 n = now(CLOCK_REALTIME);
2250 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2255 if (d >= USEC_PER_YEAR)
2256 snprintf(buf, l, "%llu years and %llu months ago",
2257 (unsigned long long) (d / USEC_PER_YEAR),
2258 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2259 else if (d >= USEC_PER_MONTH)
2260 snprintf(buf, l, "%llu months and %llu days ago",
2261 (unsigned long long) (d / USEC_PER_MONTH),
2262 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2263 else if (d >= USEC_PER_WEEK)
2264 snprintf(buf, l, "%llu weeks and %llu days ago",
2265 (unsigned long long) (d / USEC_PER_WEEK),
2266 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2267 else if (d >= 2*USEC_PER_DAY)
2268 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2269 else if (d >= 25*USEC_PER_HOUR)
2270 snprintf(buf, l, "1 day and %lluh ago",
2271 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2272 else if (d >= 6*USEC_PER_HOUR)
2273 snprintf(buf, l, "%lluh ago",
2274 (unsigned long long) (d / USEC_PER_HOUR));
2275 else if (d >= USEC_PER_HOUR)
2276 snprintf(buf, l, "%lluh %llumin ago",
2277 (unsigned long long) (d / USEC_PER_HOUR),
2278 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2279 else if (d >= 5*USEC_PER_MINUTE)
2280 snprintf(buf, l, "%llumin ago",
2281 (unsigned long long) (d / USEC_PER_MINUTE));
2282 else if (d >= USEC_PER_MINUTE)
2283 snprintf(buf, l, "%llumin %llus ago",
2284 (unsigned long long) (d / USEC_PER_MINUTE),
2285 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2286 else if (d >= USEC_PER_SEC)
2287 snprintf(buf, l, "%llus ago",
2288 (unsigned long long) (d / USEC_PER_SEC));
2289 else if (d >= USEC_PER_MSEC)
2290 snprintf(buf, l, "%llums ago",
2291 (unsigned long long) (d / USEC_PER_MSEC));
2293 snprintf(buf, l, "%lluus ago",
2294 (unsigned long long) d);
2296 snprintf(buf, l, "now");
2302 char *format_timespan(char *buf, size_t l, usec_t t) {
2303 static const struct {
2307 { "w", USEC_PER_WEEK },
2308 { "d", USEC_PER_DAY },
2309 { "h", USEC_PER_HOUR },
2310 { "min", USEC_PER_MINUTE },
2311 { "s", USEC_PER_SEC },
2312 { "ms", USEC_PER_MSEC },
2322 if (t == (usec_t) -1)
2326 snprintf(p, l, "0");
2331 /* The result of this function can be parsed with parse_usec */
2333 for (i = 0; i < ELEMENTSOF(table); i++) {
2337 if (t < table[i].usec)
2343 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2344 n = MIN((size_t) k, l);
2357 bool fstype_is_network(const char *fstype) {
2358 static const char * const table[] = {
2370 for (i = 0; i < ELEMENTSOF(table); i++)
2371 if (streq(table[i], fstype))
2380 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2385 TIOCL_GETKMSGREDIRECT,
2389 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2394 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2397 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2401 close_nointr_nofail(fd);
2405 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2406 struct termios old_termios, new_termios;
2408 char line[LINE_MAX];
2413 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2414 new_termios = old_termios;
2416 new_termios.c_lflag &= ~ICANON;
2417 new_termios.c_cc[VMIN] = 1;
2418 new_termios.c_cc[VTIME] = 0;
2420 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2423 if (t != (usec_t) -1) {
2424 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2425 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2430 k = fread(&c, 1, 1, f);
2432 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2438 *need_nl = c != '\n';
2445 if (t != (usec_t) -1)
2446 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2449 if (!fgets(line, sizeof(line), f))
2454 if (strlen(line) != 1)
2464 int ask(char *ret, const char *replies, const char *text, ...) {
2471 on_tty = isatty(STDOUT_FILENO);
2477 bool need_nl = true;
2480 fputs(ANSI_HIGHLIGHT_ON, stdout);
2487 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2491 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2494 if (r == -EBADMSG) {
2495 puts("Bad input, please try again.");
2506 if (strchr(replies, c)) {
2511 puts("Read unexpected character, please try again.");
2515 int reset_terminal_fd(int fd, bool switch_to_text) {
2516 struct termios termios;
2519 /* Set terminal to some sane defaults */
2523 /* We leave locked terminal attributes untouched, so that
2524 * Plymouth may set whatever it wants to set, and we don't
2525 * interfere with that. */
2527 /* Disable exclusive mode, just in case */
2528 ioctl(fd, TIOCNXCL);
2530 /* Switch to text mode */
2532 ioctl(fd, KDSETMODE, KD_TEXT);
2534 /* Enable console unicode mode */
2535 ioctl(fd, KDSKBMODE, K_UNICODE);
2537 if (tcgetattr(fd, &termios) < 0) {
2542 /* We only reset the stuff that matters to the software. How
2543 * hardware is set up we don't touch assuming that somebody
2544 * else will do that for us */
2546 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2547 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2548 termios.c_oflag |= ONLCR;
2549 termios.c_cflag |= CREAD;
2550 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2552 termios.c_cc[VINTR] = 03; /* ^C */
2553 termios.c_cc[VQUIT] = 034; /* ^\ */
2554 termios.c_cc[VERASE] = 0177;
2555 termios.c_cc[VKILL] = 025; /* ^X */
2556 termios.c_cc[VEOF] = 04; /* ^D */
2557 termios.c_cc[VSTART] = 021; /* ^Q */
2558 termios.c_cc[VSTOP] = 023; /* ^S */
2559 termios.c_cc[VSUSP] = 032; /* ^Z */
2560 termios.c_cc[VLNEXT] = 026; /* ^V */
2561 termios.c_cc[VWERASE] = 027; /* ^W */
2562 termios.c_cc[VREPRINT] = 022; /* ^R */
2563 termios.c_cc[VEOL] = 0;
2564 termios.c_cc[VEOL2] = 0;
2566 termios.c_cc[VTIME] = 0;
2567 termios.c_cc[VMIN] = 1;
2569 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2573 /* Just in case, flush all crap out */
2574 tcflush(fd, TCIOFLUSH);
2579 int reset_terminal(const char *name) {
2582 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2586 r = reset_terminal_fd(fd, true);
2587 close_nointr_nofail(fd);
2592 int open_terminal(const char *name, int mode) {
2597 * If a TTY is in the process of being closed opening it might
2598 * cause EIO. This is horribly awful, but unlikely to be
2599 * changed in the kernel. Hence we work around this problem by
2600 * retrying a couple of times.
2602 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2606 if ((fd = open(name, mode)) >= 0)
2615 usleep(50 * USEC_PER_MSEC);
2622 if ((r = isatty(fd)) < 0) {
2623 close_nointr_nofail(fd);
2628 close_nointr_nofail(fd);
2635 int flush_fd(int fd) {
2636 struct pollfd pollfd;
2640 pollfd.events = POLLIN;
2647 if ((r = poll(&pollfd, 1, 0)) < 0) {
2658 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2663 if (errno == EAGAIN)
2674 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2675 int fd = -1, notify = -1, r, wd = -1;
2679 /* We use inotify to be notified when the tty is closed. We
2680 * create the watch before checking if we can actually acquire
2681 * it, so that we don't lose any event.
2683 * Note: strictly speaking this actually watches for the
2684 * device being closed, it does *not* really watch whether a
2685 * tty loses its controlling process. However, unless some
2686 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2687 * its tty otherwise this will not become a problem. As long
2688 * as the administrator makes sure not configure any service
2689 * on the same tty as an untrusted user this should not be a
2690 * problem. (Which he probably should not do anyway.) */
2692 if (!fail && !force) {
2693 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2698 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2706 if ((r = flush_fd(notify)) < 0)
2709 /* We pass here O_NOCTTY only so that we can check the return
2710 * value TIOCSCTTY and have a reliable way to figure out if we
2711 * successfully became the controlling process of the tty */
2712 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2715 /* First, try to get the tty */
2716 r = ioctl(fd, TIOCSCTTY, force);
2718 /* Sometimes it makes sense to ignore TIOCSCTTY
2719 * returning EPERM, i.e. when very likely we already
2720 * are have this controlling terminal. */
2721 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2724 if (r < 0 && (force || fail || errno != EPERM)) {
2734 assert(notify >= 0);
2737 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2739 struct inotify_event *e;
2741 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2750 e = (struct inotify_event*) inotify_buffer;
2755 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2760 step = sizeof(struct inotify_event) + e->len;
2761 assert(step <= (size_t) l);
2763 e = (struct inotify_event*) ((uint8_t*) e + step);
2770 /* We close the tty fd here since if the old session
2771 * ended our handle will be dead. It's important that
2772 * we do this after sleeping, so that we don't enter
2773 * an endless loop. */
2774 close_nointr_nofail(fd);
2778 close_nointr_nofail(notify);
2780 r = reset_terminal_fd(fd, true);
2782 log_warning("Failed to reset terminal: %s", strerror(-r));
2788 close_nointr_nofail(fd);
2791 close_nointr_nofail(notify);
2796 int release_terminal(void) {
2798 struct sigaction sa_old, sa_new;
2800 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2803 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2804 * by our own TIOCNOTTY */
2807 sa_new.sa_handler = SIG_IGN;
2808 sa_new.sa_flags = SA_RESTART;
2809 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2811 if (ioctl(fd, TIOCNOTTY) < 0)
2814 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2816 close_nointr_nofail(fd);
2820 int sigaction_many(const struct sigaction *sa, ...) {
2825 while ((sig = va_arg(ap, int)) > 0)
2826 if (sigaction(sig, sa, NULL) < 0)
2833 int ignore_signals(int sig, ...) {
2834 struct sigaction sa;
2839 sa.sa_handler = SIG_IGN;
2840 sa.sa_flags = SA_RESTART;
2842 if (sigaction(sig, &sa, NULL) < 0)
2846 while ((sig = va_arg(ap, int)) > 0)
2847 if (sigaction(sig, &sa, NULL) < 0)
2854 int default_signals(int sig, ...) {
2855 struct sigaction sa;
2860 sa.sa_handler = SIG_DFL;
2861 sa.sa_flags = SA_RESTART;
2863 if (sigaction(sig, &sa, NULL) < 0)
2867 while ((sig = va_arg(ap, int)) > 0)
2868 if (sigaction(sig, &sa, NULL) < 0)
2875 int close_pipe(int p[]) {
2881 a = close_nointr(p[0]);
2886 b = close_nointr(p[1]);
2890 return a < 0 ? a : b;
2893 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2902 while (nbytes > 0) {
2905 if ((k = read(fd, p, nbytes)) <= 0) {
2907 if (k < 0 && errno == EINTR)
2910 if (k < 0 && errno == EAGAIN && do_poll) {
2911 struct pollfd pollfd;
2915 pollfd.events = POLLIN;
2917 if (poll(&pollfd, 1, -1) < 0) {
2921 return n > 0 ? n : -errno;
2924 if (pollfd.revents != POLLIN)
2925 return n > 0 ? n : -EIO;
2930 return n > 0 ? n : (k < 0 ? -errno : 0);
2941 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2950 while (nbytes > 0) {
2953 k = write(fd, p, nbytes);
2956 if (k < 0 && errno == EINTR)
2959 if (k < 0 && errno == EAGAIN && do_poll) {
2960 struct pollfd pollfd;
2964 pollfd.events = POLLOUT;
2966 if (poll(&pollfd, 1, -1) < 0) {
2970 return n > 0 ? n : -errno;
2973 if (pollfd.revents != POLLOUT)
2974 return n > 0 ? n : -EIO;
2979 return n > 0 ? n : (k < 0 ? -errno : 0);
2990 int path_is_mount_point(const char *t, bool allow_symlink) {
3001 if (errno == ENOENT)
3007 r = parent_of_path(t, &parent);
3011 r = lstat(parent, &b);
3017 return a.st_dev != b.st_dev;
3020 int parse_usec(const char *t, usec_t *usec) {
3021 static const struct {
3025 { "sec", USEC_PER_SEC },
3026 { "s", USEC_PER_SEC },
3027 { "min", USEC_PER_MINUTE },
3028 { "hr", USEC_PER_HOUR },
3029 { "h", USEC_PER_HOUR },
3030 { "d", USEC_PER_DAY },
3031 { "w", USEC_PER_WEEK },
3032 { "msec", USEC_PER_MSEC },
3033 { "ms", USEC_PER_MSEC },
3034 { "m", USEC_PER_MINUTE },
3037 { "", USEC_PER_SEC },
3053 l = strtoll(p, &e, 10);
3064 e += strspn(e, WHITESPACE);
3066 for (i = 0; i < ELEMENTSOF(table); i++)
3067 if (startswith(e, table[i].suffix)) {
3068 r += (usec_t) l * table[i].usec;
3069 p = e + strlen(table[i].suffix);
3073 if (i >= ELEMENTSOF(table))
3083 int parse_bytes(const char *t, off_t *bytes) {
3084 static const struct {
3090 { "M", 1024ULL*1024ULL },
3091 { "G", 1024ULL*1024ULL*1024ULL },
3092 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3093 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3094 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3111 l = strtoll(p, &e, 10);
3122 e += strspn(e, WHITESPACE);
3124 for (i = 0; i < ELEMENTSOF(table); i++)
3125 if (startswith(e, table[i].suffix)) {
3126 r += (off_t) l * table[i].factor;
3127 p = e + strlen(table[i].suffix);
3131 if (i >= ELEMENTSOF(table))
3141 int make_stdio(int fd) {
3146 r = dup2(fd, STDIN_FILENO);
3147 s = dup2(fd, STDOUT_FILENO);
3148 t = dup2(fd, STDERR_FILENO);
3151 close_nointr_nofail(fd);
3153 if (r < 0 || s < 0 || t < 0)
3156 fd_cloexec(STDIN_FILENO, false);
3157 fd_cloexec(STDOUT_FILENO, false);
3158 fd_cloexec(STDERR_FILENO, false);
3163 int make_null_stdio(void) {
3166 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3169 return make_stdio(null_fd);
3172 bool is_device_path(const char *path) {
3174 /* Returns true on paths that refer to a device, either in
3175 * sysfs or in /dev */
3178 path_startswith(path, "/dev/") ||
3179 path_startswith(path, "/sys/");
3182 int dir_is_empty(const char *path) {
3185 struct dirent buf, *de;
3187 if (!(d = opendir(path)))
3191 if ((r = readdir_r(d, &buf, &de)) > 0) {
3201 if (!ignore_file(de->d_name)) {
3211 unsigned long long random_ull(void) {
3216 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3219 r = loop_read(fd, &ull, sizeof(ull), true);
3220 close_nointr_nofail(fd);
3222 if (r != sizeof(ull))
3228 return random() * RAND_MAX + random();
3231 void rename_process(const char name[8]) {
3234 /* This is a like a poor man's setproctitle(). It changes the
3235 * comm field, argv[0], and also the glibc's internally used
3236 * name of the process. For the first one a limit of 16 chars
3237 * applies, to the second one usually one of 10 (i.e. length
3238 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3239 * "systemd"). If you pass a longer string it will be
3242 prctl(PR_SET_NAME, name);
3244 if (program_invocation_name)
3245 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3247 if (saved_argc > 0) {
3251 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3253 for (i = 1; i < saved_argc; i++) {
3257 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3262 void sigset_add_many(sigset_t *ss, ...) {
3269 while ((sig = va_arg(ap, int)) > 0)
3270 assert_se(sigaddset(ss, sig) == 0);
3274 char* gethostname_malloc(void) {
3277 assert_se(uname(&u) >= 0);
3280 return strdup(u.nodename);
3282 return strdup(u.sysname);
3285 char* getlogname_malloc(void) {
3289 struct passwd pwbuf, *pw = NULL;
3292 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3297 /* Shortcut things to avoid NSS lookups */
3299 return strdup("root");
3301 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3304 if (!(buf = malloc(bufsize)))
3307 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3308 name = strdup(pw->pw_name);
3315 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3321 int getttyname_malloc(int fd, char **r) {
3322 char path[PATH_MAX], *c;
3327 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3332 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3339 int getttyname_harder(int fd, char **r) {
3343 if ((k = getttyname_malloc(fd, &s)) < 0)
3346 if (streq(s, "tty")) {
3348 return get_ctty(0, NULL, r);
3355 int get_ctty_devnr(pid_t pid, dev_t *d) {
3357 char line[LINE_MAX], *p, *fn;
3358 unsigned long ttynr;
3361 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3364 f = fopen(fn, "re");
3369 if (!fgets(line, sizeof(line), f)) {
3370 k = feof(f) ? -EIO : -errno;
3377 p = strrchr(line, ')');
3387 "%*d " /* session */
3396 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3398 char fn[PATH_MAX], *s, *b, *p;
3403 k = get_ctty_devnr(pid, &devnr);
3407 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3410 if ((k = readlink_malloc(fn, &s)) < 0) {
3415 /* This is an ugly hack */
3416 if (major(devnr) == 136) {
3417 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3427 /* Probably something like the ptys which have no
3428 * symlink in /dev/char. Let's return something
3429 * vaguely useful. */
3431 if (!(b = strdup(fn + 5)))
3441 if (startswith(s, "/dev/"))
3443 else if (startswith(s, "../"))
3461 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3467 /* This returns the first error we run into, but nevertheless
3470 if (!(d = fdopendir(fd))) {
3471 close_nointr_nofail(fd);
3473 return errno == ENOENT ? 0 : -errno;
3477 struct dirent buf, *de;
3478 bool is_dir, keep_around = false;
3481 if ((r = readdir_r(d, &buf, &de)) != 0) {
3490 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3493 if (de->d_type == DT_UNKNOWN) {
3496 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3497 if (ret == 0 && errno != ENOENT)
3504 (st.st_uid == 0 || st.st_uid == getuid()) &&
3505 (st.st_mode & S_ISVTX);
3507 is_dir = S_ISDIR(st.st_mode);
3510 if (honour_sticky) {
3513 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3514 if (ret == 0 && errno != ENOENT)
3520 (st.st_uid == 0 || st.st_uid == getuid()) &&
3521 (st.st_mode & S_ISVTX);
3524 is_dir = de->d_type == DT_DIR;
3530 subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
3531 if (subdir_fd < 0) {
3532 if (ret == 0 && errno != ENOENT)
3537 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3543 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3544 if (ret == 0 && errno != ENOENT)
3548 } else if (!only_dirs && !keep_around) {
3550 if (unlinkat(fd, de->d_name, 0) < 0) {
3551 if (ret == 0 && errno != ENOENT)
3562 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3568 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3570 if (errno != ENOTDIR)
3573 if (delete_root && !only_dirs)
3574 if (unlink(path) < 0)
3580 r = rm_rf_children(fd, only_dirs, honour_sticky);
3584 if (honour_sticky && file_is_priv_sticky(path) > 0)
3587 if (rmdir(path) < 0 && errno != ENOENT) {
3596 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3599 /* Under the assumption that we are running privileged we
3600 * first change the access mode and only then hand out
3601 * ownership to avoid a window where access is too open. */
3603 if (mode != (mode_t) -1)
3604 if (chmod(path, mode) < 0)
3607 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3608 if (chown(path, uid, gid) < 0)
3614 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3617 /* Under the assumption that we are running privileged we
3618 * first change the access mode and only then hand out
3619 * ownership to avoid a window where access is too open. */
3621 if (fchmod(fd, mode) < 0)
3624 if (fchown(fd, uid, gid) < 0)
3630 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3634 /* Allocates the cpuset in the right size */
3637 if (!(r = CPU_ALLOC(n)))
3640 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3641 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3651 if (errno != EINVAL)
3658 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3659 char *s = NULL, *spaces = NULL, *e;
3661 size_t emax, sl, left;
3662 struct iovec iovec[5];
3667 /* This independent of logging, as status messages are
3668 * optional and go exclusively to the console. */
3670 if (vasprintf(&s, format, ap) < 0)
3673 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3683 sl = 2 + 6 + 1; /* " [" status "]" */
3684 emax = (size_t) c > sl ? c - sl - 1 : 0;
3688 e = ellipsize(s, emax, 75);
3696 IOVEC_SET_STRING(iovec[n++], s);
3700 left = emax > sl ? emax - sl : 0;
3702 spaces = malloc(left);
3704 memset(spaces, ' ', left);
3705 iovec[n].iov_base = spaces;
3706 iovec[n].iov_len = left;
3713 IOVEC_SET_STRING(iovec[n++], " [");
3714 IOVEC_SET_STRING(iovec[n++], status);
3715 IOVEC_SET_STRING(iovec[n++], "]\n");
3717 IOVEC_SET_STRING(iovec[n++], "\n");
3719 writev(fd, iovec, n);
3726 close_nointr_nofail(fd);
3729 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3734 va_start(ap, format);
3735 status_vprintf(status, ellipse, format, ap);
3739 void status_welcome(void) {
3740 char *pretty_name = NULL, *ansi_color = NULL;
3741 const char *const_pretty = NULL, *const_color = NULL;
3744 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3745 "PRETTY_NAME", &pretty_name,
3746 "ANSI_COLOR", &ansi_color,
3750 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3753 if (!pretty_name && !const_pretty)
3754 const_pretty = "Linux";
3756 if (!ansi_color && !const_color)
3761 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3762 const_color ? const_color : ansi_color,
3763 const_pretty ? const_pretty : pretty_name);
3769 char *replace_env(const char *format, char **env) {
3776 const char *e, *word = format;
3781 for (e = format; *e; e ++) {
3792 if (!(k = strnappend(r, word, e-word-1)))
3801 } else if (*e == '$') {
3802 if (!(k = strnappend(r, word, e-word)))
3818 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3821 if (!(k = strappend(r, t)))
3834 if (!(k = strnappend(r, word, e-word)))
3845 char **replace_env_argv(char **argv, char **env) {
3847 unsigned k = 0, l = 0;
3849 l = strv_length(argv);
3851 if (!(r = new(char*, l+1)))
3854 STRV_FOREACH(i, argv) {
3856 /* If $FOO appears as single word, replace it by the split up variable */
3857 if ((*i)[0] == '$' && (*i)[1] != '{') {
3862 if ((e = strv_env_get(env, *i+1))) {
3864 if (!(m = strv_split_quoted(e))) {
3875 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3884 memcpy(r + k, m, q * sizeof(char*));
3892 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3893 if (!(r[k++] = replace_env(*i, env))) {
3903 int fd_columns(int fd) {
3907 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3916 unsigned columns(void) {
3917 static __thread int parsed_columns = 0;
3920 if (_likely_(parsed_columns > 0))
3921 return parsed_columns;
3923 e = getenv("COLUMNS");
3925 parsed_columns = atoi(e);
3927 if (parsed_columns <= 0)
3928 parsed_columns = fd_columns(STDOUT_FILENO);
3930 if (parsed_columns <= 0)
3931 parsed_columns = 80;
3933 return parsed_columns;
3936 int fd_lines(int fd) {
3940 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3949 unsigned lines(void) {
3950 static __thread int parsed_lines = 0;
3953 if (_likely_(parsed_lines > 0))
3954 return parsed_lines;
3956 e = getenv("LINES");
3958 parsed_lines = atoi(e);
3960 if (parsed_lines <= 0)
3961 parsed_lines = fd_lines(STDOUT_FILENO);
3963 if (parsed_lines <= 0)
3966 return parsed_lines;
3969 int running_in_chroot(void) {
3975 /* Only works as root */
3977 if (stat("/proc/1/root", &a) < 0)
3980 if (stat("/", &b) < 0)
3984 a.st_dev != b.st_dev ||
3985 a.st_ino != b.st_ino;
3988 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3993 assert(percent <= 100);
3994 assert(new_length >= 3);
3996 if (old_length <= 3 || old_length <= new_length)
3997 return strndup(s, old_length);
3999 r = new0(char, new_length+1);
4003 x = (new_length * percent) / 100;
4005 if (x > new_length - 3)
4013 s + old_length - (new_length - x - 3),
4014 new_length - x - 3);
4019 char *ellipsize(const char *s, size_t length, unsigned percent) {
4020 return ellipsize_mem(s, strlen(s), length, percent);
4023 int touch(const char *path) {
4028 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4031 close_nointr_nofail(fd);
4035 char *unquote(const char *s, const char* quotes) {
4043 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4044 return strndup(s+1, l-2);
4049 char *normalize_env_assignment(const char *s) {
4050 char *name, *value, *p, *r;
4055 if (!(r = strdup(s)))
4061 if (!(name = strndup(s, p - s)))
4064 if (!(p = strdup(p+1))) {
4069 value = unquote(strstrip(p), QUOTES);
4077 if (asprintf(&r, "%s=%s", name, value) < 0)
4086 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4097 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4109 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4116 if ((r = wait_for_terminate(pid, &status)) < 0) {
4117 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4121 if (status.si_code == CLD_EXITED) {
4122 if (status.si_status != 0) {
4123 log_warning("%s failed with error code %i.", name, status.si_status);
4124 return status.si_status;
4127 log_debug("%s succeeded.", name);
4130 } else if (status.si_code == CLD_KILLED ||
4131 status.si_code == CLD_DUMPED) {
4133 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4137 log_warning("%s failed due to unknown reason.", name);
4142 _noreturn_ void freeze(void) {
4144 /* Make sure nobody waits for us on a socket anymore */
4145 close_all_fds(NULL, 0);
4153 bool null_or_empty(struct stat *st) {
4156 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4159 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4165 int null_or_empty_path(const char *fn) {
4170 if (stat(fn, &st) < 0)
4173 return null_or_empty(&st);
4176 DIR *xopendirat(int fd, const char *name, int flags) {
4180 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4183 if (!(d = fdopendir(nfd))) {
4184 close_nointr_nofail(nfd);
4191 int signal_from_string_try_harder(const char *s) {
4195 if ((signo = signal_from_string(s)) <= 0)
4196 if (startswith(s, "SIG"))
4197 return signal_from_string(s+3);
4202 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4208 if (!dual_timestamp_is_set(t))
4211 fprintf(f, "%s=%llu %llu\n",
4213 (unsigned long long) t->realtime,
4214 (unsigned long long) t->monotonic);
4217 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4218 unsigned long long a, b;
4223 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4224 log_debug("Failed to parse finish timestamp value %s", value);
4231 char *fstab_node_to_udev_node(const char *p) {
4235 /* FIXME: to follow udev's logic 100% we need to leave valid
4236 * UTF8 chars unescaped */
4238 if (startswith(p, "LABEL=")) {
4240 if (!(u = unquote(p+6, "\"\'")))
4243 t = xescape(u, "/ ");
4249 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4258 if (startswith(p, "UUID=")) {
4260 if (!(u = unquote(p+5, "\"\'")))
4263 t = xescape(u, "/ ");
4269 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4281 bool tty_is_vc(const char *tty) {
4284 if (startswith(tty, "/dev/"))
4287 return vtnr_from_tty(tty) >= 0;
4290 int vtnr_from_tty(const char *tty) {
4295 if (startswith(tty, "/dev/"))
4298 if (!startswith(tty, "tty") )
4301 if (tty[3] < '0' || tty[3] > '9')
4304 r = safe_atoi(tty+3, &i);
4308 if (i < 0 || i > 63)
4314 bool tty_is_vc_resolve(const char *tty) {
4315 char *active = NULL;
4320 if (startswith(tty, "/dev/"))
4323 /* Resolve where /dev/console is pointing to, if /sys is
4324 * actually ours (i.e. not read-only-mounted which is a sign
4325 * for container setups) */
4326 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4327 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4328 /* If multiple log outputs are configured the
4329 * last one is what /dev/console points to */
4330 tty = strrchr(active, ' ');
4343 const char *default_term_for_tty(const char *tty) {
4346 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4349 bool dirent_is_file(const struct dirent *de) {
4352 if (ignore_file(de->d_name))
4355 if (de->d_type != DT_REG &&
4356 de->d_type != DT_LNK &&
4357 de->d_type != DT_UNKNOWN)
4363 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4366 if (!dirent_is_file(de))
4369 return endswith(de->d_name, suffix);
4372 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4375 Hashmap *pids = NULL;
4379 /* Executes all binaries in a directory in parallel and waits
4380 * until all they all finished. */
4383 if (!(_d = opendir(directory))) {
4385 if (errno == ENOENT)
4388 log_error("Failed to enumerate directory %s: %m", directory);
4395 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4396 log_error("Failed to allocate set.");
4400 while ((de = readdir(d))) {
4405 if (!dirent_is_file(de))
4408 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4409 log_error("Out of memory");
4413 if ((pid = fork()) < 0) {
4414 log_error("Failed to fork: %m");
4433 log_error("Failed to execute %s: %m", path);
4434 _exit(EXIT_FAILURE);
4437 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4439 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4440 log_error("Failed to add PID to set: %s", strerror(-k));
4445 while (!hashmap_isempty(pids)) {
4446 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4451 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4456 log_error("waitid() failed: %m");
4460 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4461 if (!is_clean_exit(si.si_code, si.si_status)) {
4462 if (si.si_code == CLD_EXITED)
4463 log_error("%s exited with exit status %i.", path, si.si_status);
4465 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4467 log_debug("%s exited successfully.", path);
4478 hashmap_free_free(pids);
4481 int kill_and_sigcont(pid_t pid, int sig) {
4484 r = kill(pid, sig) < 0 ? -errno : 0;
4492 bool nulstr_contains(const char*nulstr, const char *needle) {
4498 NULSTR_FOREACH(i, nulstr)
4499 if (streq(i, needle))
4505 bool plymouth_running(void) {
4506 return access("/run/plymouth/pid", F_OK) >= 0;
4509 void parse_syslog_priority(char **p, int *priority) {
4510 int a = 0, b = 0, c = 0;
4520 if (!strchr(*p, '>'))
4523 if ((*p)[2] == '>') {
4524 c = undecchar((*p)[1]);
4526 } else if ((*p)[3] == '>') {
4527 b = undecchar((*p)[1]);
4528 c = undecchar((*p)[2]);
4530 } else if ((*p)[4] == '>') {
4531 a = undecchar((*p)[1]);
4532 b = undecchar((*p)[2]);
4533 c = undecchar((*p)[3]);
4538 if (a < 0 || b < 0 || c < 0)
4541 *priority = a*100+b*10+c;
4545 void skip_syslog_pid(char **buf) {
4557 p += strspn(p, "0123456789");
4567 void skip_syslog_date(char **buf) {
4575 LETTER, LETTER, LETTER,
4577 SPACE_OR_NUMBER, NUMBER,
4579 SPACE_OR_NUMBER, NUMBER,
4581 SPACE_OR_NUMBER, NUMBER,
4583 SPACE_OR_NUMBER, NUMBER,
4595 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4600 switch (sequence[i]) {
4607 case SPACE_OR_NUMBER:
4614 if (*p < '0' || *p > '9')
4620 if (!(*p >= 'A' && *p <= 'Z') &&
4621 !(*p >= 'a' && *p <= 'z'))
4637 char* strshorten(char *s, size_t l) {
4646 static bool hostname_valid_char(char c) {
4648 (c >= 'a' && c <= 'z') ||
4649 (c >= 'A' && c <= 'Z') ||
4650 (c >= '0' && c <= '9') ||
4656 bool hostname_is_valid(const char *s) {
4662 for (p = s; *p; p++)
4663 if (!hostname_valid_char(*p))
4666 if (p-s > HOST_NAME_MAX)
4672 char* hostname_cleanup(char *s) {
4675 for (p = s, d = s; *p; p++)
4676 if ((*p >= 'a' && *p <= 'z') ||
4677 (*p >= 'A' && *p <= 'Z') ||
4678 (*p >= '0' && *p <= '9') ||
4686 strshorten(s, HOST_NAME_MAX);
4690 int pipe_eof(int fd) {
4691 struct pollfd pollfd;
4696 pollfd.events = POLLIN|POLLHUP;
4698 r = poll(&pollfd, 1, 0);
4705 return pollfd.revents & POLLHUP;
4708 int fd_wait_for_event(int fd, int event, usec_t t) {
4709 struct pollfd pollfd;
4714 pollfd.events = event;
4716 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4723 return pollfd.revents;
4726 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4737 t = new(char, strlen(path) + 1 + 6 + 1);
4741 fn = file_name_from_path(path);
4745 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4747 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4753 f = fdopen(fd, "we");
4766 int terminal_vhangup_fd(int fd) {
4769 if (ioctl(fd, TIOCVHANGUP) < 0)
4775 int terminal_vhangup(const char *name) {
4778 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4782 r = terminal_vhangup_fd(fd);
4783 close_nointr_nofail(fd);
4788 int vt_disallocate(const char *name) {
4792 /* Deallocate the VT if possible. If not possible
4793 * (i.e. because it is the active one), at least clear it
4794 * entirely (including the scrollback buffer) */
4796 if (!startswith(name, "/dev/"))
4799 if (!tty_is_vc(name)) {
4800 /* So this is not a VT. I guess we cannot deallocate
4801 * it then. But let's at least clear the screen */
4803 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4808 "\033[r" /* clear scrolling region */
4809 "\033[H" /* move home */
4810 "\033[2J", /* clear screen */
4812 close_nointr_nofail(fd);
4817 if (!startswith(name, "/dev/tty"))
4820 r = safe_atou(name+8, &u);
4827 /* Try to deallocate */
4828 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4832 r = ioctl(fd, VT_DISALLOCATE, u);
4833 close_nointr_nofail(fd);
4841 /* Couldn't deallocate, so let's clear it fully with
4843 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4848 "\033[r" /* clear scrolling region */
4849 "\033[H" /* move home */
4850 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4852 close_nointr_nofail(fd);
4857 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4859 struct dirent buffer, *de;
4862 dir = opendir(path);
4864 if (errno == ENOENT)
4873 k = readdir_r(dir, &buffer, &de);
4882 if (!dirent_is_file_with_suffix(de, suffix))
4885 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4890 f = canonicalize_file_name(p);
4892 log_error("Failed to canonicalize file name '%s': %m", p);
4898 log_debug("found: %s\n", f);
4899 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4908 static int base_cmp(const void *a, const void *b) {
4909 const char *s1, *s2;
4911 s1 = *(char * const *)a;
4912 s2 = *(char * const *)b;
4913 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4916 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4919 char **files = NULL;
4925 dirs = strv_new_ap(dir, ap);
4931 if (!strv_path_canonicalize(dirs)) {
4935 if (!strv_uniq(dirs)) {
4940 fh = hashmap_new(string_hash_func, string_compare_func);
4946 STRV_FOREACH(p, dirs) {
4947 if (files_add(fh, *p, suffix) < 0) {
4948 log_error("Failed to search for files.");
4954 files = hashmap_get_strv(fh);
4955 if (files == NULL) {
4956 log_error("Failed to compose list of files.");
4961 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4970 int hwclock_is_localtime(void) {
4975 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4981 f = fopen("/etc/adjtime", "re");
4983 char line[LINE_MAX];
4986 b = fgets(line, sizeof(line), f) &&
4987 fgets(line, sizeof(line), f) &&
4988 fgets(line, sizeof(line), f);
4997 local = streq(line, "LOCAL");
4999 } else if (errno != -ENOENT)
5005 int hwclock_apply_localtime_delta(int *min) {
5006 const struct timeval *tv_null = NULL;
5012 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5013 assert_se(tm = localtime(&ts.tv_sec));
5014 minuteswest = tm->tm_gmtoff / 60;
5016 tz.tz_minuteswest = -minuteswest;
5017 tz.tz_dsttime = 0; /* DST_NONE*/
5020 * If the hardware clock does not run in UTC, but in local time:
5021 * The very first time we set the kernel's timezone, it will warp
5022 * the clock so that it runs in UTC instead of local time.
5024 if (settimeofday(tv_null, &tz) < 0)
5031 int hwclock_reset_localtime_delta(void) {
5032 const struct timeval *tv_null = NULL;
5035 tz.tz_minuteswest = 0;
5036 tz.tz_dsttime = 0; /* DST_NONE*/
5038 if (settimeofday(tv_null, &tz) < 0)
5044 int rtc_open(int flags) {
5048 /* First, we try to make use of the /dev/rtc symlink. If that
5049 * doesn't exist, we open the first RTC which has hctosys=1
5050 * set. If we don't find any we just take the first RTC that
5053 fd = open("/dev/rtc", flags);
5057 d = opendir("/sys/class/rtc");
5063 struct dirent buf, *de;
5066 r = readdir_r(d, &buf, &de);
5073 if (ignore_file(de->d_name))
5076 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5082 r = read_one_line_file(p, &v);
5088 r = parse_boolean(v);
5094 p = strappend("/dev/", de->d_name);
5095 fd = open(p, flags);
5108 fd = open("/dev/rtc0", flags);
5115 int hwclock_get_time(struct tm *tm) {
5121 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5125 /* This leaves the timezone fields of struct tm
5127 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5130 /* We don't now daylight saving, so we reset this in order not
5131 * to confused mktime(). */
5134 close_nointr_nofail(fd);
5139 int hwclock_set_time(const struct tm *tm) {
5145 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5149 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5152 close_nointr_nofail(fd);
5157 int copy_file(const char *from, const char *to) {
5163 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5167 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5169 close_nointr_nofail(fdf);
5177 n = read(fdf, buf, sizeof(buf));
5181 close_nointr_nofail(fdf);
5192 k = loop_write(fdt, buf, n, false);
5194 r = k < 0 ? k : (errno ? -errno : -EIO);
5196 close_nointr_nofail(fdf);
5204 close_nointr_nofail(fdf);
5205 r = close_nointr(fdt);
5215 int symlink_or_copy(const char *from, const char *to) {
5216 char *pf = NULL, *pt = NULL;
5223 if (parent_of_path(from, &pf) < 0 ||
5224 parent_of_path(to, &pt) < 0) {
5229 if (stat(pf, &a) < 0 ||
5235 if (a.st_dev != b.st_dev) {
5239 return copy_file(from, to);
5242 if (symlink(from, to) < 0) {
5256 int symlink_or_copy_atomic(const char *from, const char *to) {
5260 unsigned long long ull;
5267 t = new(char, strlen(to) + 1 + 16 + 1);
5271 fn = file_name_from_path(to);
5275 x = stpcpy(t+k+1, fn);
5278 for (i = 0; i < 16; i++) {
5279 *(x++) = hexchar(ull & 0xF);
5285 r = symlink_or_copy(from, t);
5292 if (rename(t, to) < 0) {
5303 bool display_is_local(const char *display) {
5307 display[0] == ':' &&
5308 display[1] >= '0' &&
5312 int socket_from_display(const char *display, char **path) {
5319 if (!display_is_local(display))
5322 k = strspn(display+1, "0123456789");
5324 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5328 c = stpcpy(f, "/tmp/.X11-unix/X");
5329 memcpy(c, display+1, k);
5337 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5344 /* We enforce some special rules for uid=0: in order to avoid
5345 * NSS lookups for root we hardcode its data. */
5347 if (streq(*username, "root") || streq(*username, "0")) {
5361 if (parse_uid(*username, &u) >= 0) {
5365 /* If there are multiple users with the same id, make
5366 * sure to leave $USER to the configured value instead
5367 * of the first occurrence in the database. However if
5368 * the uid was configured by a numeric uid, then let's
5369 * pick the real username from /etc/passwd. */
5371 *username = p->pw_name;
5374 p = getpwnam(*username);
5378 return errno != 0 ? -errno : -ESRCH;
5392 int get_group_creds(const char **groupname, gid_t *gid) {
5398 /* We enforce some special rules for gid=0: in order to avoid
5399 * NSS lookups for root we hardcode its data. */
5401 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5402 *groupname = "root";
5410 if (parse_gid(*groupname, &id) >= 0) {
5415 *groupname = g->gr_name;
5418 g = getgrnam(*groupname);
5422 return errno != 0 ? -errno : -ESRCH;
5430 int in_group(const char *name) {
5432 int ngroups_max, r, i;
5434 r = get_group_creds(&name, &gid);
5438 if (getgid() == gid)
5441 if (getegid() == gid)
5444 ngroups_max = sysconf(_SC_NGROUPS_MAX);
5445 assert(ngroups_max > 0);
5447 gids = alloca(sizeof(gid_t) * ngroups_max);
5449 r = getgroups(ngroups_max, gids);
5453 for (i = 0; i < r; i++)
5460 int glob_exists(const char *path) {
5468 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5470 if (k == GLOB_NOMATCH)
5472 else if (k == GLOB_NOSPACE)
5475 r = !strv_isempty(g.gl_pathv);
5477 r = errno ? -errno : -EIO;
5484 int dirent_ensure_type(DIR *d, struct dirent *de) {
5490 if (de->d_type != DT_UNKNOWN)
5493 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5497 S_ISREG(st.st_mode) ? DT_REG :
5498 S_ISDIR(st.st_mode) ? DT_DIR :
5499 S_ISLNK(st.st_mode) ? DT_LNK :
5500 S_ISFIFO(st.st_mode) ? DT_FIFO :
5501 S_ISSOCK(st.st_mode) ? DT_SOCK :
5502 S_ISCHR(st.st_mode) ? DT_CHR :
5503 S_ISBLK(st.st_mode) ? DT_BLK :
5509 int in_search_path(const char *path, char **search) {
5513 r = parent_of_path(path, &parent);
5519 STRV_FOREACH(i, search) {
5520 if (path_equal(parent, *i)) {
5531 int get_files_in_directory(const char *path, char ***list) {
5539 /* Returns all files in a directory in *list, and the number
5540 * of files as return value. If list is NULL returns only the
5548 struct dirent buffer, *de;
5551 k = readdir_r(d, &buffer, &de);
5560 dirent_ensure_type(d, de);
5562 if (!dirent_is_file(de))
5566 if ((unsigned) r >= n) {
5570 t = realloc(l, sizeof(char*) * n);
5579 assert((unsigned) r < n);
5581 l[r] = strdup(de->d_name);
5605 char *join(const char *x, ...) {
5618 t = va_arg(ap, const char *);
5641 t = va_arg(ap, const char *);
5655 bool is_main_thread(void) {
5656 static __thread int cached = 0;
5658 if (_unlikely_(cached == 0))
5659 cached = getpid() == gettid() ? 1 : -1;
5664 int block_get_whole_disk(dev_t d, dev_t *ret) {
5671 /* If it has a queue this is good enough for us */
5672 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5675 r = access(p, F_OK);
5683 /* If it is a partition find the originating device */
5684 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5687 r = access(p, F_OK);
5693 /* Get parent dev_t */
5694 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5697 r = read_one_line_file(p, &s);
5703 r = sscanf(s, "%u:%u", &m, &n);
5709 /* Only return this if it is really good enough for us. */
5710 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5713 r = access(p, F_OK);
5717 *ret = makedev(m, n);
5724 int file_is_priv_sticky(const char *p) {
5729 if (lstat(p, &st) < 0)
5733 (st.st_uid == 0 || st.st_uid == getuid()) &&
5734 (st.st_mode & S_ISVTX);
5737 static const char *const ioprio_class_table[] = {
5738 [IOPRIO_CLASS_NONE] = "none",
5739 [IOPRIO_CLASS_RT] = "realtime",
5740 [IOPRIO_CLASS_BE] = "best-effort",
5741 [IOPRIO_CLASS_IDLE] = "idle"
5744 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5746 static const char *const sigchld_code_table[] = {
5747 [CLD_EXITED] = "exited",
5748 [CLD_KILLED] = "killed",
5749 [CLD_DUMPED] = "dumped",
5750 [CLD_TRAPPED] = "trapped",
5751 [CLD_STOPPED] = "stopped",
5752 [CLD_CONTINUED] = "continued",
5755 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5757 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5758 [LOG_FAC(LOG_KERN)] = "kern",
5759 [LOG_FAC(LOG_USER)] = "user",
5760 [LOG_FAC(LOG_MAIL)] = "mail",
5761 [LOG_FAC(LOG_DAEMON)] = "daemon",
5762 [LOG_FAC(LOG_AUTH)] = "auth",
5763 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5764 [LOG_FAC(LOG_LPR)] = "lpr",
5765 [LOG_FAC(LOG_NEWS)] = "news",
5766 [LOG_FAC(LOG_UUCP)] = "uucp",
5767 [LOG_FAC(LOG_CRON)] = "cron",
5768 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5769 [LOG_FAC(LOG_FTP)] = "ftp",
5770 [LOG_FAC(LOG_LOCAL0)] = "local0",
5771 [LOG_FAC(LOG_LOCAL1)] = "local1",
5772 [LOG_FAC(LOG_LOCAL2)] = "local2",
5773 [LOG_FAC(LOG_LOCAL3)] = "local3",
5774 [LOG_FAC(LOG_LOCAL4)] = "local4",
5775 [LOG_FAC(LOG_LOCAL5)] = "local5",
5776 [LOG_FAC(LOG_LOCAL6)] = "local6",
5777 [LOG_FAC(LOG_LOCAL7)] = "local7"
5780 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5782 static const char *const log_level_table[] = {
5783 [LOG_EMERG] = "emerg",
5784 [LOG_ALERT] = "alert",
5785 [LOG_CRIT] = "crit",
5787 [LOG_WARNING] = "warning",
5788 [LOG_NOTICE] = "notice",
5789 [LOG_INFO] = "info",
5790 [LOG_DEBUG] = "debug"
5793 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5795 static const char* const sched_policy_table[] = {
5796 [SCHED_OTHER] = "other",
5797 [SCHED_BATCH] = "batch",
5798 [SCHED_IDLE] = "idle",
5799 [SCHED_FIFO] = "fifo",
5803 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5805 static const char* const rlimit_table[] = {
5806 [RLIMIT_CPU] = "LimitCPU",
5807 [RLIMIT_FSIZE] = "LimitFSIZE",
5808 [RLIMIT_DATA] = "LimitDATA",
5809 [RLIMIT_STACK] = "LimitSTACK",
5810 [RLIMIT_CORE] = "LimitCORE",
5811 [RLIMIT_RSS] = "LimitRSS",
5812 [RLIMIT_NOFILE] = "LimitNOFILE",
5813 [RLIMIT_AS] = "LimitAS",
5814 [RLIMIT_NPROC] = "LimitNPROC",
5815 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5816 [RLIMIT_LOCKS] = "LimitLOCKS",
5817 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5818 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5819 [RLIMIT_NICE] = "LimitNICE",
5820 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5821 [RLIMIT_RTTIME] = "LimitRTTIME"
5824 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5826 static const char* const ip_tos_table[] = {
5827 [IPTOS_LOWDELAY] = "low-delay",
5828 [IPTOS_THROUGHPUT] = "throughput",
5829 [IPTOS_RELIABILITY] = "reliability",
5830 [IPTOS_LOWCOST] = "low-cost",
5833 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5835 static const char *const __signal_table[] = {
5852 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5863 [SIGVTALRM] = "VTALRM",
5865 [SIGWINCH] = "WINCH",
5871 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5873 const char *signal_to_string(int signo) {
5874 static __thread char buf[12];
5877 name = __signal_to_string(signo);
5881 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5882 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5884 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5889 int signal_from_string(const char *s) {
5894 signo =__signal_from_string(s);
5898 if (startswith(s, "RTMIN+")) {
5902 if (safe_atou(s, &u) >= 0) {
5903 signo = (int) u + offset;
5904 if (signo > 0 && signo < _NSIG)
5910 bool kexec_loaded(void) {
5911 bool loaded = false;
5914 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5922 int strdup_or_null(const char *a, char **b) {
5940 int prot_from_flags(int flags) {
5942 switch (flags & O_ACCMODE) {
5951 return PROT_READ|PROT_WRITE;
5958 char *format_bytes(char *buf, size_t l, off_t t) {
5961 static const struct {
5965 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5966 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5967 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5968 { "G", 1024ULL*1024ULL*1024ULL },
5969 { "M", 1024ULL*1024ULL },
5973 for (i = 0; i < ELEMENTSOF(table); i++) {
5975 if (t >= table[i].factor) {
5978 (unsigned long long) (t / table[i].factor),
5979 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5986 snprintf(buf, l, "%lluB", (unsigned long long) t);
5994 void* memdup(const void *p, size_t l) {
6007 int fd_inc_sndbuf(int fd, size_t n) {
6009 socklen_t l = sizeof(value);
6011 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6013 l == sizeof(value) &&
6014 (size_t) value >= n*2)
6018 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6025 int fd_inc_rcvbuf(int fd, size_t n) {
6027 socklen_t l = sizeof(value);
6029 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6031 l == sizeof(value) &&
6032 (size_t) value >= n*2)
6036 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6043 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
6044 pid_t parent_pid, agent_pid;
6046 bool stdout_is_tty, stderr_is_tty;
6054 parent_pid = getpid();
6056 /* Spawns a temporary TTY agent, making sure it goes away when
6063 if (agent_pid != 0) {
6070 * Make sure the agent goes away when the parent dies */
6071 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
6072 _exit(EXIT_FAILURE);
6074 /* Check whether our parent died before we were able
6075 * to set the death signal */
6076 if (getppid() != parent_pid)
6077 _exit(EXIT_SUCCESS);
6079 /* Don't leak fds to the agent */
6080 close_all_fds(except, n_except);
6082 stdout_is_tty = isatty(STDOUT_FILENO);
6083 stderr_is_tty = isatty(STDERR_FILENO);
6085 if (!stdout_is_tty || !stderr_is_tty) {
6086 /* Detach from stdout/stderr. and reopen
6087 * /dev/tty for them. This is important to
6088 * ensure that when systemctl is started via
6089 * popen() or a similar call that expects to
6090 * read EOF we actually do generate EOF and
6091 * not delay this indefinitely by because we
6092 * keep an unused copy of stdin around. */
6093 fd = open("/dev/tty", O_WRONLY);
6095 log_error("Failed to open /dev/tty: %m");
6096 _exit(EXIT_FAILURE);
6100 dup2(fd, STDOUT_FILENO);
6103 dup2(fd, STDERR_FILENO);
6109 /* Count arguments */
6111 for (n = 0; va_arg(ap, char*); n++)
6116 l = alloca(sizeof(char *) * (n + 1));
6118 /* Fill in arguments */
6120 for (i = 0; i <= n; i++)
6121 l[i] = va_arg(ap, char*);
6125 _exit(EXIT_FAILURE);
6128 int setrlimit_closest(int resource, const struct rlimit *rlim) {
6129 struct rlimit highest, fixed;
6133 if (setrlimit(resource, rlim) >= 0)
6139 /* So we failed to set the desired setrlimit, then let's try
6140 * to get as close as we can */
6141 assert_se(getrlimit(resource, &highest) == 0);
6143 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
6144 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
6146 if (setrlimit(resource, &fixed) < 0)
6152 int path_is_read_only_fs(const char *path) {
6157 if (statvfs(path, &st) < 0)
6160 return !!(st.f_flag & ST_RDONLY);