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>
67 #include "path-util.h"
68 #include "exit-status.h"
72 char **saved_argv = NULL;
74 static int parsed_columns = 0;
76 size_t page_size(void) {
77 static __thread size_t pgsz = 0;
80 if (_likely_(pgsz > 0))
83 r = sysconf(_SC_PAGESIZE);
90 bool streq_ptr(const char *a, const char *b) {
92 /* Like streq(), but tries to make sense of NULL pointers */
103 usec_t now(clockid_t clock_id) {
106 assert_se(clock_gettime(clock_id, &ts) == 0);
108 return timespec_load(&ts);
111 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
114 ts->realtime = now(CLOCK_REALTIME);
115 ts->monotonic = now(CLOCK_MONOTONIC);
120 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
129 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
131 ts->monotonic = now(CLOCK_MONOTONIC);
133 if ((int64_t) ts->monotonic > delta)
134 ts->monotonic -= delta;
142 usec_t timespec_load(const struct timespec *ts) {
146 (usec_t) ts->tv_sec * USEC_PER_SEC +
147 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
150 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
153 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
154 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
159 usec_t timeval_load(const struct timeval *tv) {
163 (usec_t) tv->tv_sec * USEC_PER_SEC +
164 (usec_t) tv->tv_usec;
167 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
170 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
171 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
176 bool endswith(const char *s, const char *postfix) {
183 pl = strlen(postfix);
191 return memcmp(s + sl - pl, postfix, pl) == 0;
194 bool startswith(const char *s, const char *prefix) {
209 return memcmp(s, prefix, pl) == 0;
212 bool startswith_no_case(const char *s, const char *prefix) {
228 for(i = 0; i < pl; ++i)
229 if (tolower(s[i]) != tolower(prefix[i]))
235 bool first_word(const char *s, const char *word) {
250 if (memcmp(s, word, wl) != 0)
254 strchr(WHITESPACE, s[wl]);
257 int close_nointr(int fd) {
272 void close_nointr_nofail(int fd) {
273 int saved_errno = errno;
275 /* like close_nointr() but cannot fail, and guarantees errno
278 assert_se(close_nointr(fd) == 0);
283 void close_many(const int fds[], unsigned n_fd) {
286 for (i = 0; i < n_fd; i++)
287 close_nointr_nofail(fds[i]);
290 int parse_boolean(const char *v) {
293 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
295 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
301 int parse_pid(const char *s, pid_t* ret_pid) {
302 unsigned long ul = 0;
309 r = safe_atolu(s, &ul);
315 if ((unsigned long) pid != ul)
325 int parse_uid(const char *s, uid_t* ret_uid) {
326 unsigned long ul = 0;
333 r = safe_atolu(s, &ul);
339 if ((unsigned long) uid != ul)
346 int safe_atou(const char *s, unsigned *ret_u) {
354 l = strtoul(s, &x, 0);
356 if (!x || *x || errno)
357 return errno ? -errno : -EINVAL;
359 if ((unsigned long) (unsigned) l != l)
362 *ret_u = (unsigned) l;
366 int safe_atoi(const char *s, int *ret_i) {
374 l = strtol(s, &x, 0);
376 if (!x || *x || errno)
377 return errno ? -errno : -EINVAL;
379 if ((long) (int) l != l)
386 int safe_atollu(const char *s, long long unsigned *ret_llu) {
388 unsigned long long l;
394 l = strtoull(s, &x, 0);
396 if (!x || *x || errno)
397 return errno ? -errno : -EINVAL;
403 int safe_atolli(const char *s, long long int *ret_lli) {
411 l = strtoll(s, &x, 0);
413 if (!x || *x || errno)
414 return errno ? -errno : -EINVAL;
420 /* Split a string into words. */
421 char *split(const char *c, size_t *l, const char *separator, char **state) {
424 current = *state ? *state : (char*) c;
426 if (!*current || *c == 0)
429 current += strspn(current, separator);
430 *l = strcspn(current, separator);
433 return (char*) current;
436 /* Split a string into words, but consider strings enclosed in '' and
437 * "" as words even if they include spaces. */
438 char *split_quoted(const char *c, size_t *l, char **state) {
440 bool escaped = false;
442 current = *state ? *state : (char*) c;
444 if (!*current || *c == 0)
447 current += strspn(current, WHITESPACE);
449 if (*current == '\'') {
452 for (e = current; *e; e++) {
462 *state = *e == 0 ? e : e+1;
463 } else if (*current == '\"') {
466 for (e = current; *e; e++) {
476 *state = *e == 0 ? e : e+1;
478 for (e = current; *e; e++) {
483 else if (strchr(WHITESPACE, *e))
490 return (char*) current;
493 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
495 _cleanup_fclose_ FILE *f = NULL;
496 char fn[PATH_MAX], line[LINE_MAX], *p;
502 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
509 if (!fgets(line, sizeof(line), f)) {
510 r = feof(f) ? -EIO : -errno;
515 /* Let's skip the pid and comm fields. The latter is enclosed
516 * in () but does not escape any () in its value, so let's
517 * skip over it manually */
519 p = strrchr(line, ')');
531 if ((long unsigned) (pid_t) ppid != ppid)
534 *_ppid = (pid_t) ppid;
539 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
540 _cleanup_fclose_ FILE *f = NULL;
541 char fn[PATH_MAX], line[LINE_MAX], *p;
546 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
553 if (!fgets(line, sizeof(line), f)) {
560 /* Let's skip the pid and comm fields. The latter is enclosed
561 * in () but does not escape any () in its value, so let's
562 * skip over it manually */
564 p = strrchr(line, ')');
586 "%*d " /* priority */
588 "%*d " /* num_threads */
589 "%*d " /* itrealvalue */
590 "%llu " /* starttime */,
597 int write_one_line_file(const char *fn, const char *line) {
598 _cleanup_fclose_ FILE *f = NULL;
608 if (fputs(line, f) < 0)
609 return errno ? -errno : -EIO;
611 if (!endswith(line, "\n"))
617 return errno ? -errno : -EIO;
622 int fchmod_umask(int fd, mode_t m) {
627 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
633 int write_one_line_file_atomic(const char *fn, const char *line) {
641 r = fopen_temporary(fn, &f, &p);
645 fchmod_umask(fileno(f), 0644);
648 if (fputs(line, f) < 0) {
653 if (!endswith(line, "\n"))
664 if (rename(p, fn) < 0)
680 int read_one_line_file(const char *fn, char **line) {
681 _cleanup_fclose_ FILE *f = NULL;
682 char t[LINE_MAX], *c;
691 if (!fgets(t, sizeof(t), f)) {
694 return errno ? -errno : -EIO;
708 int read_full_file(const char *fn, char **contents, size_t *size) {
709 _cleanup_fclose_ FILE *f = NULL;
711 _cleanup_free_ char *buf = NULL;
718 if (fstat(fileno(f), &st) < 0)
722 if (st.st_size > 4*1024*1024)
725 n = st.st_size > 0 ? st.st_size : LINE_MAX;
732 t = realloc(buf, n+1);
737 k = fread(buf + l, 1, n - l, f);
766 const char *separator, ...) {
769 char *contents = NULL, *p;
774 if ((r = read_full_file(fname, &contents, NULL)) < 0)
779 const char *key = NULL;
781 p += strspn(p, separator);
782 p += strspn(p, WHITESPACE);
787 if (!strchr(COMMENTS, *p)) {
791 va_start(ap, separator);
792 while ((key = va_arg(ap, char *))) {
796 value = va_arg(ap, char **);
799 if (strncmp(p, key, n) != 0 ||
804 n = strcspn(p, separator);
807 strchr(QUOTES, p[0]) &&
809 v = strndup(p+1, n-2);
820 /* return empty value strings as NULL */
837 p += strcspn(p, separator);
856 if (!(f = fopen(fname, "re")))
860 char l[LINE_MAX], *p, *u;
863 if (!fgets(l, sizeof(l), f)) {
876 if (strchr(COMMENTS, *p))
879 if (!(u = normalize_env_assignment(p))) {
884 t = strv_append(m, u);
910 int write_env_file(const char *fname, char **l) {
915 r = fopen_temporary(fname, &f, &p);
919 fchmod_umask(fileno(f), 0644);
935 if (rename(p, fname) < 0)
950 char *truncate_nl(char *s) {
953 s[strcspn(s, NEWLINE)] = 0;
957 int get_process_comm(pid_t pid, char **name) {
963 r = read_one_line_file("/proc/self/comm", name);
966 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
969 r = read_one_line_file(p, name);
976 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
983 assert(max_length > 0);
987 f = fopen("/proc/self/cmdline", "re");
990 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1000 r = new(char, max_length);
1008 while ((c = getc(f)) != EOF) {
1030 size_t n = MIN(left-1, 3U);
1031 memcpy(k, "...", n);
1038 /* Kernel threads have no argv[] */
1048 h = get_process_comm(pid, &t);
1052 r = strjoin("[", t, "]", NULL);
1063 int is_kernel_thread(pid_t pid) {
1073 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1082 count = fread(&c, 1, 1, f);
1086 /* Kernel threads have an empty cmdline */
1089 return eof ? 1 : -errno;
1094 int get_process_exe(pid_t pid, char **name) {
1100 r = readlink_malloc("/proc/self/exe", name);
1103 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1106 r = readlink_malloc(p, name);
1113 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1123 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1133 char line[LINE_MAX], *l;
1135 if (!fgets(line, sizeof(line), f)) {
1145 if (startswith(l, field)) {
1147 l += strspn(l, WHITESPACE);
1149 l[strcspn(l, WHITESPACE)] = 0;
1151 r = parse_uid(l, uid);
1164 int get_process_uid(pid_t pid, uid_t *uid) {
1165 return get_process_id(pid, "Uid:", uid);
1168 int get_process_gid(pid_t pid, gid_t *gid) {
1169 return get_process_id(pid, "Gid:", gid);
1172 char *strnappend(const char *s, const char *suffix, size_t b) {
1180 return strndup(suffix, b);
1189 if (b > ((size_t) -1) - a)
1192 r = new(char, a+b+1);
1197 memcpy(r+a, suffix, b);
1203 char *strappend(const char *s, const char *suffix) {
1204 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1207 int readlink_malloc(const char *p, char **r) {
1217 if (!(c = new(char, l)))
1220 if ((n = readlink(p, c, l-1)) < 0) {
1226 if ((size_t) n < l-1) {
1237 int readlink_and_make_absolute(const char *p, char **r) {
1244 if ((j = readlink_malloc(p, &target)) < 0)
1247 k = file_in_same_dir(p, target);
1257 int readlink_and_canonicalize(const char *p, char **r) {
1264 j = readlink_and_make_absolute(p, &t);
1268 s = canonicalize_file_name(t);
1275 path_kill_slashes(*r);
1280 int reset_all_signal_handlers(void) {
1283 for (sig = 1; sig < _NSIG; sig++) {
1284 struct sigaction sa;
1286 if (sig == SIGKILL || sig == SIGSTOP)
1290 sa.sa_handler = SIG_DFL;
1291 sa.sa_flags = SA_RESTART;
1293 /* On Linux the first two RT signals are reserved by
1294 * glibc, and sigaction() will return EINVAL for them. */
1295 if ((sigaction(sig, &sa, NULL) < 0))
1296 if (errno != EINVAL)
1303 char *strstrip(char *s) {
1306 /* Drops trailing whitespace. Modifies the string in
1307 * place. Returns pointer to first non-space character */
1309 s += strspn(s, WHITESPACE);
1311 for (e = strchr(s, 0); e > s; e --)
1312 if (!strchr(WHITESPACE, e[-1]))
1320 char *delete_chars(char *s, const char *bad) {
1323 /* Drops all whitespace, regardless where in the string */
1325 for (f = s, t = s; *f; f++) {
1326 if (strchr(bad, *f))
1337 bool in_charset(const char *s, const char* charset) {
1343 for (i = s; *i; i++)
1344 if (!strchr(charset, *i))
1350 char *file_in_same_dir(const char *path, const char *filename) {
1357 /* This removes the last component of path and appends
1358 * filename, unless the latter is absolute anyway or the
1361 if (path_is_absolute(filename))
1362 return strdup(filename);
1364 if (!(e = strrchr(path, '/')))
1365 return strdup(filename);
1367 k = strlen(filename);
1368 if (!(r = new(char, e-path+1+k+1)))
1371 memcpy(r, path, e-path+1);
1372 memcpy(r+(e-path)+1, filename, k+1);
1377 int rmdir_parents(const char *path, const char *stop) {
1386 /* Skip trailing slashes */
1387 while (l > 0 && path[l-1] == '/')
1393 /* Skip last component */
1394 while (l > 0 && path[l-1] != '/')
1397 /* Skip trailing slashes */
1398 while (l > 0 && path[l-1] == '/')
1404 if (!(t = strndup(path, l)))
1407 if (path_startswith(stop, t)) {
1416 if (errno != ENOENT)
1424 char hexchar(int x) {
1425 static const char table[16] = "0123456789abcdef";
1427 return table[x & 15];
1430 int unhexchar(char c) {
1432 if (c >= '0' && c <= '9')
1435 if (c >= 'a' && c <= 'f')
1436 return c - 'a' + 10;
1438 if (c >= 'A' && c <= 'F')
1439 return c - 'A' + 10;
1444 char octchar(int x) {
1445 return '0' + (x & 7);
1448 int unoctchar(char c) {
1450 if (c >= '0' && c <= '7')
1456 char decchar(int x) {
1457 return '0' + (x % 10);
1460 int undecchar(char c) {
1462 if (c >= '0' && c <= '9')
1468 char *cescape(const char *s) {
1474 /* Does C style string escaping. */
1476 r = new(char, strlen(s)*4 + 1);
1480 for (f = s, t = r; *f; f++)
1526 /* For special chars we prefer octal over
1527 * hexadecimal encoding, simply because glib's
1528 * g_strescape() does the same */
1529 if ((*f < ' ') || (*f >= 127)) {
1531 *(t++) = octchar((unsigned char) *f >> 6);
1532 *(t++) = octchar((unsigned char) *f >> 3);
1533 *(t++) = octchar((unsigned char) *f);
1544 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1551 /* Undoes C style string escaping, and optionally prefixes it. */
1553 pl = prefix ? strlen(prefix) : 0;
1555 r = new(char, pl+length+1);
1560 memcpy(r, prefix, pl);
1562 for (f = s, t = r + pl; f < s + length; f++) {
1605 /* This is an extension of the XDG syntax files */
1610 /* hexadecimal encoding */
1613 a = unhexchar(f[1]);
1614 b = unhexchar(f[2]);
1616 if (a < 0 || b < 0) {
1617 /* Invalid escape code, let's take it literal then */
1621 *(t++) = (char) ((a << 4) | b);
1636 /* octal encoding */
1639 a = unoctchar(f[0]);
1640 b = unoctchar(f[1]);
1641 c = unoctchar(f[2]);
1643 if (a < 0 || b < 0 || c < 0) {
1644 /* Invalid escape code, let's take it literal then */
1648 *(t++) = (char) ((a << 6) | (b << 3) | c);
1656 /* premature end of string.*/
1661 /* Invalid escape code, let's take it literal then */
1673 char *cunescape_length(const char *s, size_t length) {
1674 return cunescape_length_with_prefix(s, length, NULL);
1677 char *cunescape(const char *s) {
1680 return cunescape_length(s, strlen(s));
1683 char *xescape(const char *s, const char *bad) {
1687 /* Escapes all chars in bad, in addition to \ and all special
1688 * chars, in \xFF style escaping. May be reversed with
1691 r = new(char, strlen(s) * 4 + 1);
1695 for (f = s, t = r; *f; f++) {
1697 if ((*f < ' ') || (*f >= 127) ||
1698 (*f == '\\') || strchr(bad, *f)) {
1701 *(t++) = hexchar(*f >> 4);
1702 *(t++) = hexchar(*f);
1712 char *bus_path_escape(const char *s) {
1718 /* Escapes all chars that D-Bus' object path cannot deal
1719 * with. Can be reverse with bus_path_unescape() */
1721 if (!(r = new(char, strlen(s)*3+1)))
1724 for (f = s, t = r; *f; f++) {
1726 if (!(*f >= 'A' && *f <= 'Z') &&
1727 !(*f >= 'a' && *f <= 'z') &&
1728 !(*f >= '0' && *f <= '9')) {
1730 *(t++) = hexchar(*f >> 4);
1731 *(t++) = hexchar(*f);
1741 char *bus_path_unescape(const char *f) {
1746 if (!(r = strdup(f)))
1749 for (t = r; *f; f++) {
1754 if ((a = unhexchar(f[1])) < 0 ||
1755 (b = unhexchar(f[2])) < 0) {
1756 /* Invalid escape code, let's take it literal then */
1759 *(t++) = (char) ((a << 4) | b);
1771 char *ascii_strlower(char *t) {
1776 for (p = t; *p; p++)
1777 if (*p >= 'A' && *p <= 'Z')
1778 *p = *p - 'A' + 'a';
1783 static bool ignore_file_allow_backup(const char *filename) {
1787 filename[0] == '.' ||
1788 streq(filename, "lost+found") ||
1789 streq(filename, "aquota.user") ||
1790 streq(filename, "aquota.group") ||
1791 endswith(filename, ".rpmnew") ||
1792 endswith(filename, ".rpmsave") ||
1793 endswith(filename, ".rpmorig") ||
1794 endswith(filename, ".dpkg-old") ||
1795 endswith(filename, ".dpkg-new") ||
1796 endswith(filename, ".swp");
1799 bool ignore_file(const char *filename) {
1802 if (endswith(filename, "~"))
1805 return ignore_file_allow_backup(filename);
1808 int fd_nonblock(int fd, bool nonblock) {
1813 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1817 flags |= O_NONBLOCK;
1819 flags &= ~O_NONBLOCK;
1821 if (fcntl(fd, F_SETFL, flags) < 0)
1827 int fd_cloexec(int fd, bool cloexec) {
1832 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1836 flags |= FD_CLOEXEC;
1838 flags &= ~FD_CLOEXEC;
1840 if (fcntl(fd, F_SETFD, flags) < 0)
1846 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1849 assert(n_fdset == 0 || fdset);
1851 for (i = 0; i < n_fdset; i++)
1858 int close_all_fds(const int except[], unsigned n_except) {
1863 assert(n_except == 0 || except);
1865 d = opendir("/proc/self/fd");
1870 /* When /proc isn't available (for example in chroots)
1871 * the fallback is brute forcing through the fd
1874 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1875 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1877 if (fd_in_set(fd, except, n_except))
1880 if (close_nointr(fd) < 0)
1881 if (errno != EBADF && r == 0)
1888 while ((de = readdir(d))) {
1891 if (ignore_file(de->d_name))
1894 if (safe_atoi(de->d_name, &fd) < 0)
1895 /* Let's better ignore this, just in case */
1904 if (fd_in_set(fd, except, n_except))
1907 if (close_nointr(fd) < 0) {
1908 /* Valgrind has its own FD and doesn't want to have it closed */
1909 if (errno != EBADF && r == 0)
1918 bool chars_intersect(const char *a, const char *b) {
1921 /* Returns true if any of the chars in a are in b. */
1922 for (p = a; *p; p++)
1929 char *format_timestamp(char *buf, size_t l, usec_t t) {
1939 sec = (time_t) (t / USEC_PER_SEC);
1941 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1947 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1950 n = now(CLOCK_REALTIME);
1952 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1957 if (d >= USEC_PER_YEAR)
1958 snprintf(buf, l, "%llu years and %llu months ago",
1959 (unsigned long long) (d / USEC_PER_YEAR),
1960 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1961 else if (d >= USEC_PER_MONTH)
1962 snprintf(buf, l, "%llu months and %llu days ago",
1963 (unsigned long long) (d / USEC_PER_MONTH),
1964 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1965 else if (d >= USEC_PER_WEEK)
1966 snprintf(buf, l, "%llu weeks and %llu days ago",
1967 (unsigned long long) (d / USEC_PER_WEEK),
1968 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1969 else if (d >= 2*USEC_PER_DAY)
1970 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1971 else if (d >= 25*USEC_PER_HOUR)
1972 snprintf(buf, l, "1 day and %lluh ago",
1973 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1974 else if (d >= 6*USEC_PER_HOUR)
1975 snprintf(buf, l, "%lluh ago",
1976 (unsigned long long) (d / USEC_PER_HOUR));
1977 else if (d >= USEC_PER_HOUR)
1978 snprintf(buf, l, "%lluh %llumin ago",
1979 (unsigned long long) (d / USEC_PER_HOUR),
1980 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1981 else if (d >= 5*USEC_PER_MINUTE)
1982 snprintf(buf, l, "%llumin ago",
1983 (unsigned long long) (d / USEC_PER_MINUTE));
1984 else if (d >= USEC_PER_MINUTE)
1985 snprintf(buf, l, "%llumin %llus ago",
1986 (unsigned long long) (d / USEC_PER_MINUTE),
1987 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1988 else if (d >= USEC_PER_SEC)
1989 snprintf(buf, l, "%llus ago",
1990 (unsigned long long) (d / USEC_PER_SEC));
1991 else if (d >= USEC_PER_MSEC)
1992 snprintf(buf, l, "%llums ago",
1993 (unsigned long long) (d / USEC_PER_MSEC));
1995 snprintf(buf, l, "%lluus ago",
1996 (unsigned long long) d);
1998 snprintf(buf, l, "now");
2004 char *format_timespan(char *buf, size_t l, usec_t t) {
2005 static const struct {
2009 { "w", USEC_PER_WEEK },
2010 { "d", USEC_PER_DAY },
2011 { "h", USEC_PER_HOUR },
2012 { "min", USEC_PER_MINUTE },
2013 { "s", USEC_PER_SEC },
2014 { "ms", USEC_PER_MSEC },
2024 if (t == (usec_t) -1)
2028 snprintf(p, l, "0");
2033 /* The result of this function can be parsed with parse_usec */
2035 for (i = 0; i < ELEMENTSOF(table); i++) {
2039 if (t < table[i].usec)
2045 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2046 n = MIN((size_t) k, l);
2059 bool fstype_is_network(const char *fstype) {
2060 static const char table[] =
2069 return nulstr_contains(table, fstype);
2073 _cleanup_close_ int fd;
2075 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2081 TIOCL_GETKMSGREDIRECT,
2085 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2088 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2091 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2097 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2098 struct termios old_termios, new_termios;
2100 char line[LINE_MAX];
2105 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2106 new_termios = old_termios;
2108 new_termios.c_lflag &= ~ICANON;
2109 new_termios.c_cc[VMIN] = 1;
2110 new_termios.c_cc[VTIME] = 0;
2112 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2115 if (t != (usec_t) -1) {
2116 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2117 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2122 k = fread(&c, 1, 1, f);
2124 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2130 *need_nl = c != '\n';
2137 if (t != (usec_t) -1)
2138 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2141 if (!fgets(line, sizeof(line), f))
2146 if (strlen(line) != 1)
2156 int ask(char *ret, const char *replies, const char *text, ...) {
2163 on_tty = isatty(STDOUT_FILENO);
2169 bool need_nl = true;
2172 fputs(ANSI_HIGHLIGHT_ON, stdout);
2179 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2183 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2186 if (r == -EBADMSG) {
2187 puts("Bad input, please try again.");
2198 if (strchr(replies, c)) {
2203 puts("Read unexpected character, please try again.");
2207 int reset_terminal_fd(int fd, bool switch_to_text) {
2208 struct termios termios;
2211 /* Set terminal to some sane defaults */
2215 /* We leave locked terminal attributes untouched, so that
2216 * Plymouth may set whatever it wants to set, and we don't
2217 * interfere with that. */
2219 /* Disable exclusive mode, just in case */
2220 ioctl(fd, TIOCNXCL);
2222 /* Switch to text mode */
2224 ioctl(fd, KDSETMODE, KD_TEXT);
2226 /* Enable console unicode mode */
2227 ioctl(fd, KDSKBMODE, K_UNICODE);
2229 if (tcgetattr(fd, &termios) < 0) {
2234 /* We only reset the stuff that matters to the software. How
2235 * hardware is set up we don't touch assuming that somebody
2236 * else will do that for us */
2238 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2239 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2240 termios.c_oflag |= ONLCR;
2241 termios.c_cflag |= CREAD;
2242 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2244 termios.c_cc[VINTR] = 03; /* ^C */
2245 termios.c_cc[VQUIT] = 034; /* ^\ */
2246 termios.c_cc[VERASE] = 0177;
2247 termios.c_cc[VKILL] = 025; /* ^X */
2248 termios.c_cc[VEOF] = 04; /* ^D */
2249 termios.c_cc[VSTART] = 021; /* ^Q */
2250 termios.c_cc[VSTOP] = 023; /* ^S */
2251 termios.c_cc[VSUSP] = 032; /* ^Z */
2252 termios.c_cc[VLNEXT] = 026; /* ^V */
2253 termios.c_cc[VWERASE] = 027; /* ^W */
2254 termios.c_cc[VREPRINT] = 022; /* ^R */
2255 termios.c_cc[VEOL] = 0;
2256 termios.c_cc[VEOL2] = 0;
2258 termios.c_cc[VTIME] = 0;
2259 termios.c_cc[VMIN] = 1;
2261 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2265 /* Just in case, flush all crap out */
2266 tcflush(fd, TCIOFLUSH);
2271 int reset_terminal(const char *name) {
2274 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2278 r = reset_terminal_fd(fd, true);
2279 close_nointr_nofail(fd);
2284 int open_terminal(const char *name, int mode) {
2289 * If a TTY is in the process of being closed opening it might
2290 * cause EIO. This is horribly awful, but unlikely to be
2291 * changed in the kernel. Hence we work around this problem by
2292 * retrying a couple of times.
2294 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2298 fd = open(name, mode);
2305 /* Max 1s in total */
2309 usleep(50 * USEC_PER_MSEC);
2318 close_nointr_nofail(fd);
2323 close_nointr_nofail(fd);
2330 int flush_fd(int fd) {
2331 struct pollfd pollfd;
2335 pollfd.events = POLLIN;
2342 if ((r = poll(&pollfd, 1, 0)) < 0) {
2353 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2358 if (errno == EAGAIN)
2369 int acquire_terminal(
2373 bool ignore_tiocstty_eperm,
2376 int fd = -1, notify = -1, r = 0, wd = -1;
2378 struct sigaction sa_old, sa_new;
2382 /* We use inotify to be notified when the tty is closed. We
2383 * create the watch before checking if we can actually acquire
2384 * it, so that we don't lose any event.
2386 * Note: strictly speaking this actually watches for the
2387 * device being closed, it does *not* really watch whether a
2388 * tty loses its controlling process. However, unless some
2389 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2390 * its tty otherwise this will not become a problem. As long
2391 * as the administrator makes sure not configure any service
2392 * on the same tty as an untrusted user this should not be a
2393 * problem. (Which he probably should not do anyway.) */
2395 if (timeout != (usec_t) -1)
2396 ts = now(CLOCK_MONOTONIC);
2398 if (!fail && !force) {
2399 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2405 wd = inotify_add_watch(notify, name, IN_CLOSE);
2414 r = flush_fd(notify);
2419 /* We pass here O_NOCTTY only so that we can check the return
2420 * value TIOCSCTTY and have a reliable way to figure out if we
2421 * successfully became the controlling process of the tty */
2422 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2426 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2427 * if we already own the tty. */
2429 sa_new.sa_handler = SIG_IGN;
2430 sa_new.sa_flags = SA_RESTART;
2431 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2433 /* First, try to get the tty */
2434 if (ioctl(fd, TIOCSCTTY, force) < 0)
2437 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2439 /* Sometimes it makes sense to ignore TIOCSCTTY
2440 * returning EPERM, i.e. when very likely we already
2441 * are have this controlling terminal. */
2442 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2445 if (r < 0 && (force || fail || r != -EPERM)) {
2454 assert(notify >= 0);
2457 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2459 struct inotify_event *e;
2461 if (timeout != (usec_t) -1) {
2464 n = now(CLOCK_MONOTONIC);
2465 if (ts + timeout < n) {
2470 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2480 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2483 if (errno == EINTR || errno == EAGAIN)
2490 e = (struct inotify_event*) inotify_buffer;
2495 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2500 step = sizeof(struct inotify_event) + e->len;
2501 assert(step <= (size_t) l);
2503 e = (struct inotify_event*) ((uint8_t*) e + step);
2510 /* We close the tty fd here since if the old session
2511 * ended our handle will be dead. It's important that
2512 * we do this after sleeping, so that we don't enter
2513 * an endless loop. */
2514 close_nointr_nofail(fd);
2518 close_nointr_nofail(notify);
2520 r = reset_terminal_fd(fd, true);
2522 log_warning("Failed to reset terminal: %s", strerror(-r));
2528 close_nointr_nofail(fd);
2531 close_nointr_nofail(notify);
2536 int release_terminal(void) {
2538 struct sigaction sa_old, sa_new;
2540 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2543 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2544 * by our own TIOCNOTTY */
2547 sa_new.sa_handler = SIG_IGN;
2548 sa_new.sa_flags = SA_RESTART;
2549 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2551 if (ioctl(fd, TIOCNOTTY) < 0)
2554 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2556 close_nointr_nofail(fd);
2560 int sigaction_many(const struct sigaction *sa, ...) {
2565 while ((sig = va_arg(ap, int)) > 0)
2566 if (sigaction(sig, sa, NULL) < 0)
2573 int ignore_signals(int sig, ...) {
2574 struct sigaction sa;
2579 sa.sa_handler = SIG_IGN;
2580 sa.sa_flags = SA_RESTART;
2582 if (sigaction(sig, &sa, NULL) < 0)
2586 while ((sig = va_arg(ap, int)) > 0)
2587 if (sigaction(sig, &sa, NULL) < 0)
2594 int default_signals(int sig, ...) {
2595 struct sigaction sa;
2600 sa.sa_handler = SIG_DFL;
2601 sa.sa_flags = SA_RESTART;
2603 if (sigaction(sig, &sa, NULL) < 0)
2607 while ((sig = va_arg(ap, int)) > 0)
2608 if (sigaction(sig, &sa, NULL) < 0)
2615 int close_pipe(int p[]) {
2621 a = close_nointr(p[0]);
2626 b = close_nointr(p[1]);
2630 return a < 0 ? a : b;
2633 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2642 while (nbytes > 0) {
2645 if ((k = read(fd, p, nbytes)) <= 0) {
2647 if (k < 0 && errno == EINTR)
2650 if (k < 0 && errno == EAGAIN && do_poll) {
2651 struct pollfd pollfd;
2655 pollfd.events = POLLIN;
2657 if (poll(&pollfd, 1, -1) < 0) {
2661 return n > 0 ? n : -errno;
2664 if (pollfd.revents != POLLIN)
2665 return n > 0 ? n : -EIO;
2670 return n > 0 ? n : (k < 0 ? -errno : 0);
2681 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2690 while (nbytes > 0) {
2693 k = write(fd, p, nbytes);
2696 if (k < 0 && errno == EINTR)
2699 if (k < 0 && errno == EAGAIN && do_poll) {
2700 struct pollfd pollfd;
2704 pollfd.events = POLLOUT;
2706 if (poll(&pollfd, 1, -1) < 0) {
2710 return n > 0 ? n : -errno;
2713 if (pollfd.revents != POLLOUT)
2714 return n > 0 ? n : -EIO;
2719 return n > 0 ? n : (k < 0 ? -errno : 0);
2730 int parse_usec(const char *t, usec_t *usec) {
2731 static const struct {
2735 { "sec", USEC_PER_SEC },
2736 { "s", USEC_PER_SEC },
2737 { "min", USEC_PER_MINUTE },
2738 { "hr", USEC_PER_HOUR },
2739 { "h", USEC_PER_HOUR },
2740 { "d", USEC_PER_DAY },
2741 { "w", USEC_PER_WEEK },
2742 { "msec", USEC_PER_MSEC },
2743 { "ms", USEC_PER_MSEC },
2744 { "m", USEC_PER_MINUTE },
2747 { "", USEC_PER_SEC }, /* default is sec */
2763 l = strtoll(p, &e, 10);
2774 e += strspn(e, WHITESPACE);
2776 for (i = 0; i < ELEMENTSOF(table); i++)
2777 if (startswith(e, table[i].suffix)) {
2778 r += (usec_t) l * table[i].usec;
2779 p = e + strlen(table[i].suffix);
2783 if (i >= ELEMENTSOF(table))
2793 int parse_nsec(const char *t, nsec_t *nsec) {
2794 static const struct {
2798 { "sec", NSEC_PER_SEC },
2799 { "s", NSEC_PER_SEC },
2800 { "min", NSEC_PER_MINUTE },
2801 { "hr", NSEC_PER_HOUR },
2802 { "h", NSEC_PER_HOUR },
2803 { "d", NSEC_PER_DAY },
2804 { "w", NSEC_PER_WEEK },
2805 { "msec", NSEC_PER_MSEC },
2806 { "ms", NSEC_PER_MSEC },
2807 { "m", NSEC_PER_MINUTE },
2808 { "usec", NSEC_PER_USEC },
2809 { "us", NSEC_PER_USEC },
2812 { "", 1ULL }, /* default is nsec */
2828 l = strtoll(p, &e, 10);
2839 e += strspn(e, WHITESPACE);
2841 for (i = 0; i < ELEMENTSOF(table); i++)
2842 if (startswith(e, table[i].suffix)) {
2843 r += (nsec_t) l * table[i].nsec;
2844 p = e + strlen(table[i].suffix);
2848 if (i >= ELEMENTSOF(table))
2858 int parse_bytes(const char *t, off_t *bytes) {
2859 static const struct {
2865 { "M", 1024ULL*1024ULL },
2866 { "G", 1024ULL*1024ULL*1024ULL },
2867 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2868 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2869 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2886 l = strtoll(p, &e, 10);
2897 e += strspn(e, WHITESPACE);
2899 for (i = 0; i < ELEMENTSOF(table); i++)
2900 if (startswith(e, table[i].suffix)) {
2901 r += (off_t) l * table[i].factor;
2902 p = e + strlen(table[i].suffix);
2906 if (i >= ELEMENTSOF(table))
2916 int make_stdio(int fd) {
2921 r = dup3(fd, STDIN_FILENO, 0);
2922 s = dup3(fd, STDOUT_FILENO, 0);
2923 t = dup3(fd, STDERR_FILENO, 0);
2926 close_nointr_nofail(fd);
2928 if (r < 0 || s < 0 || t < 0)
2931 /* We rely here that the new fd has O_CLOEXEC not set */
2936 int make_null_stdio(void) {
2939 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2943 return make_stdio(null_fd);
2946 bool is_device_path(const char *path) {
2948 /* Returns true on paths that refer to a device, either in
2949 * sysfs or in /dev */
2952 path_startswith(path, "/dev/") ||
2953 path_startswith(path, "/sys/");
2956 int dir_is_empty(const char *path) {
2957 _cleanup_closedir_ DIR *d;
2966 union dirent_storage buf;
2968 r = readdir_r(d, &buf.de, &de);
2975 if (!ignore_file(de->d_name))
2980 unsigned long long random_ull(void) {
2981 _cleanup_close_ int fd;
2985 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2989 r = loop_read(fd, &ull, sizeof(ull), true);
2990 if (r != sizeof(ull))
2996 return random() * RAND_MAX + random();
2999 void rename_process(const char name[8]) {
3002 /* This is a like a poor man's setproctitle(). It changes the
3003 * comm field, argv[0], and also the glibc's internally used
3004 * name of the process. For the first one a limit of 16 chars
3005 * applies, to the second one usually one of 10 (i.e. length
3006 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3007 * "systemd"). If you pass a longer string it will be
3010 prctl(PR_SET_NAME, name);
3012 if (program_invocation_name)
3013 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3015 if (saved_argc > 0) {
3019 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3021 for (i = 1; i < saved_argc; i++) {
3025 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3030 void sigset_add_many(sigset_t *ss, ...) {
3037 while ((sig = va_arg(ap, int)) > 0)
3038 assert_se(sigaddset(ss, sig) == 0);
3042 char* gethostname_malloc(void) {
3045 assert_se(uname(&u) >= 0);
3047 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3048 return strdup(u.nodename);
3050 return strdup(u.sysname);
3053 bool hostname_is_set(void) {
3056 assert_se(uname(&u) >= 0);
3058 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3061 static char *lookup_uid(uid_t uid) {
3064 _cleanup_free_ char *buf = NULL;
3065 struct passwd pwbuf, *pw = NULL;
3067 /* Shortcut things to avoid NSS lookups */
3069 return strdup("root");
3071 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3075 buf = malloc(bufsize);
3079 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3080 return strdup(pw->pw_name);
3082 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3088 char* getlogname_malloc(void) {
3092 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3097 return lookup_uid(uid);
3100 char *getusername_malloc(void) {
3107 return lookup_uid(getuid());
3110 int getttyname_malloc(int fd, char **r) {
3111 char path[PATH_MAX], *c;
3116 k = ttyname_r(fd, path, sizeof(path));
3122 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3130 int getttyname_harder(int fd, char **r) {
3134 k = getttyname_malloc(fd, &s);
3138 if (streq(s, "tty")) {
3140 return get_ctty(0, NULL, r);
3147 int get_ctty_devnr(pid_t pid, dev_t *d) {
3149 char line[LINE_MAX], *p, *fn;
3150 unsigned long ttynr;
3153 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3156 f = fopen(fn, "re");
3161 if (!fgets(line, sizeof(line), f)) {
3162 k = feof(f) ? -EIO : -errno;
3169 p = strrchr(line, ')');
3179 "%*d " /* session */
3188 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3190 char fn[PATH_MAX], *s, *b, *p;
3195 k = get_ctty_devnr(pid, &devnr);
3199 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3202 if ((k = readlink_malloc(fn, &s)) < 0) {
3207 /* This is an ugly hack */
3208 if (major(devnr) == 136) {
3209 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3219 /* Probably something like the ptys which have no
3220 * symlink in /dev/char. Let's return something
3221 * vaguely useful. */
3223 if (!(b = strdup(fn + 5)))
3233 if (startswith(s, "/dev/"))
3235 else if (startswith(s, "../"))
3253 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3259 /* This returns the first error we run into, but nevertheless
3260 * tries to go on. This closes the passed fd. */
3264 close_nointr_nofail(fd);
3266 return errno == ENOENT ? 0 : -errno;
3271 union dirent_storage buf;
3272 bool is_dir, keep_around;
3276 r = readdir_r(d, &buf.de, &de);
3277 if (r != 0 && ret == 0) {
3285 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3288 if (de->d_type == DT_UNKNOWN ||
3290 (de->d_type == DT_DIR && root_dev)) {
3291 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3292 if (ret == 0 && errno != ENOENT)
3297 is_dir = S_ISDIR(st.st_mode);
3300 (st.st_uid == 0 || st.st_uid == getuid()) &&
3301 (st.st_mode & S_ISVTX);
3303 is_dir = de->d_type == DT_DIR;
3304 keep_around = false;
3310 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3311 if (root_dev && st.st_dev != root_dev->st_dev)
3314 subdir_fd = openat(fd, de->d_name,
3315 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3316 if (subdir_fd < 0) {
3317 if (ret == 0 && errno != ENOENT)
3322 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3323 if (r < 0 && ret == 0)
3327 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3328 if (ret == 0 && errno != ENOENT)
3332 } else if (!only_dirs && !keep_around) {
3334 if (unlinkat(fd, de->d_name, 0) < 0) {
3335 if (ret == 0 && errno != ENOENT)
3346 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3351 if (fstatfs(fd, &s) < 0) {
3352 close_nointr_nofail(fd);
3356 /* We refuse to clean disk file systems with this call. This
3357 * is extra paranoia just to be sure we never ever remove
3360 if (s.f_type != TMPFS_MAGIC &&
3361 s.f_type != RAMFS_MAGIC) {
3362 log_error("Attempted to remove disk file system, and we can't allow that.");
3363 close_nointr_nofail(fd);
3367 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3370 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3376 /* We refuse to clean the root file system with this
3377 * call. This is extra paranoia to never cause a really
3378 * seriously broken system. */
3379 if (path_equal(path, "/")) {
3380 log_error("Attempted to remove entire root file system, and we can't allow that.");
3384 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3387 if (errno != ENOTDIR)
3391 if (statfs(path, &s) < 0)
3394 if (s.f_type != TMPFS_MAGIC &&
3395 s.f_type != RAMFS_MAGIC) {
3396 log_error("Attempted to remove disk file system, and we can't allow that.");
3401 if (delete_root && !only_dirs)
3402 if (unlink(path) < 0 && errno != ENOENT)
3409 if (fstatfs(fd, &s) < 0) {
3410 close_nointr_nofail(fd);
3414 if (s.f_type != TMPFS_MAGIC &&
3415 s.f_type != RAMFS_MAGIC) {
3416 log_error("Attempted to remove disk file system, and we can't allow that.");
3417 close_nointr_nofail(fd);
3422 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3425 if (honour_sticky && file_is_priv_sticky(path) > 0)
3428 if (rmdir(path) < 0 && errno != ENOENT) {
3437 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3438 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3441 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3442 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3445 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3448 /* Under the assumption that we are running privileged we
3449 * first change the access mode and only then hand out
3450 * ownership to avoid a window where access is too open. */
3452 if (mode != (mode_t) -1)
3453 if (chmod(path, mode) < 0)
3456 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3457 if (chown(path, uid, gid) < 0)
3463 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3466 /* Under the assumption that we are running privileged we
3467 * first change the access mode and only then hand out
3468 * ownership to avoid a window where access is too open. */
3470 if (fchmod(fd, mode) < 0)
3473 if (fchown(fd, uid, gid) < 0)
3479 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3483 /* Allocates the cpuset in the right size */
3486 if (!(r = CPU_ALLOC(n)))
3489 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3490 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3500 if (errno != EINVAL)
3507 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3508 static const char status_indent[] = " "; /* "[" STATUS "] " */
3509 _cleanup_free_ char *s = NULL;
3510 _cleanup_close_ int fd = -1;
3511 struct iovec iovec[5];
3516 /* This is independent of logging, as status messages are
3517 * optional and go exclusively to the console. */
3519 if (vasprintf(&s, format, ap) < 0)
3522 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3535 sl = status ? sizeof(status_indent)-1 : 0;
3541 e = ellipsize(s, emax, 75);
3551 if (!isempty(status)) {
3552 IOVEC_SET_STRING(iovec[n++], "[");
3553 IOVEC_SET_STRING(iovec[n++], status);
3554 IOVEC_SET_STRING(iovec[n++], "] ");
3556 IOVEC_SET_STRING(iovec[n++], status_indent);
3559 IOVEC_SET_STRING(iovec[n++], s);
3560 IOVEC_SET_STRING(iovec[n++], "\n");
3562 if (writev(fd, iovec, n) < 0)
3568 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3574 va_start(ap, format);
3575 r = status_vprintf(status, ellipse, format, ap);
3581 int status_welcome(void) {
3583 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3585 r = parse_env_file("/etc/os-release", NEWLINE,
3586 "PRETTY_NAME", &pretty_name,
3587 "ANSI_COLOR", &ansi_color,
3589 if (r < 0 && r != -ENOENT)
3590 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3592 return status_printf(NULL, false,
3593 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3594 isempty(ansi_color) ? "1" : ansi_color,
3595 isempty(pretty_name) ? "Linux" : pretty_name);
3598 char *replace_env(const char *format, char **env) {
3605 const char *e, *word = format;
3610 for (e = format; *e; e ++) {
3621 if (!(k = strnappend(r, word, e-word-1)))
3630 } else if (*e == '$') {
3631 if (!(k = strnappend(r, word, e-word)))
3647 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3650 if (!(k = strappend(r, t)))
3663 if (!(k = strnappend(r, word, e-word)))
3674 char **replace_env_argv(char **argv, char **env) {
3676 unsigned k = 0, l = 0;
3678 l = strv_length(argv);
3680 if (!(r = new(char*, l+1)))
3683 STRV_FOREACH(i, argv) {
3685 /* If $FOO appears as single word, replace it by the split up variable */
3686 if ((*i)[0] == '$' && (*i)[1] != '{') {
3691 if ((e = strv_env_get(env, *i+1))) {
3693 if (!(m = strv_split_quoted(e))) {
3704 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3713 memcpy(r + k, m, q * sizeof(char*));
3721 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3722 if (!(r[k++] = replace_env(*i, env))) {
3732 int fd_columns(int fd) {
3736 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3745 static unsigned columns_cached(bool cached) {
3746 static __thread int env_columns = -1;
3749 if (_likely_(parsed_columns > 0 && cached))
3750 return parsed_columns;
3752 if (_unlikely_(env_columns == -1)) {
3753 e = getenv("COLUMNS");
3755 env_columns = atoi(e);
3760 if (env_columns > 0) {
3761 parsed_columns = env_columns;
3762 return parsed_columns;
3765 if (parsed_columns <= 0 || !cached)
3766 parsed_columns = fd_columns(STDOUT_FILENO);
3768 if (parsed_columns <= 0)
3769 parsed_columns = 80;
3771 return parsed_columns;
3774 unsigned columns(void) {
3775 return columns_cached(true);
3778 unsigned columns_uncached(void) {
3779 return columns_cached(false);
3782 /* intended to be used as a SIGWINCH sighandler */
3783 void columns_cache_reset(int signum) {
3787 int fd_lines(int fd) {
3791 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3800 unsigned lines(void) {
3801 static __thread int parsed_lines = 0;
3804 if (_likely_(parsed_lines > 0))
3805 return parsed_lines;
3807 e = getenv("LINES");
3809 parsed_lines = atoi(e);
3811 if (parsed_lines <= 0)
3812 parsed_lines = fd_lines(STDOUT_FILENO);
3814 if (parsed_lines <= 0)
3817 return parsed_lines;
3820 int running_in_chroot(void) {
3826 /* Only works as root */
3828 if (stat("/proc/1/root", &a) < 0)
3831 if (stat("/", &b) < 0)
3835 a.st_dev != b.st_dev ||
3836 a.st_ino != b.st_ino;
3839 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3844 assert(percent <= 100);
3845 assert(new_length >= 3);
3847 if (old_length <= 3 || old_length <= new_length)
3848 return strndup(s, old_length);
3850 r = new0(char, new_length+1);
3854 x = (new_length * percent) / 100;
3856 if (x > new_length - 3)
3864 s + old_length - (new_length - x - 3),
3865 new_length - x - 3);
3870 char *ellipsize(const char *s, size_t length, unsigned percent) {
3871 return ellipsize_mem(s, strlen(s), length, percent);
3874 int touch(const char *path) {
3879 /* This just opens the file for writing, ensuring it
3880 * exists. It doesn't call utimensat() the way /usr/bin/touch
3883 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3887 close_nointr_nofail(fd);
3891 char *unquote(const char *s, const char* quotes) {
3895 /* This is rather stupid, simply removes the heading and
3896 * trailing quotes if there is one. Doesn't care about
3897 * escaping or anything. We should make this smarter one
3904 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3905 return strndup(s+1, l-2);
3910 char *normalize_env_assignment(const char *s) {
3911 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3914 eq = strchr(s, '=');
3926 memmove(r, t, strlen(t) + 1);
3930 name = strndup(s, eq - s);
3938 value = unquote(strstrip(p), QUOTES);
3942 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3948 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3959 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3971 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3978 r = wait_for_terminate(pid, &status);
3980 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3984 if (status.si_code == CLD_EXITED) {
3985 if (status.si_status != 0) {
3986 log_warning("%s failed with error code %i.", name, status.si_status);
3987 return status.si_status;
3990 log_debug("%s succeeded.", name);
3993 } else if (status.si_code == CLD_KILLED ||
3994 status.si_code == CLD_DUMPED) {
3996 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4000 log_warning("%s failed due to unknown reason.", name);
4004 _noreturn_ void freeze(void) {
4006 /* Make sure nobody waits for us on a socket anymore */
4007 close_all_fds(NULL, 0);
4015 bool null_or_empty(struct stat *st) {
4018 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4021 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4027 int null_or_empty_path(const char *fn) {
4032 if (stat(fn, &st) < 0)
4035 return null_or_empty(&st);
4038 DIR *xopendirat(int fd, const char *name, int flags) {
4042 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4048 close_nointr_nofail(nfd);
4055 int signal_from_string_try_harder(const char *s) {
4059 signo = signal_from_string(s);
4061 if (startswith(s, "SIG"))
4062 return signal_from_string(s+3);
4067 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4073 if (!dual_timestamp_is_set(t))
4076 fprintf(f, "%s=%llu %llu\n",
4078 (unsigned long long) t->realtime,
4079 (unsigned long long) t->monotonic);
4082 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4083 unsigned long long a, b;
4088 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4089 log_debug("Failed to parse finish timestamp value %s", value);
4096 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4100 /* FIXME: to follow udev's logic 100% we need to leave valid
4101 * UTF8 chars unescaped */
4103 u = unquote(tagvalue, "\"\'");
4107 t = xescape(u, "/ ");
4113 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4122 char *fstab_node_to_udev_node(const char *p) {
4125 if (startswith(p, "LABEL="))
4126 return tag_to_udev_node(p+6, "label");
4128 if (startswith(p, "UUID="))
4129 return tag_to_udev_node(p+5, "uuid");
4131 if (startswith(p, "PARTUUID="))
4132 return tag_to_udev_node(p+9, "partuuid");
4134 if (startswith(p, "PARTLABEL="))
4135 return tag_to_udev_node(p+10, "partlabel");
4140 bool tty_is_vc(const char *tty) {
4143 if (startswith(tty, "/dev/"))
4146 return vtnr_from_tty(tty) >= 0;
4149 bool tty_is_console(const char *tty) {
4152 if (startswith(tty, "/dev/"))
4155 return streq(tty, "console");
4158 int vtnr_from_tty(const char *tty) {
4163 if (startswith(tty, "/dev/"))
4166 if (!startswith(tty, "tty") )
4169 if (tty[3] < '0' || tty[3] > '9')
4172 r = safe_atoi(tty+3, &i);
4176 if (i < 0 || i > 63)
4182 bool tty_is_vc_resolve(const char *tty) {
4183 char *active = NULL;
4188 if (startswith(tty, "/dev/"))
4191 /* Resolve where /dev/console is pointing to, if /sys is
4192 * actually ours (i.e. not read-only-mounted which is a sign
4193 * for container setups) */
4194 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4195 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4196 /* If multiple log outputs are configured the
4197 * last one is what /dev/console points to */
4198 tty = strrchr(active, ' ');
4211 const char *default_term_for_tty(const char *tty) {
4214 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4217 bool dirent_is_file(const struct dirent *de) {
4220 if (ignore_file(de->d_name))
4223 if (de->d_type != DT_REG &&
4224 de->d_type != DT_LNK &&
4225 de->d_type != DT_UNKNOWN)
4231 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4234 if (de->d_type != DT_REG &&
4235 de->d_type != DT_LNK &&
4236 de->d_type != DT_UNKNOWN)
4239 if (ignore_file_allow_backup(de->d_name))
4242 return endswith(de->d_name, suffix);
4245 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4248 Hashmap *pids = NULL;
4252 /* Executes all binaries in a directory in parallel and waits
4253 * until all they all finished. */
4256 if (!(_d = opendir(directory))) {
4258 if (errno == ENOENT)
4261 log_error("Failed to enumerate directory %s: %m", directory);
4268 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4269 log_error("Failed to allocate set.");
4273 while ((de = readdir(d))) {
4278 if (!dirent_is_file(de))
4281 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4286 if ((pid = fork()) < 0) {
4287 log_error("Failed to fork: %m");
4305 log_error("Failed to execute %s: %m", path);
4306 _exit(EXIT_FAILURE);
4309 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4311 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4312 log_error("Failed to add PID to set: %s", strerror(-k));
4317 while (!hashmap_isempty(pids)) {
4318 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4323 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4328 log_error("waitid() failed: %m");
4332 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4333 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4334 if (si.si_code == CLD_EXITED)
4335 log_error("%s exited with exit status %i.", path, si.si_status);
4337 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4339 log_debug("%s exited successfully.", path);
4350 hashmap_free_free(pids);
4353 int kill_and_sigcont(pid_t pid, int sig) {
4356 r = kill(pid, sig) < 0 ? -errno : 0;
4364 bool nulstr_contains(const char*nulstr, const char *needle) {
4370 NULSTR_FOREACH(i, nulstr)
4371 if (streq(i, needle))
4377 bool plymouth_running(void) {
4378 return access("/run/plymouth/pid", F_OK) >= 0;
4381 char* strshorten(char *s, size_t l) {
4390 static bool hostname_valid_char(char c) {
4392 (c >= 'a' && c <= 'z') ||
4393 (c >= 'A' && c <= 'Z') ||
4394 (c >= '0' && c <= '9') ||
4400 bool hostname_is_valid(const char *s) {
4406 for (p = s; *p; p++)
4407 if (!hostname_valid_char(*p))
4410 if (p-s > HOST_NAME_MAX)
4416 char* hostname_cleanup(char *s) {
4419 for (p = s, d = s; *p; p++)
4420 if ((*p >= 'a' && *p <= 'z') ||
4421 (*p >= 'A' && *p <= 'Z') ||
4422 (*p >= '0' && *p <= '9') ||
4430 strshorten(s, HOST_NAME_MAX);
4434 int pipe_eof(int fd) {
4435 struct pollfd pollfd;
4440 pollfd.events = POLLIN|POLLHUP;
4442 r = poll(&pollfd, 1, 0);
4449 return pollfd.revents & POLLHUP;
4452 int fd_wait_for_event(int fd, int event, usec_t t) {
4453 struct pollfd pollfd;
4458 pollfd.events = event;
4460 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4467 return pollfd.revents;
4470 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4481 t = new(char, strlen(path) + 1 + 6 + 1);
4485 fn = path_get_file_name(path);
4489 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4491 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4497 f = fdopen(fd, "we");
4510 int terminal_vhangup_fd(int fd) {
4513 if (ioctl(fd, TIOCVHANGUP) < 0)
4519 int terminal_vhangup(const char *name) {
4522 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4526 r = terminal_vhangup_fd(fd);
4527 close_nointr_nofail(fd);
4532 int vt_disallocate(const char *name) {
4536 /* Deallocate the VT if possible. If not possible
4537 * (i.e. because it is the active one), at least clear it
4538 * entirely (including the scrollback buffer) */
4540 if (!startswith(name, "/dev/"))
4543 if (!tty_is_vc(name)) {
4544 /* So this is not a VT. I guess we cannot deallocate
4545 * it then. But let's at least clear the screen */
4547 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4552 "\033[r" /* clear scrolling region */
4553 "\033[H" /* move home */
4554 "\033[2J", /* clear screen */
4556 close_nointr_nofail(fd);
4561 if (!startswith(name, "/dev/tty"))
4564 r = safe_atou(name+8, &u);
4571 /* Try to deallocate */
4572 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4576 r = ioctl(fd, VT_DISALLOCATE, u);
4577 close_nointr_nofail(fd);
4585 /* Couldn't deallocate, so let's clear it fully with
4587 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4592 "\033[r" /* clear scrolling region */
4593 "\033[H" /* move home */
4594 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4596 close_nointr_nofail(fd);
4601 int copy_file(const char *from, const char *to) {
4607 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4611 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4613 close_nointr_nofail(fdf);
4621 n = read(fdf, buf, sizeof(buf));
4625 close_nointr_nofail(fdf);
4636 k = loop_write(fdt, buf, n, false);
4638 r = k < 0 ? k : (errno ? -errno : -EIO);
4640 close_nointr_nofail(fdf);
4648 close_nointr_nofail(fdf);
4649 r = close_nointr(fdt);
4659 int symlink_atomic(const char *from, const char *to) {
4661 _cleanup_free_ char *t;
4664 unsigned long long ull;
4671 t = new(char, strlen(to) + 1 + 16 + 1);
4675 fn = path_get_file_name(to);
4679 x = stpcpy(t+k+1, fn);
4682 for (i = 0; i < 16; i++) {
4683 *(x++) = hexchar(ull & 0xF);
4689 if (symlink(from, t) < 0)
4692 if (rename(t, to) < 0) {
4701 bool display_is_local(const char *display) {
4705 display[0] == ':' &&
4706 display[1] >= '0' &&
4710 int socket_from_display(const char *display, char **path) {
4717 if (!display_is_local(display))
4720 k = strspn(display+1, "0123456789");
4722 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4726 c = stpcpy(f, "/tmp/.X11-unix/X");
4727 memcpy(c, display+1, k);
4736 const char **username,
4737 uid_t *uid, gid_t *gid,
4739 const char **shell) {
4747 /* We enforce some special rules for uid=0: in order to avoid
4748 * NSS lookups for root we hardcode its data. */
4750 if (streq(*username, "root") || streq(*username, "0")) {
4768 if (parse_uid(*username, &u) >= 0) {
4772 /* If there are multiple users with the same id, make
4773 * sure to leave $USER to the configured value instead
4774 * of the first occurrence in the database. However if
4775 * the uid was configured by a numeric uid, then let's
4776 * pick the real username from /etc/passwd. */
4778 *username = p->pw_name;
4781 p = getpwnam(*username);
4785 return errno != 0 ? -errno : -ESRCH;
4797 *shell = p->pw_shell;
4802 int get_group_creds(const char **groupname, gid_t *gid) {
4808 /* We enforce some special rules for gid=0: in order to avoid
4809 * NSS lookups for root we hardcode its data. */
4811 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4812 *groupname = "root";
4820 if (parse_gid(*groupname, &id) >= 0) {
4825 *groupname = g->gr_name;
4828 g = getgrnam(*groupname);
4832 return errno != 0 ? -errno : -ESRCH;
4840 int in_group(const char *name) {
4842 int ngroups_max, r, i;
4844 r = get_group_creds(&name, &gid);
4848 if (getgid() == gid)
4851 if (getegid() == gid)
4854 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4855 assert(ngroups_max > 0);
4857 gids = alloca(sizeof(gid_t) * ngroups_max);
4859 r = getgroups(ngroups_max, gids);
4863 for (i = 0; i < r; i++)
4870 int glob_exists(const char *path) {
4878 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4880 if (k == GLOB_NOMATCH)
4882 else if (k == GLOB_NOSPACE)
4885 r = !strv_isempty(g.gl_pathv);
4887 r = errno ? -errno : -EIO;
4894 int dirent_ensure_type(DIR *d, struct dirent *de) {
4900 if (de->d_type != DT_UNKNOWN)
4903 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4907 S_ISREG(st.st_mode) ? DT_REG :
4908 S_ISDIR(st.st_mode) ? DT_DIR :
4909 S_ISLNK(st.st_mode) ? DT_LNK :
4910 S_ISFIFO(st.st_mode) ? DT_FIFO :
4911 S_ISSOCK(st.st_mode) ? DT_SOCK :
4912 S_ISCHR(st.st_mode) ? DT_CHR :
4913 S_ISBLK(st.st_mode) ? DT_BLK :
4919 int in_search_path(const char *path, char **search) {
4923 r = path_get_parent(path, &parent);
4929 STRV_FOREACH(i, search) {
4930 if (path_equal(parent, *i)) {
4941 int get_files_in_directory(const char *path, char ***list) {
4949 /* Returns all files in a directory in *list, and the number
4950 * of files as return value. If list is NULL returns only the
4959 union dirent_storage buf;
4962 k = readdir_r(d, &buf.de, &de);
4971 dirent_ensure_type(d, de);
4973 if (!dirent_is_file(de))
4977 if ((unsigned) r >= n) {
4981 t = realloc(l, sizeof(char*) * n);
4990 assert((unsigned) r < n);
4992 l[r] = strdup(de->d_name);
5016 char *strjoin(const char *x, ...) {
5030 t = va_arg(ap, const char *);
5035 if (n > ((size_t) -1) - l) {
5059 t = va_arg(ap, const char *);
5073 bool is_main_thread(void) {
5074 static __thread int cached = 0;
5076 if (_unlikely_(cached == 0))
5077 cached = getpid() == gettid() ? 1 : -1;
5082 int block_get_whole_disk(dev_t d, dev_t *ret) {
5089 /* If it has a queue this is good enough for us */
5090 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5093 r = access(p, F_OK);
5101 /* If it is a partition find the originating device */
5102 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5105 r = access(p, F_OK);
5111 /* Get parent dev_t */
5112 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5115 r = read_one_line_file(p, &s);
5121 r = sscanf(s, "%u:%u", &m, &n);
5127 /* Only return this if it is really good enough for us. */
5128 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5131 r = access(p, F_OK);
5135 *ret = makedev(m, n);
5142 int file_is_priv_sticky(const char *p) {
5147 if (lstat(p, &st) < 0)
5151 (st.st_uid == 0 || st.st_uid == getuid()) &&
5152 (st.st_mode & S_ISVTX);
5155 static const char *const ioprio_class_table[] = {
5156 [IOPRIO_CLASS_NONE] = "none",
5157 [IOPRIO_CLASS_RT] = "realtime",
5158 [IOPRIO_CLASS_BE] = "best-effort",
5159 [IOPRIO_CLASS_IDLE] = "idle"
5162 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5164 static const char *const sigchld_code_table[] = {
5165 [CLD_EXITED] = "exited",
5166 [CLD_KILLED] = "killed",
5167 [CLD_DUMPED] = "dumped",
5168 [CLD_TRAPPED] = "trapped",
5169 [CLD_STOPPED] = "stopped",
5170 [CLD_CONTINUED] = "continued",
5173 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5175 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5176 [LOG_FAC(LOG_KERN)] = "kern",
5177 [LOG_FAC(LOG_USER)] = "user",
5178 [LOG_FAC(LOG_MAIL)] = "mail",
5179 [LOG_FAC(LOG_DAEMON)] = "daemon",
5180 [LOG_FAC(LOG_AUTH)] = "auth",
5181 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5182 [LOG_FAC(LOG_LPR)] = "lpr",
5183 [LOG_FAC(LOG_NEWS)] = "news",
5184 [LOG_FAC(LOG_UUCP)] = "uucp",
5185 [LOG_FAC(LOG_CRON)] = "cron",
5186 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5187 [LOG_FAC(LOG_FTP)] = "ftp",
5188 [LOG_FAC(LOG_LOCAL0)] = "local0",
5189 [LOG_FAC(LOG_LOCAL1)] = "local1",
5190 [LOG_FAC(LOG_LOCAL2)] = "local2",
5191 [LOG_FAC(LOG_LOCAL3)] = "local3",
5192 [LOG_FAC(LOG_LOCAL4)] = "local4",
5193 [LOG_FAC(LOG_LOCAL5)] = "local5",
5194 [LOG_FAC(LOG_LOCAL6)] = "local6",
5195 [LOG_FAC(LOG_LOCAL7)] = "local7"
5198 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5200 static const char *const log_level_table[] = {
5201 [LOG_EMERG] = "emerg",
5202 [LOG_ALERT] = "alert",
5203 [LOG_CRIT] = "crit",
5205 [LOG_WARNING] = "warning",
5206 [LOG_NOTICE] = "notice",
5207 [LOG_INFO] = "info",
5208 [LOG_DEBUG] = "debug"
5211 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5213 static const char* const sched_policy_table[] = {
5214 [SCHED_OTHER] = "other",
5215 [SCHED_BATCH] = "batch",
5216 [SCHED_IDLE] = "idle",
5217 [SCHED_FIFO] = "fifo",
5221 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5223 static const char* const rlimit_table[] = {
5224 [RLIMIT_CPU] = "LimitCPU",
5225 [RLIMIT_FSIZE] = "LimitFSIZE",
5226 [RLIMIT_DATA] = "LimitDATA",
5227 [RLIMIT_STACK] = "LimitSTACK",
5228 [RLIMIT_CORE] = "LimitCORE",
5229 [RLIMIT_RSS] = "LimitRSS",
5230 [RLIMIT_NOFILE] = "LimitNOFILE",
5231 [RLIMIT_AS] = "LimitAS",
5232 [RLIMIT_NPROC] = "LimitNPROC",
5233 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5234 [RLIMIT_LOCKS] = "LimitLOCKS",
5235 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5236 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5237 [RLIMIT_NICE] = "LimitNICE",
5238 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5239 [RLIMIT_RTTIME] = "LimitRTTIME"
5242 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5244 static const char* const ip_tos_table[] = {
5245 [IPTOS_LOWDELAY] = "low-delay",
5246 [IPTOS_THROUGHPUT] = "throughput",
5247 [IPTOS_RELIABILITY] = "reliability",
5248 [IPTOS_LOWCOST] = "low-cost",
5251 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5253 static const char *const __signal_table[] = {
5270 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5281 [SIGVTALRM] = "VTALRM",
5283 [SIGWINCH] = "WINCH",
5289 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5291 const char *signal_to_string(int signo) {
5292 static __thread char buf[12];
5295 name = __signal_to_string(signo);
5299 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5300 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5302 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5307 int signal_from_string(const char *s) {
5312 signo = __signal_from_string(s);
5316 if (startswith(s, "RTMIN+")) {
5320 if (safe_atou(s, &u) >= 0) {
5321 signo = (int) u + offset;
5322 if (signo > 0 && signo < _NSIG)
5328 bool kexec_loaded(void) {
5329 bool loaded = false;
5332 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5340 int strdup_or_null(const char *a, char **b) {
5358 int prot_from_flags(int flags) {
5360 switch (flags & O_ACCMODE) {
5369 return PROT_READ|PROT_WRITE;
5376 char *format_bytes(char *buf, size_t l, off_t t) {
5379 static const struct {
5383 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5384 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5385 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5386 { "G", 1024ULL*1024ULL*1024ULL },
5387 { "M", 1024ULL*1024ULL },
5391 for (i = 0; i < ELEMENTSOF(table); i++) {
5393 if (t >= table[i].factor) {
5396 (unsigned long long) (t / table[i].factor),
5397 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5404 snprintf(buf, l, "%lluB", (unsigned long long) t);
5412 void* memdup(const void *p, size_t l) {
5425 int fd_inc_sndbuf(int fd, size_t n) {
5427 socklen_t l = sizeof(value);
5429 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5431 l == sizeof(value) &&
5432 (size_t) value >= n*2)
5436 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5443 int fd_inc_rcvbuf(int fd, size_t n) {
5445 socklen_t l = sizeof(value);
5447 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5449 l == sizeof(value) &&
5450 (size_t) value >= n*2)
5454 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5461 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5462 pid_t parent_pid, agent_pid;
5464 bool stdout_is_tty, stderr_is_tty;
5472 parent_pid = getpid();
5474 /* Spawns a temporary TTY agent, making sure it goes away when
5481 if (agent_pid != 0) {
5488 * Make sure the agent goes away when the parent dies */
5489 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5490 _exit(EXIT_FAILURE);
5492 /* Check whether our parent died before we were able
5493 * to set the death signal */
5494 if (getppid() != parent_pid)
5495 _exit(EXIT_SUCCESS);
5497 /* Don't leak fds to the agent */
5498 close_all_fds(except, n_except);
5500 stdout_is_tty = isatty(STDOUT_FILENO);
5501 stderr_is_tty = isatty(STDERR_FILENO);
5503 if (!stdout_is_tty || !stderr_is_tty) {
5504 /* Detach from stdout/stderr. and reopen
5505 * /dev/tty for them. This is important to
5506 * ensure that when systemctl is started via
5507 * popen() or a similar call that expects to
5508 * read EOF we actually do generate EOF and
5509 * not delay this indefinitely by because we
5510 * keep an unused copy of stdin around. */
5511 fd = open("/dev/tty", O_WRONLY);
5513 log_error("Failed to open /dev/tty: %m");
5514 _exit(EXIT_FAILURE);
5518 dup2(fd, STDOUT_FILENO);
5521 dup2(fd, STDERR_FILENO);
5527 /* Count arguments */
5529 for (n = 0; va_arg(ap, char*); n++)
5534 l = alloca(sizeof(char *) * (n + 1));
5536 /* Fill in arguments */
5538 for (i = 0; i <= n; i++)
5539 l[i] = va_arg(ap, char*);
5543 _exit(EXIT_FAILURE);
5546 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5547 struct rlimit highest, fixed;
5551 if (setrlimit(resource, rlim) >= 0)
5557 /* So we failed to set the desired setrlimit, then let's try
5558 * to get as close as we can */
5559 assert_se(getrlimit(resource, &highest) == 0);
5561 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5562 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5564 if (setrlimit(resource, &fixed) < 0)
5570 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5571 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5583 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5586 f = fopen(path, "re");
5594 char line[LINE_MAX];
5597 for (i = 0; i < sizeof(line)-1; i++) {
5601 if (_unlikely_(c == EOF)) {
5611 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5612 value = strdup(line + l + 1);
5632 int can_sleep(const char *type) {
5636 _cleanup_free_ char *p = NULL;
5640 r = read_one_line_file("/sys/power/state", &p);
5642 return r == -ENOENT ? 0 : r;
5645 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5646 if (l == k && memcmp(w, type, l) == 0)
5652 bool is_valid_documentation_url(const char *url) {
5655 if (startswith(url, "http://") && url[7])
5658 if (startswith(url, "https://") && url[8])
5661 if (startswith(url, "file:") && url[5])
5664 if (startswith(url, "info:") && url[5])
5667 if (startswith(url, "man:") && url[4])
5673 bool in_initrd(void) {
5674 static __thread int saved = -1;
5680 /* We make two checks here:
5682 * 1. the flag file /etc/initrd-release must exist
5683 * 2. the root file system must be a memory file system
5685 * The second check is extra paranoia, since misdetecting an
5686 * initrd can have bad bad consequences due the initrd
5687 * emptying when transititioning to the main systemd.
5690 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5691 statfs("/", &s) >= 0 &&
5692 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5697 void warn_melody(void) {
5698 _cleanup_close_ int fd = -1;
5700 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5704 /* Yeah, this is synchronous. Kinda sucks. But well... */
5706 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5707 usleep(125*USEC_PER_MSEC);
5709 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5710 usleep(125*USEC_PER_MSEC);
5712 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5713 usleep(125*USEC_PER_MSEC);
5715 ioctl(fd, KIOCSOUND, 0);
5718 int make_console_stdio(void) {
5721 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5723 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5725 log_error("Failed to acquire terminal: %s", strerror(-fd));
5731 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5738 int get_home_dir(char **_h) {
5746 /* Take the user specified one */
5757 /* Hardcode home directory for root to avoid NSS */
5760 h = strdup("/root");
5768 /* Check the database... */
5772 return errno ? -errno : -ESRCH;
5774 if (!path_is_absolute(p->pw_dir))
5777 h = strdup(p->pw_dir);
5785 int get_shell(char **_sh) {
5793 /* Take the user specified one */
5794 e = getenv("SHELL");
5804 /* Hardcode home directory for root to avoid NSS */
5807 sh = strdup("/bin/sh");
5815 /* Check the database... */
5819 return errno ? -errno : -ESRCH;
5821 if (!path_is_absolute(p->pw_shell))
5824 sh = strdup(p->pw_shell);
5832 void freep(void *p) {
5836 void fclosep(FILE **f) {
5841 void closep(int *fd) {
5843 close_nointr_nofail(*fd);
5846 void closedirp(DIR **d) {
5851 void umaskp(mode_t *u) {