1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
68 #include "path-util.h"
69 #include "exit-status.h"
73 char **saved_argv = NULL;
75 static int parsed_columns = 0;
77 size_t page_size(void) {
78 static __thread size_t pgsz = 0;
81 if (_likely_(pgsz > 0))
84 r = sysconf(_SC_PAGESIZE);
91 bool streq_ptr(const char *a, const char *b) {
93 /* Like streq(), but tries to make sense of NULL pointers */
104 usec_t now(clockid_t clock_id) {
107 assert_se(clock_gettime(clock_id, &ts) == 0);
109 return timespec_load(&ts);
112 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
115 ts->realtime = now(CLOCK_REALTIME);
116 ts->monotonic = now(CLOCK_MONOTONIC);
121 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
130 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
132 ts->monotonic = now(CLOCK_MONOTONIC);
134 if ((int64_t) ts->monotonic > delta)
135 ts->monotonic -= delta;
143 usec_t timespec_load(const struct timespec *ts) {
147 (usec_t) ts->tv_sec * USEC_PER_SEC +
148 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
151 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
154 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
155 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
160 usec_t timeval_load(const struct timeval *tv) {
164 (usec_t) tv->tv_sec * USEC_PER_SEC +
165 (usec_t) tv->tv_usec;
168 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
171 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
172 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
177 bool endswith(const char *s, const char *postfix) {
184 pl = strlen(postfix);
192 return memcmp(s + sl - pl, postfix, pl) == 0;
195 bool startswith(const char *s, const char *prefix) {
210 return memcmp(s, prefix, pl) == 0;
213 bool startswith_no_case(const char *s, const char *prefix) {
229 for(i = 0; i < pl; ++i)
230 if (tolower(s[i]) != tolower(prefix[i]))
236 bool first_word(const char *s, const char *word) {
251 if (memcmp(s, word, wl) != 0)
255 strchr(WHITESPACE, s[wl]);
258 int close_nointr(int fd) {
273 void close_nointr_nofail(int fd) {
274 int saved_errno = errno;
276 /* like close_nointr() but cannot fail, and guarantees errno
279 assert_se(close_nointr(fd) == 0);
284 void close_many(const int fds[], unsigned n_fd) {
287 for (i = 0; i < n_fd; i++)
288 close_nointr_nofail(fds[i]);
291 int parse_boolean(const char *v) {
294 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
296 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
302 int parse_pid(const char *s, pid_t* ret_pid) {
303 unsigned long ul = 0;
310 r = safe_atolu(s, &ul);
316 if ((unsigned long) pid != ul)
326 int parse_uid(const char *s, uid_t* ret_uid) {
327 unsigned long ul = 0;
334 r = safe_atolu(s, &ul);
340 if ((unsigned long) uid != ul)
347 int safe_atou(const char *s, unsigned *ret_u) {
355 l = strtoul(s, &x, 0);
357 if (!x || *x || errno)
358 return errno ? -errno : -EINVAL;
360 if ((unsigned long) (unsigned) l != l)
363 *ret_u = (unsigned) l;
367 int safe_atoi(const char *s, int *ret_i) {
375 l = strtol(s, &x, 0);
377 if (!x || *x || errno)
378 return errno ? -errno : -EINVAL;
380 if ((long) (int) l != l)
387 int safe_atollu(const char *s, long long unsigned *ret_llu) {
389 unsigned long long l;
395 l = strtoull(s, &x, 0);
397 if (!x || *x || errno)
398 return errno ? -errno : -EINVAL;
404 int safe_atolli(const char *s, long long int *ret_lli) {
412 l = strtoll(s, &x, 0);
414 if (!x || *x || errno)
415 return errno ? -errno : -EINVAL;
421 /* Split a string into words. */
422 char *split(const char *c, size_t *l, const char *separator, char **state) {
425 current = *state ? *state : (char*) c;
427 if (!*current || *c == 0)
430 current += strspn(current, separator);
431 *l = strcspn(current, separator);
434 return (char*) current;
437 /* Split a string into words, but consider strings enclosed in '' and
438 * "" as words even if they include spaces. */
439 char *split_quoted(const char *c, size_t *l, char **state) {
441 bool escaped = false;
443 current = *state ? *state : (char*) c;
445 if (!*current || *c == 0)
448 current += strspn(current, WHITESPACE);
450 if (*current == '\'') {
453 for (e = current; *e; e++) {
463 *state = *e == 0 ? e : e+1;
464 } else if (*current == '\"') {
467 for (e = current; *e; e++) {
477 *state = *e == 0 ? e : e+1;
479 for (e = current; *e; e++) {
484 else if (strchr(WHITESPACE, *e))
491 return (char*) current;
494 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
496 _cleanup_fclose_ FILE *f = NULL;
497 char fn[PATH_MAX], line[LINE_MAX], *p;
503 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
510 if (!fgets(line, sizeof(line), f)) {
511 r = feof(f) ? -EIO : -errno;
516 /* Let's skip the pid and comm fields. The latter is enclosed
517 * in () but does not escape any () in its value, so let's
518 * skip over it manually */
520 p = strrchr(line, ')');
532 if ((long unsigned) (pid_t) ppid != ppid)
535 *_ppid = (pid_t) ppid;
540 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
541 _cleanup_fclose_ FILE *f = NULL;
542 char fn[PATH_MAX], line[LINE_MAX], *p;
547 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
554 if (!fgets(line, sizeof(line), f)) {
561 /* Let's skip the pid and comm fields. The latter is enclosed
562 * in () but does not escape any () in its value, so let's
563 * skip over it manually */
565 p = strrchr(line, ')');
587 "%*d " /* priority */
589 "%*d " /* num_threads */
590 "%*d " /* itrealvalue */
591 "%llu " /* starttime */,
598 int write_one_line_file(const char *fn, const char *line) {
599 _cleanup_fclose_ FILE *f = NULL;
609 if (fputs(line, f) < 0)
610 return errno ? -errno : -EIO;
612 if (!endswith(line, "\n"))
618 return errno ? -errno : -EIO;
623 int fchmod_umask(int fd, mode_t m) {
628 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
634 int write_one_line_file_atomic(const char *fn, const char *line) {
642 r = fopen_temporary(fn, &f, &p);
646 fchmod_umask(fileno(f), 0644);
649 if (fputs(line, f) < 0) {
654 if (!endswith(line, "\n"))
665 if (rename(p, fn) < 0)
681 int read_one_line_file(const char *fn, char **line) {
682 _cleanup_fclose_ FILE *f = NULL;
683 char t[LINE_MAX], *c;
692 if (!fgets(t, sizeof(t), f)) {
695 return errno ? -errno : -EIO;
709 int read_full_file(const char *fn, char **contents, size_t *size) {
710 _cleanup_fclose_ FILE *f = NULL;
712 _cleanup_free_ char *buf = NULL;
719 if (fstat(fileno(f), &st) < 0)
723 if (st.st_size > 4*1024*1024)
726 n = st.st_size > 0 ? st.st_size : LINE_MAX;
733 t = realloc(buf, n+1);
738 k = fread(buf + l, 1, n - l, f);
767 const char *separator, ...) {
770 char *contents = NULL, *p;
775 if ((r = read_full_file(fname, &contents, NULL)) < 0)
780 const char *key = NULL;
782 p += strspn(p, separator);
783 p += strspn(p, WHITESPACE);
788 if (!strchr(COMMENTS, *p)) {
792 va_start(ap, separator);
793 while ((key = va_arg(ap, char *))) {
797 value = va_arg(ap, char **);
800 if (strncmp(p, key, n) != 0 ||
805 n = strcspn(p, separator);
808 strchr(QUOTES, p[0]) &&
810 v = strndup(p+1, n-2);
821 /* return empty value strings as NULL */
838 p += strcspn(p, separator);
857 if (!(f = fopen(fname, "re")))
861 char l[LINE_MAX], *p, *u;
864 if (!fgets(l, sizeof(l), f)) {
877 if (strchr(COMMENTS, *p))
880 if (!(u = normalize_env_assignment(p))) {
885 t = strv_append(m, u);
911 int write_env_file(const char *fname, char **l) {
916 r = fopen_temporary(fname, &f, &p);
920 fchmod_umask(fileno(f), 0644);
936 if (rename(p, fname) < 0)
951 char *truncate_nl(char *s) {
954 s[strcspn(s, NEWLINE)] = 0;
958 int get_process_comm(pid_t pid, char **name) {
964 r = read_one_line_file("/proc/self/comm", name);
967 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
970 r = read_one_line_file(p, name);
977 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
984 assert(max_length > 0);
988 f = fopen("/proc/self/cmdline", "re");
991 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1001 r = new(char, max_length);
1009 while ((c = getc(f)) != EOF) {
1031 size_t n = MIN(left-1, 3U);
1032 memcpy(k, "...", n);
1039 /* Kernel threads have no argv[] */
1049 h = get_process_comm(pid, &t);
1053 r = strjoin("[", t, "]", NULL);
1064 int is_kernel_thread(pid_t pid) {
1074 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1083 count = fread(&c, 1, 1, f);
1087 /* Kernel threads have an empty cmdline */
1090 return eof ? 1 : -errno;
1095 int get_process_exe(pid_t pid, char **name) {
1101 r = readlink_malloc("/proc/self/exe", name);
1104 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1107 r = readlink_malloc(p, name);
1114 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1124 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1134 char line[LINE_MAX], *l;
1136 if (!fgets(line, sizeof(line), f)) {
1146 if (startswith(l, field)) {
1148 l += strspn(l, WHITESPACE);
1150 l[strcspn(l, WHITESPACE)] = 0;
1152 r = parse_uid(l, uid);
1165 int get_process_uid(pid_t pid, uid_t *uid) {
1166 return get_process_id(pid, "Uid:", uid);
1169 int get_process_gid(pid_t pid, gid_t *gid) {
1170 return get_process_id(pid, "Gid:", gid);
1173 char *strnappend(const char *s, const char *suffix, size_t b) {
1181 return strndup(suffix, b);
1190 if (b > ((size_t) -1) - a)
1193 r = new(char, a+b+1);
1198 memcpy(r+a, suffix, b);
1204 char *strappend(const char *s, const char *suffix) {
1205 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1208 int readlink_malloc(const char *p, char **r) {
1218 if (!(c = new(char, l)))
1221 if ((n = readlink(p, c, l-1)) < 0) {
1227 if ((size_t) n < l-1) {
1238 int readlink_and_make_absolute(const char *p, char **r) {
1245 if ((j = readlink_malloc(p, &target)) < 0)
1248 k = file_in_same_dir(p, target);
1258 int readlink_and_canonicalize(const char *p, char **r) {
1265 j = readlink_and_make_absolute(p, &t);
1269 s = canonicalize_file_name(t);
1276 path_kill_slashes(*r);
1281 int reset_all_signal_handlers(void) {
1284 for (sig = 1; sig < _NSIG; sig++) {
1285 struct sigaction sa;
1287 if (sig == SIGKILL || sig == SIGSTOP)
1291 sa.sa_handler = SIG_DFL;
1292 sa.sa_flags = SA_RESTART;
1294 /* On Linux the first two RT signals are reserved by
1295 * glibc, and sigaction() will return EINVAL for them. */
1296 if ((sigaction(sig, &sa, NULL) < 0))
1297 if (errno != EINVAL)
1304 char *strstrip(char *s) {
1307 /* Drops trailing whitespace. Modifies the string in
1308 * place. Returns pointer to first non-space character */
1310 s += strspn(s, WHITESPACE);
1312 for (e = strchr(s, 0); e > s; e --)
1313 if (!strchr(WHITESPACE, e[-1]))
1321 char *delete_chars(char *s, const char *bad) {
1324 /* Drops all whitespace, regardless where in the string */
1326 for (f = s, t = s; *f; f++) {
1327 if (strchr(bad, *f))
1338 bool in_charset(const char *s, const char* charset) {
1344 for (i = s; *i; i++)
1345 if (!strchr(charset, *i))
1351 char *file_in_same_dir(const char *path, const char *filename) {
1358 /* This removes the last component of path and appends
1359 * filename, unless the latter is absolute anyway or the
1362 if (path_is_absolute(filename))
1363 return strdup(filename);
1365 if (!(e = strrchr(path, '/')))
1366 return strdup(filename);
1368 k = strlen(filename);
1369 if (!(r = new(char, e-path+1+k+1)))
1372 memcpy(r, path, e-path+1);
1373 memcpy(r+(e-path)+1, filename, k+1);
1378 int rmdir_parents(const char *path, const char *stop) {
1387 /* Skip trailing slashes */
1388 while (l > 0 && path[l-1] == '/')
1394 /* Skip last component */
1395 while (l > 0 && path[l-1] != '/')
1398 /* Skip trailing slashes */
1399 while (l > 0 && path[l-1] == '/')
1405 if (!(t = strndup(path, l)))
1408 if (path_startswith(stop, t)) {
1417 if (errno != ENOENT)
1425 char hexchar(int x) {
1426 static const char table[16] = "0123456789abcdef";
1428 return table[x & 15];
1431 int unhexchar(char c) {
1433 if (c >= '0' && c <= '9')
1436 if (c >= 'a' && c <= 'f')
1437 return c - 'a' + 10;
1439 if (c >= 'A' && c <= 'F')
1440 return c - 'A' + 10;
1445 char octchar(int x) {
1446 return '0' + (x & 7);
1449 int unoctchar(char c) {
1451 if (c >= '0' && c <= '7')
1457 char decchar(int x) {
1458 return '0' + (x % 10);
1461 int undecchar(char c) {
1463 if (c >= '0' && c <= '9')
1469 char *cescape(const char *s) {
1475 /* Does C style string escaping. */
1477 r = new(char, strlen(s)*4 + 1);
1481 for (f = s, t = r; *f; f++)
1527 /* For special chars we prefer octal over
1528 * hexadecimal encoding, simply because glib's
1529 * g_strescape() does the same */
1530 if ((*f < ' ') || (*f >= 127)) {
1532 *(t++) = octchar((unsigned char) *f >> 6);
1533 *(t++) = octchar((unsigned char) *f >> 3);
1534 *(t++) = octchar((unsigned char) *f);
1545 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1552 /* Undoes C style string escaping, and optionally prefixes it. */
1554 pl = prefix ? strlen(prefix) : 0;
1556 r = new(char, pl+length+1);
1561 memcpy(r, prefix, pl);
1563 for (f = s, t = r + pl; f < s + length; f++) {
1606 /* This is an extension of the XDG syntax files */
1611 /* hexadecimal encoding */
1614 a = unhexchar(f[1]);
1615 b = unhexchar(f[2]);
1617 if (a < 0 || b < 0) {
1618 /* Invalid escape code, let's take it literal then */
1622 *(t++) = (char) ((a << 4) | b);
1637 /* octal encoding */
1640 a = unoctchar(f[0]);
1641 b = unoctchar(f[1]);
1642 c = unoctchar(f[2]);
1644 if (a < 0 || b < 0 || c < 0) {
1645 /* Invalid escape code, let's take it literal then */
1649 *(t++) = (char) ((a << 6) | (b << 3) | c);
1657 /* premature end of string.*/
1662 /* Invalid escape code, let's take it literal then */
1674 char *cunescape_length(const char *s, size_t length) {
1675 return cunescape_length_with_prefix(s, length, NULL);
1678 char *cunescape(const char *s) {
1681 return cunescape_length(s, strlen(s));
1684 char *xescape(const char *s, const char *bad) {
1688 /* Escapes all chars in bad, in addition to \ and all special
1689 * chars, in \xFF style escaping. May be reversed with
1692 r = new(char, strlen(s) * 4 + 1);
1696 for (f = s, t = r; *f; f++) {
1698 if ((*f < ' ') || (*f >= 127) ||
1699 (*f == '\\') || strchr(bad, *f)) {
1702 *(t++) = hexchar(*f >> 4);
1703 *(t++) = hexchar(*f);
1713 char *bus_path_escape(const char *s) {
1719 /* Escapes all chars that D-Bus' object path cannot deal
1720 * with. Can be reverse with bus_path_unescape() */
1722 if (!(r = new(char, strlen(s)*3+1)))
1725 for (f = s, t = r; *f; f++) {
1727 if (!(*f >= 'A' && *f <= 'Z') &&
1728 !(*f >= 'a' && *f <= 'z') &&
1729 !(*f >= '0' && *f <= '9')) {
1731 *(t++) = hexchar(*f >> 4);
1732 *(t++) = hexchar(*f);
1742 char *bus_path_unescape(const char *f) {
1747 if (!(r = strdup(f)))
1750 for (t = r; *f; f++) {
1755 if ((a = unhexchar(f[1])) < 0 ||
1756 (b = unhexchar(f[2])) < 0) {
1757 /* Invalid escape code, let's take it literal then */
1760 *(t++) = (char) ((a << 4) | b);
1772 char *ascii_strlower(char *t) {
1777 for (p = t; *p; p++)
1778 if (*p >= 'A' && *p <= 'Z')
1779 *p = *p - 'A' + 'a';
1784 static bool ignore_file_allow_backup(const char *filename) {
1788 filename[0] == '.' ||
1789 streq(filename, "lost+found") ||
1790 streq(filename, "aquota.user") ||
1791 streq(filename, "aquota.group") ||
1792 endswith(filename, ".rpmnew") ||
1793 endswith(filename, ".rpmsave") ||
1794 endswith(filename, ".rpmorig") ||
1795 endswith(filename, ".dpkg-old") ||
1796 endswith(filename, ".dpkg-new") ||
1797 endswith(filename, ".swp");
1800 bool ignore_file(const char *filename) {
1803 if (endswith(filename, "~"))
1806 return ignore_file_allow_backup(filename);
1809 int fd_nonblock(int fd, bool nonblock) {
1814 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1818 flags |= O_NONBLOCK;
1820 flags &= ~O_NONBLOCK;
1822 if (fcntl(fd, F_SETFL, flags) < 0)
1828 int fd_cloexec(int fd, bool cloexec) {
1833 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1837 flags |= FD_CLOEXEC;
1839 flags &= ~FD_CLOEXEC;
1841 if (fcntl(fd, F_SETFD, flags) < 0)
1847 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1850 assert(n_fdset == 0 || fdset);
1852 for (i = 0; i < n_fdset; i++)
1859 int close_all_fds(const int except[], unsigned n_except) {
1864 assert(n_except == 0 || except);
1866 d = opendir("/proc/self/fd");
1871 /* When /proc isn't available (for example in chroots)
1872 * the fallback is brute forcing through the fd
1875 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1876 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1878 if (fd_in_set(fd, except, n_except))
1881 if (close_nointr(fd) < 0)
1882 if (errno != EBADF && r == 0)
1889 while ((de = readdir(d))) {
1892 if (ignore_file(de->d_name))
1895 if (safe_atoi(de->d_name, &fd) < 0)
1896 /* Let's better ignore this, just in case */
1905 if (fd_in_set(fd, except, n_except))
1908 if (close_nointr(fd) < 0) {
1909 /* Valgrind has its own FD and doesn't want to have it closed */
1910 if (errno != EBADF && r == 0)
1919 bool chars_intersect(const char *a, const char *b) {
1922 /* Returns true if any of the chars in a are in b. */
1923 for (p = a; *p; p++)
1930 char *format_timestamp(char *buf, size_t l, usec_t t) {
1940 sec = (time_t) (t / USEC_PER_SEC);
1942 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1948 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1951 n = now(CLOCK_REALTIME);
1953 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1958 if (d >= USEC_PER_YEAR)
1959 snprintf(buf, l, "%llu years and %llu months ago",
1960 (unsigned long long) (d / USEC_PER_YEAR),
1961 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1962 else if (d >= USEC_PER_MONTH)
1963 snprintf(buf, l, "%llu months and %llu days ago",
1964 (unsigned long long) (d / USEC_PER_MONTH),
1965 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1966 else if (d >= USEC_PER_WEEK)
1967 snprintf(buf, l, "%llu weeks and %llu days ago",
1968 (unsigned long long) (d / USEC_PER_WEEK),
1969 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1970 else if (d >= 2*USEC_PER_DAY)
1971 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1972 else if (d >= 25*USEC_PER_HOUR)
1973 snprintf(buf, l, "1 day and %lluh ago",
1974 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1975 else if (d >= 6*USEC_PER_HOUR)
1976 snprintf(buf, l, "%lluh ago",
1977 (unsigned long long) (d / USEC_PER_HOUR));
1978 else if (d >= USEC_PER_HOUR)
1979 snprintf(buf, l, "%lluh %llumin ago",
1980 (unsigned long long) (d / USEC_PER_HOUR),
1981 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1982 else if (d >= 5*USEC_PER_MINUTE)
1983 snprintf(buf, l, "%llumin ago",
1984 (unsigned long long) (d / USEC_PER_MINUTE));
1985 else if (d >= USEC_PER_MINUTE)
1986 snprintf(buf, l, "%llumin %llus ago",
1987 (unsigned long long) (d / USEC_PER_MINUTE),
1988 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1989 else if (d >= USEC_PER_SEC)
1990 snprintf(buf, l, "%llus ago",
1991 (unsigned long long) (d / USEC_PER_SEC));
1992 else if (d >= USEC_PER_MSEC)
1993 snprintf(buf, l, "%llums ago",
1994 (unsigned long long) (d / USEC_PER_MSEC));
1996 snprintf(buf, l, "%lluus ago",
1997 (unsigned long long) d);
1999 snprintf(buf, l, "now");
2005 char *format_timespan(char *buf, size_t l, usec_t t) {
2006 static const struct {
2010 { "w", USEC_PER_WEEK },
2011 { "d", USEC_PER_DAY },
2012 { "h", USEC_PER_HOUR },
2013 { "min", USEC_PER_MINUTE },
2014 { "s", USEC_PER_SEC },
2015 { "ms", USEC_PER_MSEC },
2025 if (t == (usec_t) -1)
2029 snprintf(p, l, "0");
2034 /* The result of this function can be parsed with parse_usec */
2036 for (i = 0; i < ELEMENTSOF(table); i++) {
2040 if (t < table[i].usec)
2046 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2047 n = MIN((size_t) k, l);
2060 bool fstype_is_network(const char *fstype) {
2061 static const char table[] =
2070 return nulstr_contains(table, fstype);
2074 _cleanup_close_ int fd;
2076 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2082 TIOCL_GETKMSGREDIRECT,
2086 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2089 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2092 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2098 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2099 struct termios old_termios, new_termios;
2101 char line[LINE_MAX];
2106 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2107 new_termios = old_termios;
2109 new_termios.c_lflag &= ~ICANON;
2110 new_termios.c_cc[VMIN] = 1;
2111 new_termios.c_cc[VTIME] = 0;
2113 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2116 if (t != (usec_t) -1) {
2117 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2118 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2123 k = fread(&c, 1, 1, f);
2125 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2131 *need_nl = c != '\n';
2138 if (t != (usec_t) -1)
2139 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2142 if (!fgets(line, sizeof(line), f))
2147 if (strlen(line) != 1)
2157 int ask(char *ret, const char *replies, const char *text, ...) {
2164 on_tty = isatty(STDOUT_FILENO);
2170 bool need_nl = true;
2173 fputs(ANSI_HIGHLIGHT_ON, stdout);
2180 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2184 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2187 if (r == -EBADMSG) {
2188 puts("Bad input, please try again.");
2199 if (strchr(replies, c)) {
2204 puts("Read unexpected character, please try again.");
2208 int reset_terminal_fd(int fd, bool switch_to_text) {
2209 struct termios termios;
2212 /* Set terminal to some sane defaults */
2216 /* We leave locked terminal attributes untouched, so that
2217 * Plymouth may set whatever it wants to set, and we don't
2218 * interfere with that. */
2220 /* Disable exclusive mode, just in case */
2221 ioctl(fd, TIOCNXCL);
2223 /* Switch to text mode */
2225 ioctl(fd, KDSETMODE, KD_TEXT);
2227 /* Enable console unicode mode */
2228 ioctl(fd, KDSKBMODE, K_UNICODE);
2230 if (tcgetattr(fd, &termios) < 0) {
2235 /* We only reset the stuff that matters to the software. How
2236 * hardware is set up we don't touch assuming that somebody
2237 * else will do that for us */
2239 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2240 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2241 termios.c_oflag |= ONLCR;
2242 termios.c_cflag |= CREAD;
2243 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2245 termios.c_cc[VINTR] = 03; /* ^C */
2246 termios.c_cc[VQUIT] = 034; /* ^\ */
2247 termios.c_cc[VERASE] = 0177;
2248 termios.c_cc[VKILL] = 025; /* ^X */
2249 termios.c_cc[VEOF] = 04; /* ^D */
2250 termios.c_cc[VSTART] = 021; /* ^Q */
2251 termios.c_cc[VSTOP] = 023; /* ^S */
2252 termios.c_cc[VSUSP] = 032; /* ^Z */
2253 termios.c_cc[VLNEXT] = 026; /* ^V */
2254 termios.c_cc[VWERASE] = 027; /* ^W */
2255 termios.c_cc[VREPRINT] = 022; /* ^R */
2256 termios.c_cc[VEOL] = 0;
2257 termios.c_cc[VEOL2] = 0;
2259 termios.c_cc[VTIME] = 0;
2260 termios.c_cc[VMIN] = 1;
2262 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2266 /* Just in case, flush all crap out */
2267 tcflush(fd, TCIOFLUSH);
2272 int reset_terminal(const char *name) {
2275 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2279 r = reset_terminal_fd(fd, true);
2280 close_nointr_nofail(fd);
2285 int open_terminal(const char *name, int mode) {
2290 * If a TTY is in the process of being closed opening it might
2291 * cause EIO. This is horribly awful, but unlikely to be
2292 * changed in the kernel. Hence we work around this problem by
2293 * retrying a couple of times.
2295 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2299 fd = open(name, mode);
2306 /* Max 1s in total */
2310 usleep(50 * USEC_PER_MSEC);
2319 close_nointr_nofail(fd);
2324 close_nointr_nofail(fd);
2331 int flush_fd(int fd) {
2332 struct pollfd pollfd;
2336 pollfd.events = POLLIN;
2343 if ((r = poll(&pollfd, 1, 0)) < 0) {
2354 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2359 if (errno == EAGAIN)
2370 int acquire_terminal(
2374 bool ignore_tiocstty_eperm,
2377 int fd = -1, notify = -1, r = 0, wd = -1;
2379 struct sigaction sa_old, sa_new;
2383 /* We use inotify to be notified when the tty is closed. We
2384 * create the watch before checking if we can actually acquire
2385 * it, so that we don't lose any event.
2387 * Note: strictly speaking this actually watches for the
2388 * device being closed, it does *not* really watch whether a
2389 * tty loses its controlling process. However, unless some
2390 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2391 * its tty otherwise this will not become a problem. As long
2392 * as the administrator makes sure not configure any service
2393 * on the same tty as an untrusted user this should not be a
2394 * problem. (Which he probably should not do anyway.) */
2396 if (timeout != (usec_t) -1)
2397 ts = now(CLOCK_MONOTONIC);
2399 if (!fail && !force) {
2400 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2406 wd = inotify_add_watch(notify, name, IN_CLOSE);
2415 r = flush_fd(notify);
2420 /* We pass here O_NOCTTY only so that we can check the return
2421 * value TIOCSCTTY and have a reliable way to figure out if we
2422 * successfully became the controlling process of the tty */
2423 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2427 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2428 * if we already own the tty. */
2430 sa_new.sa_handler = SIG_IGN;
2431 sa_new.sa_flags = SA_RESTART;
2432 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2434 /* First, try to get the tty */
2435 if (ioctl(fd, TIOCSCTTY, force) < 0)
2438 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2440 /* Sometimes it makes sense to ignore TIOCSCTTY
2441 * returning EPERM, i.e. when very likely we already
2442 * are have this controlling terminal. */
2443 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2446 if (r < 0 && (force || fail || r != -EPERM)) {
2455 assert(notify >= 0);
2458 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2460 struct inotify_event *e;
2462 if (timeout != (usec_t) -1) {
2465 n = now(CLOCK_MONOTONIC);
2466 if (ts + timeout < n) {
2471 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2481 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2484 if (errno == EINTR || errno == EAGAIN)
2491 e = (struct inotify_event*) inotify_buffer;
2496 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2501 step = sizeof(struct inotify_event) + e->len;
2502 assert(step <= (size_t) l);
2504 e = (struct inotify_event*) ((uint8_t*) e + step);
2511 /* We close the tty fd here since if the old session
2512 * ended our handle will be dead. It's important that
2513 * we do this after sleeping, so that we don't enter
2514 * an endless loop. */
2515 close_nointr_nofail(fd);
2519 close_nointr_nofail(notify);
2521 r = reset_terminal_fd(fd, true);
2523 log_warning("Failed to reset terminal: %s", strerror(-r));
2529 close_nointr_nofail(fd);
2532 close_nointr_nofail(notify);
2537 int release_terminal(void) {
2539 struct sigaction sa_old, sa_new;
2541 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2544 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2545 * by our own TIOCNOTTY */
2548 sa_new.sa_handler = SIG_IGN;
2549 sa_new.sa_flags = SA_RESTART;
2550 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2552 if (ioctl(fd, TIOCNOTTY) < 0)
2555 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2557 close_nointr_nofail(fd);
2561 int sigaction_many(const struct sigaction *sa, ...) {
2566 while ((sig = va_arg(ap, int)) > 0)
2567 if (sigaction(sig, sa, NULL) < 0)
2574 int ignore_signals(int sig, ...) {
2575 struct sigaction sa;
2580 sa.sa_handler = SIG_IGN;
2581 sa.sa_flags = SA_RESTART;
2583 if (sigaction(sig, &sa, NULL) < 0)
2587 while ((sig = va_arg(ap, int)) > 0)
2588 if (sigaction(sig, &sa, NULL) < 0)
2595 int default_signals(int sig, ...) {
2596 struct sigaction sa;
2601 sa.sa_handler = SIG_DFL;
2602 sa.sa_flags = SA_RESTART;
2604 if (sigaction(sig, &sa, NULL) < 0)
2608 while ((sig = va_arg(ap, int)) > 0)
2609 if (sigaction(sig, &sa, NULL) < 0)
2616 int close_pipe(int p[]) {
2622 a = close_nointr(p[0]);
2627 b = close_nointr(p[1]);
2631 return a < 0 ? a : b;
2634 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2643 while (nbytes > 0) {
2646 if ((k = read(fd, p, nbytes)) <= 0) {
2648 if (k < 0 && errno == EINTR)
2651 if (k < 0 && errno == EAGAIN && do_poll) {
2652 struct pollfd pollfd;
2656 pollfd.events = POLLIN;
2658 if (poll(&pollfd, 1, -1) < 0) {
2662 return n > 0 ? n : -errno;
2665 if (pollfd.revents != POLLIN)
2666 return n > 0 ? n : -EIO;
2671 return n > 0 ? n : (k < 0 ? -errno : 0);
2682 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2691 while (nbytes > 0) {
2694 k = write(fd, p, nbytes);
2697 if (k < 0 && errno == EINTR)
2700 if (k < 0 && errno == EAGAIN && do_poll) {
2701 struct pollfd pollfd;
2705 pollfd.events = POLLOUT;
2707 if (poll(&pollfd, 1, -1) < 0) {
2711 return n > 0 ? n : -errno;
2714 if (pollfd.revents != POLLOUT)
2715 return n > 0 ? n : -EIO;
2720 return n > 0 ? n : (k < 0 ? -errno : 0);
2731 int parse_usec(const char *t, usec_t *usec) {
2732 static const struct {
2736 { "sec", USEC_PER_SEC },
2737 { "s", USEC_PER_SEC },
2738 { "min", USEC_PER_MINUTE },
2739 { "hr", USEC_PER_HOUR },
2740 { "h", USEC_PER_HOUR },
2741 { "d", USEC_PER_DAY },
2742 { "w", USEC_PER_WEEK },
2743 { "msec", USEC_PER_MSEC },
2744 { "ms", USEC_PER_MSEC },
2745 { "m", USEC_PER_MINUTE },
2748 { "", USEC_PER_SEC }, /* default is sec */
2764 l = strtoll(p, &e, 10);
2775 e += strspn(e, WHITESPACE);
2777 for (i = 0; i < ELEMENTSOF(table); i++)
2778 if (startswith(e, table[i].suffix)) {
2779 r += (usec_t) l * table[i].usec;
2780 p = e + strlen(table[i].suffix);
2784 if (i >= ELEMENTSOF(table))
2794 int parse_nsec(const char *t, nsec_t *nsec) {
2795 static const struct {
2799 { "sec", NSEC_PER_SEC },
2800 { "s", NSEC_PER_SEC },
2801 { "min", NSEC_PER_MINUTE },
2802 { "hr", NSEC_PER_HOUR },
2803 { "h", NSEC_PER_HOUR },
2804 { "d", NSEC_PER_DAY },
2805 { "w", NSEC_PER_WEEK },
2806 { "msec", NSEC_PER_MSEC },
2807 { "ms", NSEC_PER_MSEC },
2808 { "m", NSEC_PER_MINUTE },
2809 { "usec", NSEC_PER_USEC },
2810 { "us", NSEC_PER_USEC },
2813 { "", 1ULL }, /* default is nsec */
2829 l = strtoll(p, &e, 10);
2840 e += strspn(e, WHITESPACE);
2842 for (i = 0; i < ELEMENTSOF(table); i++)
2843 if (startswith(e, table[i].suffix)) {
2844 r += (nsec_t) l * table[i].nsec;
2845 p = e + strlen(table[i].suffix);
2849 if (i >= ELEMENTSOF(table))
2859 int parse_bytes(const char *t, off_t *bytes) {
2860 static const struct {
2866 { "M", 1024ULL*1024ULL },
2867 { "G", 1024ULL*1024ULL*1024ULL },
2868 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2869 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2870 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2887 l = strtoll(p, &e, 10);
2898 e += strspn(e, WHITESPACE);
2900 for (i = 0; i < ELEMENTSOF(table); i++)
2901 if (startswith(e, table[i].suffix)) {
2902 r += (off_t) l * table[i].factor;
2903 p = e + strlen(table[i].suffix);
2907 if (i >= ELEMENTSOF(table))
2917 int make_stdio(int fd) {
2922 r = dup3(fd, STDIN_FILENO, 0);
2923 s = dup3(fd, STDOUT_FILENO, 0);
2924 t = dup3(fd, STDERR_FILENO, 0);
2927 close_nointr_nofail(fd);
2929 if (r < 0 || s < 0 || t < 0)
2932 /* We rely here that the new fd has O_CLOEXEC not set */
2937 int make_null_stdio(void) {
2940 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2944 return make_stdio(null_fd);
2947 bool is_device_path(const char *path) {
2949 /* Returns true on paths that refer to a device, either in
2950 * sysfs or in /dev */
2953 path_startswith(path, "/dev/") ||
2954 path_startswith(path, "/sys/");
2957 int dir_is_empty(const char *path) {
2958 _cleanup_closedir_ DIR *d;
2967 union dirent_storage buf;
2969 r = readdir_r(d, &buf.de, &de);
2976 if (!ignore_file(de->d_name))
2981 unsigned long long random_ull(void) {
2982 _cleanup_close_ int fd;
2986 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2990 r = loop_read(fd, &ull, sizeof(ull), true);
2991 if (r != sizeof(ull))
2997 return random() * RAND_MAX + random();
3000 void rename_process(const char name[8]) {
3003 /* This is a like a poor man's setproctitle(). It changes the
3004 * comm field, argv[0], and also the glibc's internally used
3005 * name of the process. For the first one a limit of 16 chars
3006 * applies, to the second one usually one of 10 (i.e. length
3007 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3008 * "systemd"). If you pass a longer string it will be
3011 prctl(PR_SET_NAME, name);
3013 if (program_invocation_name)
3014 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3016 if (saved_argc > 0) {
3020 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3022 for (i = 1; i < saved_argc; i++) {
3026 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3031 void sigset_add_many(sigset_t *ss, ...) {
3038 while ((sig = va_arg(ap, int)) > 0)
3039 assert_se(sigaddset(ss, sig) == 0);
3043 char* gethostname_malloc(void) {
3046 assert_se(uname(&u) >= 0);
3048 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3049 return strdup(u.nodename);
3051 return strdup(u.sysname);
3054 bool hostname_is_set(void) {
3057 assert_se(uname(&u) >= 0);
3059 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3062 static char *lookup_uid(uid_t uid) {
3065 _cleanup_free_ char *buf = NULL;
3066 struct passwd pwbuf, *pw = NULL;
3068 /* Shortcut things to avoid NSS lookups */
3070 return strdup("root");
3072 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3076 buf = malloc(bufsize);
3080 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3081 return strdup(pw->pw_name);
3083 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3089 char* getlogname_malloc(void) {
3093 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3098 return lookup_uid(uid);
3101 char *getusername_malloc(void) {
3108 return lookup_uid(getuid());
3111 int getttyname_malloc(int fd, char **r) {
3112 char path[PATH_MAX], *c;
3117 k = ttyname_r(fd, path, sizeof(path));
3123 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3131 int getttyname_harder(int fd, char **r) {
3135 k = getttyname_malloc(fd, &s);
3139 if (streq(s, "tty")) {
3141 return get_ctty(0, NULL, r);
3148 int get_ctty_devnr(pid_t pid, dev_t *d) {
3150 char line[LINE_MAX], *p, *fn;
3151 unsigned long ttynr;
3154 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3157 f = fopen(fn, "re");
3162 if (!fgets(line, sizeof(line), f)) {
3163 k = feof(f) ? -EIO : -errno;
3170 p = strrchr(line, ')');
3180 "%*d " /* session */
3189 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3191 char fn[PATH_MAX], *s, *b, *p;
3196 k = get_ctty_devnr(pid, &devnr);
3200 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3203 if ((k = readlink_malloc(fn, &s)) < 0) {
3208 /* This is an ugly hack */
3209 if (major(devnr) == 136) {
3210 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3220 /* Probably something like the ptys which have no
3221 * symlink in /dev/char. Let's return something
3222 * vaguely useful. */
3224 if (!(b = strdup(fn + 5)))
3234 if (startswith(s, "/dev/"))
3236 else if (startswith(s, "../"))
3254 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3260 /* This returns the first error we run into, but nevertheless
3261 * tries to go on. This closes the passed fd. */
3265 close_nointr_nofail(fd);
3267 return errno == ENOENT ? 0 : -errno;
3272 union dirent_storage buf;
3273 bool is_dir, keep_around;
3277 r = readdir_r(d, &buf.de, &de);
3278 if (r != 0 && ret == 0) {
3286 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3289 if (de->d_type == DT_UNKNOWN ||
3291 (de->d_type == DT_DIR && root_dev)) {
3292 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3293 if (ret == 0 && errno != ENOENT)
3298 is_dir = S_ISDIR(st.st_mode);
3301 (st.st_uid == 0 || st.st_uid == getuid()) &&
3302 (st.st_mode & S_ISVTX);
3304 is_dir = de->d_type == DT_DIR;
3305 keep_around = false;
3311 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3312 if (root_dev && st.st_dev != root_dev->st_dev)
3315 subdir_fd = openat(fd, de->d_name,
3316 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3317 if (subdir_fd < 0) {
3318 if (ret == 0 && errno != ENOENT)
3323 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3324 if (r < 0 && ret == 0)
3328 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3329 if (ret == 0 && errno != ENOENT)
3333 } else if (!only_dirs && !keep_around) {
3335 if (unlinkat(fd, de->d_name, 0) < 0) {
3336 if (ret == 0 && errno != ENOENT)
3347 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3352 if (fstatfs(fd, &s) < 0) {
3353 close_nointr_nofail(fd);
3357 /* We refuse to clean disk file systems with this call. This
3358 * is extra paranoia just to be sure we never ever remove
3361 if (s.f_type != TMPFS_MAGIC &&
3362 s.f_type != RAMFS_MAGIC) {
3363 log_error("Attempted to remove disk file system, and we can't allow that.");
3364 close_nointr_nofail(fd);
3368 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3371 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3377 /* We refuse to clean the root file system with this
3378 * call. This is extra paranoia to never cause a really
3379 * seriously broken system. */
3380 if (path_equal(path, "/")) {
3381 log_error("Attempted to remove entire root file system, and we can't allow that.");
3385 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3388 if (errno != ENOTDIR)
3392 if (statfs(path, &s) < 0)
3395 if (s.f_type != TMPFS_MAGIC &&
3396 s.f_type != RAMFS_MAGIC) {
3397 log_error("Attempted to remove disk file system, and we can't allow that.");
3402 if (delete_root && !only_dirs)
3403 if (unlink(path) < 0 && errno != ENOENT)
3410 if (fstatfs(fd, &s) < 0) {
3411 close_nointr_nofail(fd);
3415 if (s.f_type != TMPFS_MAGIC &&
3416 s.f_type != RAMFS_MAGIC) {
3417 log_error("Attempted to remove disk file system, and we can't allow that.");
3418 close_nointr_nofail(fd);
3423 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3426 if (honour_sticky && file_is_priv_sticky(path) > 0)
3429 if (rmdir(path) < 0 && errno != ENOENT) {
3438 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3439 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3442 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3443 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3446 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3449 /* Under the assumption that we are running privileged we
3450 * first change the access mode and only then hand out
3451 * ownership to avoid a window where access is too open. */
3453 if (mode != (mode_t) -1)
3454 if (chmod(path, mode) < 0)
3457 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3458 if (chown(path, uid, gid) < 0)
3464 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3467 /* Under the assumption that we are running privileged we
3468 * first change the access mode and only then hand out
3469 * ownership to avoid a window where access is too open. */
3471 if (fchmod(fd, mode) < 0)
3474 if (fchown(fd, uid, gid) < 0)
3480 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3484 /* Allocates the cpuset in the right size */
3487 if (!(r = CPU_ALLOC(n)))
3490 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3491 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3501 if (errno != EINVAL)
3508 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3509 static const char status_indent[] = " "; /* "[" STATUS "] " */
3510 _cleanup_free_ char *s = NULL;
3511 _cleanup_close_ int fd = -1;
3512 struct iovec iovec[5];
3517 /* This is independent of logging, as status messages are
3518 * optional and go exclusively to the console. */
3520 if (vasprintf(&s, format, ap) < 0)
3523 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3536 sl = status ? sizeof(status_indent)-1 : 0;
3542 e = ellipsize(s, emax, 75);
3552 if (!isempty(status)) {
3553 IOVEC_SET_STRING(iovec[n++], "[");
3554 IOVEC_SET_STRING(iovec[n++], status);
3555 IOVEC_SET_STRING(iovec[n++], "] ");
3557 IOVEC_SET_STRING(iovec[n++], status_indent);
3560 IOVEC_SET_STRING(iovec[n++], s);
3561 IOVEC_SET_STRING(iovec[n++], "\n");
3563 if (writev(fd, iovec, n) < 0)
3569 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3575 va_start(ap, format);
3576 r = status_vprintf(status, ellipse, format, ap);
3582 int status_welcome(void) {
3584 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3586 r = parse_env_file("/etc/os-release", NEWLINE,
3587 "PRETTY_NAME", &pretty_name,
3588 "ANSI_COLOR", &ansi_color,
3590 if (r < 0 && r != -ENOENT)
3591 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3593 return status_printf(NULL, false,
3594 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3595 isempty(ansi_color) ? "1" : ansi_color,
3596 isempty(pretty_name) ? "Linux" : pretty_name);
3599 char *replace_env(const char *format, char **env) {
3606 const char *e, *word = format;
3611 for (e = format; *e; e ++) {
3622 if (!(k = strnappend(r, word, e-word-1)))
3631 } else if (*e == '$') {
3632 if (!(k = strnappend(r, word, e-word)))
3648 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3651 if (!(k = strappend(r, t)))
3664 if (!(k = strnappend(r, word, e-word)))
3675 char **replace_env_argv(char **argv, char **env) {
3677 unsigned k = 0, l = 0;
3679 l = strv_length(argv);
3681 if (!(r = new(char*, l+1)))
3684 STRV_FOREACH(i, argv) {
3686 /* If $FOO appears as single word, replace it by the split up variable */
3687 if ((*i)[0] == '$' && (*i)[1] != '{') {
3692 if ((e = strv_env_get(env, *i+1))) {
3694 if (!(m = strv_split_quoted(e))) {
3705 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3714 memcpy(r + k, m, q * sizeof(char*));
3722 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3723 if (!(r[k++] = replace_env(*i, env))) {
3733 int fd_columns(int fd) {
3737 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3746 static unsigned columns_cached(bool cached) {
3747 static __thread int env_columns = -1;
3750 if (_likely_(parsed_columns > 0 && cached))
3751 return parsed_columns;
3753 if (_unlikely_(env_columns == -1)) {
3754 e = getenv("COLUMNS");
3756 env_columns = atoi(e);
3761 if (env_columns > 0) {
3762 parsed_columns = env_columns;
3763 return parsed_columns;
3766 if (parsed_columns <= 0 || !cached)
3767 parsed_columns = fd_columns(STDOUT_FILENO);
3769 if (parsed_columns <= 0)
3770 parsed_columns = 80;
3772 return parsed_columns;
3775 unsigned columns(void) {
3776 return columns_cached(true);
3779 unsigned columns_uncached(void) {
3780 return columns_cached(false);
3783 /* intended to be used as a SIGWINCH sighandler */
3784 void columns_cache_reset(int signum) {
3788 int fd_lines(int fd) {
3792 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3801 unsigned lines(void) {
3802 static __thread int parsed_lines = 0;
3805 if (_likely_(parsed_lines > 0))
3806 return parsed_lines;
3808 e = getenv("LINES");
3810 parsed_lines = atoi(e);
3812 if (parsed_lines <= 0)
3813 parsed_lines = fd_lines(STDOUT_FILENO);
3815 if (parsed_lines <= 0)
3818 return parsed_lines;
3821 int running_in_chroot(void) {
3827 /* Only works as root */
3829 if (stat("/proc/1/root", &a) < 0)
3832 if (stat("/", &b) < 0)
3836 a.st_dev != b.st_dev ||
3837 a.st_ino != b.st_ino;
3840 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3845 assert(percent <= 100);
3846 assert(new_length >= 3);
3848 if (old_length <= 3 || old_length <= new_length)
3849 return strndup(s, old_length);
3851 r = new0(char, new_length+1);
3855 x = (new_length * percent) / 100;
3857 if (x > new_length - 3)
3865 s + old_length - (new_length - x - 3),
3866 new_length - x - 3);
3871 char *ellipsize(const char *s, size_t length, unsigned percent) {
3872 return ellipsize_mem(s, strlen(s), length, percent);
3875 int touch(const char *path) {
3880 /* This just opens the file for writing, ensuring it
3881 * exists. It doesn't call utimensat() the way /usr/bin/touch
3884 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3888 close_nointr_nofail(fd);
3892 char *unquote(const char *s, const char* quotes) {
3896 /* This is rather stupid, simply removes the heading and
3897 * trailing quotes if there is one. Doesn't care about
3898 * escaping or anything. We should make this smarter one
3905 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3906 return strndup(s+1, l-2);
3911 char *normalize_env_assignment(const char *s) {
3912 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3915 eq = strchr(s, '=');
3927 memmove(r, t, strlen(t) + 1);
3931 name = strndup(s, eq - s);
3939 value = unquote(strstrip(p), QUOTES);
3943 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3949 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3960 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3972 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3979 r = wait_for_terminate(pid, &status);
3981 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3985 if (status.si_code == CLD_EXITED) {
3986 if (status.si_status != 0) {
3987 log_warning("%s failed with error code %i.", name, status.si_status);
3988 return status.si_status;
3991 log_debug("%s succeeded.", name);
3994 } else if (status.si_code == CLD_KILLED ||
3995 status.si_code == CLD_DUMPED) {
3997 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4001 log_warning("%s failed due to unknown reason.", name);
4005 _noreturn_ void freeze(void) {
4007 /* Make sure nobody waits for us on a socket anymore */
4008 close_all_fds(NULL, 0);
4016 bool null_or_empty(struct stat *st) {
4019 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4022 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4028 int null_or_empty_path(const char *fn) {
4033 if (stat(fn, &st) < 0)
4036 return null_or_empty(&st);
4039 DIR *xopendirat(int fd, const char *name, int flags) {
4043 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4049 close_nointr_nofail(nfd);
4056 int signal_from_string_try_harder(const char *s) {
4060 signo = signal_from_string(s);
4062 if (startswith(s, "SIG"))
4063 return signal_from_string(s+3);
4068 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4074 if (!dual_timestamp_is_set(t))
4077 fprintf(f, "%s=%llu %llu\n",
4079 (unsigned long long) t->realtime,
4080 (unsigned long long) t->monotonic);
4083 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4084 unsigned long long a, b;
4089 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4090 log_debug("Failed to parse finish timestamp value %s", value);
4097 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4101 /* FIXME: to follow udev's logic 100% we need to leave valid
4102 * UTF8 chars unescaped */
4104 u = unquote(tagvalue, "\"\'");
4108 t = xescape(u, "/ ");
4114 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4123 char *fstab_node_to_udev_node(const char *p) {
4126 if (startswith(p, "LABEL="))
4127 return tag_to_udev_node(p+6, "label");
4129 if (startswith(p, "UUID="))
4130 return tag_to_udev_node(p+5, "uuid");
4132 if (startswith(p, "PARTUUID="))
4133 return tag_to_udev_node(p+9, "partuuid");
4135 if (startswith(p, "PARTLABEL="))
4136 return tag_to_udev_node(p+10, "partlabel");
4141 bool tty_is_vc(const char *tty) {
4144 if (startswith(tty, "/dev/"))
4147 return vtnr_from_tty(tty) >= 0;
4150 bool tty_is_console(const char *tty) {
4153 if (startswith(tty, "/dev/"))
4156 return streq(tty, "console");
4159 int vtnr_from_tty(const char *tty) {
4164 if (startswith(tty, "/dev/"))
4167 if (!startswith(tty, "tty") )
4170 if (tty[3] < '0' || tty[3] > '9')
4173 r = safe_atoi(tty+3, &i);
4177 if (i < 0 || i > 63)
4183 bool tty_is_vc_resolve(const char *tty) {
4184 char *active = NULL;
4189 if (startswith(tty, "/dev/"))
4192 /* Resolve where /dev/console is pointing to, if /sys is
4193 * actually ours (i.e. not read-only-mounted which is a sign
4194 * for container setups) */
4195 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4196 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4197 /* If multiple log outputs are configured the
4198 * last one is what /dev/console points to */
4199 tty = strrchr(active, ' ');
4212 const char *default_term_for_tty(const char *tty) {
4215 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4218 bool dirent_is_file(const struct dirent *de) {
4221 if (ignore_file(de->d_name))
4224 if (de->d_type != DT_REG &&
4225 de->d_type != DT_LNK &&
4226 de->d_type != DT_UNKNOWN)
4232 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4235 if (de->d_type != DT_REG &&
4236 de->d_type != DT_LNK &&
4237 de->d_type != DT_UNKNOWN)
4240 if (ignore_file_allow_backup(de->d_name))
4243 return endswith(de->d_name, suffix);
4246 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4249 Hashmap *pids = NULL;
4253 /* Executes all binaries in a directory in parallel and waits
4254 * until all they all finished. */
4257 if (!(_d = opendir(directory))) {
4259 if (errno == ENOENT)
4262 log_error("Failed to enumerate directory %s: %m", directory);
4269 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4270 log_error("Failed to allocate set.");
4274 while ((de = readdir(d))) {
4279 if (!dirent_is_file(de))
4282 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4287 if ((pid = fork()) < 0) {
4288 log_error("Failed to fork: %m");
4306 log_error("Failed to execute %s: %m", path);
4307 _exit(EXIT_FAILURE);
4310 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4312 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4313 log_error("Failed to add PID to set: %s", strerror(-k));
4318 while (!hashmap_isempty(pids)) {
4319 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4324 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4329 log_error("waitid() failed: %m");
4333 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4334 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4335 if (si.si_code == CLD_EXITED)
4336 log_error("%s exited with exit status %i.", path, si.si_status);
4338 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4340 log_debug("%s exited successfully.", path);
4351 hashmap_free_free(pids);
4354 int kill_and_sigcont(pid_t pid, int sig) {
4357 r = kill(pid, sig) < 0 ? -errno : 0;
4365 bool nulstr_contains(const char*nulstr, const char *needle) {
4371 NULSTR_FOREACH(i, nulstr)
4372 if (streq(i, needle))
4378 bool plymouth_running(void) {
4379 return access("/run/plymouth/pid", F_OK) >= 0;
4382 char* strshorten(char *s, size_t l) {
4391 static bool hostname_valid_char(char c) {
4393 (c >= 'a' && c <= 'z') ||
4394 (c >= 'A' && c <= 'Z') ||
4395 (c >= '0' && c <= '9') ||
4401 bool hostname_is_valid(const char *s) {
4407 for (p = s; *p; p++)
4408 if (!hostname_valid_char(*p))
4411 if (p-s > HOST_NAME_MAX)
4417 char* hostname_cleanup(char *s) {
4420 for (p = s, d = s; *p; p++)
4421 if ((*p >= 'a' && *p <= 'z') ||
4422 (*p >= 'A' && *p <= 'Z') ||
4423 (*p >= '0' && *p <= '9') ||
4431 strshorten(s, HOST_NAME_MAX);
4435 int pipe_eof(int fd) {
4436 struct pollfd pollfd;
4441 pollfd.events = POLLIN|POLLHUP;
4443 r = poll(&pollfd, 1, 0);
4450 return pollfd.revents & POLLHUP;
4453 int fd_wait_for_event(int fd, int event, usec_t t) {
4454 struct pollfd pollfd;
4459 pollfd.events = event;
4461 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4468 return pollfd.revents;
4471 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4482 t = new(char, strlen(path) + 1 + 6 + 1);
4486 fn = path_get_file_name(path);
4490 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4492 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4498 f = fdopen(fd, "we");
4511 int terminal_vhangup_fd(int fd) {
4514 if (ioctl(fd, TIOCVHANGUP) < 0)
4520 int terminal_vhangup(const char *name) {
4523 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4527 r = terminal_vhangup_fd(fd);
4528 close_nointr_nofail(fd);
4533 int vt_disallocate(const char *name) {
4537 /* Deallocate the VT if possible. If not possible
4538 * (i.e. because it is the active one), at least clear it
4539 * entirely (including the scrollback buffer) */
4541 if (!startswith(name, "/dev/"))
4544 if (!tty_is_vc(name)) {
4545 /* So this is not a VT. I guess we cannot deallocate
4546 * it then. But let's at least clear the screen */
4548 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4553 "\033[r" /* clear scrolling region */
4554 "\033[H" /* move home */
4555 "\033[2J", /* clear screen */
4557 close_nointr_nofail(fd);
4562 if (!startswith(name, "/dev/tty"))
4565 r = safe_atou(name+8, &u);
4572 /* Try to deallocate */
4573 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4577 r = ioctl(fd, VT_DISALLOCATE, u);
4578 close_nointr_nofail(fd);
4586 /* Couldn't deallocate, so let's clear it fully with
4588 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4593 "\033[r" /* clear scrolling region */
4594 "\033[H" /* move home */
4595 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4597 close_nointr_nofail(fd);
4602 int copy_file(const char *from, const char *to) {
4608 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4612 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4614 close_nointr_nofail(fdf);
4622 n = read(fdf, buf, sizeof(buf));
4626 close_nointr_nofail(fdf);
4637 k = loop_write(fdt, buf, n, false);
4639 r = k < 0 ? k : (errno ? -errno : -EIO);
4641 close_nointr_nofail(fdf);
4649 close_nointr_nofail(fdf);
4650 r = close_nointr(fdt);
4660 int symlink_atomic(const char *from, const char *to) {
4662 _cleanup_free_ char *t;
4665 unsigned long long ull;
4672 t = new(char, strlen(to) + 1 + 16 + 1);
4676 fn = path_get_file_name(to);
4680 x = stpcpy(t+k+1, fn);
4683 for (i = 0; i < 16; i++) {
4684 *(x++) = hexchar(ull & 0xF);
4690 if (symlink(from, t) < 0)
4693 if (rename(t, to) < 0) {
4702 bool display_is_local(const char *display) {
4706 display[0] == ':' &&
4707 display[1] >= '0' &&
4711 int socket_from_display(const char *display, char **path) {
4718 if (!display_is_local(display))
4721 k = strspn(display+1, "0123456789");
4723 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4727 c = stpcpy(f, "/tmp/.X11-unix/X");
4728 memcpy(c, display+1, k);
4737 const char **username,
4738 uid_t *uid, gid_t *gid,
4740 const char **shell) {
4748 /* We enforce some special rules for uid=0: in order to avoid
4749 * NSS lookups for root we hardcode its data. */
4751 if (streq(*username, "root") || streq(*username, "0")) {
4769 if (parse_uid(*username, &u) >= 0) {
4773 /* If there are multiple users with the same id, make
4774 * sure to leave $USER to the configured value instead
4775 * of the first occurrence in the database. However if
4776 * the uid was configured by a numeric uid, then let's
4777 * pick the real username from /etc/passwd. */
4779 *username = p->pw_name;
4782 p = getpwnam(*username);
4786 return errno != 0 ? -errno : -ESRCH;
4798 *shell = p->pw_shell;
4803 int get_group_creds(const char **groupname, gid_t *gid) {
4809 /* We enforce some special rules for gid=0: in order to avoid
4810 * NSS lookups for root we hardcode its data. */
4812 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4813 *groupname = "root";
4821 if (parse_gid(*groupname, &id) >= 0) {
4826 *groupname = g->gr_name;
4829 g = getgrnam(*groupname);
4833 return errno != 0 ? -errno : -ESRCH;
4841 int in_group(const char *name) {
4843 int ngroups_max, r, i;
4845 r = get_group_creds(&name, &gid);
4849 if (getgid() == gid)
4852 if (getegid() == gid)
4855 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4856 assert(ngroups_max > 0);
4858 gids = alloca(sizeof(gid_t) * ngroups_max);
4860 r = getgroups(ngroups_max, gids);
4864 for (i = 0; i < r; i++)
4871 int glob_exists(const char *path) {
4879 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4881 if (k == GLOB_NOMATCH)
4883 else if (k == GLOB_NOSPACE)
4886 r = !strv_isempty(g.gl_pathv);
4888 r = errno ? -errno : -EIO;
4895 int dirent_ensure_type(DIR *d, struct dirent *de) {
4901 if (de->d_type != DT_UNKNOWN)
4904 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4908 S_ISREG(st.st_mode) ? DT_REG :
4909 S_ISDIR(st.st_mode) ? DT_DIR :
4910 S_ISLNK(st.st_mode) ? DT_LNK :
4911 S_ISFIFO(st.st_mode) ? DT_FIFO :
4912 S_ISSOCK(st.st_mode) ? DT_SOCK :
4913 S_ISCHR(st.st_mode) ? DT_CHR :
4914 S_ISBLK(st.st_mode) ? DT_BLK :
4920 int in_search_path(const char *path, char **search) {
4924 r = path_get_parent(path, &parent);
4930 STRV_FOREACH(i, search) {
4931 if (path_equal(parent, *i)) {
4942 int get_files_in_directory(const char *path, char ***list) {
4950 /* Returns all files in a directory in *list, and the number
4951 * of files as return value. If list is NULL returns only the
4960 union dirent_storage buf;
4963 k = readdir_r(d, &buf.de, &de);
4972 dirent_ensure_type(d, de);
4974 if (!dirent_is_file(de))
4978 if ((unsigned) r >= n) {
4982 t = realloc(l, sizeof(char*) * n);
4991 assert((unsigned) r < n);
4993 l[r] = strdup(de->d_name);
5017 char *strjoin(const char *x, ...) {
5031 t = va_arg(ap, const char *);
5036 if (n > ((size_t) -1) - l) {
5060 t = va_arg(ap, const char *);
5074 bool is_main_thread(void) {
5075 static __thread int cached = 0;
5077 if (_unlikely_(cached == 0))
5078 cached = getpid() == gettid() ? 1 : -1;
5083 int block_get_whole_disk(dev_t d, dev_t *ret) {
5090 /* If it has a queue this is good enough for us */
5091 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5094 r = access(p, F_OK);
5102 /* If it is a partition find the originating device */
5103 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5106 r = access(p, F_OK);
5112 /* Get parent dev_t */
5113 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5116 r = read_one_line_file(p, &s);
5122 r = sscanf(s, "%u:%u", &m, &n);
5128 /* Only return this if it is really good enough for us. */
5129 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5132 r = access(p, F_OK);
5136 *ret = makedev(m, n);
5143 int file_is_priv_sticky(const char *p) {
5148 if (lstat(p, &st) < 0)
5152 (st.st_uid == 0 || st.st_uid == getuid()) &&
5153 (st.st_mode & S_ISVTX);
5156 static const char *const ioprio_class_table[] = {
5157 [IOPRIO_CLASS_NONE] = "none",
5158 [IOPRIO_CLASS_RT] = "realtime",
5159 [IOPRIO_CLASS_BE] = "best-effort",
5160 [IOPRIO_CLASS_IDLE] = "idle"
5163 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5165 static const char *const sigchld_code_table[] = {
5166 [CLD_EXITED] = "exited",
5167 [CLD_KILLED] = "killed",
5168 [CLD_DUMPED] = "dumped",
5169 [CLD_TRAPPED] = "trapped",
5170 [CLD_STOPPED] = "stopped",
5171 [CLD_CONTINUED] = "continued",
5174 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5176 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5177 [LOG_FAC(LOG_KERN)] = "kern",
5178 [LOG_FAC(LOG_USER)] = "user",
5179 [LOG_FAC(LOG_MAIL)] = "mail",
5180 [LOG_FAC(LOG_DAEMON)] = "daemon",
5181 [LOG_FAC(LOG_AUTH)] = "auth",
5182 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5183 [LOG_FAC(LOG_LPR)] = "lpr",
5184 [LOG_FAC(LOG_NEWS)] = "news",
5185 [LOG_FAC(LOG_UUCP)] = "uucp",
5186 [LOG_FAC(LOG_CRON)] = "cron",
5187 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5188 [LOG_FAC(LOG_FTP)] = "ftp",
5189 [LOG_FAC(LOG_LOCAL0)] = "local0",
5190 [LOG_FAC(LOG_LOCAL1)] = "local1",
5191 [LOG_FAC(LOG_LOCAL2)] = "local2",
5192 [LOG_FAC(LOG_LOCAL3)] = "local3",
5193 [LOG_FAC(LOG_LOCAL4)] = "local4",
5194 [LOG_FAC(LOG_LOCAL5)] = "local5",
5195 [LOG_FAC(LOG_LOCAL6)] = "local6",
5196 [LOG_FAC(LOG_LOCAL7)] = "local7"
5199 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5201 static const char *const log_level_table[] = {
5202 [LOG_EMERG] = "emerg",
5203 [LOG_ALERT] = "alert",
5204 [LOG_CRIT] = "crit",
5206 [LOG_WARNING] = "warning",
5207 [LOG_NOTICE] = "notice",
5208 [LOG_INFO] = "info",
5209 [LOG_DEBUG] = "debug"
5212 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5214 static const char* const sched_policy_table[] = {
5215 [SCHED_OTHER] = "other",
5216 [SCHED_BATCH] = "batch",
5217 [SCHED_IDLE] = "idle",
5218 [SCHED_FIFO] = "fifo",
5222 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5224 static const char* const rlimit_table[] = {
5225 [RLIMIT_CPU] = "LimitCPU",
5226 [RLIMIT_FSIZE] = "LimitFSIZE",
5227 [RLIMIT_DATA] = "LimitDATA",
5228 [RLIMIT_STACK] = "LimitSTACK",
5229 [RLIMIT_CORE] = "LimitCORE",
5230 [RLIMIT_RSS] = "LimitRSS",
5231 [RLIMIT_NOFILE] = "LimitNOFILE",
5232 [RLIMIT_AS] = "LimitAS",
5233 [RLIMIT_NPROC] = "LimitNPROC",
5234 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5235 [RLIMIT_LOCKS] = "LimitLOCKS",
5236 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5237 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5238 [RLIMIT_NICE] = "LimitNICE",
5239 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5240 [RLIMIT_RTTIME] = "LimitRTTIME"
5243 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5245 static const char* const ip_tos_table[] = {
5246 [IPTOS_LOWDELAY] = "low-delay",
5247 [IPTOS_THROUGHPUT] = "throughput",
5248 [IPTOS_RELIABILITY] = "reliability",
5249 [IPTOS_LOWCOST] = "low-cost",
5252 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5254 static const char *const __signal_table[] = {
5271 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5282 [SIGVTALRM] = "VTALRM",
5284 [SIGWINCH] = "WINCH",
5290 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5292 const char *signal_to_string(int signo) {
5293 static __thread char buf[12];
5296 name = __signal_to_string(signo);
5300 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5301 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5303 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5308 int signal_from_string(const char *s) {
5313 signo = __signal_from_string(s);
5317 if (startswith(s, "RTMIN+")) {
5321 if (safe_atou(s, &u) >= 0) {
5322 signo = (int) u + offset;
5323 if (signo > 0 && signo < _NSIG)
5329 bool kexec_loaded(void) {
5330 bool loaded = false;
5333 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5341 int strdup_or_null(const char *a, char **b) {
5359 int prot_from_flags(int flags) {
5361 switch (flags & O_ACCMODE) {
5370 return PROT_READ|PROT_WRITE;
5377 char *format_bytes(char *buf, size_t l, off_t t) {
5380 static const struct {
5384 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5385 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5386 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5387 { "G", 1024ULL*1024ULL*1024ULL },
5388 { "M", 1024ULL*1024ULL },
5392 for (i = 0; i < ELEMENTSOF(table); i++) {
5394 if (t >= table[i].factor) {
5397 (unsigned long long) (t / table[i].factor),
5398 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5405 snprintf(buf, l, "%lluB", (unsigned long long) t);
5413 void* memdup(const void *p, size_t l) {
5426 int fd_inc_sndbuf(int fd, size_t n) {
5428 socklen_t l = sizeof(value);
5430 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5432 l == sizeof(value) &&
5433 (size_t) value >= n*2)
5437 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5444 int fd_inc_rcvbuf(int fd, size_t n) {
5446 socklen_t l = sizeof(value);
5448 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5450 l == sizeof(value) &&
5451 (size_t) value >= n*2)
5455 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5462 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5463 pid_t parent_pid, agent_pid;
5465 bool stdout_is_tty, stderr_is_tty;
5473 parent_pid = getpid();
5475 /* Spawns a temporary TTY agent, making sure it goes away when
5482 if (agent_pid != 0) {
5489 * Make sure the agent goes away when the parent dies */
5490 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5491 _exit(EXIT_FAILURE);
5493 /* Check whether our parent died before we were able
5494 * to set the death signal */
5495 if (getppid() != parent_pid)
5496 _exit(EXIT_SUCCESS);
5498 /* Don't leak fds to the agent */
5499 close_all_fds(except, n_except);
5501 stdout_is_tty = isatty(STDOUT_FILENO);
5502 stderr_is_tty = isatty(STDERR_FILENO);
5504 if (!stdout_is_tty || !stderr_is_tty) {
5505 /* Detach from stdout/stderr. and reopen
5506 * /dev/tty for them. This is important to
5507 * ensure that when systemctl is started via
5508 * popen() or a similar call that expects to
5509 * read EOF we actually do generate EOF and
5510 * not delay this indefinitely by because we
5511 * keep an unused copy of stdin around. */
5512 fd = open("/dev/tty", O_WRONLY);
5514 log_error("Failed to open /dev/tty: %m");
5515 _exit(EXIT_FAILURE);
5519 dup2(fd, STDOUT_FILENO);
5522 dup2(fd, STDERR_FILENO);
5528 /* Count arguments */
5530 for (n = 0; va_arg(ap, char*); n++)
5535 l = alloca(sizeof(char *) * (n + 1));
5537 /* Fill in arguments */
5539 for (i = 0; i <= n; i++)
5540 l[i] = va_arg(ap, char*);
5544 _exit(EXIT_FAILURE);
5547 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5548 struct rlimit highest, fixed;
5552 if (setrlimit(resource, rlim) >= 0)
5558 /* So we failed to set the desired setrlimit, then let's try
5559 * to get as close as we can */
5560 assert_se(getrlimit(resource, &highest) == 0);
5562 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5563 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5565 if (setrlimit(resource, &fixed) < 0)
5571 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5572 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5584 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5587 f = fopen(path, "re");
5595 char line[LINE_MAX];
5598 for (i = 0; i < sizeof(line)-1; i++) {
5602 if (_unlikely_(c == EOF)) {
5612 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5613 value = strdup(line + l + 1);
5633 int can_sleep(const char *type) {
5637 _cleanup_free_ char *p = NULL;
5641 r = read_one_line_file("/sys/power/state", &p);
5643 return r == -ENOENT ? 0 : r;
5646 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5647 if (l == k && memcmp(w, type, l) == 0)
5653 bool is_valid_documentation_url(const char *url) {
5656 if (startswith(url, "http://") && url[7])
5659 if (startswith(url, "https://") && url[8])
5662 if (startswith(url, "file:") && url[5])
5665 if (startswith(url, "info:") && url[5])
5668 if (startswith(url, "man:") && url[4])
5674 bool in_initrd(void) {
5675 static __thread int saved = -1;
5681 /* We make two checks here:
5683 * 1. the flag file /etc/initrd-release must exist
5684 * 2. the root file system must be a memory file system
5686 * The second check is extra paranoia, since misdetecting an
5687 * initrd can have bad bad consequences due the initrd
5688 * emptying when transititioning to the main systemd.
5691 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5692 statfs("/", &s) >= 0 &&
5693 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5698 void warn_melody(void) {
5699 _cleanup_close_ int fd = -1;
5701 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5705 /* Yeah, this is synchronous. Kinda sucks. But well... */
5707 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5708 usleep(125*USEC_PER_MSEC);
5710 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5711 usleep(125*USEC_PER_MSEC);
5713 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5714 usleep(125*USEC_PER_MSEC);
5716 ioctl(fd, KIOCSOUND, 0);
5719 int make_console_stdio(void) {
5722 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5724 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5726 log_error("Failed to acquire terminal: %s", strerror(-fd));
5732 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5739 int get_home_dir(char **_h) {
5747 /* Take the user specified one */
5758 /* Hardcode home directory for root to avoid NSS */
5761 h = strdup("/root");
5769 /* Check the database... */
5773 return errno ? -errno : -ESRCH;
5775 if (!path_is_absolute(p->pw_dir))
5778 h = strdup(p->pw_dir);
5786 int get_shell(char **_sh) {
5794 /* Take the user specified one */
5795 e = getenv("SHELL");
5805 /* Hardcode home directory for root to avoid NSS */
5808 sh = strdup("/bin/sh");
5816 /* Check the database... */
5820 return errno ? -errno : -ESRCH;
5822 if (!path_is_absolute(p->pw_shell))
5825 sh = strdup(p->pw_shell);
5833 void freep(void *p) {
5837 void fclosep(FILE **f) {
5842 void closep(int *fd) {
5844 close_nointr_nofail(*fd);
5847 void closedirp(DIR **d) {
5852 void umaskp(mode_t *u) {
5856 bool filename_is_safe(const char *p) {
5870 if (strlen(p) > FILENAME_MAX)
5876 bool string_is_safe(const char *p) {
5881 for (t = p; *t; t++) {
5885 if (strchr("\\\"\'", *t))