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;
73 int parsed_columns = 0;
75 size_t page_size(void) {
76 static __thread size_t pgsz = 0;
79 if (_likely_(pgsz > 0))
82 r = sysconf(_SC_PAGESIZE);
89 bool streq_ptr(const char *a, const char *b) {
91 /* Like streq(), but tries to make sense of NULL pointers */
102 usec_t now(clockid_t clock_id) {
105 assert_se(clock_gettime(clock_id, &ts) == 0);
107 return timespec_load(&ts);
110 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
113 ts->realtime = now(CLOCK_REALTIME);
114 ts->monotonic = now(CLOCK_MONOTONIC);
119 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
128 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
130 ts->monotonic = now(CLOCK_MONOTONIC);
132 if ((int64_t) ts->monotonic > delta)
133 ts->monotonic -= delta;
141 usec_t timespec_load(const struct timespec *ts) {
145 (usec_t) ts->tv_sec * USEC_PER_SEC +
146 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
149 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
152 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
153 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
158 usec_t timeval_load(const struct timeval *tv) {
162 (usec_t) tv->tv_sec * USEC_PER_SEC +
163 (usec_t) tv->tv_usec;
166 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
169 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
170 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
175 bool endswith(const char *s, const char *postfix) {
182 pl = strlen(postfix);
190 return memcmp(s + sl - pl, postfix, pl) == 0;
193 bool startswith(const char *s, const char *prefix) {
208 return memcmp(s, prefix, pl) == 0;
211 bool startswith_no_case(const char *s, const char *prefix) {
227 for(i = 0; i < pl; ++i)
228 if (tolower(s[i]) != tolower(prefix[i]))
234 bool first_word(const char *s, const char *word) {
249 if (memcmp(s, word, wl) != 0)
253 strchr(WHITESPACE, s[wl]);
256 int close_nointr(int fd) {
271 void close_nointr_nofail(int fd) {
272 int saved_errno = errno;
274 /* like close_nointr() but cannot fail, and guarantees errno
277 assert_se(close_nointr(fd) == 0);
282 void close_many(const int fds[], unsigned n_fd) {
285 for (i = 0; i < n_fd; i++)
286 close_nointr_nofail(fds[i]);
289 int parse_boolean(const char *v) {
292 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
294 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
300 int parse_pid(const char *s, pid_t* ret_pid) {
301 unsigned long ul = 0;
308 r = safe_atolu(s, &ul);
314 if ((unsigned long) pid != ul)
324 int parse_uid(const char *s, uid_t* ret_uid) {
325 unsigned long ul = 0;
332 r = safe_atolu(s, &ul);
338 if ((unsigned long) uid != ul)
345 int safe_atou(const char *s, unsigned *ret_u) {
353 l = strtoul(s, &x, 0);
355 if (!x || *x || errno)
356 return errno ? -errno : -EINVAL;
358 if ((unsigned long) (unsigned) l != l)
361 *ret_u = (unsigned) l;
365 int safe_atoi(const char *s, int *ret_i) {
373 l = strtol(s, &x, 0);
375 if (!x || *x || errno)
376 return errno ? -errno : -EINVAL;
378 if ((long) (int) l != l)
385 int safe_atollu(const char *s, long long unsigned *ret_llu) {
387 unsigned long long l;
393 l = strtoull(s, &x, 0);
395 if (!x || *x || errno)
396 return errno ? -errno : -EINVAL;
402 int safe_atolli(const char *s, long long int *ret_lli) {
410 l = strtoll(s, &x, 0);
412 if (!x || *x || errno)
413 return errno ? -errno : -EINVAL;
419 /* Split a string into words. */
420 char *split(const char *c, size_t *l, const char *separator, char **state) {
423 current = *state ? *state : (char*) c;
425 if (!*current || *c == 0)
428 current += strspn(current, separator);
429 *l = strcspn(current, separator);
432 return (char*) current;
435 /* Split a string into words, but consider strings enclosed in '' and
436 * "" as words even if they include spaces. */
437 char *split_quoted(const char *c, size_t *l, char **state) {
439 bool escaped = false;
441 current = *state ? *state : (char*) c;
443 if (!*current || *c == 0)
446 current += strspn(current, WHITESPACE);
448 if (*current == '\'') {
451 for (e = current; *e; e++) {
461 *state = *e == 0 ? e : e+1;
462 } else if (*current == '\"') {
465 for (e = current; *e; e++) {
475 *state = *e == 0 ? e : e+1;
477 for (e = current; *e; e++) {
482 else if (strchr(WHITESPACE, *e))
489 return (char*) current;
492 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
494 _cleanup_fclose_ FILE *f = NULL;
495 char fn[PATH_MAX], line[LINE_MAX], *p;
501 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
508 if (!fgets(line, sizeof(line), f)) {
509 r = feof(f) ? -EIO : -errno;
514 /* Let's skip the pid and comm fields. The latter is enclosed
515 * in () but does not escape any () in its value, so let's
516 * skip over it manually */
518 p = strrchr(line, ')');
530 if ((long unsigned) (pid_t) ppid != ppid)
533 *_ppid = (pid_t) ppid;
538 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
539 _cleanup_fclose_ FILE *f = NULL;
540 char fn[PATH_MAX], line[LINE_MAX], *p;
545 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
552 if (!fgets(line, sizeof(line), f)) {
559 /* Let's skip the pid and comm fields. The latter is enclosed
560 * in () but does not escape any () in its value, so let's
561 * skip over it manually */
563 p = strrchr(line, ')');
585 "%*d " /* priority */
587 "%*d " /* num_threads */
588 "%*d " /* itrealvalue */
589 "%llu " /* starttime */,
596 int write_one_line_file(const char *fn, const char *line) {
597 _cleanup_fclose_ FILE *f = NULL;
607 if (fputs(line, f) < 0)
608 return errno ? -errno : -EIO;
610 if (!endswith(line, "\n"))
616 return errno ? -errno : -EIO;
621 int fchmod_umask(int fd, mode_t m) {
626 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
632 int write_one_line_file_atomic(const char *fn, const char *line) {
640 r = fopen_temporary(fn, &f, &p);
644 fchmod_umask(fileno(f), 0644);
647 if (fputs(line, f) < 0) {
652 if (!endswith(line, "\n"))
663 if (rename(p, fn) < 0)
679 int read_one_line_file(const char *fn, char **line) {
680 _cleanup_fclose_ FILE *f = NULL;
681 char t[LINE_MAX], *c;
690 if (!fgets(t, sizeof(t), f)) {
693 return errno ? -errno : -EIO;
707 int read_full_file(const char *fn, char **contents, size_t *size) {
708 _cleanup_fclose_ FILE *f = NULL;
710 _cleanup_free_ char *buf = NULL;
717 if (fstat(fileno(f), &st) < 0)
721 if (st.st_size > 4*1024*1024)
724 n = st.st_size > 0 ? st.st_size : LINE_MAX;
731 t = realloc(buf, n+1);
736 k = fread(buf + l, 1, n - l, f);
765 const char *separator, ...) {
768 char *contents = NULL, *p;
773 if ((r = read_full_file(fname, &contents, NULL)) < 0)
778 const char *key = NULL;
780 p += strspn(p, separator);
781 p += strspn(p, WHITESPACE);
786 if (!strchr(COMMENTS, *p)) {
790 va_start(ap, separator);
791 while ((key = va_arg(ap, char *))) {
795 value = va_arg(ap, char **);
798 if (strncmp(p, key, n) != 0 ||
803 n = strcspn(p, separator);
806 strchr(QUOTES, p[0]) &&
808 v = strndup(p+1, n-2);
819 /* return empty value strings as NULL */
836 p += strcspn(p, separator);
855 if (!(f = fopen(fname, "re")))
859 char l[LINE_MAX], *p, *u;
862 if (!fgets(l, sizeof(l), f)) {
875 if (strchr(COMMENTS, *p))
878 if (!(u = normalize_env_assignment(p))) {
883 t = strv_append(m, u);
909 int write_env_file(const char *fname, char **l) {
914 r = fopen_temporary(fname, &f, &p);
918 fchmod_umask(fileno(f), 0644);
934 if (rename(p, fname) < 0)
949 char *truncate_nl(char *s) {
952 s[strcspn(s, NEWLINE)] = 0;
956 int get_process_comm(pid_t pid, char **name) {
962 r = read_one_line_file("/proc/self/comm", name);
965 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
968 r = read_one_line_file(p, name);
975 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
982 assert(max_length > 0);
986 f = fopen("/proc/self/cmdline", "re");
989 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
999 r = new(char, max_length);
1007 while ((c = getc(f)) != EOF) {
1029 size_t n = MIN(left-1, 3U);
1030 memcpy(k, "...", n);
1037 /* Kernel threads have no argv[] */
1047 h = get_process_comm(pid, &t);
1051 r = strjoin("[", t, "]", NULL);
1062 int is_kernel_thread(pid_t pid) {
1072 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1081 count = fread(&c, 1, 1, f);
1085 /* Kernel threads have an empty cmdline */
1088 return eof ? 1 : -errno;
1093 int get_process_exe(pid_t pid, char **name) {
1099 r = readlink_malloc("/proc/self/exe", name);
1102 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1105 r = readlink_malloc(p, name);
1112 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1122 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1132 char line[LINE_MAX], *l;
1134 if (!fgets(line, sizeof(line), f)) {
1144 if (startswith(l, field)) {
1146 l += strspn(l, WHITESPACE);
1148 l[strcspn(l, WHITESPACE)] = 0;
1150 r = parse_uid(l, uid);
1163 int get_process_uid(pid_t pid, uid_t *uid) {
1164 return get_process_id(pid, "Uid:", uid);
1167 int get_process_gid(pid_t pid, gid_t *gid) {
1168 return get_process_id(pid, "Gid:", gid);
1171 char *strnappend(const char *s, const char *suffix, size_t b) {
1179 return strndup(suffix, b);
1188 if (b > ((size_t) -1) - a)
1191 r = new(char, a+b+1);
1196 memcpy(r+a, suffix, b);
1202 char *strappend(const char *s, const char *suffix) {
1203 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1206 int readlink_malloc(const char *p, char **r) {
1216 if (!(c = new(char, l)))
1219 if ((n = readlink(p, c, l-1)) < 0) {
1225 if ((size_t) n < l-1) {
1236 int readlink_and_make_absolute(const char *p, char **r) {
1243 if ((j = readlink_malloc(p, &target)) < 0)
1246 k = file_in_same_dir(p, target);
1256 int readlink_and_canonicalize(const char *p, char **r) {
1263 j = readlink_and_make_absolute(p, &t);
1267 s = canonicalize_file_name(t);
1274 path_kill_slashes(*r);
1279 int reset_all_signal_handlers(void) {
1282 for (sig = 1; sig < _NSIG; sig++) {
1283 struct sigaction sa;
1285 if (sig == SIGKILL || sig == SIGSTOP)
1289 sa.sa_handler = SIG_DFL;
1290 sa.sa_flags = SA_RESTART;
1292 /* On Linux the first two RT signals are reserved by
1293 * glibc, and sigaction() will return EINVAL for them. */
1294 if ((sigaction(sig, &sa, NULL) < 0))
1295 if (errno != EINVAL)
1302 char *strstrip(char *s) {
1305 /* Drops trailing whitespace. Modifies the string in
1306 * place. Returns pointer to first non-space character */
1308 s += strspn(s, WHITESPACE);
1310 for (e = strchr(s, 0); e > s; e --)
1311 if (!strchr(WHITESPACE, e[-1]))
1319 char *delete_chars(char *s, const char *bad) {
1322 /* Drops all whitespace, regardless where in the string */
1324 for (f = s, t = s; *f; f++) {
1325 if (strchr(bad, *f))
1336 bool in_charset(const char *s, const char* charset) {
1342 for (i = s; *i; i++)
1343 if (!strchr(charset, *i))
1349 char *file_in_same_dir(const char *path, const char *filename) {
1356 /* This removes the last component of path and appends
1357 * filename, unless the latter is absolute anyway or the
1360 if (path_is_absolute(filename))
1361 return strdup(filename);
1363 if (!(e = strrchr(path, '/')))
1364 return strdup(filename);
1366 k = strlen(filename);
1367 if (!(r = new(char, e-path+1+k+1)))
1370 memcpy(r, path, e-path+1);
1371 memcpy(r+(e-path)+1, filename, k+1);
1376 int rmdir_parents(const char *path, const char *stop) {
1385 /* Skip trailing slashes */
1386 while (l > 0 && path[l-1] == '/')
1392 /* Skip last component */
1393 while (l > 0 && path[l-1] != '/')
1396 /* Skip trailing slashes */
1397 while (l > 0 && path[l-1] == '/')
1403 if (!(t = strndup(path, l)))
1406 if (path_startswith(stop, t)) {
1415 if (errno != ENOENT)
1423 char hexchar(int x) {
1424 static const char table[16] = "0123456789abcdef";
1426 return table[x & 15];
1429 int unhexchar(char c) {
1431 if (c >= '0' && c <= '9')
1434 if (c >= 'a' && c <= 'f')
1435 return c - 'a' + 10;
1437 if (c >= 'A' && c <= 'F')
1438 return c - 'A' + 10;
1443 char octchar(int x) {
1444 return '0' + (x & 7);
1447 int unoctchar(char c) {
1449 if (c >= '0' && c <= '7')
1455 char decchar(int x) {
1456 return '0' + (x % 10);
1459 int undecchar(char c) {
1461 if (c >= '0' && c <= '9')
1467 char *cescape(const char *s) {
1473 /* Does C style string escaping. */
1475 r = new(char, strlen(s)*4 + 1);
1479 for (f = s, t = r; *f; f++)
1525 /* For special chars we prefer octal over
1526 * hexadecimal encoding, simply because glib's
1527 * g_strescape() does the same */
1528 if ((*f < ' ') || (*f >= 127)) {
1530 *(t++) = octchar((unsigned char) *f >> 6);
1531 *(t++) = octchar((unsigned char) *f >> 3);
1532 *(t++) = octchar((unsigned char) *f);
1543 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1550 /* Undoes C style string escaping, and optionally prefixes it. */
1552 pl = prefix ? strlen(prefix) : 0;
1554 r = new(char, pl+length+1);
1559 memcpy(r, prefix, pl);
1561 for (f = s, t = r + pl; f < s + length; f++) {
1604 /* This is an extension of the XDG syntax files */
1609 /* hexadecimal encoding */
1612 a = unhexchar(f[1]);
1613 b = unhexchar(f[2]);
1615 if (a < 0 || b < 0) {
1616 /* Invalid escape code, let's take it literal then */
1620 *(t++) = (char) ((a << 4) | b);
1635 /* octal encoding */
1638 a = unoctchar(f[0]);
1639 b = unoctchar(f[1]);
1640 c = unoctchar(f[2]);
1642 if (a < 0 || b < 0 || c < 0) {
1643 /* Invalid escape code, let's take it literal then */
1647 *(t++) = (char) ((a << 6) | (b << 3) | c);
1655 /* premature end of string.*/
1660 /* Invalid escape code, let's take it literal then */
1672 char *cunescape_length(const char *s, size_t length) {
1673 return cunescape_length_with_prefix(s, length, NULL);
1676 char *cunescape(const char *s) {
1679 return cunescape_length(s, strlen(s));
1682 char *xescape(const char *s, const char *bad) {
1686 /* Escapes all chars in bad, in addition to \ and all special
1687 * chars, in \xFF style escaping. May be reversed with
1690 if (!(r = new(char, strlen(s)*4+1)))
1693 for (f = s, t = r; *f; f++) {
1695 if ((*f < ' ') || (*f >= 127) ||
1696 (*f == '\\') || strchr(bad, *f)) {
1699 *(t++) = hexchar(*f >> 4);
1700 *(t++) = hexchar(*f);
1710 char *bus_path_escape(const char *s) {
1716 /* Escapes all chars that D-Bus' object path cannot deal
1717 * with. Can be reverse with bus_path_unescape() */
1719 if (!(r = new(char, strlen(s)*3+1)))
1722 for (f = s, t = r; *f; f++) {
1724 if (!(*f >= 'A' && *f <= 'Z') &&
1725 !(*f >= 'a' && *f <= 'z') &&
1726 !(*f >= '0' && *f <= '9')) {
1728 *(t++) = hexchar(*f >> 4);
1729 *(t++) = hexchar(*f);
1739 char *bus_path_unescape(const char *f) {
1744 if (!(r = strdup(f)))
1747 for (t = r; *f; f++) {
1752 if ((a = unhexchar(f[1])) < 0 ||
1753 (b = unhexchar(f[2])) < 0) {
1754 /* Invalid escape code, let's take it literal then */
1757 *(t++) = (char) ((a << 4) | b);
1769 char *ascii_strlower(char *t) {
1774 for (p = t; *p; p++)
1775 if (*p >= 'A' && *p <= 'Z')
1776 *p = *p - 'A' + 'a';
1781 static bool ignore_file_allow_backup(const char *filename) {
1785 filename[0] == '.' ||
1786 streq(filename, "lost+found") ||
1787 streq(filename, "aquota.user") ||
1788 streq(filename, "aquota.group") ||
1789 endswith(filename, ".rpmnew") ||
1790 endswith(filename, ".rpmsave") ||
1791 endswith(filename, ".rpmorig") ||
1792 endswith(filename, ".dpkg-old") ||
1793 endswith(filename, ".dpkg-new") ||
1794 endswith(filename, ".swp");
1797 bool ignore_file(const char *filename) {
1800 if (endswith(filename, "~"))
1803 return ignore_file_allow_backup(filename);
1806 int fd_nonblock(int fd, bool nonblock) {
1811 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1815 flags |= O_NONBLOCK;
1817 flags &= ~O_NONBLOCK;
1819 if (fcntl(fd, F_SETFL, flags) < 0)
1825 int fd_cloexec(int fd, bool cloexec) {
1830 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1834 flags |= FD_CLOEXEC;
1836 flags &= ~FD_CLOEXEC;
1838 if (fcntl(fd, F_SETFD, flags) < 0)
1844 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1847 assert(n_fdset == 0 || fdset);
1849 for (i = 0; i < n_fdset; i++)
1856 int close_all_fds(const int except[], unsigned n_except) {
1861 assert(n_except == 0 || except);
1863 d = opendir("/proc/self/fd");
1868 /* When /proc isn't available (for example in chroots)
1869 * the fallback is brute forcing through the fd
1872 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1873 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1875 if (fd_in_set(fd, except, n_except))
1878 if (close_nointr(fd) < 0)
1879 if (errno != EBADF && r == 0)
1886 while ((de = readdir(d))) {
1889 if (ignore_file(de->d_name))
1892 if (safe_atoi(de->d_name, &fd) < 0)
1893 /* Let's better ignore this, just in case */
1902 if (fd_in_set(fd, except, n_except))
1905 if (close_nointr(fd) < 0) {
1906 /* Valgrind has its own FD and doesn't want to have it closed */
1907 if (errno != EBADF && r == 0)
1916 bool chars_intersect(const char *a, const char *b) {
1919 /* Returns true if any of the chars in a are in b. */
1920 for (p = a; *p; p++)
1927 char *format_timestamp(char *buf, size_t l, usec_t t) {
1937 sec = (time_t) (t / USEC_PER_SEC);
1939 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1945 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1948 n = now(CLOCK_REALTIME);
1950 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1955 if (d >= USEC_PER_YEAR)
1956 snprintf(buf, l, "%llu years and %llu months ago",
1957 (unsigned long long) (d / USEC_PER_YEAR),
1958 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1959 else if (d >= USEC_PER_MONTH)
1960 snprintf(buf, l, "%llu months and %llu days ago",
1961 (unsigned long long) (d / USEC_PER_MONTH),
1962 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1963 else if (d >= USEC_PER_WEEK)
1964 snprintf(buf, l, "%llu weeks and %llu days ago",
1965 (unsigned long long) (d / USEC_PER_WEEK),
1966 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1967 else if (d >= 2*USEC_PER_DAY)
1968 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1969 else if (d >= 25*USEC_PER_HOUR)
1970 snprintf(buf, l, "1 day and %lluh ago",
1971 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1972 else if (d >= 6*USEC_PER_HOUR)
1973 snprintf(buf, l, "%lluh ago",
1974 (unsigned long long) (d / USEC_PER_HOUR));
1975 else if (d >= USEC_PER_HOUR)
1976 snprintf(buf, l, "%lluh %llumin ago",
1977 (unsigned long long) (d / USEC_PER_HOUR),
1978 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1979 else if (d >= 5*USEC_PER_MINUTE)
1980 snprintf(buf, l, "%llumin ago",
1981 (unsigned long long) (d / USEC_PER_MINUTE));
1982 else if (d >= USEC_PER_MINUTE)
1983 snprintf(buf, l, "%llumin %llus ago",
1984 (unsigned long long) (d / USEC_PER_MINUTE),
1985 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1986 else if (d >= USEC_PER_SEC)
1987 snprintf(buf, l, "%llus ago",
1988 (unsigned long long) (d / USEC_PER_SEC));
1989 else if (d >= USEC_PER_MSEC)
1990 snprintf(buf, l, "%llums ago",
1991 (unsigned long long) (d / USEC_PER_MSEC));
1993 snprintf(buf, l, "%lluus ago",
1994 (unsigned long long) d);
1996 snprintf(buf, l, "now");
2002 char *format_timespan(char *buf, size_t l, usec_t t) {
2003 static const struct {
2007 { "w", USEC_PER_WEEK },
2008 { "d", USEC_PER_DAY },
2009 { "h", USEC_PER_HOUR },
2010 { "min", USEC_PER_MINUTE },
2011 { "s", USEC_PER_SEC },
2012 { "ms", USEC_PER_MSEC },
2022 if (t == (usec_t) -1)
2026 snprintf(p, l, "0");
2031 /* The result of this function can be parsed with parse_usec */
2033 for (i = 0; i < ELEMENTSOF(table); i++) {
2037 if (t < table[i].usec)
2043 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2044 n = MIN((size_t) k, l);
2057 bool fstype_is_network(const char *fstype) {
2058 static const char table[] =
2067 return nulstr_contains(table, fstype);
2071 _cleanup_close_ int fd;
2073 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2079 TIOCL_GETKMSGREDIRECT,
2083 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2086 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2089 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2095 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2096 struct termios old_termios, new_termios;
2098 char line[LINE_MAX];
2103 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2104 new_termios = old_termios;
2106 new_termios.c_lflag &= ~ICANON;
2107 new_termios.c_cc[VMIN] = 1;
2108 new_termios.c_cc[VTIME] = 0;
2110 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2113 if (t != (usec_t) -1) {
2114 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2115 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2120 k = fread(&c, 1, 1, f);
2122 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2128 *need_nl = c != '\n';
2135 if (t != (usec_t) -1)
2136 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2139 if (!fgets(line, sizeof(line), f))
2144 if (strlen(line) != 1)
2154 int ask(char *ret, const char *replies, const char *text, ...) {
2161 on_tty = isatty(STDOUT_FILENO);
2167 bool need_nl = true;
2170 fputs(ANSI_HIGHLIGHT_ON, stdout);
2177 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2181 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2184 if (r == -EBADMSG) {
2185 puts("Bad input, please try again.");
2196 if (strchr(replies, c)) {
2201 puts("Read unexpected character, please try again.");
2205 int reset_terminal_fd(int fd, bool switch_to_text) {
2206 struct termios termios;
2209 /* Set terminal to some sane defaults */
2213 /* We leave locked terminal attributes untouched, so that
2214 * Plymouth may set whatever it wants to set, and we don't
2215 * interfere with that. */
2217 /* Disable exclusive mode, just in case */
2218 ioctl(fd, TIOCNXCL);
2220 /* Switch to text mode */
2222 ioctl(fd, KDSETMODE, KD_TEXT);
2224 /* Enable console unicode mode */
2225 ioctl(fd, KDSKBMODE, K_UNICODE);
2227 if (tcgetattr(fd, &termios) < 0) {
2232 /* We only reset the stuff that matters to the software. How
2233 * hardware is set up we don't touch assuming that somebody
2234 * else will do that for us */
2236 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2237 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2238 termios.c_oflag |= ONLCR;
2239 termios.c_cflag |= CREAD;
2240 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2242 termios.c_cc[VINTR] = 03; /* ^C */
2243 termios.c_cc[VQUIT] = 034; /* ^\ */
2244 termios.c_cc[VERASE] = 0177;
2245 termios.c_cc[VKILL] = 025; /* ^X */
2246 termios.c_cc[VEOF] = 04; /* ^D */
2247 termios.c_cc[VSTART] = 021; /* ^Q */
2248 termios.c_cc[VSTOP] = 023; /* ^S */
2249 termios.c_cc[VSUSP] = 032; /* ^Z */
2250 termios.c_cc[VLNEXT] = 026; /* ^V */
2251 termios.c_cc[VWERASE] = 027; /* ^W */
2252 termios.c_cc[VREPRINT] = 022; /* ^R */
2253 termios.c_cc[VEOL] = 0;
2254 termios.c_cc[VEOL2] = 0;
2256 termios.c_cc[VTIME] = 0;
2257 termios.c_cc[VMIN] = 1;
2259 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2263 /* Just in case, flush all crap out */
2264 tcflush(fd, TCIOFLUSH);
2269 int reset_terminal(const char *name) {
2272 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2276 r = reset_terminal_fd(fd, true);
2277 close_nointr_nofail(fd);
2282 int open_terminal(const char *name, int mode) {
2287 * If a TTY is in the process of being closed opening it might
2288 * cause EIO. This is horribly awful, but unlikely to be
2289 * changed in the kernel. Hence we work around this problem by
2290 * retrying a couple of times.
2292 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2296 fd = open(name, mode);
2303 /* Max 1s in total */
2307 usleep(50 * USEC_PER_MSEC);
2316 close_nointr_nofail(fd);
2321 close_nointr_nofail(fd);
2328 int flush_fd(int fd) {
2329 struct pollfd pollfd;
2333 pollfd.events = POLLIN;
2340 if ((r = poll(&pollfd, 1, 0)) < 0) {
2351 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2356 if (errno == EAGAIN)
2367 int acquire_terminal(
2371 bool ignore_tiocstty_eperm,
2374 int fd = -1, notify = -1, r = 0, wd = -1;
2376 struct sigaction sa_old, sa_new;
2380 /* We use inotify to be notified when the tty is closed. We
2381 * create the watch before checking if we can actually acquire
2382 * it, so that we don't lose any event.
2384 * Note: strictly speaking this actually watches for the
2385 * device being closed, it does *not* really watch whether a
2386 * tty loses its controlling process. However, unless some
2387 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2388 * its tty otherwise this will not become a problem. As long
2389 * as the administrator makes sure not configure any service
2390 * on the same tty as an untrusted user this should not be a
2391 * problem. (Which he probably should not do anyway.) */
2393 if (timeout != (usec_t) -1)
2394 ts = now(CLOCK_MONOTONIC);
2396 if (!fail && !force) {
2397 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2403 wd = inotify_add_watch(notify, name, IN_CLOSE);
2412 r = flush_fd(notify);
2417 /* We pass here O_NOCTTY only so that we can check the return
2418 * value TIOCSCTTY and have a reliable way to figure out if we
2419 * successfully became the controlling process of the tty */
2420 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2424 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2425 * if we already own the tty. */
2427 sa_new.sa_handler = SIG_IGN;
2428 sa_new.sa_flags = SA_RESTART;
2429 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2431 /* First, try to get the tty */
2432 if (ioctl(fd, TIOCSCTTY, force) < 0)
2435 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2437 /* Sometimes it makes sense to ignore TIOCSCTTY
2438 * returning EPERM, i.e. when very likely we already
2439 * are have this controlling terminal. */
2440 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2443 if (r < 0 && (force || fail || r != -EPERM)) {
2452 assert(notify >= 0);
2455 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2457 struct inotify_event *e;
2459 if (timeout != (usec_t) -1) {
2462 n = now(CLOCK_MONOTONIC);
2463 if (ts + timeout < n) {
2468 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2478 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2481 if (errno == EINTR || errno == EAGAIN)
2488 e = (struct inotify_event*) inotify_buffer;
2493 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2498 step = sizeof(struct inotify_event) + e->len;
2499 assert(step <= (size_t) l);
2501 e = (struct inotify_event*) ((uint8_t*) e + step);
2508 /* We close the tty fd here since if the old session
2509 * ended our handle will be dead. It's important that
2510 * we do this after sleeping, so that we don't enter
2511 * an endless loop. */
2512 close_nointr_nofail(fd);
2516 close_nointr_nofail(notify);
2518 r = reset_terminal_fd(fd, true);
2520 log_warning("Failed to reset terminal: %s", strerror(-r));
2526 close_nointr_nofail(fd);
2529 close_nointr_nofail(notify);
2534 int release_terminal(void) {
2536 struct sigaction sa_old, sa_new;
2538 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2541 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2542 * by our own TIOCNOTTY */
2545 sa_new.sa_handler = SIG_IGN;
2546 sa_new.sa_flags = SA_RESTART;
2547 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2549 if (ioctl(fd, TIOCNOTTY) < 0)
2552 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2554 close_nointr_nofail(fd);
2558 int sigaction_many(const struct sigaction *sa, ...) {
2563 while ((sig = va_arg(ap, int)) > 0)
2564 if (sigaction(sig, sa, NULL) < 0)
2571 int ignore_signals(int sig, ...) {
2572 struct sigaction sa;
2577 sa.sa_handler = SIG_IGN;
2578 sa.sa_flags = SA_RESTART;
2580 if (sigaction(sig, &sa, NULL) < 0)
2584 while ((sig = va_arg(ap, int)) > 0)
2585 if (sigaction(sig, &sa, NULL) < 0)
2592 int default_signals(int sig, ...) {
2593 struct sigaction sa;
2598 sa.sa_handler = SIG_DFL;
2599 sa.sa_flags = SA_RESTART;
2601 if (sigaction(sig, &sa, NULL) < 0)
2605 while ((sig = va_arg(ap, int)) > 0)
2606 if (sigaction(sig, &sa, NULL) < 0)
2613 int close_pipe(int p[]) {
2619 a = close_nointr(p[0]);
2624 b = close_nointr(p[1]);
2628 return a < 0 ? a : b;
2631 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2640 while (nbytes > 0) {
2643 if ((k = read(fd, p, nbytes)) <= 0) {
2645 if (k < 0 && errno == EINTR)
2648 if (k < 0 && errno == EAGAIN && do_poll) {
2649 struct pollfd pollfd;
2653 pollfd.events = POLLIN;
2655 if (poll(&pollfd, 1, -1) < 0) {
2659 return n > 0 ? n : -errno;
2662 if (pollfd.revents != POLLIN)
2663 return n > 0 ? n : -EIO;
2668 return n > 0 ? n : (k < 0 ? -errno : 0);
2679 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2688 while (nbytes > 0) {
2691 k = write(fd, p, nbytes);
2694 if (k < 0 && errno == EINTR)
2697 if (k < 0 && errno == EAGAIN && do_poll) {
2698 struct pollfd pollfd;
2702 pollfd.events = POLLOUT;
2704 if (poll(&pollfd, 1, -1) < 0) {
2708 return n > 0 ? n : -errno;
2711 if (pollfd.revents != POLLOUT)
2712 return n > 0 ? n : -EIO;
2717 return n > 0 ? n : (k < 0 ? -errno : 0);
2728 int parse_usec(const char *t, usec_t *usec) {
2729 static const struct {
2733 { "sec", USEC_PER_SEC },
2734 { "s", USEC_PER_SEC },
2735 { "min", USEC_PER_MINUTE },
2736 { "hr", USEC_PER_HOUR },
2737 { "h", USEC_PER_HOUR },
2738 { "d", USEC_PER_DAY },
2739 { "w", USEC_PER_WEEK },
2740 { "msec", USEC_PER_MSEC },
2741 { "ms", USEC_PER_MSEC },
2742 { "m", USEC_PER_MINUTE },
2745 { "", USEC_PER_SEC }, /* default is sec */
2761 l = strtoll(p, &e, 10);
2772 e += strspn(e, WHITESPACE);
2774 for (i = 0; i < ELEMENTSOF(table); i++)
2775 if (startswith(e, table[i].suffix)) {
2776 r += (usec_t) l * table[i].usec;
2777 p = e + strlen(table[i].suffix);
2781 if (i >= ELEMENTSOF(table))
2791 int parse_nsec(const char *t, nsec_t *nsec) {
2792 static const struct {
2796 { "sec", NSEC_PER_SEC },
2797 { "s", NSEC_PER_SEC },
2798 { "min", NSEC_PER_MINUTE },
2799 { "hr", NSEC_PER_HOUR },
2800 { "h", NSEC_PER_HOUR },
2801 { "d", NSEC_PER_DAY },
2802 { "w", NSEC_PER_WEEK },
2803 { "msec", NSEC_PER_MSEC },
2804 { "ms", NSEC_PER_MSEC },
2805 { "m", NSEC_PER_MINUTE },
2806 { "usec", NSEC_PER_USEC },
2807 { "us", NSEC_PER_USEC },
2810 { "", 1ULL }, /* default is nsec */
2826 l = strtoll(p, &e, 10);
2837 e += strspn(e, WHITESPACE);
2839 for (i = 0; i < ELEMENTSOF(table); i++)
2840 if (startswith(e, table[i].suffix)) {
2841 r += (nsec_t) l * table[i].nsec;
2842 p = e + strlen(table[i].suffix);
2846 if (i >= ELEMENTSOF(table))
2856 int parse_bytes(const char *t, off_t *bytes) {
2857 static const struct {
2863 { "M", 1024ULL*1024ULL },
2864 { "G", 1024ULL*1024ULL*1024ULL },
2865 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2866 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2867 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2884 l = strtoll(p, &e, 10);
2895 e += strspn(e, WHITESPACE);
2897 for (i = 0; i < ELEMENTSOF(table); i++)
2898 if (startswith(e, table[i].suffix)) {
2899 r += (off_t) l * table[i].factor;
2900 p = e + strlen(table[i].suffix);
2904 if (i >= ELEMENTSOF(table))
2914 int make_stdio(int fd) {
2919 r = dup3(fd, STDIN_FILENO, 0);
2920 s = dup3(fd, STDOUT_FILENO, 0);
2921 t = dup3(fd, STDERR_FILENO, 0);
2924 close_nointr_nofail(fd);
2926 if (r < 0 || s < 0 || t < 0)
2929 /* We rely here that the new fd has O_CLOEXEC not set */
2934 int make_null_stdio(void) {
2937 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2941 return make_stdio(null_fd);
2944 bool is_device_path(const char *path) {
2946 /* Returns true on paths that refer to a device, either in
2947 * sysfs or in /dev */
2950 path_startswith(path, "/dev/") ||
2951 path_startswith(path, "/sys/");
2954 int dir_is_empty(const char *path) {
2955 _cleanup_closedir_ DIR *d;
2964 union dirent_storage buf;
2966 r = readdir_r(d, &buf.de, &de);
2973 if (!ignore_file(de->d_name))
2978 unsigned long long random_ull(void) {
2979 _cleanup_close_ int fd;
2983 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2987 r = loop_read(fd, &ull, sizeof(ull), true);
2988 if (r != sizeof(ull))
2994 return random() * RAND_MAX + random();
2997 void rename_process(const char name[8]) {
3000 /* This is a like a poor man's setproctitle(). It changes the
3001 * comm field, argv[0], and also the glibc's internally used
3002 * name of the process. For the first one a limit of 16 chars
3003 * applies, to the second one usually one of 10 (i.e. length
3004 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3005 * "systemd"). If you pass a longer string it will be
3008 prctl(PR_SET_NAME, name);
3010 if (program_invocation_name)
3011 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3013 if (saved_argc > 0) {
3017 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3019 for (i = 1; i < saved_argc; i++) {
3023 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3028 void sigset_add_many(sigset_t *ss, ...) {
3035 while ((sig = va_arg(ap, int)) > 0)
3036 assert_se(sigaddset(ss, sig) == 0);
3040 char* gethostname_malloc(void) {
3043 assert_se(uname(&u) >= 0);
3045 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3046 return strdup(u.nodename);
3048 return strdup(u.sysname);
3051 bool hostname_is_set(void) {
3054 assert_se(uname(&u) >= 0);
3056 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3059 static char *lookup_uid(uid_t uid) {
3062 _cleanup_free_ char *buf = NULL;
3063 struct passwd pwbuf, *pw = NULL;
3065 /* Shortcut things to avoid NSS lookups */
3067 return strdup("root");
3069 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3073 buf = malloc(bufsize);
3077 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3078 return strdup(pw->pw_name);
3080 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3086 char* getlogname_malloc(void) {
3090 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3095 return lookup_uid(uid);
3098 char *getusername_malloc(void) {
3105 return lookup_uid(getuid());
3108 int getttyname_malloc(int fd, char **r) {
3109 char path[PATH_MAX], *c;
3114 k = ttyname_r(fd, path, sizeof(path));
3120 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3128 int getttyname_harder(int fd, char **r) {
3132 k = getttyname_malloc(fd, &s);
3136 if (streq(s, "tty")) {
3138 return get_ctty(0, NULL, r);
3145 int get_ctty_devnr(pid_t pid, dev_t *d) {
3147 char line[LINE_MAX], *p, *fn;
3148 unsigned long ttynr;
3151 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3154 f = fopen(fn, "re");
3159 if (!fgets(line, sizeof(line), f)) {
3160 k = feof(f) ? -EIO : -errno;
3167 p = strrchr(line, ')');
3177 "%*d " /* session */
3186 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3188 char fn[PATH_MAX], *s, *b, *p;
3193 k = get_ctty_devnr(pid, &devnr);
3197 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3200 if ((k = readlink_malloc(fn, &s)) < 0) {
3205 /* This is an ugly hack */
3206 if (major(devnr) == 136) {
3207 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3217 /* Probably something like the ptys which have no
3218 * symlink in /dev/char. Let's return something
3219 * vaguely useful. */
3221 if (!(b = strdup(fn + 5)))
3231 if (startswith(s, "/dev/"))
3233 else if (startswith(s, "../"))
3251 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3257 /* This returns the first error we run into, but nevertheless
3258 * tries to go on. This closes the passed fd. */
3262 close_nointr_nofail(fd);
3264 return errno == ENOENT ? 0 : -errno;
3269 union dirent_storage buf;
3270 bool is_dir, keep_around;
3274 r = readdir_r(d, &buf.de, &de);
3275 if (r != 0 && ret == 0) {
3283 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3286 if (de->d_type == DT_UNKNOWN ||
3288 (de->d_type == DT_DIR && root_dev)) {
3289 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3290 if (ret == 0 && errno != ENOENT)
3295 is_dir = S_ISDIR(st.st_mode);
3298 (st.st_uid == 0 || st.st_uid == getuid()) &&
3299 (st.st_mode & S_ISVTX);
3301 is_dir = de->d_type == DT_DIR;
3302 keep_around = false;
3308 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3309 if (root_dev && st.st_dev != root_dev->st_dev)
3312 subdir_fd = openat(fd, de->d_name,
3313 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3314 if (subdir_fd < 0) {
3315 if (ret == 0 && errno != ENOENT)
3320 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3321 if (r < 0 && ret == 0)
3325 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3326 if (ret == 0 && errno != ENOENT)
3330 } else if (!only_dirs && !keep_around) {
3332 if (unlinkat(fd, de->d_name, 0) < 0) {
3333 if (ret == 0 && errno != ENOENT)
3344 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3349 if (fstatfs(fd, &s) < 0) {
3350 close_nointr_nofail(fd);
3354 /* We refuse to clean disk file systems with this call. This
3355 * is extra paranoia just to be sure we never ever remove
3358 if (s.f_type != TMPFS_MAGIC &&
3359 s.f_type != RAMFS_MAGIC) {
3360 log_error("Attempted to remove disk file system, and we can't allow that.");
3361 close_nointr_nofail(fd);
3365 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3368 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3374 /* We refuse to clean the root file system with this
3375 * call. This is extra paranoia to never cause a really
3376 * seriously broken system. */
3377 if (path_equal(path, "/")) {
3378 log_error("Attempted to remove entire root file system, and we can't allow that.");
3382 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3385 if (errno != ENOTDIR)
3389 if (statfs(path, &s) < 0)
3392 if (s.f_type != TMPFS_MAGIC &&
3393 s.f_type != RAMFS_MAGIC) {
3394 log_error("Attempted to remove disk file system, and we can't allow that.");
3399 if (delete_root && !only_dirs)
3400 if (unlink(path) < 0 && errno != ENOENT)
3407 if (fstatfs(fd, &s) < 0) {
3408 close_nointr_nofail(fd);
3412 if (s.f_type != TMPFS_MAGIC &&
3413 s.f_type != RAMFS_MAGIC) {
3414 log_error("Attempted to remove disk file system, and we can't allow that.");
3415 close_nointr_nofail(fd);
3420 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3423 if (honour_sticky && file_is_priv_sticky(path) > 0)
3426 if (rmdir(path) < 0 && errno != ENOENT) {
3435 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3436 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3439 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3440 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3443 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3446 /* Under the assumption that we are running privileged we
3447 * first change the access mode and only then hand out
3448 * ownership to avoid a window where access is too open. */
3450 if (mode != (mode_t) -1)
3451 if (chmod(path, mode) < 0)
3454 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3455 if (chown(path, uid, gid) < 0)
3461 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3464 /* Under the assumption that we are running privileged we
3465 * first change the access mode and only then hand out
3466 * ownership to avoid a window where access is too open. */
3468 if (fchmod(fd, mode) < 0)
3471 if (fchown(fd, uid, gid) < 0)
3477 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3481 /* Allocates the cpuset in the right size */
3484 if (!(r = CPU_ALLOC(n)))
3487 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3488 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3498 if (errno != EINVAL)
3505 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3506 static const char status_indent[] = " "; /* "[" STATUS "] " */
3507 _cleanup_free_ char *s = NULL;
3508 _cleanup_close_ int fd = -1;
3509 struct iovec iovec[5];
3514 /* This is independent of logging, as status messages are
3515 * optional and go exclusively to the console. */
3517 if (vasprintf(&s, format, ap) < 0)
3520 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3533 sl = status ? sizeof(status_indent)-1 : 0;
3539 e = ellipsize(s, emax, 75);
3549 if (!isempty(status)) {
3550 IOVEC_SET_STRING(iovec[n++], "[");
3551 IOVEC_SET_STRING(iovec[n++], status);
3552 IOVEC_SET_STRING(iovec[n++], "] ");
3554 IOVEC_SET_STRING(iovec[n++], status_indent);
3557 IOVEC_SET_STRING(iovec[n++], s);
3558 IOVEC_SET_STRING(iovec[n++], "\n");
3560 if (writev(fd, iovec, n) < 0)
3566 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3572 va_start(ap, format);
3573 r = status_vprintf(status, ellipse, format, ap);
3579 int status_welcome(void) {
3581 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3583 r = parse_env_file("/etc/os-release", NEWLINE,
3584 "PRETTY_NAME", &pretty_name,
3585 "ANSI_COLOR", &ansi_color,
3587 if (r < 0 && r != -ENOENT)
3588 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3590 return status_printf(NULL, false,
3591 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3592 isempty(ansi_color) ? "1" : ansi_color,
3593 isempty(pretty_name) ? "Linux" : pretty_name);
3596 char *replace_env(const char *format, char **env) {
3603 const char *e, *word = format;
3608 for (e = format; *e; e ++) {
3619 if (!(k = strnappend(r, word, e-word-1)))
3628 } else if (*e == '$') {
3629 if (!(k = strnappend(r, word, e-word)))
3645 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3648 if (!(k = strappend(r, t)))
3661 if (!(k = strnappend(r, word, e-word)))
3672 char **replace_env_argv(char **argv, char **env) {
3674 unsigned k = 0, l = 0;
3676 l = strv_length(argv);
3678 if (!(r = new(char*, l+1)))
3681 STRV_FOREACH(i, argv) {
3683 /* If $FOO appears as single word, replace it by the split up variable */
3684 if ((*i)[0] == '$' && (*i)[1] != '{') {
3689 if ((e = strv_env_get(env, *i+1))) {
3691 if (!(m = strv_split_quoted(e))) {
3702 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3711 memcpy(r + k, m, q * sizeof(char*));
3719 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3720 if (!(r[k++] = replace_env(*i, env))) {
3730 int fd_columns(int fd) {
3734 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3743 static unsigned columns_cached(bool cached) {
3744 static __thread int env_columns = -1;
3747 if (_likely_(parsed_columns > 0 && cached))
3748 return parsed_columns;
3750 if (_unlikely_(env_columns == -1)) {
3751 e = getenv("COLUMNS");
3753 env_columns = atoi(e);
3758 if (env_columns > 0) {
3759 parsed_columns = env_columns;
3760 return parsed_columns;
3763 if (parsed_columns <= 0 || !cached)
3764 parsed_columns = fd_columns(STDOUT_FILENO);
3766 if (parsed_columns <= 0)
3767 parsed_columns = 80;
3769 return parsed_columns;
3772 unsigned columns(void) {
3773 return columns_cached(true);
3776 unsigned columns_uncached(void) {
3777 return columns_cached(false);
3780 /* intended to be used as a SIGWINCH sighandler */
3781 void columns_cache_reset(int signum) {
3785 int fd_lines(int fd) {
3789 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3798 unsigned lines(void) {
3799 static __thread int parsed_lines = 0;
3802 if (_likely_(parsed_lines > 0))
3803 return parsed_lines;
3805 e = getenv("LINES");
3807 parsed_lines = atoi(e);
3809 if (parsed_lines <= 0)
3810 parsed_lines = fd_lines(STDOUT_FILENO);
3812 if (parsed_lines <= 0)
3815 return parsed_lines;
3818 int running_in_chroot(void) {
3824 /* Only works as root */
3826 if (stat("/proc/1/root", &a) < 0)
3829 if (stat("/", &b) < 0)
3833 a.st_dev != b.st_dev ||
3834 a.st_ino != b.st_ino;
3837 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3842 assert(percent <= 100);
3843 assert(new_length >= 3);
3845 if (old_length <= 3 || old_length <= new_length)
3846 return strndup(s, old_length);
3848 r = new0(char, new_length+1);
3852 x = (new_length * percent) / 100;
3854 if (x > new_length - 3)
3862 s + old_length - (new_length - x - 3),
3863 new_length - x - 3);
3868 char *ellipsize(const char *s, size_t length, unsigned percent) {
3869 return ellipsize_mem(s, strlen(s), length, percent);
3872 int touch(const char *path) {
3877 /* This just opens the file for writing, ensuring it
3878 * exists. It doesn't call utimensat() the way /usr/bin/touch
3881 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3885 close_nointr_nofail(fd);
3889 char *unquote(const char *s, const char* quotes) {
3893 /* This is rather stupid, simply removes the heading and
3894 * trailing quotes if there is one. Doesn't care about
3895 * escaping or anything. We should make this smarter one
3902 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3903 return strndup(s+1, l-2);
3908 char *normalize_env_assignment(const char *s) {
3909 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3912 eq = strchr(s, '=');
3924 memmove(r, t, strlen(t) + 1);
3928 name = strndup(s, eq - s);
3936 value = unquote(strstrip(p), QUOTES);
3940 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3946 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3957 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3969 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3976 r = wait_for_terminate(pid, &status);
3978 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3982 if (status.si_code == CLD_EXITED) {
3983 if (status.si_status != 0) {
3984 log_warning("%s failed with error code %i.", name, status.si_status);
3985 return status.si_status;
3988 log_debug("%s succeeded.", name);
3991 } else if (status.si_code == CLD_KILLED ||
3992 status.si_code == CLD_DUMPED) {
3994 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3998 log_warning("%s failed due to unknown reason.", name);
4002 _noreturn_ void freeze(void) {
4004 /* Make sure nobody waits for us on a socket anymore */
4005 close_all_fds(NULL, 0);
4013 bool null_or_empty(struct stat *st) {
4016 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4019 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4025 int null_or_empty_path(const char *fn) {
4030 if (stat(fn, &st) < 0)
4033 return null_or_empty(&st);
4036 DIR *xopendirat(int fd, const char *name, int flags) {
4040 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4046 close_nointr_nofail(nfd);
4053 int signal_from_string_try_harder(const char *s) {
4057 signo = signal_from_string(s);
4059 if (startswith(s, "SIG"))
4060 return signal_from_string(s+3);
4065 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4071 if (!dual_timestamp_is_set(t))
4074 fprintf(f, "%s=%llu %llu\n",
4076 (unsigned long long) t->realtime,
4077 (unsigned long long) t->monotonic);
4080 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4081 unsigned long long a, b;
4086 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4087 log_debug("Failed to parse finish timestamp value %s", value);
4094 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4098 /* FIXME: to follow udev's logic 100% we need to leave valid
4099 * UTF8 chars unescaped */
4101 u = unquote(tagvalue, "\"\'");
4105 t = xescape(u, "/ ");
4111 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4120 char *fstab_node_to_udev_node(const char *p) {
4123 if (startswith(p, "LABEL="))
4124 return tag_to_udev_node(p+6, "label");
4126 if (startswith(p, "UUID="))
4127 return tag_to_udev_node(p+5, "uuid");
4129 if (startswith(p, "PARTUUID="))
4130 return tag_to_udev_node(p+9, "partuuid");
4132 if (startswith(p, "PARTLABEL="))
4133 return tag_to_udev_node(p+10, "partlabel");
4138 bool tty_is_vc(const char *tty) {
4141 if (startswith(tty, "/dev/"))
4144 return vtnr_from_tty(tty) >= 0;
4147 bool tty_is_console(const char *tty) {
4150 if (startswith(tty, "/dev/"))
4153 return streq(tty, "console");
4156 int vtnr_from_tty(const char *tty) {
4161 if (startswith(tty, "/dev/"))
4164 if (!startswith(tty, "tty") )
4167 if (tty[3] < '0' || tty[3] > '9')
4170 r = safe_atoi(tty+3, &i);
4174 if (i < 0 || i > 63)
4180 bool tty_is_vc_resolve(const char *tty) {
4181 char *active = NULL;
4186 if (startswith(tty, "/dev/"))
4189 /* Resolve where /dev/console is pointing to, if /sys is
4190 * actually ours (i.e. not read-only-mounted which is a sign
4191 * for container setups) */
4192 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4193 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4194 /* If multiple log outputs are configured the
4195 * last one is what /dev/console points to */
4196 tty = strrchr(active, ' ');
4209 const char *default_term_for_tty(const char *tty) {
4212 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4215 bool dirent_is_file(const struct dirent *de) {
4218 if (ignore_file(de->d_name))
4221 if (de->d_type != DT_REG &&
4222 de->d_type != DT_LNK &&
4223 de->d_type != DT_UNKNOWN)
4229 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4232 if (de->d_type != DT_REG &&
4233 de->d_type != DT_LNK &&
4234 de->d_type != DT_UNKNOWN)
4237 if (ignore_file_allow_backup(de->d_name))
4240 return endswith(de->d_name, suffix);
4243 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4246 Hashmap *pids = NULL;
4250 /* Executes all binaries in a directory in parallel and waits
4251 * until all they all finished. */
4254 if (!(_d = opendir(directory))) {
4256 if (errno == ENOENT)
4259 log_error("Failed to enumerate directory %s: %m", directory);
4266 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4267 log_error("Failed to allocate set.");
4271 while ((de = readdir(d))) {
4276 if (!dirent_is_file(de))
4279 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4284 if ((pid = fork()) < 0) {
4285 log_error("Failed to fork: %m");
4303 log_error("Failed to execute %s: %m", path);
4304 _exit(EXIT_FAILURE);
4307 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4309 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4310 log_error("Failed to add PID to set: %s", strerror(-k));
4315 while (!hashmap_isempty(pids)) {
4316 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4321 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4326 log_error("waitid() failed: %m");
4330 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4331 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4332 if (si.si_code == CLD_EXITED)
4333 log_error("%s exited with exit status %i.", path, si.si_status);
4335 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4337 log_debug("%s exited successfully.", path);
4348 hashmap_free_free(pids);
4351 int kill_and_sigcont(pid_t pid, int sig) {
4354 r = kill(pid, sig) < 0 ? -errno : 0;
4362 bool nulstr_contains(const char*nulstr, const char *needle) {
4368 NULSTR_FOREACH(i, nulstr)
4369 if (streq(i, needle))
4375 bool plymouth_running(void) {
4376 return access("/run/plymouth/pid", F_OK) >= 0;
4379 char* strshorten(char *s, size_t l) {
4388 static bool hostname_valid_char(char c) {
4390 (c >= 'a' && c <= 'z') ||
4391 (c >= 'A' && c <= 'Z') ||
4392 (c >= '0' && c <= '9') ||
4398 bool hostname_is_valid(const char *s) {
4404 for (p = s; *p; p++)
4405 if (!hostname_valid_char(*p))
4408 if (p-s > HOST_NAME_MAX)
4414 char* hostname_cleanup(char *s) {
4417 for (p = s, d = s; *p; p++)
4418 if ((*p >= 'a' && *p <= 'z') ||
4419 (*p >= 'A' && *p <= 'Z') ||
4420 (*p >= '0' && *p <= '9') ||
4428 strshorten(s, HOST_NAME_MAX);
4432 int pipe_eof(int fd) {
4433 struct pollfd pollfd;
4438 pollfd.events = POLLIN|POLLHUP;
4440 r = poll(&pollfd, 1, 0);
4447 return pollfd.revents & POLLHUP;
4450 int fd_wait_for_event(int fd, int event, usec_t t) {
4451 struct pollfd pollfd;
4456 pollfd.events = event;
4458 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4465 return pollfd.revents;
4468 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4479 t = new(char, strlen(path) + 1 + 6 + 1);
4483 fn = path_get_file_name(path);
4487 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4489 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4495 f = fdopen(fd, "we");
4508 int terminal_vhangup_fd(int fd) {
4511 if (ioctl(fd, TIOCVHANGUP) < 0)
4517 int terminal_vhangup(const char *name) {
4520 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4524 r = terminal_vhangup_fd(fd);
4525 close_nointr_nofail(fd);
4530 int vt_disallocate(const char *name) {
4534 /* Deallocate the VT if possible. If not possible
4535 * (i.e. because it is the active one), at least clear it
4536 * entirely (including the scrollback buffer) */
4538 if (!startswith(name, "/dev/"))
4541 if (!tty_is_vc(name)) {
4542 /* So this is not a VT. I guess we cannot deallocate
4543 * it then. But let's at least clear the screen */
4545 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4550 "\033[r" /* clear scrolling region */
4551 "\033[H" /* move home */
4552 "\033[2J", /* clear screen */
4554 close_nointr_nofail(fd);
4559 if (!startswith(name, "/dev/tty"))
4562 r = safe_atou(name+8, &u);
4569 /* Try to deallocate */
4570 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4574 r = ioctl(fd, VT_DISALLOCATE, u);
4575 close_nointr_nofail(fd);
4583 /* Couldn't deallocate, so let's clear it fully with
4585 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4590 "\033[r" /* clear scrolling region */
4591 "\033[H" /* move home */
4592 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4594 close_nointr_nofail(fd);
4599 int copy_file(const char *from, const char *to) {
4605 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4609 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4611 close_nointr_nofail(fdf);
4619 n = read(fdf, buf, sizeof(buf));
4623 close_nointr_nofail(fdf);
4634 k = loop_write(fdt, buf, n, false);
4636 r = k < 0 ? k : (errno ? -errno : -EIO);
4638 close_nointr_nofail(fdf);
4646 close_nointr_nofail(fdf);
4647 r = close_nointr(fdt);
4657 int symlink_atomic(const char *from, const char *to) {
4659 _cleanup_free_ char *t;
4662 unsigned long long ull;
4669 t = new(char, strlen(to) + 1 + 16 + 1);
4673 fn = path_get_file_name(to);
4677 x = stpcpy(t+k+1, fn);
4680 for (i = 0; i < 16; i++) {
4681 *(x++) = hexchar(ull & 0xF);
4687 if (symlink(from, t) < 0)
4690 if (rename(t, to) < 0) {
4699 bool display_is_local(const char *display) {
4703 display[0] == ':' &&
4704 display[1] >= '0' &&
4708 int socket_from_display(const char *display, char **path) {
4715 if (!display_is_local(display))
4718 k = strspn(display+1, "0123456789");
4720 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4724 c = stpcpy(f, "/tmp/.X11-unix/X");
4725 memcpy(c, display+1, k);
4734 const char **username,
4735 uid_t *uid, gid_t *gid,
4737 const char **shell) {
4745 /* We enforce some special rules for uid=0: in order to avoid
4746 * NSS lookups for root we hardcode its data. */
4748 if (streq(*username, "root") || streq(*username, "0")) {
4766 if (parse_uid(*username, &u) >= 0) {
4770 /* If there are multiple users with the same id, make
4771 * sure to leave $USER to the configured value instead
4772 * of the first occurrence in the database. However if
4773 * the uid was configured by a numeric uid, then let's
4774 * pick the real username from /etc/passwd. */
4776 *username = p->pw_name;
4779 p = getpwnam(*username);
4783 return errno != 0 ? -errno : -ESRCH;
4795 *shell = p->pw_shell;
4800 int get_group_creds(const char **groupname, gid_t *gid) {
4806 /* We enforce some special rules for gid=0: in order to avoid
4807 * NSS lookups for root we hardcode its data. */
4809 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4810 *groupname = "root";
4818 if (parse_gid(*groupname, &id) >= 0) {
4823 *groupname = g->gr_name;
4826 g = getgrnam(*groupname);
4830 return errno != 0 ? -errno : -ESRCH;
4838 int in_group(const char *name) {
4840 int ngroups_max, r, i;
4842 r = get_group_creds(&name, &gid);
4846 if (getgid() == gid)
4849 if (getegid() == gid)
4852 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4853 assert(ngroups_max > 0);
4855 gids = alloca(sizeof(gid_t) * ngroups_max);
4857 r = getgroups(ngroups_max, gids);
4861 for (i = 0; i < r; i++)
4868 int glob_exists(const char *path) {
4876 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4878 if (k == GLOB_NOMATCH)
4880 else if (k == GLOB_NOSPACE)
4883 r = !strv_isempty(g.gl_pathv);
4885 r = errno ? -errno : -EIO;
4892 int dirent_ensure_type(DIR *d, struct dirent *de) {
4898 if (de->d_type != DT_UNKNOWN)
4901 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4905 S_ISREG(st.st_mode) ? DT_REG :
4906 S_ISDIR(st.st_mode) ? DT_DIR :
4907 S_ISLNK(st.st_mode) ? DT_LNK :
4908 S_ISFIFO(st.st_mode) ? DT_FIFO :
4909 S_ISSOCK(st.st_mode) ? DT_SOCK :
4910 S_ISCHR(st.st_mode) ? DT_CHR :
4911 S_ISBLK(st.st_mode) ? DT_BLK :
4917 int in_search_path(const char *path, char **search) {
4921 r = path_get_parent(path, &parent);
4927 STRV_FOREACH(i, search) {
4928 if (path_equal(parent, *i)) {
4939 int get_files_in_directory(const char *path, char ***list) {
4947 /* Returns all files in a directory in *list, and the number
4948 * of files as return value. If list is NULL returns only the
4957 union dirent_storage buf;
4960 k = readdir_r(d, &buf.de, &de);
4969 dirent_ensure_type(d, de);
4971 if (!dirent_is_file(de))
4975 if ((unsigned) r >= n) {
4979 t = realloc(l, sizeof(char*) * n);
4988 assert((unsigned) r < n);
4990 l[r] = strdup(de->d_name);
5014 char *strjoin(const char *x, ...) {
5028 t = va_arg(ap, const char *);
5033 if (n > ((size_t) -1) - l) {
5057 t = va_arg(ap, const char *);
5071 bool is_main_thread(void) {
5072 static __thread int cached = 0;
5074 if (_unlikely_(cached == 0))
5075 cached = getpid() == gettid() ? 1 : -1;
5080 int block_get_whole_disk(dev_t d, dev_t *ret) {
5087 /* If it has a queue this is good enough for us */
5088 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5091 r = access(p, F_OK);
5099 /* If it is a partition find the originating device */
5100 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5103 r = access(p, F_OK);
5109 /* Get parent dev_t */
5110 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5113 r = read_one_line_file(p, &s);
5119 r = sscanf(s, "%u:%u", &m, &n);
5125 /* Only return this if it is really good enough for us. */
5126 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5129 r = access(p, F_OK);
5133 *ret = makedev(m, n);
5140 int file_is_priv_sticky(const char *p) {
5145 if (lstat(p, &st) < 0)
5149 (st.st_uid == 0 || st.st_uid == getuid()) &&
5150 (st.st_mode & S_ISVTX);
5153 static const char *const ioprio_class_table[] = {
5154 [IOPRIO_CLASS_NONE] = "none",
5155 [IOPRIO_CLASS_RT] = "realtime",
5156 [IOPRIO_CLASS_BE] = "best-effort",
5157 [IOPRIO_CLASS_IDLE] = "idle"
5160 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5162 static const char *const sigchld_code_table[] = {
5163 [CLD_EXITED] = "exited",
5164 [CLD_KILLED] = "killed",
5165 [CLD_DUMPED] = "dumped",
5166 [CLD_TRAPPED] = "trapped",
5167 [CLD_STOPPED] = "stopped",
5168 [CLD_CONTINUED] = "continued",
5171 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5173 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5174 [LOG_FAC(LOG_KERN)] = "kern",
5175 [LOG_FAC(LOG_USER)] = "user",
5176 [LOG_FAC(LOG_MAIL)] = "mail",
5177 [LOG_FAC(LOG_DAEMON)] = "daemon",
5178 [LOG_FAC(LOG_AUTH)] = "auth",
5179 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5180 [LOG_FAC(LOG_LPR)] = "lpr",
5181 [LOG_FAC(LOG_NEWS)] = "news",
5182 [LOG_FAC(LOG_UUCP)] = "uucp",
5183 [LOG_FAC(LOG_CRON)] = "cron",
5184 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5185 [LOG_FAC(LOG_FTP)] = "ftp",
5186 [LOG_FAC(LOG_LOCAL0)] = "local0",
5187 [LOG_FAC(LOG_LOCAL1)] = "local1",
5188 [LOG_FAC(LOG_LOCAL2)] = "local2",
5189 [LOG_FAC(LOG_LOCAL3)] = "local3",
5190 [LOG_FAC(LOG_LOCAL4)] = "local4",
5191 [LOG_FAC(LOG_LOCAL5)] = "local5",
5192 [LOG_FAC(LOG_LOCAL6)] = "local6",
5193 [LOG_FAC(LOG_LOCAL7)] = "local7"
5196 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5198 static const char *const log_level_table[] = {
5199 [LOG_EMERG] = "emerg",
5200 [LOG_ALERT] = "alert",
5201 [LOG_CRIT] = "crit",
5203 [LOG_WARNING] = "warning",
5204 [LOG_NOTICE] = "notice",
5205 [LOG_INFO] = "info",
5206 [LOG_DEBUG] = "debug"
5209 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5211 static const char* const sched_policy_table[] = {
5212 [SCHED_OTHER] = "other",
5213 [SCHED_BATCH] = "batch",
5214 [SCHED_IDLE] = "idle",
5215 [SCHED_FIFO] = "fifo",
5219 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5221 static const char* const rlimit_table[] = {
5222 [RLIMIT_CPU] = "LimitCPU",
5223 [RLIMIT_FSIZE] = "LimitFSIZE",
5224 [RLIMIT_DATA] = "LimitDATA",
5225 [RLIMIT_STACK] = "LimitSTACK",
5226 [RLIMIT_CORE] = "LimitCORE",
5227 [RLIMIT_RSS] = "LimitRSS",
5228 [RLIMIT_NOFILE] = "LimitNOFILE",
5229 [RLIMIT_AS] = "LimitAS",
5230 [RLIMIT_NPROC] = "LimitNPROC",
5231 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5232 [RLIMIT_LOCKS] = "LimitLOCKS",
5233 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5234 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5235 [RLIMIT_NICE] = "LimitNICE",
5236 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5237 [RLIMIT_RTTIME] = "LimitRTTIME"
5240 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5242 static const char* const ip_tos_table[] = {
5243 [IPTOS_LOWDELAY] = "low-delay",
5244 [IPTOS_THROUGHPUT] = "throughput",
5245 [IPTOS_RELIABILITY] = "reliability",
5246 [IPTOS_LOWCOST] = "low-cost",
5249 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5251 static const char *const __signal_table[] = {
5268 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5279 [SIGVTALRM] = "VTALRM",
5281 [SIGWINCH] = "WINCH",
5287 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5289 const char *signal_to_string(int signo) {
5290 static __thread char buf[12];
5293 name = __signal_to_string(signo);
5297 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5298 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5300 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5305 int signal_from_string(const char *s) {
5310 signo = __signal_from_string(s);
5314 if (startswith(s, "RTMIN+")) {
5318 if (safe_atou(s, &u) >= 0) {
5319 signo = (int) u + offset;
5320 if (signo > 0 && signo < _NSIG)
5326 bool kexec_loaded(void) {
5327 bool loaded = false;
5330 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5338 int strdup_or_null(const char *a, char **b) {
5356 int prot_from_flags(int flags) {
5358 switch (flags & O_ACCMODE) {
5367 return PROT_READ|PROT_WRITE;
5374 char *format_bytes(char *buf, size_t l, off_t t) {
5377 static const struct {
5381 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5382 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5383 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5384 { "G", 1024ULL*1024ULL*1024ULL },
5385 { "M", 1024ULL*1024ULL },
5389 for (i = 0; i < ELEMENTSOF(table); i++) {
5391 if (t >= table[i].factor) {
5394 (unsigned long long) (t / table[i].factor),
5395 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5402 snprintf(buf, l, "%lluB", (unsigned long long) t);
5410 void* memdup(const void *p, size_t l) {
5423 int fd_inc_sndbuf(int fd, size_t n) {
5425 socklen_t l = sizeof(value);
5427 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5429 l == sizeof(value) &&
5430 (size_t) value >= n*2)
5434 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5441 int fd_inc_rcvbuf(int fd, size_t n) {
5443 socklen_t l = sizeof(value);
5445 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5447 l == sizeof(value) &&
5448 (size_t) value >= n*2)
5452 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5459 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5460 pid_t parent_pid, agent_pid;
5462 bool stdout_is_tty, stderr_is_tty;
5470 parent_pid = getpid();
5472 /* Spawns a temporary TTY agent, making sure it goes away when
5479 if (agent_pid != 0) {
5486 * Make sure the agent goes away when the parent dies */
5487 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5488 _exit(EXIT_FAILURE);
5490 /* Check whether our parent died before we were able
5491 * to set the death signal */
5492 if (getppid() != parent_pid)
5493 _exit(EXIT_SUCCESS);
5495 /* Don't leak fds to the agent */
5496 close_all_fds(except, n_except);
5498 stdout_is_tty = isatty(STDOUT_FILENO);
5499 stderr_is_tty = isatty(STDERR_FILENO);
5501 if (!stdout_is_tty || !stderr_is_tty) {
5502 /* Detach from stdout/stderr. and reopen
5503 * /dev/tty for them. This is important to
5504 * ensure that when systemctl is started via
5505 * popen() or a similar call that expects to
5506 * read EOF we actually do generate EOF and
5507 * not delay this indefinitely by because we
5508 * keep an unused copy of stdin around. */
5509 fd = open("/dev/tty", O_WRONLY);
5511 log_error("Failed to open /dev/tty: %m");
5512 _exit(EXIT_FAILURE);
5516 dup2(fd, STDOUT_FILENO);
5519 dup2(fd, STDERR_FILENO);
5525 /* Count arguments */
5527 for (n = 0; va_arg(ap, char*); n++)
5532 l = alloca(sizeof(char *) * (n + 1));
5534 /* Fill in arguments */
5536 for (i = 0; i <= n; i++)
5537 l[i] = va_arg(ap, char*);
5541 _exit(EXIT_FAILURE);
5544 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5545 struct rlimit highest, fixed;
5549 if (setrlimit(resource, rlim) >= 0)
5555 /* So we failed to set the desired setrlimit, then let's try
5556 * to get as close as we can */
5557 assert_se(getrlimit(resource, &highest) == 0);
5559 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5560 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5562 if (setrlimit(resource, &fixed) < 0)
5568 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5569 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5581 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5584 f = fopen(path, "re");
5592 char line[LINE_MAX];
5595 for (i = 0; i < sizeof(line)-1; i++) {
5599 if (_unlikely_(c == EOF)) {
5609 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5610 value = strdup(line + l + 1);
5630 int can_sleep(const char *type) {
5634 _cleanup_free_ char *p = NULL;
5638 r = read_one_line_file("/sys/power/state", &p);
5640 return r == -ENOENT ? 0 : r;
5643 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5644 if (l == k && memcmp(w, type, l) == 0)
5650 bool is_valid_documentation_url(const char *url) {
5653 if (startswith(url, "http://") && url[7])
5656 if (startswith(url, "https://") && url[8])
5659 if (startswith(url, "file:") && url[5])
5662 if (startswith(url, "info:") && url[5])
5665 if (startswith(url, "man:") && url[4])
5671 bool in_initrd(void) {
5672 static __thread int saved = -1;
5678 /* We make two checks here:
5680 * 1. the flag file /etc/initrd-release must exist
5681 * 2. the root file system must be a memory file system
5683 * The second check is extra paranoia, since misdetecting an
5684 * initrd can have bad bad consequences due the initrd
5685 * emptying when transititioning to the main systemd.
5688 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5689 statfs("/", &s) >= 0 &&
5690 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5695 void warn_melody(void) {
5696 _cleanup_close_ int fd = -1;
5698 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5702 /* Yeah, this is synchronous. Kinda sucks. But well... */
5704 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5705 usleep(125*USEC_PER_MSEC);
5707 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5708 usleep(125*USEC_PER_MSEC);
5710 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5711 usleep(125*USEC_PER_MSEC);
5713 ioctl(fd, KIOCSOUND, 0);
5716 int make_console_stdio(void) {
5719 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5721 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5723 log_error("Failed to acquire terminal: %s", strerror(-fd));
5729 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5736 int get_home_dir(char **_h) {
5744 /* Take the user specified one */
5755 /* Hardcode home directory for root to avoid NSS */
5758 h = strdup("/root");
5766 /* Check the database... */
5770 return errno ? -errno : -ESRCH;
5772 if (!path_is_absolute(p->pw_dir))
5775 h = strdup(p->pw_dir);
5783 int get_shell(char **_sh) {
5791 /* Take the user specified one */
5792 e = getenv("SHELL");
5802 /* Hardcode home directory for root to avoid NSS */
5805 sh = strdup("/bin/sh");
5813 /* Check the database... */
5817 return errno ? -errno : -ESRCH;
5819 if (!path_is_absolute(p->pw_shell))
5822 sh = strdup(p->pw_shell);
5830 void freep(void *p) {
5834 void fclosep(FILE **f) {
5839 void closep(int *fd) {
5841 close_nointr_nofail(*fd);
5844 void closedirp(DIR **d) {
5849 void umaskp(mode_t *u) {