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>
58 #include <linux/magic.h>
68 #include "path-util.h"
69 #include "exit-status.h"
73 char **saved_argv = NULL;
75 static volatile unsigned cached_columns = 0;
76 static volatile unsigned cached_lines = 0;
78 size_t page_size(void) {
79 static __thread size_t pgsz = 0;
82 if (_likely_(pgsz > 0))
85 r = sysconf(_SC_PAGESIZE);
92 bool streq_ptr(const char *a, const char *b) {
94 /* Like streq(), but tries to make sense of NULL pointers */
105 usec_t now(clockid_t clock_id) {
108 assert_se(clock_gettime(clock_id, &ts) == 0);
110 return timespec_load(&ts);
113 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
116 ts->realtime = now(CLOCK_REALTIME);
117 ts->monotonic = now(CLOCK_MONOTONIC);
122 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
131 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
133 ts->monotonic = now(CLOCK_MONOTONIC);
135 if ((int64_t) ts->monotonic > delta)
136 ts->monotonic -= delta;
144 usec_t timespec_load(const struct timespec *ts) {
147 if (ts->tv_sec == (time_t) -1 &&
148 ts->tv_nsec == (long) -1)
152 (usec_t) ts->tv_sec * USEC_PER_SEC +
153 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
156 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
159 if (u == (usec_t) -1) {
160 ts->tv_sec = (time_t) -1;
161 ts->tv_nsec = (long) -1;
165 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
166 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
171 usec_t timeval_load(const struct timeval *tv) {
174 if (tv->tv_sec == (time_t) -1 &&
175 tv->tv_usec == (suseconds_t) -1)
179 (usec_t) tv->tv_sec * USEC_PER_SEC +
180 (usec_t) tv->tv_usec;
183 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
186 if (u == (usec_t) -1) {
187 tv->tv_sec = (time_t) -1;
188 tv->tv_usec = (suseconds_t) -1;
192 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
193 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
198 char* endswith(const char *s, const char *postfix) {
205 pl = strlen(postfix);
208 return (char*) s + sl;
213 if (memcmp(s + sl - pl, postfix, pl) != 0)
216 return (char*) s + sl - pl;
219 char* startswith(const char *s, const char *prefix) {
236 char* startswith_no_case(const char *s, const char *prefix) {
246 if (tolower(*a) != tolower(*b))
253 bool first_word(const char *s, const char *word) {
268 if (memcmp(s, word, wl) != 0)
272 strchr(WHITESPACE, s[wl]);
275 int close_nointr(int fd) {
290 void close_nointr_nofail(int fd) {
291 int saved_errno = errno;
293 /* like close_nointr() but cannot fail, and guarantees errno
296 assert_se(close_nointr(fd) == 0);
301 void close_many(const int fds[], unsigned n_fd) {
304 for (i = 0; i < n_fd; i++)
305 close_nointr_nofail(fds[i]);
308 int parse_boolean(const char *v) {
311 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
313 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
319 int parse_pid(const char *s, pid_t* ret_pid) {
320 unsigned long ul = 0;
327 r = safe_atolu(s, &ul);
333 if ((unsigned long) pid != ul)
343 int parse_uid(const char *s, uid_t* ret_uid) {
344 unsigned long ul = 0;
351 r = safe_atolu(s, &ul);
357 if ((unsigned long) uid != ul)
364 int safe_atou(const char *s, unsigned *ret_u) {
372 l = strtoul(s, &x, 0);
374 if (!x || *x || errno)
375 return errno ? -errno : -EINVAL;
377 if ((unsigned long) (unsigned) l != l)
380 *ret_u = (unsigned) l;
384 int safe_atoi(const char *s, int *ret_i) {
392 l = strtol(s, &x, 0);
394 if (!x || *x || errno)
395 return errno ? -errno : -EINVAL;
397 if ((long) (int) l != l)
404 int safe_atollu(const char *s, long long unsigned *ret_llu) {
406 unsigned long long l;
412 l = strtoull(s, &x, 0);
414 if (!x || *x || errno)
415 return errno ? -errno : -EINVAL;
421 int safe_atolli(const char *s, long long int *ret_lli) {
429 l = strtoll(s, &x, 0);
431 if (!x || *x || errno)
432 return errno ? -errno : -EINVAL;
438 /* Split a string into words. */
439 char *split(const char *c, size_t *l, const char *separator, char **state) {
442 current = *state ? *state : (char*) c;
444 if (!*current || *c == 0)
447 current += strspn(current, separator);
448 *l = strcspn(current, separator);
451 return (char*) current;
454 /* Split a string into words, but consider strings enclosed in '' and
455 * "" as words even if they include spaces. */
456 char *split_quoted(const char *c, size_t *l, char **state) {
458 bool escaped = false;
460 current = *state ? *state : (char*) c;
462 if (!*current || *c == 0)
465 current += strspn(current, WHITESPACE);
467 if (*current == '\'') {
470 for (e = current; *e; e++) {
480 *state = *e == 0 ? e : e+1;
481 } else if (*current == '\"') {
484 for (e = current; *e; e++) {
494 *state = *e == 0 ? e : e+1;
496 for (e = current; *e; e++) {
501 else if (strchr(WHITESPACE, *e))
508 return (char*) current;
511 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
513 _cleanup_fclose_ FILE *f = NULL;
514 char fn[PATH_MAX], line[LINE_MAX], *p;
520 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
527 if (!fgets(line, sizeof(line), f)) {
528 r = feof(f) ? -EIO : -errno;
533 /* Let's skip the pid and comm fields. The latter is enclosed
534 * in () but does not escape any () in its value, so let's
535 * skip over it manually */
537 p = strrchr(line, ')');
549 if ((long unsigned) (pid_t) ppid != ppid)
552 *_ppid = (pid_t) ppid;
557 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
558 _cleanup_fclose_ FILE *f = NULL;
559 char fn[PATH_MAX], line[LINE_MAX], *p;
564 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
571 if (!fgets(line, sizeof(line), f)) {
578 /* Let's skip the pid and comm fields. The latter is enclosed
579 * in () but does not escape any () in its value, so let's
580 * skip over it manually */
582 p = strrchr(line, ')');
604 "%*d " /* priority */
606 "%*d " /* num_threads */
607 "%*d " /* itrealvalue */
608 "%llu " /* starttime */,
615 int write_one_line_file(const char *fn, const char *line) {
616 _cleanup_fclose_ FILE *f = NULL;
626 if (fputs(line, f) < 0)
627 return errno ? -errno : -EIO;
629 if (!endswith(line, "\n"))
635 return errno ? -errno : -EIO;
640 int fchmod_umask(int fd, mode_t m) {
645 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
651 int write_one_line_file_atomic(const char *fn, const char *line) {
659 r = fopen_temporary(fn, &f, &p);
663 fchmod_umask(fileno(f), 0644);
666 if (fputs(line, f) < 0) {
671 if (!endswith(line, "\n"))
682 if (rename(p, fn) < 0)
698 int read_one_line_file(const char *fn, char **line) {
699 _cleanup_fclose_ FILE *f = NULL;
700 char t[LINE_MAX], *c;
709 if (!fgets(t, sizeof(t), f)) {
712 return errno ? -errno : -EIO;
726 int read_full_file(const char *fn, char **contents, size_t *size) {
727 _cleanup_fclose_ FILE *f = NULL;
729 _cleanup_free_ char *buf = NULL;
736 if (fstat(fileno(f), &st) < 0)
740 if (st.st_size > 4*1024*1024)
743 n = st.st_size > 0 ? st.st_size : LINE_MAX;
750 t = realloc(buf, n+1);
755 k = fread(buf + l, 1, n - l, f);
784 const char *separator, ...) {
787 char *contents = NULL, *p;
792 if ((r = read_full_file(fname, &contents, NULL)) < 0)
797 const char *key = NULL;
799 p += strspn(p, separator);
800 p += strspn(p, WHITESPACE);
805 if (!strchr(COMMENTS, *p)) {
809 va_start(ap, separator);
810 while ((key = va_arg(ap, char *))) {
814 value = va_arg(ap, char **);
817 if (strncmp(p, key, n) != 0 ||
822 n = strcspn(p, separator);
825 strchr(QUOTES, p[0]) &&
827 v = strndup(p+1, n-2);
838 /* return empty value strings as NULL */
855 p += strcspn(p, separator);
874 if (!(f = fopen(fname, "re")))
878 char l[LINE_MAX], *p, *u;
881 if (!fgets(l, sizeof(l), f)) {
894 if (strchr(COMMENTS, *p))
897 if (!(u = normalize_env_assignment(p))) {
902 t = strv_append(m, u);
928 int write_env_file(const char *fname, char **l) {
933 r = fopen_temporary(fname, &f, &p);
937 fchmod_umask(fileno(f), 0644);
953 if (rename(p, fname) < 0)
968 char *truncate_nl(char *s) {
971 s[strcspn(s, NEWLINE)] = 0;
975 int get_process_comm(pid_t pid, char **name) {
981 r = read_one_line_file("/proc/self/comm", name);
984 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
987 r = read_one_line_file(p, name);
994 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1001 assert(max_length > 0);
1005 f = fopen("/proc/self/cmdline", "re");
1008 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1018 r = new(char, max_length);
1026 while ((c = getc(f)) != EOF) {
1048 size_t n = MIN(left-1, 3U);
1049 memcpy(k, "...", n);
1056 /* Kernel threads have no argv[] */
1066 h = get_process_comm(pid, &t);
1070 r = strjoin("[", t, "]", NULL);
1081 int is_kernel_thread(pid_t pid) {
1091 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1100 count = fread(&c, 1, 1, f);
1104 /* Kernel threads have an empty cmdline */
1107 return eof ? 1 : -errno;
1112 int get_process_exe(pid_t pid, char **name) {
1118 r = readlink_malloc("/proc/self/exe", name);
1121 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1124 r = readlink_malloc(p, name);
1131 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1141 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1151 char line[LINE_MAX], *l;
1153 if (!fgets(line, sizeof(line), f)) {
1163 if (startswith(l, field)) {
1165 l += strspn(l, WHITESPACE);
1167 l[strcspn(l, WHITESPACE)] = 0;
1169 r = parse_uid(l, uid);
1182 int get_process_uid(pid_t pid, uid_t *uid) {
1183 return get_process_id(pid, "Uid:", uid);
1186 int get_process_gid(pid_t pid, gid_t *gid) {
1187 return get_process_id(pid, "Gid:", gid);
1190 char *strnappend(const char *s, const char *suffix, size_t b) {
1198 return strndup(suffix, b);
1207 if (b > ((size_t) -1) - a)
1210 r = new(char, a+b+1);
1215 memcpy(r+a, suffix, b);
1221 char *strappend(const char *s, const char *suffix) {
1222 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1225 int readlink_malloc(const char *p, char **r) {
1235 if (!(c = new(char, l)))
1238 if ((n = readlink(p, c, l-1)) < 0) {
1244 if ((size_t) n < l-1) {
1255 int readlink_and_make_absolute(const char *p, char **r) {
1262 if ((j = readlink_malloc(p, &target)) < 0)
1265 k = file_in_same_dir(p, target);
1275 int readlink_and_canonicalize(const char *p, char **r) {
1282 j = readlink_and_make_absolute(p, &t);
1286 s = canonicalize_file_name(t);
1293 path_kill_slashes(*r);
1298 int reset_all_signal_handlers(void) {
1301 for (sig = 1; sig < _NSIG; sig++) {
1302 struct sigaction sa;
1304 if (sig == SIGKILL || sig == SIGSTOP)
1308 sa.sa_handler = SIG_DFL;
1309 sa.sa_flags = SA_RESTART;
1311 /* On Linux the first two RT signals are reserved by
1312 * glibc, and sigaction() will return EINVAL for them. */
1313 if ((sigaction(sig, &sa, NULL) < 0))
1314 if (errno != EINVAL)
1321 char *strstrip(char *s) {
1324 /* Drops trailing whitespace. Modifies the string in
1325 * place. Returns pointer to first non-space character */
1327 s += strspn(s, WHITESPACE);
1329 for (e = strchr(s, 0); e > s; e --)
1330 if (!strchr(WHITESPACE, e[-1]))
1338 char *delete_chars(char *s, const char *bad) {
1341 /* Drops all whitespace, regardless where in the string */
1343 for (f = s, t = s; *f; f++) {
1344 if (strchr(bad, *f))
1355 bool in_charset(const char *s, const char* charset) {
1361 for (i = s; *i; i++)
1362 if (!strchr(charset, *i))
1368 char *file_in_same_dir(const char *path, const char *filename) {
1375 /* This removes the last component of path and appends
1376 * filename, unless the latter is absolute anyway or the
1379 if (path_is_absolute(filename))
1380 return strdup(filename);
1382 if (!(e = strrchr(path, '/')))
1383 return strdup(filename);
1385 k = strlen(filename);
1386 if (!(r = new(char, e-path+1+k+1)))
1389 memcpy(r, path, e-path+1);
1390 memcpy(r+(e-path)+1, filename, k+1);
1395 int rmdir_parents(const char *path, const char *stop) {
1404 /* Skip trailing slashes */
1405 while (l > 0 && path[l-1] == '/')
1411 /* Skip last component */
1412 while (l > 0 && path[l-1] != '/')
1415 /* Skip trailing slashes */
1416 while (l > 0 && path[l-1] == '/')
1422 if (!(t = strndup(path, l)))
1425 if (path_startswith(stop, t)) {
1434 if (errno != ENOENT)
1442 char hexchar(int x) {
1443 static const char table[16] = "0123456789abcdef";
1445 return table[x & 15];
1448 int unhexchar(char c) {
1450 if (c >= '0' && c <= '9')
1453 if (c >= 'a' && c <= 'f')
1454 return c - 'a' + 10;
1456 if (c >= 'A' && c <= 'F')
1457 return c - 'A' + 10;
1462 char octchar(int x) {
1463 return '0' + (x & 7);
1466 int unoctchar(char c) {
1468 if (c >= '0' && c <= '7')
1474 char decchar(int x) {
1475 return '0' + (x % 10);
1478 int undecchar(char c) {
1480 if (c >= '0' && c <= '9')
1486 char *cescape(const char *s) {
1492 /* Does C style string escaping. */
1494 r = new(char, strlen(s)*4 + 1);
1498 for (f = s, t = r; *f; f++)
1544 /* For special chars we prefer octal over
1545 * hexadecimal encoding, simply because glib's
1546 * g_strescape() does the same */
1547 if ((*f < ' ') || (*f >= 127)) {
1549 *(t++) = octchar((unsigned char) *f >> 6);
1550 *(t++) = octchar((unsigned char) *f >> 3);
1551 *(t++) = octchar((unsigned char) *f);
1562 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1569 /* Undoes C style string escaping, and optionally prefixes it. */
1571 pl = prefix ? strlen(prefix) : 0;
1573 r = new(char, pl+length+1);
1578 memcpy(r, prefix, pl);
1580 for (f = s, t = r + pl; f < s + length; f++) {
1623 /* This is an extension of the XDG syntax files */
1628 /* hexadecimal encoding */
1631 a = unhexchar(f[1]);
1632 b = unhexchar(f[2]);
1634 if (a < 0 || b < 0) {
1635 /* Invalid escape code, let's take it literal then */
1639 *(t++) = (char) ((a << 4) | b);
1654 /* octal encoding */
1657 a = unoctchar(f[0]);
1658 b = unoctchar(f[1]);
1659 c = unoctchar(f[2]);
1661 if (a < 0 || b < 0 || c < 0) {
1662 /* Invalid escape code, let's take it literal then */
1666 *(t++) = (char) ((a << 6) | (b << 3) | c);
1674 /* premature end of string.*/
1679 /* Invalid escape code, let's take it literal then */
1691 char *cunescape_length(const char *s, size_t length) {
1692 return cunescape_length_with_prefix(s, length, NULL);
1695 char *cunescape(const char *s) {
1698 return cunescape_length(s, strlen(s));
1701 char *xescape(const char *s, const char *bad) {
1705 /* Escapes all chars in bad, in addition to \ and all special
1706 * chars, in \xFF style escaping. May be reversed with
1709 r = new(char, strlen(s) * 4 + 1);
1713 for (f = s, t = r; *f; f++) {
1715 if ((*f < ' ') || (*f >= 127) ||
1716 (*f == '\\') || strchr(bad, *f)) {
1719 *(t++) = hexchar(*f >> 4);
1720 *(t++) = hexchar(*f);
1730 char *bus_path_escape(const char *s) {
1736 /* Escapes all chars that D-Bus' object path cannot deal
1737 * with. Can be reverse with bus_path_unescape() */
1739 if (!(r = new(char, strlen(s)*3+1)))
1742 for (f = s, t = r; *f; f++) {
1744 if (!(*f >= 'A' && *f <= 'Z') &&
1745 !(*f >= 'a' && *f <= 'z') &&
1746 !(*f >= '0' && *f <= '9')) {
1748 *(t++) = hexchar(*f >> 4);
1749 *(t++) = hexchar(*f);
1759 char *bus_path_unescape(const char *f) {
1764 if (!(r = strdup(f)))
1767 for (t = r; *f; f++) {
1772 if ((a = unhexchar(f[1])) < 0 ||
1773 (b = unhexchar(f[2])) < 0) {
1774 /* Invalid escape code, let's take it literal then */
1777 *(t++) = (char) ((a << 4) | b);
1789 char *ascii_strlower(char *t) {
1794 for (p = t; *p; p++)
1795 if (*p >= 'A' && *p <= 'Z')
1796 *p = *p - 'A' + 'a';
1801 static bool ignore_file_allow_backup(const char *filename) {
1805 filename[0] == '.' ||
1806 streq(filename, "lost+found") ||
1807 streq(filename, "aquota.user") ||
1808 streq(filename, "aquota.group") ||
1809 endswith(filename, ".rpmnew") ||
1810 endswith(filename, ".rpmsave") ||
1811 endswith(filename, ".rpmorig") ||
1812 endswith(filename, ".dpkg-old") ||
1813 endswith(filename, ".dpkg-new") ||
1814 endswith(filename, ".swp");
1817 bool ignore_file(const char *filename) {
1820 if (endswith(filename, "~"))
1823 return ignore_file_allow_backup(filename);
1826 int fd_nonblock(int fd, bool nonblock) {
1831 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1835 flags |= O_NONBLOCK;
1837 flags &= ~O_NONBLOCK;
1839 if (fcntl(fd, F_SETFL, flags) < 0)
1845 int fd_cloexec(int fd, bool cloexec) {
1850 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1854 flags |= FD_CLOEXEC;
1856 flags &= ~FD_CLOEXEC;
1858 if (fcntl(fd, F_SETFD, flags) < 0)
1864 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1867 assert(n_fdset == 0 || fdset);
1869 for (i = 0; i < n_fdset; i++)
1876 int close_all_fds(const int except[], unsigned n_except) {
1881 assert(n_except == 0 || except);
1883 d = opendir("/proc/self/fd");
1888 /* When /proc isn't available (for example in chroots)
1889 * the fallback is brute forcing through the fd
1892 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1893 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1895 if (fd_in_set(fd, except, n_except))
1898 if (close_nointr(fd) < 0)
1899 if (errno != EBADF && r == 0)
1906 while ((de = readdir(d))) {
1909 if (ignore_file(de->d_name))
1912 if (safe_atoi(de->d_name, &fd) < 0)
1913 /* Let's better ignore this, just in case */
1922 if (fd_in_set(fd, except, n_except))
1925 if (close_nointr(fd) < 0) {
1926 /* Valgrind has its own FD and doesn't want to have it closed */
1927 if (errno != EBADF && r == 0)
1936 bool chars_intersect(const char *a, const char *b) {
1939 /* Returns true if any of the chars in a are in b. */
1940 for (p = a; *p; p++)
1947 char *format_timestamp(char *buf, size_t l, usec_t t) {
1957 sec = (time_t) (t / USEC_PER_SEC);
1959 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1965 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1968 n = now(CLOCK_REALTIME);
1970 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1975 if (d >= USEC_PER_YEAR)
1976 snprintf(buf, l, "%llu years and %llu months ago",
1977 (unsigned long long) (d / USEC_PER_YEAR),
1978 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1979 else if (d >= USEC_PER_MONTH)
1980 snprintf(buf, l, "%llu months and %llu days ago",
1981 (unsigned long long) (d / USEC_PER_MONTH),
1982 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1983 else if (d >= USEC_PER_WEEK)
1984 snprintf(buf, l, "%llu weeks and %llu days ago",
1985 (unsigned long long) (d / USEC_PER_WEEK),
1986 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1987 else if (d >= 2*USEC_PER_DAY)
1988 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1989 else if (d >= 25*USEC_PER_HOUR)
1990 snprintf(buf, l, "1 day and %lluh ago",
1991 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1992 else if (d >= 6*USEC_PER_HOUR)
1993 snprintf(buf, l, "%lluh ago",
1994 (unsigned long long) (d / USEC_PER_HOUR));
1995 else if (d >= USEC_PER_HOUR)
1996 snprintf(buf, l, "%lluh %llumin ago",
1997 (unsigned long long) (d / USEC_PER_HOUR),
1998 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1999 else if (d >= 5*USEC_PER_MINUTE)
2000 snprintf(buf, l, "%llumin ago",
2001 (unsigned long long) (d / USEC_PER_MINUTE));
2002 else if (d >= USEC_PER_MINUTE)
2003 snprintf(buf, l, "%llumin %llus ago",
2004 (unsigned long long) (d / USEC_PER_MINUTE),
2005 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2006 else if (d >= USEC_PER_SEC)
2007 snprintf(buf, l, "%llus ago",
2008 (unsigned long long) (d / USEC_PER_SEC));
2009 else if (d >= USEC_PER_MSEC)
2010 snprintf(buf, l, "%llums ago",
2011 (unsigned long long) (d / USEC_PER_MSEC));
2013 snprintf(buf, l, "%lluus ago",
2014 (unsigned long long) d);
2016 snprintf(buf, l, "now");
2022 char *format_timespan(char *buf, size_t l, usec_t t) {
2023 static const struct {
2027 { "w", USEC_PER_WEEK },
2028 { "d", USEC_PER_DAY },
2029 { "h", USEC_PER_HOUR },
2030 { "min", USEC_PER_MINUTE },
2031 { "s", USEC_PER_SEC },
2032 { "ms", USEC_PER_MSEC },
2042 if (t == (usec_t) -1)
2046 snprintf(p, l, "0");
2051 /* The result of this function can be parsed with parse_usec */
2053 for (i = 0; i < ELEMENTSOF(table); i++) {
2057 if (t < table[i].usec)
2063 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2064 n = MIN((size_t) k, l);
2077 bool fstype_is_network(const char *fstype) {
2078 static const char table[] =
2087 return nulstr_contains(table, fstype);
2091 _cleanup_close_ int fd;
2093 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2099 TIOCL_GETKMSGREDIRECT,
2103 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2106 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2109 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2115 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2116 struct termios old_termios, new_termios;
2118 char line[LINE_MAX];
2123 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2124 new_termios = old_termios;
2126 new_termios.c_lflag &= ~ICANON;
2127 new_termios.c_cc[VMIN] = 1;
2128 new_termios.c_cc[VTIME] = 0;
2130 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2133 if (t != (usec_t) -1) {
2134 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2135 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2140 k = fread(&c, 1, 1, f);
2142 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2148 *need_nl = c != '\n';
2155 if (t != (usec_t) -1)
2156 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2159 if (!fgets(line, sizeof(line), f))
2164 if (strlen(line) != 1)
2174 int ask(char *ret, const char *replies, const char *text, ...) {
2184 bool need_nl = true;
2187 fputs(ANSI_HIGHLIGHT_ON, stdout);
2194 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2198 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2201 if (r == -EBADMSG) {
2202 puts("Bad input, please try again.");
2213 if (strchr(replies, c)) {
2218 puts("Read unexpected character, please try again.");
2222 int reset_terminal_fd(int fd, bool switch_to_text) {
2223 struct termios termios;
2226 /* Set terminal to some sane defaults */
2230 /* We leave locked terminal attributes untouched, so that
2231 * Plymouth may set whatever it wants to set, and we don't
2232 * interfere with that. */
2234 /* Disable exclusive mode, just in case */
2235 ioctl(fd, TIOCNXCL);
2237 /* Switch to text mode */
2239 ioctl(fd, KDSETMODE, KD_TEXT);
2241 /* Enable console unicode mode */
2242 ioctl(fd, KDSKBMODE, K_UNICODE);
2244 if (tcgetattr(fd, &termios) < 0) {
2249 /* We only reset the stuff that matters to the software. How
2250 * hardware is set up we don't touch assuming that somebody
2251 * else will do that for us */
2253 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2254 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2255 termios.c_oflag |= ONLCR;
2256 termios.c_cflag |= CREAD;
2257 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2259 termios.c_cc[VINTR] = 03; /* ^C */
2260 termios.c_cc[VQUIT] = 034; /* ^\ */
2261 termios.c_cc[VERASE] = 0177;
2262 termios.c_cc[VKILL] = 025; /* ^X */
2263 termios.c_cc[VEOF] = 04; /* ^D */
2264 termios.c_cc[VSTART] = 021; /* ^Q */
2265 termios.c_cc[VSTOP] = 023; /* ^S */
2266 termios.c_cc[VSUSP] = 032; /* ^Z */
2267 termios.c_cc[VLNEXT] = 026; /* ^V */
2268 termios.c_cc[VWERASE] = 027; /* ^W */
2269 termios.c_cc[VREPRINT] = 022; /* ^R */
2270 termios.c_cc[VEOL] = 0;
2271 termios.c_cc[VEOL2] = 0;
2273 termios.c_cc[VTIME] = 0;
2274 termios.c_cc[VMIN] = 1;
2276 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2280 /* Just in case, flush all crap out */
2281 tcflush(fd, TCIOFLUSH);
2286 int reset_terminal(const char *name) {
2289 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2293 r = reset_terminal_fd(fd, true);
2294 close_nointr_nofail(fd);
2299 int open_terminal(const char *name, int mode) {
2304 * If a TTY is in the process of being closed opening it might
2305 * cause EIO. This is horribly awful, but unlikely to be
2306 * changed in the kernel. Hence we work around this problem by
2307 * retrying a couple of times.
2309 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2313 fd = open(name, mode);
2320 /* Max 1s in total */
2324 usleep(50 * USEC_PER_MSEC);
2333 close_nointr_nofail(fd);
2338 close_nointr_nofail(fd);
2345 int flush_fd(int fd) {
2346 struct pollfd pollfd;
2350 pollfd.events = POLLIN;
2357 if ((r = poll(&pollfd, 1, 0)) < 0) {
2368 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2373 if (errno == EAGAIN)
2384 int acquire_terminal(
2388 bool ignore_tiocstty_eperm,
2391 int fd = -1, notify = -1, r = 0, wd = -1;
2393 struct sigaction sa_old, sa_new;
2397 /* We use inotify to be notified when the tty is closed. We
2398 * create the watch before checking if we can actually acquire
2399 * it, so that we don't lose any event.
2401 * Note: strictly speaking this actually watches for the
2402 * device being closed, it does *not* really watch whether a
2403 * tty loses its controlling process. However, unless some
2404 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2405 * its tty otherwise this will not become a problem. As long
2406 * as the administrator makes sure not configure any service
2407 * on the same tty as an untrusted user this should not be a
2408 * problem. (Which he probably should not do anyway.) */
2410 if (timeout != (usec_t) -1)
2411 ts = now(CLOCK_MONOTONIC);
2413 if (!fail && !force) {
2414 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2420 wd = inotify_add_watch(notify, name, IN_CLOSE);
2429 r = flush_fd(notify);
2434 /* We pass here O_NOCTTY only so that we can check the return
2435 * value TIOCSCTTY and have a reliable way to figure out if we
2436 * successfully became the controlling process of the tty */
2437 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2441 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2442 * if we already own the tty. */
2444 sa_new.sa_handler = SIG_IGN;
2445 sa_new.sa_flags = SA_RESTART;
2446 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2448 /* First, try to get the tty */
2449 if (ioctl(fd, TIOCSCTTY, force) < 0)
2452 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2454 /* Sometimes it makes sense to ignore TIOCSCTTY
2455 * returning EPERM, i.e. when very likely we already
2456 * are have this controlling terminal. */
2457 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2460 if (r < 0 && (force || fail || r != -EPERM)) {
2469 assert(notify >= 0);
2472 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2474 struct inotify_event *e;
2476 if (timeout != (usec_t) -1) {
2479 n = now(CLOCK_MONOTONIC);
2480 if (ts + timeout < n) {
2485 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2495 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2498 if (errno == EINTR || errno == EAGAIN)
2505 e = (struct inotify_event*) inotify_buffer;
2510 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2515 step = sizeof(struct inotify_event) + e->len;
2516 assert(step <= (size_t) l);
2518 e = (struct inotify_event*) ((uint8_t*) e + step);
2525 /* We close the tty fd here since if the old session
2526 * ended our handle will be dead. It's important that
2527 * we do this after sleeping, so that we don't enter
2528 * an endless loop. */
2529 close_nointr_nofail(fd);
2533 close_nointr_nofail(notify);
2535 r = reset_terminal_fd(fd, true);
2537 log_warning("Failed to reset terminal: %s", strerror(-r));
2543 close_nointr_nofail(fd);
2546 close_nointr_nofail(notify);
2551 int release_terminal(void) {
2553 struct sigaction sa_old, sa_new;
2555 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2558 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2559 * by our own TIOCNOTTY */
2562 sa_new.sa_handler = SIG_IGN;
2563 sa_new.sa_flags = SA_RESTART;
2564 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2566 if (ioctl(fd, TIOCNOTTY) < 0)
2569 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2571 close_nointr_nofail(fd);
2575 int sigaction_many(const struct sigaction *sa, ...) {
2580 while ((sig = va_arg(ap, int)) > 0)
2581 if (sigaction(sig, sa, NULL) < 0)
2588 int ignore_signals(int sig, ...) {
2589 struct sigaction sa;
2594 sa.sa_handler = SIG_IGN;
2595 sa.sa_flags = SA_RESTART;
2597 if (sigaction(sig, &sa, NULL) < 0)
2601 while ((sig = va_arg(ap, int)) > 0)
2602 if (sigaction(sig, &sa, NULL) < 0)
2609 int default_signals(int sig, ...) {
2610 struct sigaction sa;
2615 sa.sa_handler = SIG_DFL;
2616 sa.sa_flags = SA_RESTART;
2618 if (sigaction(sig, &sa, NULL) < 0)
2622 while ((sig = va_arg(ap, int)) > 0)
2623 if (sigaction(sig, &sa, NULL) < 0)
2630 int close_pipe(int p[]) {
2636 a = close_nointr(p[0]);
2641 b = close_nointr(p[1]);
2645 return a < 0 ? a : b;
2648 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2657 while (nbytes > 0) {
2660 if ((k = read(fd, p, nbytes)) <= 0) {
2662 if (k < 0 && errno == EINTR)
2665 if (k < 0 && errno == EAGAIN && do_poll) {
2666 struct pollfd pollfd;
2670 pollfd.events = POLLIN;
2672 if (poll(&pollfd, 1, -1) < 0) {
2676 return n > 0 ? n : -errno;
2679 if (pollfd.revents != POLLIN)
2680 return n > 0 ? n : -EIO;
2685 return n > 0 ? n : (k < 0 ? -errno : 0);
2696 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2705 while (nbytes > 0) {
2708 k = write(fd, p, nbytes);
2711 if (k < 0 && errno == EINTR)
2714 if (k < 0 && errno == EAGAIN && do_poll) {
2715 struct pollfd pollfd;
2719 pollfd.events = POLLOUT;
2721 if (poll(&pollfd, 1, -1) < 0) {
2725 return n > 0 ? n : -errno;
2728 if (pollfd.revents != POLLOUT)
2729 return n > 0 ? n : -EIO;
2734 return n > 0 ? n : (k < 0 ? -errno : 0);
2745 int parse_usec(const char *t, usec_t *usec) {
2746 static const struct {
2750 { "seconds", USEC_PER_SEC },
2751 { "second", USEC_PER_SEC },
2752 { "sec", USEC_PER_SEC },
2753 { "s", USEC_PER_SEC },
2754 { "minutes", USEC_PER_MINUTE },
2755 { "minute", USEC_PER_MINUTE },
2756 { "min", USEC_PER_MINUTE },
2757 { "months", USEC_PER_MONTH },
2758 { "month", USEC_PER_MONTH },
2759 { "msec", USEC_PER_MSEC },
2760 { "ms", USEC_PER_MSEC },
2761 { "m", USEC_PER_MINUTE },
2762 { "hours", USEC_PER_HOUR },
2763 { "hour", USEC_PER_HOUR },
2764 { "hr", USEC_PER_HOUR },
2765 { "h", USEC_PER_HOUR },
2766 { "days", USEC_PER_DAY },
2767 { "day", USEC_PER_DAY },
2768 { "d", USEC_PER_DAY },
2769 { "weeks", USEC_PER_WEEK },
2770 { "week", USEC_PER_WEEK },
2771 { "w", USEC_PER_WEEK },
2772 { "years", USEC_PER_YEAR },
2773 { "year", USEC_PER_YEAR },
2774 { "y", USEC_PER_YEAR },
2777 { "", USEC_PER_SEC }, /* default is sec */
2793 l = strtoll(p, &e, 10);
2804 e += strspn(e, WHITESPACE);
2806 for (i = 0; i < ELEMENTSOF(table); i++)
2807 if (startswith(e, table[i].suffix)) {
2808 r += (usec_t) l * table[i].usec;
2809 p = e + strlen(table[i].suffix);
2813 if (i >= ELEMENTSOF(table))
2823 int parse_nsec(const char *t, nsec_t *nsec) {
2824 static const struct {
2828 { "seconds", NSEC_PER_SEC },
2829 { "second", NSEC_PER_SEC },
2830 { "sec", NSEC_PER_SEC },
2831 { "s", NSEC_PER_SEC },
2832 { "minutes", NSEC_PER_MINUTE },
2833 { "minute", NSEC_PER_MINUTE },
2834 { "min", NSEC_PER_MINUTE },
2835 { "months", NSEC_PER_MONTH },
2836 { "month", NSEC_PER_MONTH },
2837 { "msec", NSEC_PER_MSEC },
2838 { "ms", NSEC_PER_MSEC },
2839 { "m", NSEC_PER_MINUTE },
2840 { "hours", NSEC_PER_HOUR },
2841 { "hour", NSEC_PER_HOUR },
2842 { "hr", NSEC_PER_HOUR },
2843 { "h", NSEC_PER_HOUR },
2844 { "days", NSEC_PER_DAY },
2845 { "day", NSEC_PER_DAY },
2846 { "d", NSEC_PER_DAY },
2847 { "weeks", NSEC_PER_WEEK },
2848 { "week", NSEC_PER_WEEK },
2849 { "w", NSEC_PER_WEEK },
2850 { "years", NSEC_PER_YEAR },
2851 { "year", NSEC_PER_YEAR },
2852 { "y", NSEC_PER_YEAR },
2853 { "usec", NSEC_PER_USEC },
2854 { "us", NSEC_PER_USEC },
2857 { "", 1ULL }, /* default is nsec */
2873 l = strtoll(p, &e, 10);
2884 e += strspn(e, WHITESPACE);
2886 for (i = 0; i < ELEMENTSOF(table); i++)
2887 if (startswith(e, table[i].suffix)) {
2888 r += (nsec_t) l * table[i].nsec;
2889 p = e + strlen(table[i].suffix);
2893 if (i >= ELEMENTSOF(table))
2903 int parse_bytes(const char *t, off_t *bytes) {
2904 static const struct {
2910 { "M", 1024ULL*1024ULL },
2911 { "G", 1024ULL*1024ULL*1024ULL },
2912 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2913 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2914 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2931 l = strtoll(p, &e, 10);
2942 e += strspn(e, WHITESPACE);
2944 for (i = 0; i < ELEMENTSOF(table); i++)
2945 if (startswith(e, table[i].suffix)) {
2946 r += (off_t) l * table[i].factor;
2947 p = e + strlen(table[i].suffix);
2951 if (i >= ELEMENTSOF(table))
2961 int make_stdio(int fd) {
2966 r = dup3(fd, STDIN_FILENO, 0);
2967 s = dup3(fd, STDOUT_FILENO, 0);
2968 t = dup3(fd, STDERR_FILENO, 0);
2971 close_nointr_nofail(fd);
2973 if (r < 0 || s < 0 || t < 0)
2976 /* We rely here that the new fd has O_CLOEXEC not set */
2981 int make_null_stdio(void) {
2984 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2988 return make_stdio(null_fd);
2991 bool is_device_path(const char *path) {
2993 /* Returns true on paths that refer to a device, either in
2994 * sysfs or in /dev */
2997 path_startswith(path, "/dev/") ||
2998 path_startswith(path, "/sys/");
3001 int dir_is_empty(const char *path) {
3002 _cleanup_closedir_ DIR *d;
3011 union dirent_storage buf;
3013 r = readdir_r(d, &buf.de, &de);
3020 if (!ignore_file(de->d_name))
3025 unsigned long long random_ull(void) {
3026 _cleanup_close_ int fd;
3030 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3034 r = loop_read(fd, &ull, sizeof(ull), true);
3035 if (r != sizeof(ull))
3041 return random() * RAND_MAX + random();
3044 void rename_process(const char name[8]) {
3047 /* This is a like a poor man's setproctitle(). It changes the
3048 * comm field, argv[0], and also the glibc's internally used
3049 * name of the process. For the first one a limit of 16 chars
3050 * applies, to the second one usually one of 10 (i.e. length
3051 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3052 * "systemd"). If you pass a longer string it will be
3055 prctl(PR_SET_NAME, name);
3057 if (program_invocation_name)
3058 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3060 if (saved_argc > 0) {
3064 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3066 for (i = 1; i < saved_argc; i++) {
3070 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3075 void sigset_add_many(sigset_t *ss, ...) {
3082 while ((sig = va_arg(ap, int)) > 0)
3083 assert_se(sigaddset(ss, sig) == 0);
3087 char* gethostname_malloc(void) {
3090 assert_se(uname(&u) >= 0);
3092 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3093 return strdup(u.nodename);
3095 return strdup(u.sysname);
3098 bool hostname_is_set(void) {
3101 assert_se(uname(&u) >= 0);
3103 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3106 static char *lookup_uid(uid_t uid) {
3109 _cleanup_free_ char *buf = NULL;
3110 struct passwd pwbuf, *pw = NULL;
3112 /* Shortcut things to avoid NSS lookups */
3114 return strdup("root");
3116 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3120 buf = malloc(bufsize);
3124 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3125 return strdup(pw->pw_name);
3127 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3133 char* getlogname_malloc(void) {
3137 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3142 return lookup_uid(uid);
3145 char *getusername_malloc(void) {
3152 return lookup_uid(getuid());
3155 int getttyname_malloc(int fd, char **r) {
3156 char path[PATH_MAX], *c;
3161 k = ttyname_r(fd, path, sizeof(path));
3167 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3175 int getttyname_harder(int fd, char **r) {
3179 k = getttyname_malloc(fd, &s);
3183 if (streq(s, "tty")) {
3185 return get_ctty(0, NULL, r);
3192 int get_ctty_devnr(pid_t pid, dev_t *d) {
3194 char line[LINE_MAX], *p, *fn;
3195 unsigned long ttynr;
3198 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3201 f = fopen(fn, "re");
3206 if (!fgets(line, sizeof(line), f)) {
3207 k = feof(f) ? -EIO : -errno;
3214 p = strrchr(line, ')');
3224 "%*d " /* session */
3233 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3235 char fn[PATH_MAX], *s, *b, *p;
3240 k = get_ctty_devnr(pid, &devnr);
3244 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3247 if ((k = readlink_malloc(fn, &s)) < 0) {
3252 /* This is an ugly hack */
3253 if (major(devnr) == 136) {
3254 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3264 /* Probably something like the ptys which have no
3265 * symlink in /dev/char. Let's return something
3266 * vaguely useful. */
3268 if (!(b = strdup(fn + 5)))
3278 if (startswith(s, "/dev/"))
3280 else if (startswith(s, "../"))
3298 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3304 /* This returns the first error we run into, but nevertheless
3305 * tries to go on. This closes the passed fd. */
3309 close_nointr_nofail(fd);
3311 return errno == ENOENT ? 0 : -errno;
3316 union dirent_storage buf;
3317 bool is_dir, keep_around;
3321 r = readdir_r(d, &buf.de, &de);
3322 if (r != 0 && ret == 0) {
3330 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3333 if (de->d_type == DT_UNKNOWN ||
3335 (de->d_type == DT_DIR && root_dev)) {
3336 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3337 if (ret == 0 && errno != ENOENT)
3342 is_dir = S_ISDIR(st.st_mode);
3345 (st.st_uid == 0 || st.st_uid == getuid()) &&
3346 (st.st_mode & S_ISVTX);
3348 is_dir = de->d_type == DT_DIR;
3349 keep_around = false;
3355 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3356 if (root_dev && st.st_dev != root_dev->st_dev)
3359 subdir_fd = openat(fd, de->d_name,
3360 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3361 if (subdir_fd < 0) {
3362 if (ret == 0 && errno != ENOENT)
3367 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3368 if (r < 0 && ret == 0)
3372 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3373 if (ret == 0 && errno != ENOENT)
3377 } else if (!only_dirs && !keep_around) {
3379 if (unlinkat(fd, de->d_name, 0) < 0) {
3380 if (ret == 0 && errno != ENOENT)
3391 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {