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>
67 #include "exit-status.h"
71 char **saved_argv = NULL;
73 size_t page_size(void) {
74 static __thread size_t pgsz = 0;
77 if (_likely_(pgsz > 0))
80 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
87 bool streq_ptr(const char *a, const char *b) {
89 /* Like streq(), but tries to make sense of NULL pointers */
100 usec_t now(clockid_t clock_id) {
103 assert_se(clock_gettime(clock_id, &ts) == 0);
105 return timespec_load(&ts);
108 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
111 ts->realtime = now(CLOCK_REALTIME);
112 ts->monotonic = now(CLOCK_MONOTONIC);
117 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
126 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
128 ts->monotonic = now(CLOCK_MONOTONIC);
130 if ((int64_t) ts->monotonic > delta)
131 ts->monotonic -= delta;
139 usec_t timespec_load(const struct timespec *ts) {
143 (usec_t) ts->tv_sec * USEC_PER_SEC +
144 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
147 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
150 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
151 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
156 usec_t timeval_load(const struct timeval *tv) {
160 (usec_t) tv->tv_sec * USEC_PER_SEC +
161 (usec_t) tv->tv_usec;
164 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
167 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
168 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
173 bool endswith(const char *s, const char *postfix) {
180 pl = strlen(postfix);
188 return memcmp(s + sl - pl, postfix, pl) == 0;
191 bool startswith(const char *s, const char *prefix) {
206 return memcmp(s, prefix, pl) == 0;
209 bool startswith_no_case(const char *s, const char *prefix) {
225 for(i = 0; i < pl; ++i) {
226 if (tolower(s[i]) != tolower(prefix[i]))
233 bool first_word(const char *s, const char *word) {
248 if (memcmp(s, word, wl) != 0)
252 strchr(WHITESPACE, s[wl]);
255 int close_nointr(int fd) {
270 void close_nointr_nofail(int fd) {
271 int saved_errno = errno;
273 /* like close_nointr() but cannot fail, and guarantees errno
276 assert_se(close_nointr(fd) == 0);
281 void close_many(const int fds[], unsigned n_fd) {
284 for (i = 0; i < n_fd; i++)
285 close_nointr_nofail(fds[i]);
288 int parse_boolean(const char *v) {
291 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
293 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
299 int parse_pid(const char *s, pid_t* ret_pid) {
300 unsigned long ul = 0;
307 if ((r = safe_atolu(s, &ul)) < 0)
312 if ((unsigned long) pid != ul)
322 int parse_uid(const char *s, uid_t* ret_uid) {
323 unsigned long ul = 0;
330 if ((r = safe_atolu(s, &ul)) < 0)
335 if ((unsigned long) uid != ul)
342 int safe_atou(const char *s, unsigned *ret_u) {
350 l = strtoul(s, &x, 0);
352 if (!x || *x || errno)
353 return errno ? -errno : -EINVAL;
355 if ((unsigned long) (unsigned) l != l)
358 *ret_u = (unsigned) l;
362 int safe_atoi(const char *s, int *ret_i) {
370 l = strtol(s, &x, 0);
372 if (!x || *x || errno)
373 return errno ? -errno : -EINVAL;
375 if ((long) (int) l != l)
382 int safe_atollu(const char *s, long long unsigned *ret_llu) {
384 unsigned long long l;
390 l = strtoull(s, &x, 0);
392 if (!x || *x || errno)
393 return errno ? -errno : -EINVAL;
399 int safe_atolli(const char *s, long long int *ret_lli) {
407 l = strtoll(s, &x, 0);
409 if (!x || *x || errno)
410 return errno ? -errno : -EINVAL;
416 /* Split a string into words. */
417 char *split(const char *c, size_t *l, const char *separator, char **state) {
420 current = *state ? *state : (char*) c;
422 if (!*current || *c == 0)
425 current += strspn(current, separator);
426 *l = strcspn(current, separator);
429 return (char*) current;
432 /* Split a string into words, but consider strings enclosed in '' and
433 * "" as words even if they include spaces. */
434 char *split_quoted(const char *c, size_t *l, char **state) {
436 bool escaped = false;
438 current = *state ? *state : (char*) c;
440 if (!*current || *c == 0)
443 current += strspn(current, WHITESPACE);
445 if (*current == '\'') {
448 for (e = current; *e; e++) {
458 *state = *e == 0 ? e : e+1;
459 } else if (*current == '\"') {
462 for (e = current; *e; e++) {
472 *state = *e == 0 ? e : e+1;
474 for (e = current; *e; e++) {
479 else if (strchr(WHITESPACE, *e))
486 return (char*) current;
489 char **split_path_and_make_absolute(const char *p) {
493 if (!(l = strv_split(p, ":")))
496 if (!strv_path_make_absolute_cwd(l)) {
504 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
507 char fn[PATH_MAX], line[LINE_MAX], *p;
513 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
516 if (!(f = fopen(fn, "re")))
519 if (!(fgets(line, sizeof(line), f))) {
520 r = feof(f) ? -EIO : -errno;
527 /* Let's skip the pid and comm fields. The latter is enclosed
528 * in () but does not escape any () in its value, so let's
529 * skip over it manually */
531 if (!(p = strrchr(line, ')')))
542 if ((long unsigned) (pid_t) ppid != ppid)
545 *_ppid = (pid_t) ppid;
550 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
553 char fn[PATH_MAX], line[LINE_MAX], *p;
558 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
561 if (!(f = fopen(fn, "re")))
564 if (!(fgets(line, sizeof(line), f))) {
565 r = feof(f) ? -EIO : -errno;
572 /* Let's skip the pid and comm fields. The latter is enclosed
573 * in () but does not escape any () in its value, so let's
574 * skip over it manually */
576 if (!(p = strrchr(line, ')')))
597 "%*d " /* priority */
599 "%*d " /* num_threads */
600 "%*d " /* itrealvalue */
601 "%llu " /* starttime */,
608 int write_one_line_file(const char *fn, const char *line) {
615 if (!(f = fopen(fn, "we")))
619 if (fputs(line, f) < 0) {
624 if (!endswith(line, "\n"))
642 int fchmod_umask(int fd, mode_t m) {
647 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
653 int write_one_line_file_atomic(const char *fn, const char *line) {
661 r = fopen_temporary(fn, &f, &p);
665 fchmod_umask(fileno(f), 0644);
668 if (fputs(line, f) < 0) {
673 if (!endswith(line, "\n"))
684 if (rename(p, fn) < 0)
700 int read_one_line_file(const char *fn, char **line) {
703 char t[LINE_MAX], *c;
712 if (!fgets(t, sizeof(t), f)) {
738 int read_full_file(const char *fn, char **contents, size_t *size) {
745 if (!(f = fopen(fn, "re")))
748 if (fstat(fileno(f), &st) < 0) {
754 if (st.st_size > 4*1024*1024) {
759 n = st.st_size > 0 ? st.st_size : LINE_MAX;
766 if (!(t = realloc(buf, n+1))) {
772 k = fread(buf + l, 1, n - l, f);
787 if (n > 4*1024*1024) {
811 const char *separator, ...) {
814 char *contents = NULL, *p;
819 if ((r = read_full_file(fname, &contents, NULL)) < 0)
824 const char *key = NULL;
826 p += strspn(p, separator);
827 p += strspn(p, WHITESPACE);
832 if (!strchr(COMMENTS, *p)) {
836 va_start(ap, separator);
837 while ((key = va_arg(ap, char *))) {
841 value = va_arg(ap, char **);
844 if (strncmp(p, key, n) != 0 ||
849 n = strcspn(p, separator);
852 strchr(QUOTES, p[0]) &&
854 v = strndup(p+1, n-2);
865 /* return empty value strings as NULL */
882 p += strcspn(p, separator);
901 if (!(f = fopen(fname, "re")))
905 char l[LINE_MAX], *p, *u;
908 if (!fgets(l, sizeof(l), f)) {
921 if (strchr(COMMENTS, *p))
924 if (!(u = normalize_env_assignment(p))) {
925 log_error("Out of memory");
930 t = strv_append(m, u);
934 log_error("Out of memory");
957 int write_env_file(const char *fname, char **l) {
962 r = fopen_temporary(fname, &f, &p);
966 fchmod_umask(fileno(f), 0644);
982 if (rename(p, fname) < 0)
997 char *truncate_nl(char *s) {
1000 s[strcspn(s, NEWLINE)] = 0;
1004 int get_process_comm(pid_t pid, char **name) {
1010 r = read_one_line_file("/proc/self/comm", name);
1013 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1016 r = read_one_line_file(p, name);
1023 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1030 assert(max_length > 0);
1034 f = fopen("/proc/self/cmdline", "re");
1037 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1047 r = new(char, max_length);
1055 while ((c = getc(f)) != EOF) {
1077 size_t n = MIN(left-1, 3U);
1078 memcpy(k, "...", n);
1085 /* Kernel threads have no argv[] */
1095 h = get_process_comm(pid, &t);
1099 r = join("[", t, "]", NULL);
1110 int is_kernel_thread(pid_t pid) {
1120 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1129 count = fread(&c, 1, 1, f);
1133 /* Kernel threads have an empty cmdline */
1136 return eof ? 1 : -errno;
1141 int get_process_exe(pid_t pid, char **name) {
1147 r = readlink_malloc("/proc/self/exe", name);
1150 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1153 r = readlink_malloc(p, name);
1160 int get_process_uid(pid_t pid, uid_t *uid) {
1170 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1180 char line[LINE_MAX], *l;
1182 if (!fgets(line, sizeof(line), f)) {
1192 if (startswith(l, "Uid:")) {
1194 l += strspn(l, WHITESPACE);
1196 l[strcspn(l, WHITESPACE)] = 0;
1198 r = parse_uid(l, uid);
1211 char *strnappend(const char *s, const char *suffix, size_t b) {
1219 return strndup(suffix, b);
1229 if (!(r = new(char, a+b+1)))
1233 memcpy(r+a, suffix, b);
1239 char *strappend(const char *s, const char *suffix) {
1240 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1243 int readlink_malloc(const char *p, char **r) {
1253 if (!(c = new(char, l)))
1256 if ((n = readlink(p, c, l-1)) < 0) {
1262 if ((size_t) n < l-1) {
1273 int readlink_and_make_absolute(const char *p, char **r) {
1280 if ((j = readlink_malloc(p, &target)) < 0)
1283 k = file_in_same_dir(p, target);
1293 int readlink_and_canonicalize(const char *p, char **r) {
1300 j = readlink_and_make_absolute(p, &t);
1304 s = canonicalize_file_name(t);
1311 path_kill_slashes(*r);
1316 int parent_of_path(const char *path, char **_r) {
1317 const char *e, *a = NULL, *b = NULL, *p;
1327 for (e = path; *e; e++) {
1329 if (!slash && *e == '/') {
1333 } else if (slash && *e != '/')
1348 r = strndup(path, p-path);
1358 char *file_name_from_path(const char *p) {
1363 if ((r = strrchr(p, '/')))
1369 bool path_is_absolute(const char *p) {
1375 bool is_path(const char *p) {
1377 return !!strchr(p, '/');
1380 char *path_make_absolute(const char *p, const char *prefix) {
1383 /* Makes every item in the list an absolute path by prepending
1384 * the prefix, if specified and necessary */
1386 if (path_is_absolute(p) || !prefix)
1389 return join(prefix, "/", p, NULL);
1392 char *path_make_absolute_cwd(const char *p) {
1397 /* Similar to path_make_absolute(), but prefixes with the
1398 * current working directory. */
1400 if (path_is_absolute(p))
1403 if (!(cwd = get_current_dir_name()))
1406 r = path_make_absolute(p, cwd);
1412 char **strv_path_make_absolute_cwd(char **l) {
1415 /* Goes through every item in the string list and makes it
1416 * absolute. This works in place and won't rollback any
1417 * changes on failure. */
1419 STRV_FOREACH(s, l) {
1422 if (!(t = path_make_absolute_cwd(*s)))
1432 char **strv_path_canonicalize(char **l) {
1435 bool enomem = false;
1437 if (strv_isempty(l))
1440 /* Goes through every item in the string list and canonicalize
1441 * the path. This works in place and won't rollback any
1442 * changes on failure. */
1444 STRV_FOREACH(s, l) {
1447 t = path_make_absolute_cwd(*s);
1456 u = canonicalize_file_name(t);
1460 if (errno == ENOMEM || !errno)
1477 char **strv_path_remove_empty(char **l) {
1483 for (f = t = l; *f; f++) {
1485 if (dir_is_empty(*f) > 0) {
1497 int reset_all_signal_handlers(void) {
1500 for (sig = 1; sig < _NSIG; sig++) {
1501 struct sigaction sa;
1503 if (sig == SIGKILL || sig == SIGSTOP)
1507 sa.sa_handler = SIG_DFL;
1508 sa.sa_flags = SA_RESTART;
1510 /* On Linux the first two RT signals are reserved by
1511 * glibc, and sigaction() will return EINVAL for them. */
1512 if ((sigaction(sig, &sa, NULL) < 0))
1513 if (errno != EINVAL)
1520 char *strstrip(char *s) {
1523 /* Drops trailing whitespace. Modifies the string in
1524 * place. Returns pointer to first non-space character */
1526 s += strspn(s, WHITESPACE);
1528 for (e = strchr(s, 0); e > s; e --)
1529 if (!strchr(WHITESPACE, e[-1]))
1537 char *delete_chars(char *s, const char *bad) {
1540 /* Drops all whitespace, regardless where in the string */
1542 for (f = s, t = s; *f; f++) {
1543 if (strchr(bad, *f))
1554 bool in_charset(const char *s, const char* charset) {
1560 for (i = s; *i; i++)
1561 if (!strchr(charset, *i))
1567 char *file_in_same_dir(const char *path, const char *filename) {
1574 /* This removes the last component of path and appends
1575 * filename, unless the latter is absolute anyway or the
1578 if (path_is_absolute(filename))
1579 return strdup(filename);
1581 if (!(e = strrchr(path, '/')))
1582 return strdup(filename);
1584 k = strlen(filename);
1585 if (!(r = new(char, e-path+1+k+1)))
1588 memcpy(r, path, e-path+1);
1589 memcpy(r+(e-path)+1, filename, k+1);
1594 int rmdir_parents(const char *path, const char *stop) {
1603 /* Skip trailing slashes */
1604 while (l > 0 && path[l-1] == '/')
1610 /* Skip last component */
1611 while (l > 0 && path[l-1] != '/')
1614 /* Skip trailing slashes */
1615 while (l > 0 && path[l-1] == '/')
1621 if (!(t = strndup(path, l)))
1624 if (path_startswith(stop, t)) {
1633 if (errno != ENOENT)
1641 char hexchar(int x) {
1642 static const char table[16] = "0123456789abcdef";
1644 return table[x & 15];
1647 int unhexchar(char c) {
1649 if (c >= '0' && c <= '9')
1652 if (c >= 'a' && c <= 'f')
1653 return c - 'a' + 10;
1655 if (c >= 'A' && c <= 'F')
1656 return c - 'A' + 10;
1661 char octchar(int x) {
1662 return '0' + (x & 7);
1665 int unoctchar(char c) {
1667 if (c >= '0' && c <= '7')
1673 char decchar(int x) {
1674 return '0' + (x % 10);
1677 int undecchar(char c) {
1679 if (c >= '0' && c <= '9')
1685 char *cescape(const char *s) {
1691 /* Does C style string escaping. */
1693 if (!(r = new(char, strlen(s)*4 + 1)))
1696 for (f = s, t = r; *f; f++)
1742 /* For special chars we prefer octal over
1743 * hexadecimal encoding, simply because glib's
1744 * g_strescape() does the same */
1745 if ((*f < ' ') || (*f >= 127)) {
1747 *(t++) = octchar((unsigned char) *f >> 6);
1748 *(t++) = octchar((unsigned char) *f >> 3);
1749 *(t++) = octchar((unsigned char) *f);
1760 char *cunescape_length(const char *s, size_t length) {
1766 /* Undoes C style string escaping */
1768 r = new(char, length+1);
1772 for (f = s, t = r; f < s + length; f++) {
1815 /* This is an extension of the XDG syntax files */
1820 /* hexadecimal encoding */
1823 a = unhexchar(f[1]);
1824 b = unhexchar(f[2]);
1826 if (a < 0 || b < 0) {
1827 /* Invalid escape code, let's take it literal then */
1831 *(t++) = (char) ((a << 4) | b);
1846 /* octal encoding */
1849 a = unoctchar(f[0]);
1850 b = unoctchar(f[1]);
1851 c = unoctchar(f[2]);
1853 if (a < 0 || b < 0 || c < 0) {
1854 /* Invalid escape code, let's take it literal then */
1858 *(t++) = (char) ((a << 6) | (b << 3) | c);
1866 /* premature end of string.*/
1871 /* Invalid escape code, let's take it literal then */
1883 char *cunescape(const char *s) {
1884 return cunescape_length(s, strlen(s));
1887 char *xescape(const char *s, const char *bad) {
1891 /* Escapes all chars in bad, in addition to \ and all special
1892 * chars, in \xFF style escaping. May be reversed with
1895 if (!(r = new(char, strlen(s)*4+1)))
1898 for (f = s, t = r; *f; f++) {
1900 if ((*f < ' ') || (*f >= 127) ||
1901 (*f == '\\') || strchr(bad, *f)) {
1904 *(t++) = hexchar(*f >> 4);
1905 *(t++) = hexchar(*f);
1915 char *bus_path_escape(const char *s) {
1921 /* Escapes all chars that D-Bus' object path cannot deal
1922 * with. Can be reverse with bus_path_unescape() */
1924 if (!(r = new(char, strlen(s)*3+1)))
1927 for (f = s, t = r; *f; f++) {
1929 if (!(*f >= 'A' && *f <= 'Z') &&
1930 !(*f >= 'a' && *f <= 'z') &&
1931 !(*f >= '0' && *f <= '9')) {
1933 *(t++) = hexchar(*f >> 4);
1934 *(t++) = hexchar(*f);
1944 char *bus_path_unescape(const char *f) {
1949 if (!(r = strdup(f)))
1952 for (t = r; *f; f++) {
1957 if ((a = unhexchar(f[1])) < 0 ||
1958 (b = unhexchar(f[2])) < 0) {
1959 /* Invalid escape code, let's take it literal then */
1962 *(t++) = (char) ((a << 4) | b);
1974 char *path_kill_slashes(char *path) {
1978 /* Removes redundant inner and trailing slashes. Modifies the
1979 * passed string in-place.
1981 * ///foo///bar/ becomes /foo/bar
1984 for (f = path, t = path; *f; f++) {
1999 /* Special rule, if we are talking of the root directory, a
2000 trailing slash is good */
2002 if (t == path && slash)
2009 bool path_startswith(const char *path, const char *prefix) {
2013 if ((path[0] == '/') != (prefix[0] == '/'))
2019 path += strspn(path, "/");
2020 prefix += strspn(prefix, "/");
2028 a = strcspn(path, "/");
2029 b = strcspn(prefix, "/");
2034 if (memcmp(path, prefix, a) != 0)
2042 bool path_equal(const char *a, const char *b) {
2046 if ((a[0] == '/') != (b[0] == '/'))
2052 a += strspn(a, "/");
2053 b += strspn(b, "/");
2055 if (*a == 0 && *b == 0)
2058 if (*a == 0 || *b == 0)
2061 j = strcspn(a, "/");
2062 k = strcspn(b, "/");
2067 if (memcmp(a, b, j) != 0)
2075 char *ascii_strlower(char *t) {
2080 for (p = t; *p; p++)
2081 if (*p >= 'A' && *p <= 'Z')
2082 *p = *p - 'A' + 'a';
2087 bool ignore_file(const char *filename) {
2091 filename[0] == '.' ||
2092 streq(filename, "lost+found") ||
2093 streq(filename, "aquota.user") ||
2094 streq(filename, "aquota.group") ||
2095 endswith(filename, "~") ||
2096 endswith(filename, ".rpmnew") ||
2097 endswith(filename, ".rpmsave") ||
2098 endswith(filename, ".rpmorig") ||
2099 endswith(filename, ".dpkg-old") ||
2100 endswith(filename, ".dpkg-new") ||
2101 endswith(filename, ".swp");
2104 int fd_nonblock(int fd, bool nonblock) {
2109 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2113 flags |= O_NONBLOCK;
2115 flags &= ~O_NONBLOCK;
2117 if (fcntl(fd, F_SETFL, flags) < 0)
2123 int fd_cloexec(int fd, bool cloexec) {
2128 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2132 flags |= FD_CLOEXEC;
2134 flags &= ~FD_CLOEXEC;
2136 if (fcntl(fd, F_SETFD, flags) < 0)
2142 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
2145 assert(n_fdset == 0 || fdset);
2147 for (i = 0; i < n_fdset; i++)
2154 int close_all_fds(const int except[], unsigned n_except) {
2159 assert(n_except == 0 || except);
2161 d = opendir("/proc/self/fd");
2166 /* When /proc isn't available (for example in chroots)
2167 * the fallback is brute forcing through the fd
2170 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
2171 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
2173 if (fd_in_set(fd, except, n_except))
2176 if (close_nointr(fd) < 0)
2177 if (errno != EBADF && r == 0)
2184 while ((de = readdir(d))) {
2187 if (ignore_file(de->d_name))
2190 if (safe_atoi(de->d_name, &fd) < 0)
2191 /* Let's better ignore this, just in case */
2200 if (fd_in_set(fd, except, n_except))
2203 if (close_nointr(fd) < 0) {
2204 /* Valgrind has its own FD and doesn't want to have it closed */
2205 if (errno != EBADF && r == 0)
2214 bool chars_intersect(const char *a, const char *b) {
2217 /* Returns true if any of the chars in a are in b. */
2218 for (p = a; *p; p++)
2225 char *format_timestamp(char *buf, size_t l, usec_t t) {
2235 sec = (time_t) (t / USEC_PER_SEC);
2237 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2243 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2246 n = now(CLOCK_REALTIME);
2248 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2253 if (d >= USEC_PER_YEAR)
2254 snprintf(buf, l, "%llu years and %llu months ago",
2255 (unsigned long long) (d / USEC_PER_YEAR),
2256 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2257 else if (d >= USEC_PER_MONTH)
2258 snprintf(buf, l, "%llu months and %llu days ago",
2259 (unsigned long long) (d / USEC_PER_MONTH),
2260 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2261 else if (d >= USEC_PER_WEEK)
2262 snprintf(buf, l, "%llu weeks and %llu days ago",
2263 (unsigned long long) (d / USEC_PER_WEEK),
2264 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2265 else if (d >= 2*USEC_PER_DAY)
2266 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2267 else if (d >= 25*USEC_PER_HOUR)
2268 snprintf(buf, l, "1 day and %lluh ago",
2269 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2270 else if (d >= 6*USEC_PER_HOUR)
2271 snprintf(buf, l, "%lluh ago",
2272 (unsigned long long) (d / USEC_PER_HOUR));
2273 else if (d >= USEC_PER_HOUR)
2274 snprintf(buf, l, "%lluh %llumin ago",
2275 (unsigned long long) (d / USEC_PER_HOUR),
2276 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2277 else if (d >= 5*USEC_PER_MINUTE)
2278 snprintf(buf, l, "%llumin ago",
2279 (unsigned long long) (d / USEC_PER_MINUTE));
2280 else if (d >= USEC_PER_MINUTE)
2281 snprintf(buf, l, "%llumin %llus ago",
2282 (unsigned long long) (d / USEC_PER_MINUTE),
2283 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2284 else if (d >= USEC_PER_SEC)
2285 snprintf(buf, l, "%llus ago",
2286 (unsigned long long) (d / USEC_PER_SEC));
2287 else if (d >= USEC_PER_MSEC)
2288 snprintf(buf, l, "%llums ago",
2289 (unsigned long long) (d / USEC_PER_MSEC));
2291 snprintf(buf, l, "%lluus ago",
2292 (unsigned long long) d);
2294 snprintf(buf, l, "now");
2300 char *format_timespan(char *buf, size_t l, usec_t t) {
2301 static const struct {
2305 { "w", USEC_PER_WEEK },
2306 { "d", USEC_PER_DAY },
2307 { "h", USEC_PER_HOUR },
2308 { "min", USEC_PER_MINUTE },
2309 { "s", USEC_PER_SEC },
2310 { "ms", USEC_PER_MSEC },
2320 if (t == (usec_t) -1)
2324 snprintf(p, l, "0");
2329 /* The result of this function can be parsed with parse_usec */
2331 for (i = 0; i < ELEMENTSOF(table); i++) {
2335 if (t < table[i].usec)
2341 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2342 n = MIN((size_t) k, l);
2355 bool fstype_is_network(const char *fstype) {
2356 static const char * const table[] = {
2368 for (i = 0; i < ELEMENTSOF(table); i++)
2369 if (streq(table[i], fstype))
2378 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2383 TIOCL_GETKMSGREDIRECT,
2387 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2392 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2395 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2399 close_nointr_nofail(fd);
2403 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2404 struct termios old_termios, new_termios;
2406 char line[LINE_MAX];
2411 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2412 new_termios = old_termios;
2414 new_termios.c_lflag &= ~ICANON;
2415 new_termios.c_cc[VMIN] = 1;
2416 new_termios.c_cc[VTIME] = 0;
2418 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2421 if (t != (usec_t) -1) {
2422 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2423 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2428 k = fread(&c, 1, 1, f);
2430 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2436 *need_nl = c != '\n';
2443 if (t != (usec_t) -1)
2444 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2447 if (!fgets(line, sizeof(line), f))
2452 if (strlen(line) != 1)
2462 int ask(char *ret, const char *replies, const char *text, ...) {
2469 on_tty = isatty(STDOUT_FILENO);
2475 bool need_nl = true;
2478 fputs(ANSI_HIGHLIGHT_ON, stdout);
2485 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2489 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2492 if (r == -EBADMSG) {
2493 puts("Bad input, please try again.");
2504 if (strchr(replies, c)) {
2509 puts("Read unexpected character, please try again.");
2513 int reset_terminal_fd(int fd, bool switch_to_text) {
2514 struct termios termios;
2517 /* Set terminal to some sane defaults */
2521 /* We leave locked terminal attributes untouched, so that
2522 * Plymouth may set whatever it wants to set, and we don't
2523 * interfere with that. */
2525 /* Disable exclusive mode, just in case */
2526 ioctl(fd, TIOCNXCL);
2528 /* Switch to text mode */
2530 ioctl(fd, KDSETMODE, KD_TEXT);
2532 /* Enable console unicode mode */
2533 ioctl(fd, KDSKBMODE, K_UNICODE);
2535 if (tcgetattr(fd, &termios) < 0) {
2540 /* We only reset the stuff that matters to the software. How
2541 * hardware is set up we don't touch assuming that somebody
2542 * else will do that for us */
2544 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2545 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2546 termios.c_oflag |= ONLCR;
2547 termios.c_cflag |= CREAD;
2548 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2550 termios.c_cc[VINTR] = 03; /* ^C */
2551 termios.c_cc[VQUIT] = 034; /* ^\ */
2552 termios.c_cc[VERASE] = 0177;
2553 termios.c_cc[VKILL] = 025; /* ^X */
2554 termios.c_cc[VEOF] = 04; /* ^D */
2555 termios.c_cc[VSTART] = 021; /* ^Q */
2556 termios.c_cc[VSTOP] = 023; /* ^S */
2557 termios.c_cc[VSUSP] = 032; /* ^Z */
2558 termios.c_cc[VLNEXT] = 026; /* ^V */
2559 termios.c_cc[VWERASE] = 027; /* ^W */
2560 termios.c_cc[VREPRINT] = 022; /* ^R */
2561 termios.c_cc[VEOL] = 0;
2562 termios.c_cc[VEOL2] = 0;
2564 termios.c_cc[VTIME] = 0;
2565 termios.c_cc[VMIN] = 1;
2567 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2571 /* Just in case, flush all crap out */
2572 tcflush(fd, TCIOFLUSH);
2577 int reset_terminal(const char *name) {
2580 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2584 r = reset_terminal_fd(fd, true);
2585 close_nointr_nofail(fd);
2590 int open_terminal(const char *name, int mode) {
2595 * If a TTY is in the process of being closed opening it might
2596 * cause EIO. This is horribly awful, but unlikely to be
2597 * changed in the kernel. Hence we work around this problem by
2598 * retrying a couple of times.
2600 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2604 if ((fd = open(name, mode)) >= 0)
2613 usleep(50 * USEC_PER_MSEC);
2620 if ((r = isatty(fd)) < 0) {
2621 close_nointr_nofail(fd);
2626 close_nointr_nofail(fd);
2633 int flush_fd(int fd) {
2634 struct pollfd pollfd;
2638 pollfd.events = POLLIN;
2645 if ((r = poll(&pollfd, 1, 0)) < 0) {
2656 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2661 if (errno == EAGAIN)
2672 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2673 int fd = -1, notify = -1, r, wd = -1;
2677 /* We use inotify to be notified when the tty is closed. We
2678 * create the watch before checking if we can actually acquire
2679 * it, so that we don't lose any event.
2681 * Note: strictly speaking this actually watches for the
2682 * device being closed, it does *not* really watch whether a
2683 * tty loses its controlling process. However, unless some
2684 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2685 * its tty otherwise this will not become a problem. As long
2686 * as the administrator makes sure not configure any service
2687 * on the same tty as an untrusted user this should not be a
2688 * problem. (Which he probably should not do anyway.) */
2690 if (!fail && !force) {
2691 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2696 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2704 if ((r = flush_fd(notify)) < 0)
2707 /* We pass here O_NOCTTY only so that we can check the return
2708 * value TIOCSCTTY and have a reliable way to figure out if we
2709 * successfully became the controlling process of the tty */
2710 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2713 /* First, try to get the tty */
2714 r = ioctl(fd, TIOCSCTTY, force);
2716 /* Sometimes it makes sense to ignore TIOCSCTTY
2717 * returning EPERM, i.e. when very likely we already
2718 * are have this controlling terminal. */
2719 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2722 if (r < 0 && (force || fail || errno != EPERM)) {
2732 assert(notify >= 0);
2735 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2737 struct inotify_event *e;
2739 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2748 e = (struct inotify_event*) inotify_buffer;
2753 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2758 step = sizeof(struct inotify_event) + e->len;
2759 assert(step <= (size_t) l);
2761 e = (struct inotify_event*) ((uint8_t*) e + step);
2768 /* We close the tty fd here since if the old session
2769 * ended our handle will be dead. It's important that
2770 * we do this after sleeping, so that we don't enter
2771 * an endless loop. */
2772 close_nointr_nofail(fd);
2776 close_nointr_nofail(notify);
2778 r = reset_terminal_fd(fd, true);
2780 log_warning("Failed to reset terminal: %s", strerror(-r));
2786 close_nointr_nofail(fd);
2789 close_nointr_nofail(notify);
2794 int release_terminal(void) {
2796 struct sigaction sa_old, sa_new;
2798 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2801 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2802 * by our own TIOCNOTTY */
2805 sa_new.sa_handler = SIG_IGN;
2806 sa_new.sa_flags = SA_RESTART;
2807 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2809 if (ioctl(fd, TIOCNOTTY) < 0)
2812 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2814 close_nointr_nofail(fd);
2818 int sigaction_many(const struct sigaction *sa, ...) {
2823 while ((sig = va_arg(ap, int)) > 0)
2824 if (sigaction(sig, sa, NULL) < 0)
2831 int ignore_signals(int sig, ...) {
2832 struct sigaction sa;
2837 sa.sa_handler = SIG_IGN;
2838 sa.sa_flags = SA_RESTART;
2840 if (sigaction(sig, &sa, NULL) < 0)
2844 while ((sig = va_arg(ap, int)) > 0)
2845 if (sigaction(sig, &sa, NULL) < 0)
2852 int default_signals(int sig, ...) {
2853 struct sigaction sa;
2858 sa.sa_handler = SIG_DFL;
2859 sa.sa_flags = SA_RESTART;
2861 if (sigaction(sig, &sa, NULL) < 0)
2865 while ((sig = va_arg(ap, int)) > 0)
2866 if (sigaction(sig, &sa, NULL) < 0)
2873 int close_pipe(int p[]) {
2879 a = close_nointr(p[0]);
2884 b = close_nointr(p[1]);
2888 return a < 0 ? a : b;
2891 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2900 while (nbytes > 0) {
2903 if ((k = read(fd, p, nbytes)) <= 0) {
2905 if (k < 0 && errno == EINTR)
2908 if (k < 0 && errno == EAGAIN && do_poll) {
2909 struct pollfd pollfd;
2913 pollfd.events = POLLIN;
2915 if (poll(&pollfd, 1, -1) < 0) {
2919 return n > 0 ? n : -errno;
2922 if (pollfd.revents != POLLIN)
2923 return n > 0 ? n : -EIO;
2928 return n > 0 ? n : (k < 0 ? -errno : 0);
2939 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2948 while (nbytes > 0) {
2951 k = write(fd, p, nbytes);
2954 if (k < 0 && errno == EINTR)
2957 if (k < 0 && errno == EAGAIN && do_poll) {
2958 struct pollfd pollfd;
2962 pollfd.events = POLLOUT;
2964 if (poll(&pollfd, 1, -1) < 0) {
2968 return n > 0 ? n : -errno;
2971 if (pollfd.revents != POLLOUT)
2972 return n > 0 ? n : -EIO;
2977 return n > 0 ? n : (k < 0 ? -errno : 0);
2988 int path_is_mount_point(const char *t, bool allow_symlink) {
2999 if (errno == ENOENT)
3005 r = parent_of_path(t, &parent);
3009 r = lstat(parent, &b);
3015 return a.st_dev != b.st_dev;
3018 int parse_usec(const char *t, usec_t *usec) {
3019 static const struct {
3023 { "sec", USEC_PER_SEC },
3024 { "s", USEC_PER_SEC },
3025 { "min", USEC_PER_MINUTE },
3026 { "hr", USEC_PER_HOUR },
3027 { "h", USEC_PER_HOUR },
3028 { "d", USEC_PER_DAY },
3029 { "w", USEC_PER_WEEK },
3030 { "msec", USEC_PER_MSEC },
3031 { "ms", USEC_PER_MSEC },
3032 { "m", USEC_PER_MINUTE },
3035 { "", USEC_PER_SEC },
3051 l = strtoll(p, &e, 10);
3062 e += strspn(e, WHITESPACE);
3064 for (i = 0; i < ELEMENTSOF(table); i++)
3065 if (startswith(e, table[i].suffix)) {
3066 r += (usec_t) l * table[i].usec;
3067 p = e + strlen(table[i].suffix);
3071 if (i >= ELEMENTSOF(table))
3081 int parse_bytes(const char *t, off_t *bytes) {
3082 static const struct {
3088 { "M", 1024ULL*1024ULL },
3089 { "G", 1024ULL*1024ULL*1024ULL },
3090 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3091 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3092 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3109 l = strtoll(p, &e, 10);
3120 e += strspn(e, WHITESPACE);
3122 for (i = 0; i < ELEMENTSOF(table); i++)
3123 if (startswith(e, table[i].suffix)) {
3124 r += (off_t) l * table[i].factor;
3125 p = e + strlen(table[i].suffix);
3129 if (i >= ELEMENTSOF(table))
3139 int make_stdio(int fd) {
3144 r = dup2(fd, STDIN_FILENO);
3145 s = dup2(fd, STDOUT_FILENO);
3146 t = dup2(fd, STDERR_FILENO);
3149 close_nointr_nofail(fd);
3151 if (r < 0 || s < 0 || t < 0)
3154 fd_cloexec(STDIN_FILENO, false);
3155 fd_cloexec(STDOUT_FILENO, false);
3156 fd_cloexec(STDERR_FILENO, false);
3161 int make_null_stdio(void) {
3164 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3167 return make_stdio(null_fd);
3170 bool is_device_path(const char *path) {
3172 /* Returns true on paths that refer to a device, either in
3173 * sysfs or in /dev */
3176 path_startswith(path, "/dev/") ||
3177 path_startswith(path, "/sys/");
3180 int dir_is_empty(const char *path) {
3183 struct dirent buf, *de;
3185 if (!(d = opendir(path)))
3189 if ((r = readdir_r(d, &buf, &de)) > 0) {
3199 if (!ignore_file(de->d_name)) {
3209 unsigned long long random_ull(void) {
3214 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3217 r = loop_read(fd, &ull, sizeof(ull), true);
3218 close_nointr_nofail(fd);
3220 if (r != sizeof(ull))
3226 return random() * RAND_MAX + random();
3229 void rename_process(const char name[8]) {
3232 /* This is a like a poor man's setproctitle(). It changes the
3233 * comm field, argv[0], and also the glibc's internally used
3234 * name of the process. For the first one a limit of 16 chars
3235 * applies, to the second one usually one of 10 (i.e. length
3236 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3237 * "systemd"). If you pass a longer string it will be
3240 prctl(PR_SET_NAME, name);
3242 if (program_invocation_name)
3243 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3245 if (saved_argc > 0) {
3249 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3251 for (i = 1; i < saved_argc; i++) {
3255 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3260 void sigset_add_many(sigset_t *ss, ...) {
3267 while ((sig = va_arg(ap, int)) > 0)
3268 assert_se(sigaddset(ss, sig) == 0);
3272 char* gethostname_malloc(void) {
3275 assert_se(uname(&u) >= 0);
3278 return strdup(u.nodename);
3280 return strdup(u.sysname);
3283 char* getlogname_malloc(void) {
3287 struct passwd pwbuf, *pw = NULL;
3290 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3295 /* Shortcut things to avoid NSS lookups */
3297 return strdup("root");
3299 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3302 if (!(buf = malloc(bufsize)))
3305 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3306 name = strdup(pw->pw_name);
3313 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3319 int getttyname_malloc(int fd, char **r) {
3320 char path[PATH_MAX], *c;
3325 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3330 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3337 int getttyname_harder(int fd, char **r) {
3341 if ((k = getttyname_malloc(fd, &s)) < 0)
3344 if (streq(s, "tty")) {
3346 return get_ctty(0, NULL, r);
3353 int get_ctty_devnr(pid_t pid, dev_t *d) {
3355 char line[LINE_MAX], *p, *fn;
3356 unsigned long ttynr;
3359 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3362 f = fopen(fn, "re");
3367 if (!fgets(line, sizeof(line), f)) {
3368 k = feof(f) ? -EIO : -errno;
3375 p = strrchr(line, ')');
3385 "%*d " /* session */
3394 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3396 char fn[PATH_MAX], *s, *b, *p;
3401 k = get_ctty_devnr(pid, &devnr);
3405 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3408 if ((k = readlink_malloc(fn, &s)) < 0) {
3413 /* This is an ugly hack */
3414 if (major(devnr) == 136) {
3415 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3425 /* Probably something like the ptys which have no
3426 * symlink in /dev/char. Let's return something
3427 * vaguely useful. */
3429 if (!(b = strdup(fn + 5)))
3439 if (startswith(s, "/dev/"))
3441 else if (startswith(s, "../"))
3459 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3465 /* This returns the first error we run into, but nevertheless
3468 if (!(d = fdopendir(fd))) {
3469 close_nointr_nofail(fd);
3471 return errno == ENOENT ? 0 : -errno;
3475 struct dirent buf, *de;
3476 bool is_dir, keep_around = false;
3479 if ((r = readdir_r(d, &buf, &de)) != 0) {
3488 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3491 if (de->d_type == DT_UNKNOWN) {
3494 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3495 if (ret == 0 && errno != ENOENT)
3502 (st.st_uid == 0 || st.st_uid == getuid()) &&
3503 (st.st_mode & S_ISVTX);
3505 is_dir = S_ISDIR(st.st_mode);
3508 if (honour_sticky) {
3511 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3512 if (ret == 0 && errno != ENOENT)
3518 (st.st_uid == 0 || st.st_uid == getuid()) &&
3519 (st.st_mode & S_ISVTX);
3522 is_dir = de->d_type == DT_DIR;
3528 subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
3529 if (subdir_fd < 0) {
3530 if (ret == 0 && errno != ENOENT)
3535 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3541 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3542 if (ret == 0 && errno != ENOENT)
3546 } else if (!only_dirs && !keep_around) {
3548 if (unlinkat(fd, de->d_name, 0) < 0) {
3549 if (ret == 0 && errno != ENOENT)
3560 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3566 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3568 if (errno != ENOTDIR)
3571 if (delete_root && !only_dirs)
3572 if (unlink(path) < 0)
3578 r = rm_rf_children(fd, only_dirs, honour_sticky);
3582 if (honour_sticky && file_is_priv_sticky(path) > 0)
3585 if (rmdir(path) < 0 && errno != ENOENT) {
3594 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3597 /* Under the assumption that we are running privileged we
3598 * first change the access mode and only then hand out
3599 * ownership to avoid a window where access is too open. */
3601 if (mode != (mode_t) -1)
3602 if (chmod(path, mode) < 0)
3605 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3606 if (chown(path, uid, gid) < 0)
3612 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3615 /* Under the assumption that we are running privileged we
3616 * first change the access mode and only then hand out
3617 * ownership to avoid a window where access is too open. */
3619 if (fchmod(fd, mode) < 0)
3622 if (fchown(fd, uid, gid) < 0)
3628 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3632 /* Allocates the cpuset in the right size */
3635 if (!(r = CPU_ALLOC(n)))
3638 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3639 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3649 if (errno != EINVAL)
3656 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3657 char *s = NULL, *spaces = NULL, *e;
3659 size_t emax, sl, left;
3660 struct iovec iovec[5];
3665 /* This independent of logging, as status messages are
3666 * optional and go exclusively to the console. */
3668 if (vasprintf(&s, format, ap) < 0)
3671 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3681 sl = 2 + 6 + 1; /* " [" status "]" */
3682 emax = (size_t) c > sl ? c - sl - 1 : 0;
3686 e = ellipsize(s, emax, 75);
3694 IOVEC_SET_STRING(iovec[n++], s);
3698 left = emax > sl ? emax - sl : 0;
3700 spaces = malloc(left);
3702 memset(spaces, ' ', left);
3703 iovec[n].iov_base = spaces;
3704 iovec[n].iov_len = left;
3711 IOVEC_SET_STRING(iovec[n++], " [");
3712 IOVEC_SET_STRING(iovec[n++], status);
3713 IOVEC_SET_STRING(iovec[n++], "]\n");
3715 IOVEC_SET_STRING(iovec[n++], "\n");
3717 writev(fd, iovec, n);
3724 close_nointr_nofail(fd);
3727 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3732 va_start(ap, format);
3733 status_vprintf(status, ellipse, format, ap);
3737 void status_welcome(void) {
3738 char *pretty_name = NULL, *ansi_color = NULL;
3739 const char *const_pretty = NULL, *const_color = NULL;
3742 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3743 "PRETTY_NAME", &pretty_name,
3744 "ANSI_COLOR", &ansi_color,
3748 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3751 if (!pretty_name && !const_pretty)
3752 const_pretty = "Linux";
3754 if (!ansi_color && !const_color)
3759 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3760 const_color ? const_color : ansi_color,
3761 const_pretty ? const_pretty : pretty_name);
3767 char *replace_env(const char *format, char **env) {
3774 const char *e, *word = format;
3779 for (e = format; *e; e ++) {
3790 if (!(k = strnappend(r, word, e-word-1)))
3799 } else if (*e == '$') {
3800 if (!(k = strnappend(r, word, e-word)))
3816 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3819 if (!(k = strappend(r, t)))
3832 if (!(k = strnappend(r, word, e-word)))
3843 char **replace_env_argv(char **argv, char **env) {
3845 unsigned k = 0, l = 0;
3847 l = strv_length(argv);
3849 if (!(r = new(char*, l+1)))
3852 STRV_FOREACH(i, argv) {
3854 /* If $FOO appears as single word, replace it by the split up variable */
3855 if ((*i)[0] == '$' && (*i)[1] != '{') {
3860 if ((e = strv_env_get(env, *i+1))) {
3862 if (!(m = strv_split_quoted(e))) {
3873 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3882 memcpy(r + k, m, q * sizeof(char*));
3890 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3891 if (!(r[k++] = replace_env(*i, env))) {
3901 int fd_columns(int fd) {
3905 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3914 unsigned columns(void) {
3915 static __thread int parsed_columns = 0;
3918 if (_likely_(parsed_columns > 0))
3919 return parsed_columns;
3921 e = getenv("COLUMNS");
3923 parsed_columns = atoi(e);
3925 if (parsed_columns <= 0)
3926 parsed_columns = fd_columns(STDOUT_FILENO);
3928 if (parsed_columns <= 0)
3929 parsed_columns = 80;
3931 return parsed_columns;
3934 int fd_lines(int fd) {
3938 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3947 unsigned lines(void) {
3948 static __thread int parsed_lines = 0;
3951 if (_likely_(parsed_lines > 0))
3952 return parsed_lines;
3954 e = getenv("LINES");
3956 parsed_lines = atoi(e);
3958 if (parsed_lines <= 0)
3959 parsed_lines = fd_lines(STDOUT_FILENO);
3961 if (parsed_lines <= 0)
3964 return parsed_lines;
3967 int running_in_chroot(void) {
3973 /* Only works as root */
3975 if (stat("/proc/1/root", &a) < 0)
3978 if (stat("/", &b) < 0)
3982 a.st_dev != b.st_dev ||
3983 a.st_ino != b.st_ino;
3986 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3991 assert(percent <= 100);
3992 assert(new_length >= 3);
3994 if (old_length <= 3 || old_length <= new_length)
3995 return strndup(s, old_length);
3997 r = new0(char, new_length+1);
4001 x = (new_length * percent) / 100;
4003 if (x > new_length - 3)
4011 s + old_length - (new_length - x - 3),
4012 new_length - x - 3);
4017 char *ellipsize(const char *s, size_t length, unsigned percent) {
4018 return ellipsize_mem(s, strlen(s), length, percent);
4021 int touch(const char *path) {
4026 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4029 close_nointr_nofail(fd);
4033 char *unquote(const char *s, const char* quotes) {
4041 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4042 return strndup(s+1, l-2);
4047 char *normalize_env_assignment(const char *s) {
4048 char *name, *value, *p, *r;
4053 if (!(r = strdup(s)))
4059 if (!(name = strndup(s, p - s)))
4062 if (!(p = strdup(p+1))) {
4067 value = unquote(strstrip(p), QUOTES);
4075 if (asprintf(&r, "%s=%s", name, value) < 0)
4084 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4095 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4107 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4114 if ((r = wait_for_terminate(pid, &status)) < 0) {
4115 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4119 if (status.si_code == CLD_EXITED) {
4120 if (status.si_status != 0) {
4121 log_warning("%s failed with error code %i.", name, status.si_status);
4122 return status.si_status;
4125 log_debug("%s succeeded.", name);
4128 } else if (status.si_code == CLD_KILLED ||
4129 status.si_code == CLD_DUMPED) {
4131 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4135 log_warning("%s failed due to unknown reason.", name);
4140 _noreturn_ void freeze(void) {
4142 /* Make sure nobody waits for us on a socket anymore */
4143 close_all_fds(NULL, 0);
4151 bool null_or_empty(struct stat *st) {
4154 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4157 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4163 int null_or_empty_path(const char *fn) {
4168 if (stat(fn, &st) < 0)
4171 return null_or_empty(&st);
4174 DIR *xopendirat(int fd, const char *name, int flags) {
4178 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4181 if (!(d = fdopendir(nfd))) {
4182 close_nointr_nofail(nfd);
4189 int signal_from_string_try_harder(const char *s) {
4193 if ((signo = signal_from_string(s)) <= 0)
4194 if (startswith(s, "SIG"))
4195 return signal_from_string(s+3);
4200 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4206 if (!dual_timestamp_is_set(t))
4209 fprintf(f, "%s=%llu %llu\n",
4211 (unsigned long long) t->realtime,
4212 (unsigned long long) t->monotonic);
4215 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4216 unsigned long long a, b;
4221 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4222 log_debug("Failed to parse finish timestamp value %s", value);
4229 char *fstab_node_to_udev_node(const char *p) {
4233 /* FIXME: to follow udev's logic 100% we need to leave valid
4234 * UTF8 chars unescaped */
4236 if (startswith(p, "LABEL=")) {
4238 if (!(u = unquote(p+6, "\"\'")))
4241 t = xescape(u, "/ ");
4247 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4256 if (startswith(p, "UUID=")) {
4258 if (!(u = unquote(p+5, "\"\'")))
4261 t = xescape(u, "/ ");
4267 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4279 bool tty_is_vc(const char *tty) {
4282 if (startswith(tty, "/dev/"))
4285 return vtnr_from_tty(tty) >= 0;
4288 int vtnr_from_tty(const char *tty) {
4293 if (startswith(tty, "/dev/"))
4296 if (!startswith(tty, "tty") )
4299 if (tty[3] < '0' || tty[3] > '9')
4302 r = safe_atoi(tty+3, &i);
4306 if (i < 0 || i > 63)
4312 bool tty_is_vc_resolve(const char *tty) {
4313 char *active = NULL;
4318 if (startswith(tty, "/dev/"))
4321 /* Resolve where /dev/console is pointing to */
4322 if (streq(tty, "console"))
4323 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4324 /* If multiple log outputs are configured the
4325 * last one is what /dev/console points to */
4326 tty = strrchr(active, ' ');
4339 const char *default_term_for_tty(const char *tty) {
4342 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4345 bool dirent_is_file(const struct dirent *de) {
4348 if (ignore_file(de->d_name))
4351 if (de->d_type != DT_REG &&
4352 de->d_type != DT_LNK &&
4353 de->d_type != DT_UNKNOWN)
4359 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4362 if (!dirent_is_file(de))
4365 return endswith(de->d_name, suffix);
4368 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4371 Hashmap *pids = NULL;
4375 /* Executes all binaries in a directory in parallel and waits
4376 * until all they all finished. */
4379 if (!(_d = opendir(directory))) {
4381 if (errno == ENOENT)
4384 log_error("Failed to enumerate directory %s: %m", directory);
4391 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4392 log_error("Failed to allocate set.");
4396 while ((de = readdir(d))) {
4401 if (!dirent_is_file(de))
4404 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4405 log_error("Out of memory");
4409 if ((pid = fork()) < 0) {
4410 log_error("Failed to fork: %m");
4429 log_error("Failed to execute %s: %m", path);
4430 _exit(EXIT_FAILURE);
4433 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4435 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4436 log_error("Failed to add PID to set: %s", strerror(-k));
4441 while (!hashmap_isempty(pids)) {
4442 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4447 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4452 log_error("waitid() failed: %m");
4456 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4457 if (!is_clean_exit(si.si_code, si.si_status)) {
4458 if (si.si_code == CLD_EXITED)
4459 log_error("%s exited with exit status %i.", path, si.si_status);
4461 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4463 log_debug("%s exited successfully.", path);
4474 hashmap_free_free(pids);
4477 int kill_and_sigcont(pid_t pid, int sig) {
4480 r = kill(pid, sig) < 0 ? -errno : 0;
4488 bool nulstr_contains(const char*nulstr, const char *needle) {
4494 NULSTR_FOREACH(i, nulstr)
4495 if (streq(i, needle))
4501 bool plymouth_running(void) {
4502 return access("/run/plymouth/pid", F_OK) >= 0;
4505 void parse_syslog_priority(char **p, int *priority) {
4506 int a = 0, b = 0, c = 0;
4516 if (!strchr(*p, '>'))
4519 if ((*p)[2] == '>') {
4520 c = undecchar((*p)[1]);
4522 } else if ((*p)[3] == '>') {
4523 b = undecchar((*p)[1]);
4524 c = undecchar((*p)[2]);
4526 } else if ((*p)[4] == '>') {
4527 a = undecchar((*p)[1]);
4528 b = undecchar((*p)[2]);
4529 c = undecchar((*p)[3]);
4534 if (a < 0 || b < 0 || c < 0)
4537 *priority = a*100+b*10+c;
4541 void skip_syslog_pid(char **buf) {
4553 p += strspn(p, "0123456789");
4563 void skip_syslog_date(char **buf) {
4571 LETTER, LETTER, LETTER,
4573 SPACE_OR_NUMBER, NUMBER,
4575 SPACE_OR_NUMBER, NUMBER,
4577 SPACE_OR_NUMBER, NUMBER,
4579 SPACE_OR_NUMBER, NUMBER,
4591 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4596 switch (sequence[i]) {
4603 case SPACE_OR_NUMBER:
4610 if (*p < '0' || *p > '9')
4616 if (!(*p >= 'A' && *p <= 'Z') &&
4617 !(*p >= 'a' && *p <= 'z'))
4633 char* strshorten(char *s, size_t l) {
4642 static bool hostname_valid_char(char c) {
4644 (c >= 'a' && c <= 'z') ||
4645 (c >= 'A' && c <= 'Z') ||
4646 (c >= '0' && c <= '9') ||
4652 bool hostname_is_valid(const char *s) {
4658 for (p = s; *p; p++)
4659 if (!hostname_valid_char(*p))
4662 if (p-s > HOST_NAME_MAX)
4668 char* hostname_cleanup(char *s) {
4671 for (p = s, d = s; *p; p++)
4672 if ((*p >= 'a' && *p <= 'z') ||
4673 (*p >= 'A' && *p <= 'Z') ||
4674 (*p >= '0' && *p <= '9') ||
4682 strshorten(s, HOST_NAME_MAX);
4686 int pipe_eof(int fd) {
4687 struct pollfd pollfd;
4692 pollfd.events = POLLIN|POLLHUP;
4694 r = poll(&pollfd, 1, 0);
4701 return pollfd.revents & POLLHUP;
4704 int fd_wait_for_event(int fd, int event, usec_t t) {
4705 struct pollfd pollfd;
4710 pollfd.events = event;
4712 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4719 return pollfd.revents;
4722 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4733 t = new(char, strlen(path) + 1 + 6 + 1);
4737 fn = file_name_from_path(path);
4741 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4743 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4749 f = fdopen(fd, "we");
4762 int terminal_vhangup_fd(int fd) {
4765 if (ioctl(fd, TIOCVHANGUP) < 0)
4771 int terminal_vhangup(const char *name) {
4774 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4778 r = terminal_vhangup_fd(fd);
4779 close_nointr_nofail(fd);
4784 int vt_disallocate(const char *name) {
4788 /* Deallocate the VT if possible. If not possible
4789 * (i.e. because it is the active one), at least clear it
4790 * entirely (including the scrollback buffer) */
4792 if (!startswith(name, "/dev/"))
4795 if (!tty_is_vc(name)) {
4796 /* So this is not a VT. I guess we cannot deallocate
4797 * it then. But let's at least clear the screen */
4799 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4804 "\033[r" /* clear scrolling region */
4805 "\033[H" /* move home */
4806 "\033[2J", /* clear screen */
4808 close_nointr_nofail(fd);
4813 if (!startswith(name, "/dev/tty"))
4816 r = safe_atou(name+8, &u);
4823 /* Try to deallocate */
4824 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4828 r = ioctl(fd, VT_DISALLOCATE, u);
4829 close_nointr_nofail(fd);
4837 /* Couldn't deallocate, so let's clear it fully with
4839 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4844 "\033[r" /* clear scrolling region */
4845 "\033[H" /* move home */
4846 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4848 close_nointr_nofail(fd);
4853 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4855 struct dirent buffer, *de;
4858 dir = opendir(path);
4860 if (errno == ENOENT)
4869 k = readdir_r(dir, &buffer, &de);
4878 if (!dirent_is_file_with_suffix(de, suffix))
4881 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4886 f = canonicalize_file_name(p);
4888 log_error("Failed to canonicalize file name '%s': %m", p);
4894 log_debug("found: %s\n", f);
4895 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4904 static int base_cmp(const void *a, const void *b) {
4905 const char *s1, *s2;
4907 s1 = *(char * const *)a;
4908 s2 = *(char * const *)b;
4909 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4912 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4915 char **files = NULL;
4921 dirs = strv_new_ap(dir, ap);
4927 if (!strv_path_canonicalize(dirs)) {
4931 if (!strv_uniq(dirs)) {
4936 fh = hashmap_new(string_hash_func, string_compare_func);
4942 STRV_FOREACH(p, dirs) {
4943 if (files_add(fh, *p, suffix) < 0) {
4944 log_error("Failed to search for files.");
4950 files = hashmap_get_strv(fh);
4951 if (files == NULL) {
4952 log_error("Failed to compose list of files.");
4957 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4966 int hwclock_is_localtime(void) {
4971 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4977 f = fopen("/etc/adjtime", "re");
4979 char line[LINE_MAX];
4982 b = fgets(line, sizeof(line), f) &&
4983 fgets(line, sizeof(line), f) &&
4984 fgets(line, sizeof(line), f);
4993 local = streq(line, "LOCAL");
4995 } else if (errno != -ENOENT)
5001 int hwclock_apply_localtime_delta(int *min) {
5002 const struct timeval *tv_null = NULL;
5008 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5009 assert_se(tm = localtime(&ts.tv_sec));
5010 minuteswest = tm->tm_gmtoff / 60;
5012 tz.tz_minuteswest = -minuteswest;
5013 tz.tz_dsttime = 0; /* DST_NONE*/
5016 * If the hardware clock does not run in UTC, but in local time:
5017 * The very first time we set the kernel's timezone, it will warp
5018 * the clock so that it runs in UTC instead of local time.
5020 if (settimeofday(tv_null, &tz) < 0)
5027 int hwclock_reset_localtime_delta(void) {
5028 const struct timeval *tv_null = NULL;
5031 tz.tz_minuteswest = 0;
5032 tz.tz_dsttime = 0; /* DST_NONE*/
5034 if (settimeofday(tv_null, &tz) < 0)
5040 int rtc_open(int flags) {
5044 /* First, we try to make use of the /dev/rtc symlink. If that
5045 * doesn't exist, we open the first RTC which has hctosys=1
5046 * set. If we don't find any we just take the first RTC that
5049 fd = open("/dev/rtc", flags);
5053 d = opendir("/sys/class/rtc");
5059 struct dirent buf, *de;
5062 r = readdir_r(d, &buf, &de);
5069 if (ignore_file(de->d_name))
5072 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5078 r = read_one_line_file(p, &v);
5084 r = parse_boolean(v);
5090 p = strappend("/dev/", de->d_name);
5091 fd = open(p, flags);
5104 fd = open("/dev/rtc0", flags);
5111 int hwclock_get_time(struct tm *tm) {
5117 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5121 /* This leaves the timezone fields of struct tm
5123 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5126 /* We don't now daylight saving, so we reset this in order not
5127 * to confused mktime(). */
5130 close_nointr_nofail(fd);
5135 int hwclock_set_time(const struct tm *tm) {
5141 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5145 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5148 close_nointr_nofail(fd);
5153 int copy_file(const char *from, const char *to) {
5159 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5163 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5165 close_nointr_nofail(fdf);
5173 n = read(fdf, buf, sizeof(buf));
5177 close_nointr_nofail(fdf);
5188 k = loop_write(fdt, buf, n, false);
5190 r = k < 0 ? k : (errno ? -errno : -EIO);
5192 close_nointr_nofail(fdf);
5200 close_nointr_nofail(fdf);
5201 r = close_nointr(fdt);
5211 int symlink_or_copy(const char *from, const char *to) {
5212 char *pf = NULL, *pt = NULL;
5219 if (parent_of_path(from, &pf) < 0 ||
5220 parent_of_path(to, &pt) < 0) {
5225 if (stat(pf, &a) < 0 ||
5231 if (a.st_dev != b.st_dev) {
5235 return copy_file(from, to);
5238 if (symlink(from, to) < 0) {
5252 int symlink_or_copy_atomic(const char *from, const char *to) {
5256 unsigned long long ull;
5263 t = new(char, strlen(to) + 1 + 16 + 1);
5267 fn = file_name_from_path(to);
5271 x = stpcpy(t+k+1, fn);
5274 for (i = 0; i < 16; i++) {
5275 *(x++) = hexchar(ull & 0xF);
5281 r = symlink_or_copy(from, t);
5288 if (rename(t, to) < 0) {
5299 bool display_is_local(const char *display) {
5303 display[0] == ':' &&
5304 display[1] >= '0' &&
5308 int socket_from_display(const char *display, char **path) {
5315 if (!display_is_local(display))
5318 k = strspn(display+1, "0123456789");
5320 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5324 c = stpcpy(f, "/tmp/.X11-unix/X");
5325 memcpy(c, display+1, k);
5333 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5340 /* We enforce some special rules for uid=0: in order to avoid
5341 * NSS lookups for root we hardcode its data. */
5343 if (streq(*username, "root") || streq(*username, "0")) {
5357 if (parse_uid(*username, &u) >= 0) {
5361 /* If there are multiple users with the same id, make
5362 * sure to leave $USER to the configured value instead
5363 * of the first occurrence in the database. However if
5364 * the uid was configured by a numeric uid, then let's
5365 * pick the real username from /etc/passwd. */
5367 *username = p->pw_name;
5370 p = getpwnam(*username);
5374 return errno != 0 ? -errno : -ESRCH;
5388 int get_group_creds(const char **groupname, gid_t *gid) {
5394 /* We enforce some special rules for gid=0: in order to avoid
5395 * NSS lookups for root we hardcode its data. */
5397 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5398 *groupname = "root";
5406 if (parse_gid(*groupname, &id) >= 0) {
5411 *groupname = g->gr_name;
5414 g = getgrnam(*groupname);
5418 return errno != 0 ? -errno : -ESRCH;
5426 int in_group(const char *name) {
5428 int ngroups_max, r, i;
5430 r = get_group_creds(&name, &gid);
5434 if (getgid() == gid)
5437 if (getegid() == gid)
5440 ngroups_max = sysconf(_SC_NGROUPS_MAX);
5441 assert(ngroups_max > 0);
5443 gids = alloca(sizeof(gid_t) * ngroups_max);
5445 r = getgroups(ngroups_max, gids);
5449 for (i = 0; i < r; i++)
5456 int glob_exists(const char *path) {
5464 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5466 if (k == GLOB_NOMATCH)
5468 else if (k == GLOB_NOSPACE)
5471 r = !strv_isempty(g.gl_pathv);
5473 r = errno ? -errno : -EIO;
5480 int dirent_ensure_type(DIR *d, struct dirent *de) {
5486 if (de->d_type != DT_UNKNOWN)
5489 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5493 S_ISREG(st.st_mode) ? DT_REG :
5494 S_ISDIR(st.st_mode) ? DT_DIR :
5495 S_ISLNK(st.st_mode) ? DT_LNK :
5496 S_ISFIFO(st.st_mode) ? DT_FIFO :
5497 S_ISSOCK(st.st_mode) ? DT_SOCK :
5498 S_ISCHR(st.st_mode) ? DT_CHR :
5499 S_ISBLK(st.st_mode) ? DT_BLK :
5505 int in_search_path(const char *path, char **search) {
5509 r = parent_of_path(path, &parent);
5515 STRV_FOREACH(i, search) {
5516 if (path_equal(parent, *i)) {
5527 int get_files_in_directory(const char *path, char ***list) {
5535 /* Returns all files in a directory in *list, and the number
5536 * of files as return value. If list is NULL returns only the
5544 struct dirent buffer, *de;
5547 k = readdir_r(d, &buffer, &de);
5556 dirent_ensure_type(d, de);
5558 if (!dirent_is_file(de))
5562 if ((unsigned) r >= n) {
5566 t = realloc(l, sizeof(char*) * n);
5575 assert((unsigned) r < n);
5577 l[r] = strdup(de->d_name);
5601 char *join(const char *x, ...) {
5614 t = va_arg(ap, const char *);
5637 t = va_arg(ap, const char *);
5651 bool is_main_thread(void) {
5652 static __thread int cached = 0;
5654 if (_unlikely_(cached == 0))
5655 cached = getpid() == gettid() ? 1 : -1;
5660 int block_get_whole_disk(dev_t d, dev_t *ret) {
5667 /* If it has a queue this is good enough for us */
5668 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5671 r = access(p, F_OK);
5679 /* If it is a partition find the originating device */
5680 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5683 r = access(p, F_OK);
5689 /* Get parent dev_t */
5690 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5693 r = read_one_line_file(p, &s);
5699 r = sscanf(s, "%u:%u", &m, &n);
5705 /* Only return this if it is really good enough for us. */
5706 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5709 r = access(p, F_OK);
5713 *ret = makedev(m, n);
5720 int file_is_priv_sticky(const char *p) {
5725 if (lstat(p, &st) < 0)
5729 (st.st_uid == 0 || st.st_uid == getuid()) &&
5730 (st.st_mode & S_ISVTX);
5733 static const char *const ioprio_class_table[] = {
5734 [IOPRIO_CLASS_NONE] = "none",
5735 [IOPRIO_CLASS_RT] = "realtime",
5736 [IOPRIO_CLASS_BE] = "best-effort",
5737 [IOPRIO_CLASS_IDLE] = "idle"
5740 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5742 static const char *const sigchld_code_table[] = {
5743 [CLD_EXITED] = "exited",
5744 [CLD_KILLED] = "killed",
5745 [CLD_DUMPED] = "dumped",
5746 [CLD_TRAPPED] = "trapped",
5747 [CLD_STOPPED] = "stopped",
5748 [CLD_CONTINUED] = "continued",
5751 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5753 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5754 [LOG_FAC(LOG_KERN)] = "kern",
5755 [LOG_FAC(LOG_USER)] = "user",
5756 [LOG_FAC(LOG_MAIL)] = "mail",
5757 [LOG_FAC(LOG_DAEMON)] = "daemon",
5758 [LOG_FAC(LOG_AUTH)] = "auth",
5759 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5760 [LOG_FAC(LOG_LPR)] = "lpr",
5761 [LOG_FAC(LOG_NEWS)] = "news",
5762 [LOG_FAC(LOG_UUCP)] = "uucp",
5763 [LOG_FAC(LOG_CRON)] = "cron",
5764 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5765 [LOG_FAC(LOG_FTP)] = "ftp",
5766 [LOG_FAC(LOG_LOCAL0)] = "local0",
5767 [LOG_FAC(LOG_LOCAL1)] = "local1",
5768 [LOG_FAC(LOG_LOCAL2)] = "local2",
5769 [LOG_FAC(LOG_LOCAL3)] = "local3",
5770 [LOG_FAC(LOG_LOCAL4)] = "local4",
5771 [LOG_FAC(LOG_LOCAL5)] = "local5",
5772 [LOG_FAC(LOG_LOCAL6)] = "local6",
5773 [LOG_FAC(LOG_LOCAL7)] = "local7"
5776 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5778 static const char *const log_level_table[] = {
5779 [LOG_EMERG] = "emerg",
5780 [LOG_ALERT] = "alert",
5781 [LOG_CRIT] = "crit",
5783 [LOG_WARNING] = "warning",
5784 [LOG_NOTICE] = "notice",
5785 [LOG_INFO] = "info",
5786 [LOG_DEBUG] = "debug"
5789 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5791 static const char* const sched_policy_table[] = {
5792 [SCHED_OTHER] = "other",
5793 [SCHED_BATCH] = "batch",
5794 [SCHED_IDLE] = "idle",
5795 [SCHED_FIFO] = "fifo",
5799 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5801 static const char* const rlimit_table[] = {
5802 [RLIMIT_CPU] = "LimitCPU",
5803 [RLIMIT_FSIZE] = "LimitFSIZE",
5804 [RLIMIT_DATA] = "LimitDATA",
5805 [RLIMIT_STACK] = "LimitSTACK",
5806 [RLIMIT_CORE] = "LimitCORE",
5807 [RLIMIT_RSS] = "LimitRSS",
5808 [RLIMIT_NOFILE] = "LimitNOFILE",
5809 [RLIMIT_AS] = "LimitAS",
5810 [RLIMIT_NPROC] = "LimitNPROC",
5811 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5812 [RLIMIT_LOCKS] = "LimitLOCKS",
5813 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5814 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5815 [RLIMIT_NICE] = "LimitNICE",
5816 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5817 [RLIMIT_RTTIME] = "LimitRTTIME"
5820 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5822 static const char* const ip_tos_table[] = {
5823 [IPTOS_LOWDELAY] = "low-delay",
5824 [IPTOS_THROUGHPUT] = "throughput",
5825 [IPTOS_RELIABILITY] = "reliability",
5826 [IPTOS_LOWCOST] = "low-cost",
5829 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5831 static const char *const __signal_table[] = {
5848 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5859 [SIGVTALRM] = "VTALRM",
5861 [SIGWINCH] = "WINCH",
5867 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5869 const char *signal_to_string(int signo) {
5870 static __thread char buf[12];
5873 name = __signal_to_string(signo);
5877 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5878 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5880 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5885 int signal_from_string(const char *s) {
5890 signo =__signal_from_string(s);
5894 if (startswith(s, "RTMIN+")) {
5898 if (safe_atou(s, &u) >= 0) {
5899 signo = (int) u + offset;
5900 if (signo > 0 && signo < _NSIG)
5906 bool kexec_loaded(void) {
5907 bool loaded = false;
5910 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5918 int strdup_or_null(const char *a, char **b) {
5936 int prot_from_flags(int flags) {
5938 switch (flags & O_ACCMODE) {
5947 return PROT_READ|PROT_WRITE;
5954 char *format_bytes(char *buf, size_t l, off_t t) {
5957 static const struct {
5961 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5962 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5963 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5964 { "G", 1024ULL*1024ULL*1024ULL },
5965 { "M", 1024ULL*1024ULL },
5969 for (i = 0; i < ELEMENTSOF(table); i++) {
5971 if (t >= table[i].factor) {
5974 (unsigned long long) (t / table[i].factor),
5975 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5982 snprintf(buf, l, "%lluB", (unsigned long long) t);
5990 void* memdup(const void *p, size_t l) {
6003 int fd_inc_sndbuf(int fd, size_t n) {
6005 socklen_t l = sizeof(value);
6007 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6009 l == sizeof(value) &&
6010 (size_t) value >= n*2)
6014 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6021 int fd_inc_rcvbuf(int fd, size_t n) {
6023 socklen_t l = sizeof(value);
6025 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6027 l == sizeof(value) &&
6028 (size_t) value >= n*2)
6032 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6039 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
6040 pid_t parent_pid, agent_pid;
6042 bool stdout_is_tty, stderr_is_tty;
6050 parent_pid = getpid();
6052 /* Spawns a temporary TTY agent, making sure it goes away when
6059 if (agent_pid != 0) {
6066 * Make sure the agent goes away when the parent dies */
6067 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
6068 _exit(EXIT_FAILURE);
6070 /* Check whether our parent died before we were able
6071 * to set the death signal */
6072 if (getppid() != parent_pid)
6073 _exit(EXIT_SUCCESS);
6075 /* Don't leak fds to the agent */
6076 close_all_fds(except, n_except);
6078 stdout_is_tty = isatty(STDOUT_FILENO);
6079 stderr_is_tty = isatty(STDERR_FILENO);
6081 if (!stdout_is_tty || !stderr_is_tty) {
6082 /* Detach from stdout/stderr. and reopen
6083 * /dev/tty for them. This is important to
6084 * ensure that when systemctl is started via
6085 * popen() or a similar call that expects to
6086 * read EOF we actually do generate EOF and
6087 * not delay this indefinitely by because we
6088 * keep an unused copy of stdin around. */
6089 fd = open("/dev/tty", O_WRONLY);
6091 log_error("Failed to open /dev/tty: %m");
6092 _exit(EXIT_FAILURE);
6096 dup2(fd, STDOUT_FILENO);
6099 dup2(fd, STDERR_FILENO);
6105 /* Count arguments */
6107 for (n = 0; va_arg(ap, char*); n++)
6112 l = alloca(sizeof(char *) * (n + 1));
6114 /* Fill in arguments */
6116 for (i = 0; i <= n; i++)
6117 l[i] = va_arg(ap, char*);
6121 _exit(EXIT_FAILURE);
6124 int setrlimit_closest(int resource, const struct rlimit *rlim) {
6125 struct rlimit highest, fixed;
6129 if (setrlimit(resource, rlim) >= 0)
6135 /* So we failed to set the desired setrlimit, then let's try
6136 * to get as close as we can */
6137 assert_se(getrlimit(resource, &highest) == 0);
6139 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
6140 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
6142 if (setrlimit(resource, &fixed) < 0)