1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
68 #include "path-util.h"
69 #include "exit-status.h"
73 char **saved_argv = NULL;
75 static volatile unsigned cached_columns = 0;
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) {
146 if (ts->tv_sec == (time_t) -1 &&
147 ts->tv_nsec == (long) -1)
151 (usec_t) ts->tv_sec * USEC_PER_SEC +
152 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
155 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
158 if (u == (usec_t) -1) {
159 ts->tv_sec = (time_t) -1;
160 ts->tv_nsec = (long) -1;
164 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
165 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
170 usec_t timeval_load(const struct timeval *tv) {
173 if (tv->tv_sec == (time_t) -1 &&
174 tv->tv_usec == (suseconds_t) -1)
178 (usec_t) tv->tv_sec * USEC_PER_SEC +
179 (usec_t) tv->tv_usec;
182 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
185 if (u == (usec_t) -1) {
186 tv->tv_sec = (time_t) -1;
187 tv->tv_usec = (suseconds_t) -1;
191 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
192 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
197 bool endswith(const char *s, const char *postfix) {
204 pl = strlen(postfix);
212 return memcmp(s + sl - pl, postfix, pl) == 0;
215 bool startswith(const char *s, const char *prefix) {
230 return memcmp(s, prefix, pl) == 0;
233 bool startswith_no_case(const char *s, const char *prefix) {
249 for(i = 0; i < pl; ++i)
250 if (tolower(s[i]) != tolower(prefix[i]))
256 bool first_word(const char *s, const char *word) {
271 if (memcmp(s, word, wl) != 0)
275 strchr(WHITESPACE, s[wl]);
278 int close_nointr(int fd) {
293 void close_nointr_nofail(int fd) {
294 int saved_errno = errno;
296 /* like close_nointr() but cannot fail, and guarantees errno
299 assert_se(close_nointr(fd) == 0);
304 void close_many(const int fds[], unsigned n_fd) {
307 for (i = 0; i < n_fd; i++)
308 close_nointr_nofail(fds[i]);
311 int parse_boolean(const char *v) {
314 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
316 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
322 int parse_pid(const char *s, pid_t* ret_pid) {
323 unsigned long ul = 0;
330 r = safe_atolu(s, &ul);
336 if ((unsigned long) pid != ul)
346 int parse_uid(const char *s, uid_t* ret_uid) {
347 unsigned long ul = 0;
354 r = safe_atolu(s, &ul);
360 if ((unsigned long) uid != ul)
367 int safe_atou(const char *s, unsigned *ret_u) {
375 l = strtoul(s, &x, 0);
377 if (!x || *x || errno)
378 return errno ? -errno : -EINVAL;
380 if ((unsigned long) (unsigned) l != l)
383 *ret_u = (unsigned) l;
387 int safe_atoi(const char *s, int *ret_i) {
395 l = strtol(s, &x, 0);
397 if (!x || *x || errno)
398 return errno ? -errno : -EINVAL;
400 if ((long) (int) l != l)
407 int safe_atollu(const char *s, long long unsigned *ret_llu) {
409 unsigned long long l;
415 l = strtoull(s, &x, 0);
417 if (!x || *x || errno)
418 return errno ? -errno : -EINVAL;
424 int safe_atolli(const char *s, long long int *ret_lli) {
432 l = strtoll(s, &x, 0);
434 if (!x || *x || errno)
435 return errno ? -errno : -EINVAL;
441 /* Split a string into words. */
442 char *split(const char *c, size_t *l, const char *separator, char **state) {
445 current = *state ? *state : (char*) c;
447 if (!*current || *c == 0)
450 current += strspn(current, separator);
451 *l = strcspn(current, separator);
454 return (char*) current;
457 /* Split a string into words, but consider strings enclosed in '' and
458 * "" as words even if they include spaces. */
459 char *split_quoted(const char *c, size_t *l, char **state) {
461 bool escaped = false;
463 current = *state ? *state : (char*) c;
465 if (!*current || *c == 0)
468 current += strspn(current, WHITESPACE);
470 if (*current == '\'') {
473 for (e = current; *e; e++) {
483 *state = *e == 0 ? e : e+1;
484 } else if (*current == '\"') {
487 for (e = current; *e; e++) {
497 *state = *e == 0 ? e : e+1;
499 for (e = current; *e; e++) {
504 else if (strchr(WHITESPACE, *e))
511 return (char*) current;
514 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
516 _cleanup_fclose_ FILE *f = NULL;
517 char fn[PATH_MAX], line[LINE_MAX], *p;
523 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
530 if (!fgets(line, sizeof(line), f)) {
531 r = feof(f) ? -EIO : -errno;
536 /* Let's skip the pid and comm fields. The latter is enclosed
537 * in () but does not escape any () in its value, so let's
538 * skip over it manually */
540 p = strrchr(line, ')');
552 if ((long unsigned) (pid_t) ppid != ppid)
555 *_ppid = (pid_t) ppid;
560 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
561 _cleanup_fclose_ FILE *f = NULL;
562 char fn[PATH_MAX], line[LINE_MAX], *p;
567 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
574 if (!fgets(line, sizeof(line), f)) {
581 /* Let's skip the pid and comm fields. The latter is enclosed
582 * in () but does not escape any () in its value, so let's
583 * skip over it manually */
585 p = strrchr(line, ')');
607 "%*d " /* priority */
609 "%*d " /* num_threads */
610 "%*d " /* itrealvalue */
611 "%llu " /* starttime */,
618 int write_one_line_file(const char *fn, const char *line) {
619 _cleanup_fclose_ FILE *f = NULL;
629 if (fputs(line, f) < 0)
630 return errno ? -errno : -EIO;
632 if (!endswith(line, "\n"))
638 return errno ? -errno : -EIO;
643 int fchmod_umask(int fd, mode_t m) {
648 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
654 int write_one_line_file_atomic(const char *fn, const char *line) {
662 r = fopen_temporary(fn, &f, &p);
666 fchmod_umask(fileno(f), 0644);
669 if (fputs(line, f) < 0) {
674 if (!endswith(line, "\n"))
685 if (rename(p, fn) < 0)
701 int read_one_line_file(const char *fn, char **line) {
702 _cleanup_fclose_ FILE *f = NULL;
703 char t[LINE_MAX], *c;
712 if (!fgets(t, sizeof(t), f)) {
715 return errno ? -errno : -EIO;
729 int read_full_file(const char *fn, char **contents, size_t *size) {
730 _cleanup_fclose_ FILE *f = NULL;
732 _cleanup_free_ char *buf = NULL;
739 if (fstat(fileno(f), &st) < 0)
743 if (st.st_size > 4*1024*1024)
746 n = st.st_size > 0 ? st.st_size : LINE_MAX;
753 t = realloc(buf, n+1);
758 k = fread(buf + l, 1, n - l, f);
787 const char *separator, ...) {
790 char *contents = NULL, *p;
795 if ((r = read_full_file(fname, &contents, NULL)) < 0)
800 const char *key = NULL;
802 p += strspn(p, separator);
803 p += strspn(p, WHITESPACE);
808 if (!strchr(COMMENTS, *p)) {
812 va_start(ap, separator);
813 while ((key = va_arg(ap, char *))) {
817 value = va_arg(ap, char **);
820 if (strncmp(p, key, n) != 0 ||
825 n = strcspn(p, separator);
828 strchr(QUOTES, p[0]) &&
830 v = strndup(p+1, n-2);
841 /* return empty value strings as NULL */
858 p += strcspn(p, separator);
877 if (!(f = fopen(fname, "re")))
881 char l[LINE_MAX], *p, *u;
884 if (!fgets(l, sizeof(l), f)) {
897 if (strchr(COMMENTS, *p))
900 if (!(u = normalize_env_assignment(p))) {
905 t = strv_append(m, u);
931 int write_env_file(const char *fname, char **l) {
936 r = fopen_temporary(fname, &f, &p);
940 fchmod_umask(fileno(f), 0644);
956 if (rename(p, fname) < 0)
971 char *truncate_nl(char *s) {
974 s[strcspn(s, NEWLINE)] = 0;
978 int get_process_comm(pid_t pid, char **name) {
984 r = read_one_line_file("/proc/self/comm", name);
987 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
990 r = read_one_line_file(p, name);
997 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1004 assert(max_length > 0);
1008 f = fopen("/proc/self/cmdline", "re");
1011 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1021 r = new(char, max_length);
1029 while ((c = getc(f)) != EOF) {
1051 size_t n = MIN(left-1, 3U);
1052 memcpy(k, "...", n);
1059 /* Kernel threads have no argv[] */
1069 h = get_process_comm(pid, &t);
1073 r = strjoin("[", t, "]", NULL);
1084 int is_kernel_thread(pid_t pid) {
1094 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1103 count = fread(&c, 1, 1, f);
1107 /* Kernel threads have an empty cmdline */
1110 return eof ? 1 : -errno;
1115 int get_process_exe(pid_t pid, char **name) {
1121 r = readlink_malloc("/proc/self/exe", name);
1124 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1127 r = readlink_malloc(p, name);
1134 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1144 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1154 char line[LINE_MAX], *l;
1156 if (!fgets(line, sizeof(line), f)) {
1166 if (startswith(l, field)) {
1168 l += strspn(l, WHITESPACE);
1170 l[strcspn(l, WHITESPACE)] = 0;
1172 r = parse_uid(l, uid);
1185 int get_process_uid(pid_t pid, uid_t *uid) {
1186 return get_process_id(pid, "Uid:", uid);
1189 int get_process_gid(pid_t pid, gid_t *gid) {
1190 return get_process_id(pid, "Gid:", gid);
1193 char *strnappend(const char *s, const char *suffix, size_t b) {
1201 return strndup(suffix, b);
1210 if (b > ((size_t) -1) - a)
1213 r = new(char, a+b+1);
1218 memcpy(r+a, suffix, b);
1224 char *strappend(const char *s, const char *suffix) {
1225 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1228 int readlink_malloc(const char *p, char **r) {
1238 if (!(c = new(char, l)))
1241 if ((n = readlink(p, c, l-1)) < 0) {
1247 if ((size_t) n < l-1) {
1258 int readlink_and_make_absolute(const char *p, char **r) {
1265 if ((j = readlink_malloc(p, &target)) < 0)
1268 k = file_in_same_dir(p, target);
1278 int readlink_and_canonicalize(const char *p, char **r) {
1285 j = readlink_and_make_absolute(p, &t);
1289 s = canonicalize_file_name(t);
1296 path_kill_slashes(*r);
1301 int reset_all_signal_handlers(void) {
1304 for (sig = 1; sig < _NSIG; sig++) {
1305 struct sigaction sa;
1307 if (sig == SIGKILL || sig == SIGSTOP)
1311 sa.sa_handler = SIG_DFL;
1312 sa.sa_flags = SA_RESTART;
1314 /* On Linux the first two RT signals are reserved by
1315 * glibc, and sigaction() will return EINVAL for them. */
1316 if ((sigaction(sig, &sa, NULL) < 0))
1317 if (errno != EINVAL)
1324 char *strstrip(char *s) {
1327 /* Drops trailing whitespace. Modifies the string in
1328 * place. Returns pointer to first non-space character */
1330 s += strspn(s, WHITESPACE);
1332 for (e = strchr(s, 0); e > s; e --)
1333 if (!strchr(WHITESPACE, e[-1]))
1341 char *delete_chars(char *s, const char *bad) {
1344 /* Drops all whitespace, regardless where in the string */
1346 for (f = s, t = s; *f; f++) {
1347 if (strchr(bad, *f))
1358 bool in_charset(const char *s, const char* charset) {
1364 for (i = s; *i; i++)
1365 if (!strchr(charset, *i))
1371 char *file_in_same_dir(const char *path, const char *filename) {
1378 /* This removes the last component of path and appends
1379 * filename, unless the latter is absolute anyway or the
1382 if (path_is_absolute(filename))
1383 return strdup(filename);
1385 if (!(e = strrchr(path, '/')))
1386 return strdup(filename);
1388 k = strlen(filename);
1389 if (!(r = new(char, e-path+1+k+1)))
1392 memcpy(r, path, e-path+1);
1393 memcpy(r+(e-path)+1, filename, k+1);
1398 int rmdir_parents(const char *path, const char *stop) {
1407 /* Skip trailing slashes */
1408 while (l > 0 && path[l-1] == '/')
1414 /* Skip last component */
1415 while (l > 0 && path[l-1] != '/')
1418 /* Skip trailing slashes */
1419 while (l > 0 && path[l-1] == '/')
1425 if (!(t = strndup(path, l)))
1428 if (path_startswith(stop, t)) {
1437 if (errno != ENOENT)
1445 char hexchar(int x) {
1446 static const char table[16] = "0123456789abcdef";
1448 return table[x & 15];
1451 int unhexchar(char c) {
1453 if (c >= '0' && c <= '9')
1456 if (c >= 'a' && c <= 'f')
1457 return c - 'a' + 10;
1459 if (c >= 'A' && c <= 'F')
1460 return c - 'A' + 10;
1465 char octchar(int x) {
1466 return '0' + (x & 7);
1469 int unoctchar(char c) {
1471 if (c >= '0' && c <= '7')
1477 char decchar(int x) {
1478 return '0' + (x % 10);
1481 int undecchar(char c) {
1483 if (c >= '0' && c <= '9')
1489 char *cescape(const char *s) {
1495 /* Does C style string escaping. */
1497 r = new(char, strlen(s)*4 + 1);
1501 for (f = s, t = r; *f; f++)
1547 /* For special chars we prefer octal over
1548 * hexadecimal encoding, simply because glib's
1549 * g_strescape() does the same */
1550 if ((*f < ' ') || (*f >= 127)) {
1552 *(t++) = octchar((unsigned char) *f >> 6);
1553 *(t++) = octchar((unsigned char) *f >> 3);
1554 *(t++) = octchar((unsigned char) *f);
1565 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1572 /* Undoes C style string escaping, and optionally prefixes it. */
1574 pl = prefix ? strlen(prefix) : 0;
1576 r = new(char, pl+length+1);
1581 memcpy(r, prefix, pl);
1583 for (f = s, t = r + pl; f < s + length; f++) {
1626 /* This is an extension of the XDG syntax files */
1631 /* hexadecimal encoding */
1634 a = unhexchar(f[1]);
1635 b = unhexchar(f[2]);
1637 if (a < 0 || b < 0) {
1638 /* Invalid escape code, let's take it literal then */
1642 *(t++) = (char) ((a << 4) | b);
1657 /* octal encoding */
1660 a = unoctchar(f[0]);
1661 b = unoctchar(f[1]);
1662 c = unoctchar(f[2]);
1664 if (a < 0 || b < 0 || c < 0) {
1665 /* Invalid escape code, let's take it literal then */
1669 *(t++) = (char) ((a << 6) | (b << 3) | c);
1677 /* premature end of string.*/
1682 /* Invalid escape code, let's take it literal then */
1694 char *cunescape_length(const char *s, size_t length) {
1695 return cunescape_length_with_prefix(s, length, NULL);
1698 char *cunescape(const char *s) {
1701 return cunescape_length(s, strlen(s));
1704 char *xescape(const char *s, const char *bad) {
1708 /* Escapes all chars in bad, in addition to \ and all special
1709 * chars, in \xFF style escaping. May be reversed with
1712 r = new(char, strlen(s) * 4 + 1);
1716 for (f = s, t = r; *f; f++) {
1718 if ((*f < ' ') || (*f >= 127) ||
1719 (*f == '\\') || strchr(bad, *f)) {
1722 *(t++) = hexchar(*f >> 4);
1723 *(t++) = hexchar(*f);
1733 char *bus_path_escape(const char *s) {
1739 /* Escapes all chars that D-Bus' object path cannot deal
1740 * with. Can be reverse with bus_path_unescape() */
1742 if (!(r = new(char, strlen(s)*3+1)))
1745 for (f = s, t = r; *f; f++) {
1747 if (!(*f >= 'A' && *f <= 'Z') &&
1748 !(*f >= 'a' && *f <= 'z') &&
1749 !(*f >= '0' && *f <= '9')) {
1751 *(t++) = hexchar(*f >> 4);
1752 *(t++) = hexchar(*f);
1762 char *bus_path_unescape(const char *f) {
1767 if (!(r = strdup(f)))
1770 for (t = r; *f; f++) {
1775 if ((a = unhexchar(f[1])) < 0 ||
1776 (b = unhexchar(f[2])) < 0) {
1777 /* Invalid escape code, let's take it literal then */
1780 *(t++) = (char) ((a << 4) | b);
1792 char *ascii_strlower(char *t) {
1797 for (p = t; *p; p++)
1798 if (*p >= 'A' && *p <= 'Z')
1799 *p = *p - 'A' + 'a';
1804 static bool ignore_file_allow_backup(const char *filename) {
1808 filename[0] == '.' ||
1809 streq(filename, "lost+found") ||
1810 streq(filename, "aquota.user") ||
1811 streq(filename, "aquota.group") ||
1812 endswith(filename, ".rpmnew") ||
1813 endswith(filename, ".rpmsave") ||
1814 endswith(filename, ".rpmorig") ||
1815 endswith(filename, ".dpkg-old") ||
1816 endswith(filename, ".dpkg-new") ||
1817 endswith(filename, ".swp");
1820 bool ignore_file(const char *filename) {
1823 if (endswith(filename, "~"))
1826 return ignore_file_allow_backup(filename);
1829 int fd_nonblock(int fd, bool nonblock) {
1834 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1838 flags |= O_NONBLOCK;
1840 flags &= ~O_NONBLOCK;
1842 if (fcntl(fd, F_SETFL, flags) < 0)
1848 int fd_cloexec(int fd, bool cloexec) {
1853 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1857 flags |= FD_CLOEXEC;
1859 flags &= ~FD_CLOEXEC;
1861 if (fcntl(fd, F_SETFD, flags) < 0)
1867 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1870 assert(n_fdset == 0 || fdset);
1872 for (i = 0; i < n_fdset; i++)
1879 int close_all_fds(const int except[], unsigned n_except) {
1884 assert(n_except == 0 || except);
1886 d = opendir("/proc/self/fd");
1891 /* When /proc isn't available (for example in chroots)
1892 * the fallback is brute forcing through the fd
1895 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1896 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1898 if (fd_in_set(fd, except, n_except))
1901 if (close_nointr(fd) < 0)
1902 if (errno != EBADF && r == 0)
1909 while ((de = readdir(d))) {
1912 if (ignore_file(de->d_name))
1915 if (safe_atoi(de->d_name, &fd) < 0)
1916 /* Let's better ignore this, just in case */
1925 if (fd_in_set(fd, except, n_except))
1928 if (close_nointr(fd) < 0) {
1929 /* Valgrind has its own FD and doesn't want to have it closed */
1930 if (errno != EBADF && r == 0)
1939 bool chars_intersect(const char *a, const char *b) {
1942 /* Returns true if any of the chars in a are in b. */
1943 for (p = a; *p; p++)
1950 char *format_timestamp(char *buf, size_t l, usec_t t) {
1960 sec = (time_t) (t / USEC_PER_SEC);
1962 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1968 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1971 n = now(CLOCK_REALTIME);
1973 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1978 if (d >= USEC_PER_YEAR)
1979 snprintf(buf, l, "%llu years and %llu months ago",
1980 (unsigned long long) (d / USEC_PER_YEAR),
1981 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1982 else if (d >= USEC_PER_MONTH)
1983 snprintf(buf, l, "%llu months and %llu days ago",
1984 (unsigned long long) (d / USEC_PER_MONTH),
1985 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1986 else if (d >= USEC_PER_WEEK)
1987 snprintf(buf, l, "%llu weeks and %llu days ago",
1988 (unsigned long long) (d / USEC_PER_WEEK),
1989 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1990 else if (d >= 2*USEC_PER_DAY)
1991 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1992 else if (d >= 25*USEC_PER_HOUR)
1993 snprintf(buf, l, "1 day and %lluh ago",
1994 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1995 else if (d >= 6*USEC_PER_HOUR)
1996 snprintf(buf, l, "%lluh ago",
1997 (unsigned long long) (d / USEC_PER_HOUR));
1998 else if (d >= USEC_PER_HOUR)
1999 snprintf(buf, l, "%lluh %llumin ago",
2000 (unsigned long long) (d / USEC_PER_HOUR),
2001 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2002 else if (d >= 5*USEC_PER_MINUTE)
2003 snprintf(buf, l, "%llumin ago",
2004 (unsigned long long) (d / USEC_PER_MINUTE));
2005 else if (d >= USEC_PER_MINUTE)
2006 snprintf(buf, l, "%llumin %llus ago",
2007 (unsigned long long) (d / USEC_PER_MINUTE),
2008 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2009 else if (d >= USEC_PER_SEC)
2010 snprintf(buf, l, "%llus ago",
2011 (unsigned long long) (d / USEC_PER_SEC));
2012 else if (d >= USEC_PER_MSEC)
2013 snprintf(buf, l, "%llums ago",
2014 (unsigned long long) (d / USEC_PER_MSEC));
2016 snprintf(buf, l, "%lluus ago",
2017 (unsigned long long) d);
2019 snprintf(buf, l, "now");
2025 char *format_timespan(char *buf, size_t l, usec_t t) {
2026 static const struct {
2030 { "w", USEC_PER_WEEK },
2031 { "d", USEC_PER_DAY },
2032 { "h", USEC_PER_HOUR },
2033 { "min", USEC_PER_MINUTE },
2034 { "s", USEC_PER_SEC },
2035 { "ms", USEC_PER_MSEC },
2045 if (t == (usec_t) -1)
2049 snprintf(p, l, "0");
2054 /* The result of this function can be parsed with parse_usec */
2056 for (i = 0; i < ELEMENTSOF(table); i++) {
2060 if (t < table[i].usec)
2066 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2067 n = MIN((size_t) k, l);
2080 bool fstype_is_network(const char *fstype) {
2081 static const char table[] =
2090 return nulstr_contains(table, fstype);
2094 _cleanup_close_ int fd;
2096 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2102 TIOCL_GETKMSGREDIRECT,
2106 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2109 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2112 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2118 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2119 struct termios old_termios, new_termios;
2121 char line[LINE_MAX];
2126 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2127 new_termios = old_termios;
2129 new_termios.c_lflag &= ~ICANON;
2130 new_termios.c_cc[VMIN] = 1;
2131 new_termios.c_cc[VTIME] = 0;
2133 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2136 if (t != (usec_t) -1) {
2137 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2138 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2143 k = fread(&c, 1, 1, f);
2145 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2151 *need_nl = c != '\n';
2158 if (t != (usec_t) -1)
2159 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2162 if (!fgets(line, sizeof(line), f))
2167 if (strlen(line) != 1)
2177 int ask(char *ret, const char *replies, const char *text, ...) {
2187 bool need_nl = true;
2190 fputs(ANSI_HIGHLIGHT_ON, stdout);
2197 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2201 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2204 if (r == -EBADMSG) {
2205 puts("Bad input, please try again.");
2216 if (strchr(replies, c)) {
2221 puts("Read unexpected character, please try again.");
2225 int reset_terminal_fd(int fd, bool switch_to_text) {
2226 struct termios termios;
2229 /* Set terminal to some sane defaults */
2233 /* We leave locked terminal attributes untouched, so that
2234 * Plymouth may set whatever it wants to set, and we don't
2235 * interfere with that. */
2237 /* Disable exclusive mode, just in case */
2238 ioctl(fd, TIOCNXCL);
2240 /* Switch to text mode */
2242 ioctl(fd, KDSETMODE, KD_TEXT);
2244 /* Enable console unicode mode */
2245 ioctl(fd, KDSKBMODE, K_UNICODE);
2247 if (tcgetattr(fd, &termios) < 0) {
2252 /* We only reset the stuff that matters to the software. How
2253 * hardware is set up we don't touch assuming that somebody
2254 * else will do that for us */
2256 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2257 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2258 termios.c_oflag |= ONLCR;
2259 termios.c_cflag |= CREAD;
2260 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2262 termios.c_cc[VINTR] = 03; /* ^C */
2263 termios.c_cc[VQUIT] = 034; /* ^\ */
2264 termios.c_cc[VERASE] = 0177;
2265 termios.c_cc[VKILL] = 025; /* ^X */
2266 termios.c_cc[VEOF] = 04; /* ^D */
2267 termios.c_cc[VSTART] = 021; /* ^Q */
2268 termios.c_cc[VSTOP] = 023; /* ^S */
2269 termios.c_cc[VSUSP] = 032; /* ^Z */
2270 termios.c_cc[VLNEXT] = 026; /* ^V */
2271 termios.c_cc[VWERASE] = 027; /* ^W */
2272 termios.c_cc[VREPRINT] = 022; /* ^R */
2273 termios.c_cc[VEOL] = 0;
2274 termios.c_cc[VEOL2] = 0;
2276 termios.c_cc[VTIME] = 0;
2277 termios.c_cc[VMIN] = 1;
2279 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2283 /* Just in case, flush all crap out */
2284 tcflush(fd, TCIOFLUSH);
2289 int reset_terminal(const char *name) {
2292 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2296 r = reset_terminal_fd(fd, true);
2297 close_nointr_nofail(fd);
2302 int open_terminal(const char *name, int mode) {
2307 * If a TTY is in the process of being closed opening it might
2308 * cause EIO. This is horribly awful, but unlikely to be
2309 * changed in the kernel. Hence we work around this problem by
2310 * retrying a couple of times.
2312 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2316 fd = open(name, mode);
2323 /* Max 1s in total */
2327 usleep(50 * USEC_PER_MSEC);
2336 close_nointr_nofail(fd);
2341 close_nointr_nofail(fd);
2348 int flush_fd(int fd) {
2349 struct pollfd pollfd;
2353 pollfd.events = POLLIN;
2360 if ((r = poll(&pollfd, 1, 0)) < 0) {
2371 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2376 if (errno == EAGAIN)
2387 int acquire_terminal(
2391 bool ignore_tiocstty_eperm,
2394 int fd = -1, notify = -1, r = 0, wd = -1;
2396 struct sigaction sa_old, sa_new;
2400 /* We use inotify to be notified when the tty is closed. We
2401 * create the watch before checking if we can actually acquire
2402 * it, so that we don't lose any event.
2404 * Note: strictly speaking this actually watches for the
2405 * device being closed, it does *not* really watch whether a
2406 * tty loses its controlling process. However, unless some
2407 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2408 * its tty otherwise this will not become a problem. As long
2409 * as the administrator makes sure not configure any service
2410 * on the same tty as an untrusted user this should not be a
2411 * problem. (Which he probably should not do anyway.) */
2413 if (timeout != (usec_t) -1)
2414 ts = now(CLOCK_MONOTONIC);
2416 if (!fail && !force) {
2417 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2423 wd = inotify_add_watch(notify, name, IN_CLOSE);
2432 r = flush_fd(notify);
2437 /* We pass here O_NOCTTY only so that we can check the return
2438 * value TIOCSCTTY and have a reliable way to figure out if we
2439 * successfully became the controlling process of the tty */
2440 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2444 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2445 * if we already own the tty. */
2447 sa_new.sa_handler = SIG_IGN;
2448 sa_new.sa_flags = SA_RESTART;
2449 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2451 /* First, try to get the tty */
2452 if (ioctl(fd, TIOCSCTTY, force) < 0)
2455 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2457 /* Sometimes it makes sense to ignore TIOCSCTTY
2458 * returning EPERM, i.e. when very likely we already
2459 * are have this controlling terminal. */
2460 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2463 if (r < 0 && (force || fail || r != -EPERM)) {
2472 assert(notify >= 0);
2475 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2477 struct inotify_event *e;
2479 if (timeout != (usec_t) -1) {
2482 n = now(CLOCK_MONOTONIC);
2483 if (ts + timeout < n) {
2488 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2498 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2501 if (errno == EINTR || errno == EAGAIN)
2508 e = (struct inotify_event*) inotify_buffer;
2513 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2518 step = sizeof(struct inotify_event) + e->len;
2519 assert(step <= (size_t) l);
2521 e = (struct inotify_event*) ((uint8_t*) e + step);
2528 /* We close the tty fd here since if the old session
2529 * ended our handle will be dead. It's important that
2530 * we do this after sleeping, so that we don't enter
2531 * an endless loop. */
2532 close_nointr_nofail(fd);
2536 close_nointr_nofail(notify);
2538 r = reset_terminal_fd(fd, true);
2540 log_warning("Failed to reset terminal: %s", strerror(-r));
2546 close_nointr_nofail(fd);
2549 close_nointr_nofail(notify);
2554 int release_terminal(void) {
2556 struct sigaction sa_old, sa_new;
2558 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2561 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2562 * by our own TIOCNOTTY */
2565 sa_new.sa_handler = SIG_IGN;
2566 sa_new.sa_flags = SA_RESTART;
2567 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2569 if (ioctl(fd, TIOCNOTTY) < 0)
2572 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2574 close_nointr_nofail(fd);
2578 int sigaction_many(const struct sigaction *sa, ...) {
2583 while ((sig = va_arg(ap, int)) > 0)
2584 if (sigaction(sig, sa, NULL) < 0)
2591 int ignore_signals(int sig, ...) {
2592 struct sigaction sa;
2597 sa.sa_handler = SIG_IGN;
2598 sa.sa_flags = SA_RESTART;
2600 if (sigaction(sig, &sa, NULL) < 0)
2604 while ((sig = va_arg(ap, int)) > 0)
2605 if (sigaction(sig, &sa, NULL) < 0)
2612 int default_signals(int sig, ...) {
2613 struct sigaction sa;
2618 sa.sa_handler = SIG_DFL;
2619 sa.sa_flags = SA_RESTART;
2621 if (sigaction(sig, &sa, NULL) < 0)
2625 while ((sig = va_arg(ap, int)) > 0)
2626 if (sigaction(sig, &sa, NULL) < 0)
2633 int close_pipe(int p[]) {
2639 a = close_nointr(p[0]);
2644 b = close_nointr(p[1]);
2648 return a < 0 ? a : b;
2651 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2660 while (nbytes > 0) {
2663 if ((k = read(fd, p, nbytes)) <= 0) {
2665 if (k < 0 && errno == EINTR)
2668 if (k < 0 && errno == EAGAIN && do_poll) {
2669 struct pollfd pollfd;
2673 pollfd.events = POLLIN;
2675 if (poll(&pollfd, 1, -1) < 0) {
2679 return n > 0 ? n : -errno;
2682 if (pollfd.revents != POLLIN)
2683 return n > 0 ? n : -EIO;
2688 return n > 0 ? n : (k < 0 ? -errno : 0);
2699 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2708 while (nbytes > 0) {
2711 k = write(fd, p, nbytes);
2714 if (k < 0 && errno == EINTR)
2717 if (k < 0 && errno == EAGAIN && do_poll) {
2718 struct pollfd pollfd;
2722 pollfd.events = POLLOUT;
2724 if (poll(&pollfd, 1, -1) < 0) {
2728 return n > 0 ? n : -errno;
2731 if (pollfd.revents != POLLOUT)
2732 return n > 0 ? n : -EIO;
2737 return n > 0 ? n : (k < 0 ? -errno : 0);
2748 int parse_usec(const char *t, usec_t *usec) {
2749 static const struct {
2753 { "seconds", USEC_PER_SEC },
2754 { "second", USEC_PER_SEC },
2755 { "sec", USEC_PER_SEC },
2756 { "s", USEC_PER_SEC },
2757 { "minutes", USEC_PER_MINUTE },
2758 { "minute", USEC_PER_MINUTE },
2759 { "min", USEC_PER_MINUTE },
2760 { "months", USEC_PER_MONTH },
2761 { "month", USEC_PER_MONTH },
2762 { "msec", USEC_PER_MSEC },
2763 { "ms", USEC_PER_MSEC },
2764 { "m", USEC_PER_MINUTE },
2765 { "hours", USEC_PER_HOUR },
2766 { "hour", USEC_PER_HOUR },
2767 { "hr", USEC_PER_HOUR },
2768 { "h", USEC_PER_HOUR },
2769 { "days", USEC_PER_DAY },
2770 { "day", USEC_PER_DAY },
2771 { "d", USEC_PER_DAY },
2772 { "weeks", USEC_PER_WEEK },
2773 { "week", USEC_PER_WEEK },
2774 { "w", USEC_PER_WEEK },
2775 { "years", USEC_PER_YEAR },
2776 { "year", USEC_PER_YEAR },
2777 { "y", USEC_PER_YEAR },
2780 { "", USEC_PER_SEC }, /* default is sec */
2796 l = strtoll(p, &e, 10);
2807 e += strspn(e, WHITESPACE);
2809 for (i = 0; i < ELEMENTSOF(table); i++)
2810 if (startswith(e, table[i].suffix)) {
2811 r += (usec_t) l * table[i].usec;
2812 p = e + strlen(table[i].suffix);
2816 if (i >= ELEMENTSOF(table))
2826 int parse_nsec(const char *t, nsec_t *nsec) {
2827 static const struct {
2831 { "seconds", NSEC_PER_SEC },
2832 { "second", NSEC_PER_SEC },
2833 { "sec", NSEC_PER_SEC },
2834 { "s", NSEC_PER_SEC },
2835 { "minutes", NSEC_PER_MINUTE },
2836 { "minute", NSEC_PER_MINUTE },
2837 { "min", NSEC_PER_MINUTE },
2838 { "months", NSEC_PER_MONTH },
2839 { "month", NSEC_PER_MONTH },
2840 { "msec", NSEC_PER_MSEC },
2841 { "ms", NSEC_PER_MSEC },
2842 { "m", NSEC_PER_MINUTE },
2843 { "hours", NSEC_PER_HOUR },
2844 { "hour", NSEC_PER_HOUR },
2845 { "hr", NSEC_PER_HOUR },
2846 { "h", NSEC_PER_HOUR },
2847 { "days", NSEC_PER_DAY },
2848 { "day", NSEC_PER_DAY },
2849 { "d", NSEC_PER_DAY },
2850 { "weeks", NSEC_PER_WEEK },
2851 { "week", NSEC_PER_WEEK },
2852 { "w", NSEC_PER_WEEK },
2853 { "years", NSEC_PER_YEAR },
2854 { "year", NSEC_PER_YEAR },
2855 { "y", NSEC_PER_YEAR },
2856 { "usec", NSEC_PER_USEC },
2857 { "us", NSEC_PER_USEC },
2860 { "", 1ULL }, /* default is nsec */
2876 l = strtoll(p, &e, 10);
2887 e += strspn(e, WHITESPACE);
2889 for (i = 0; i < ELEMENTSOF(table); i++)
2890 if (startswith(e, table[i].suffix)) {
2891 r += (nsec_t) l * table[i].nsec;
2892 p = e + strlen(table[i].suffix);
2896 if (i >= ELEMENTSOF(table))
2906 int parse_bytes(const char *t, off_t *bytes) {
2907 static const struct {
2913 { "M", 1024ULL*1024ULL },
2914 { "G", 1024ULL*1024ULL*1024ULL },
2915 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2916 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2917 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2934 l = strtoll(p, &e, 10);
2945 e += strspn(e, WHITESPACE);
2947 for (i = 0; i < ELEMENTSOF(table); i++)
2948 if (startswith(e, table[i].suffix)) {
2949 r += (off_t) l * table[i].factor;
2950 p = e + strlen(table[i].suffix);
2954 if (i >= ELEMENTSOF(table))
2964 int make_stdio(int fd) {
2969 r = dup3(fd, STDIN_FILENO, 0);
2970 s = dup3(fd, STDOUT_FILENO, 0);
2971 t = dup3(fd, STDERR_FILENO, 0);
2974 close_nointr_nofail(fd);
2976 if (r < 0 || s < 0 || t < 0)
2979 /* We rely here that the new fd has O_CLOEXEC not set */
2984 int make_null_stdio(void) {
2987 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2991 return make_stdio(null_fd);
2994 bool is_device_path(const char *path) {
2996 /* Returns true on paths that refer to a device, either in
2997 * sysfs or in /dev */
3000 path_startswith(path, "/dev/") ||
3001 path_startswith(path, "/sys/");
3004 int dir_is_empty(const char *path) {
3005 _cleanup_closedir_ DIR *d;
3014 union dirent_storage buf;
3016 r = readdir_r(d, &buf.de, &de);
3023 if (!ignore_file(de->d_name))
3028 unsigned long long random_ull(void) {
3029 _cleanup_close_ int fd;
3033 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3037 r = loop_read(fd, &ull, sizeof(ull), true);
3038 if (r != sizeof(ull))
3044 return random() * RAND_MAX + random();
3047 void rename_process(const char name[8]) {
3050 /* This is a like a poor man's setproctitle(). It changes the
3051 * comm field, argv[0], and also the glibc's internally used
3052 * name of the process. For the first one a limit of 16 chars
3053 * applies, to the second one usually one of 10 (i.e. length
3054 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3055 * "systemd"). If you pass a longer string it will be
3058 prctl(PR_SET_NAME, name);
3060 if (program_invocation_name)
3061 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3063 if (saved_argc > 0) {
3067 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3069 for (i = 1; i < saved_argc; i++) {
3073 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3078 void sigset_add_many(sigset_t *ss, ...) {
3085 while ((sig = va_arg(ap, int)) > 0)
3086 assert_se(sigaddset(ss, sig) == 0);
3090 char* gethostname_malloc(void) {
3093 assert_se(uname(&u) >= 0);
3095 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3096 return strdup(u.nodename);
3098 return strdup(u.sysname);
3101 bool hostname_is_set(void) {
3104 assert_se(uname(&u) >= 0);
3106 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3109 static char *lookup_uid(uid_t uid) {
3112 _cleanup_free_ char *buf = NULL;
3113 struct passwd pwbuf, *pw = NULL;
3115 /* Shortcut things to avoid NSS lookups */
3117 return strdup("root");
3119 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3123 buf = malloc(bufsize);
3127 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3128 return strdup(pw->pw_name);
3130 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3136 char* getlogname_malloc(void) {
3140 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3145 return lookup_uid(uid);
3148 char *getusername_malloc(void) {
3155 return lookup_uid(getuid());
3158 int getttyname_malloc(int fd, char **r) {
3159 char path[PATH_MAX], *c;
3164 k = ttyname_r(fd, path, sizeof(path));
3170 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3178 int getttyname_harder(int fd, char **r) {
3182 k = getttyname_malloc(fd, &s);
3186 if (streq(s, "tty")) {
3188 return get_ctty(0, NULL, r);
3195 int get_ctty_devnr(pid_t pid, dev_t *d) {
3197 char line[LINE_MAX], *p, *fn;
3198 unsigned long ttynr;
3201 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3204 f = fopen(fn, "re");
3209 if (!fgets(line, sizeof(line), f)) {
3210 k = feof(f) ? -EIO : -errno;
3217 p = strrchr(line, ')');
3227 "%*d " /* session */
3236 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3238 char fn[PATH_MAX], *s, *b, *p;
3243 k = get_ctty_devnr(pid, &devnr);
3247 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3250 if ((k = readlink_malloc(fn, &s)) < 0) {
3255 /* This is an ugly hack */
3256 if (major(devnr) == 136) {
3257 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3267 /* Probably something like the ptys which have no
3268 * symlink in /dev/char. Let's return something
3269 * vaguely useful. */
3271 if (!(b = strdup(fn + 5)))
3281 if (startswith(s, "/dev/"))
3283 else if (startswith(s, "../"))
3301 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3307 /* This returns the first error we run into, but nevertheless
3308 * tries to go on. This closes the passed fd. */
3312 close_nointr_nofail(fd);
3314 return errno == ENOENT ? 0 : -errno;
3319 union dirent_storage buf;
3320 bool is_dir, keep_around;
3324 r = readdir_r(d, &buf.de, &de);
3325 if (r != 0 && ret == 0) {
3333 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3336 if (de->d_type == DT_UNKNOWN ||
3338 (de->d_type == DT_DIR && root_dev)) {
3339 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3340 if (ret == 0 && errno != ENOENT)
3345 is_dir = S_ISDIR(st.st_mode);
3348 (st.st_uid == 0 || st.st_uid == getuid()) &&
3349 (st.st_mode & S_ISVTX);
3351 is_dir = de->d_type == DT_DIR;
3352 keep_around = false;
3358 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3359 if (root_dev && st.st_dev != root_dev->st_dev)
3362 subdir_fd = openat(fd, de->d_name,
3363 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3364 if (subdir_fd < 0) {
3365 if (ret == 0 && errno != ENOENT)
3370 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3371 if (r < 0 && ret == 0)
3375 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3376 if (ret == 0 && errno != ENOENT)
3380 } else if (!only_dirs && !keep_around) {
3382 if (unlinkat(fd, de->d_name, 0) < 0) {
3383 if (ret == 0 && errno != ENOENT)
3394 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3399 if (fstatfs(fd, &s) < 0) {
3400 close_nointr_nofail(fd);
3404 /* We refuse to clean disk file systems with this call. This
3405 * is extra paranoia just to be sure we never ever remove
3408 if (s.f_type != TMPFS_MAGIC &&
3409 s.f_type != RAMFS_MAGIC) {
3410 log_error("Attempted to remove disk file system, and we can't allow that.");
3411 close_nointr_nofail(fd);
3415 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3418 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3424 /* We refuse to clean the root file system with this
3425 * call. This is extra paranoia to never cause a really
3426 * seriously broken system. */
3427 if (path_equal(path, "/")) {
3428 log_error("Attempted to remove entire root file system, and we can't allow that.");
3432 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3435 if (errno != ENOTDIR)
3439 if (statfs(path, &s) < 0)
3442 if (s.f_type != TMPFS_MAGIC &&
3443 s.f_type != RAMFS_MAGIC) {
3444 log_error("Attempted to remove disk file system, and we can't allow that.");
3449 if (delete_root && !only_dirs)
3450 if (unlink(path) < 0 && errno != ENOENT)
3457 if (fstatfs(fd, &s) < 0) {
3458 close_nointr_nofail(fd);
3462 if (s.f_type != TMPFS_MAGIC &&
3463 s.f_type != RAMFS_MAGIC) {
3464 log_error("Attempted to remove disk file system, and we can't allow that.");
3465 close_nointr_nofail(fd);
3470 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3473 if (honour_sticky && file_is_priv_sticky(path) > 0)
3476 if (rmdir(path) < 0 && errno != ENOENT) {
3485 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3486 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3489 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3490 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3493 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3496 /* Under the assumption that we are running privileged we
3497 * first change the access mode and only then hand out
3498 * ownership to avoid a window where access is too open. */
3500 if (mode != (mode_t) -1)
3501 if (chmod(path, mode) < 0)
3504 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3505 if (chown(path, uid, gid) < 0)
3511 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3514 /* Under the assumption that we are running privileged we
3515 * first change the access mode and only then hand out
3516 * ownership to avoid a window where access is too open. */
3518 if (fchmod(fd, mode) < 0)
3521 if (fchown(fd, uid, gid) < 0)
3527 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3531 /* Allocates the cpuset in the right size */
3534 if (!(r = CPU_ALLOC(n)))
3537 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3538 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3548 if (errno != EINVAL)
3555 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3556 static const char status_indent[] = " "; /* "[" STATUS "] " */
3557 _cleanup_free_ char *s = NULL;
3558 _cleanup_close_ int fd = -1;
3559 struct iovec iovec[5];
3564 /* This is independent of logging, as status messages are
3565 * optional and go exclusively to the console. */
3567 if (vasprintf(&s, format, ap) < 0)
3570 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3583 sl = status ? sizeof(status_indent)-1 : 0;
3589 e = ellipsize(s, emax, 75);
3599 if (!isempty(status)) {
3600 IOVEC_SET_STRING(iovec[n++], "[");
3601 IOVEC_SET_STRING(iovec[n++], status);
3602 IOVEC_SET_STRING(iovec[n++], "] ");
3604 IOVEC_SET_STRING(iovec[n++], status_indent);
3607 IOVEC_SET_STRING(iovec[n++], s);
3608 IOVEC_SET_STRING(iovec[n++], "\n");
3610 if (writev(fd, iovec, n) < 0)
3616 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3622 va_start(ap, format);
3623 r = status_vprintf(status, ellipse, format, ap);
3629 int status_welcome(void) {
3631 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3633 r = parse_env_file("/etc/os-release", NEWLINE,
3634 "PRETTY_NAME", &pretty_name,
3635 "ANSI_COLOR", &ansi_color,
3637 if (r < 0 && r != -ENOENT)
3638 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3640 return status_printf(NULL, false,
3641 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3642 isempty(ansi_color) ? "1" : ansi_color,
3643 isempty(pretty_name) ? "Linux" : pretty_name);
3646 char *replace_env(const char *format, char **env) {
3653 const char *e, *word = format;
3658 for (e = format; *e; e ++) {
3669 if (!(k = strnappend(r, word, e-word-1)))
3678 } else if (*e == '$') {
3679 if (!(k = strnappend(r, word, e-word)))
3695 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3698 if (!(k = strappend(r, t)))
3711 if (!(k = strnappend(r, word, e-word)))
3722 char **replace_env_argv(char **argv, char **env) {
3724 unsigned k = 0, l = 0;
3726 l = strv_length(argv);
3728 if (!(r = new(char*, l+1)))
3731 STRV_FOREACH(i, argv) {
3733 /* If $FOO appears as single word, replace it by the split up variable */
3734 if ((*i)[0] == '$' && (*i)[1] != '{') {
3739 if ((e = strv_env_get(env, *i+1))) {
3741 if (!(m = strv_split_quoted(e))) {
3752 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3761 memcpy(r + k, m, q * sizeof(char*));
3769 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3770 if (!(r[k++] = replace_env(*i, env))) {
3780 int fd_columns(int fd) {
3784 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3793 unsigned columns(void) {
3797 if (_likely_(cached_columns > 0))
3798 return cached_columns;
3801 e = getenv("COLUMNS");
3806 c = fd_columns(STDOUT_FILENO);
3815 /* intended to be used as a SIGWINCH sighandler */
3816 void columns_cache_reset(int signum) {
3821 static int cached_on_tty = -1;
3823 if (_unlikely_(cached_on_tty < 0))
3824 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3826 return cached_on_tty;
3829 int fd_lines(int fd) {
3833 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3842 unsigned lines(void) {
3843 static __thread int parsed_lines = 0;
3846 if (_likely_(parsed_lines > 0))
3847 return parsed_lines;
3849 e = getenv("LINES");
3851 parsed_lines = atoi(e);
3853 if (parsed_lines <= 0)
3854 parsed_lines = fd_lines(STDOUT_FILENO);
3856 if (parsed_lines <= 0)
3859 return parsed_lines;
3862 int running_in_chroot(void) {
3868 /* Only works as root */
3870 if (stat("/proc/1/root", &a) < 0)
3873 if (stat("/", &b) < 0)
3877 a.st_dev != b.st_dev ||
3878 a.st_ino != b.st_ino;
3881 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3886 assert(percent <= 100);
3887 assert(new_length >= 3);
3889 if (old_length <= 3 || old_length <= new_length)
3890 return strndup(s, old_length);
3892 r = new0(char, new_length+1);
3896 x = (new_length * percent) / 100;
3898 if (x > new_length - 3)
3906 s + old_length - (new_length - x - 3),
3907 new_length - x - 3);
3912 char *ellipsize(const char *s, size_t length, unsigned percent) {
3913 return ellipsize_mem(s, strlen(s), length, percent);
3916 int touch(const char *path) {
3921 /* This just opens the file for writing, ensuring it
3922 * exists. It doesn't call utimensat() the way /usr/bin/touch
3925 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3929 close_nointr_nofail(fd);
3933 char *unquote(const char *s, const char* quotes) {
3937 /* This is rather stupid, simply removes the heading and
3938 * trailing quotes if there is one. Doesn't care about
3939 * escaping or anything. We should make this smarter one
3946 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3947 return strndup(s+1, l-2);
3952 char *normalize_env_assignment(const char *s) {
3953 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3956 eq = strchr(s, '=');
3968 memmove(r, t, strlen(t) + 1);
3972 name = strndup(s, eq - s);
3980 value = unquote(strstrip(p), QUOTES);
3984 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3990 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4001 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4013 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4020 r = wait_for_terminate(pid, &status);
4022 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4026 if (status.si_code == CLD_EXITED) {
4027 if (status.si_status != 0) {
4028 log_warning("%s failed with error code %i.", name, status.si_status);
4029 return status.si_status;
4032 log_debug("%s succeeded.", name);
4035 } else if (status.si_code == CLD_KILLED ||
4036 status.si_code == CLD_DUMPED) {
4038 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4042 log_warning("%s failed due to unknown reason.", name);
4046 _noreturn_ void freeze(void) {
4048 /* Make sure nobody waits for us on a socket anymore */
4049 close_all_fds(NULL, 0);
4057 bool null_or_empty(struct stat *st) {
4060 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4063 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4069 int null_or_empty_path(const char *fn) {
4074 if (stat(fn, &st) < 0)
4077 return null_or_empty(&st);
4080 DIR *xopendirat(int fd, const char *name, int flags) {
4084 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4090 close_nointr_nofail(nfd);
4097 int signal_from_string_try_harder(const char *s) {
4101 signo = signal_from_string(s);
4103 if (startswith(s, "SIG"))
4104 return signal_from_string(s+3);
4109 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4115 if (!dual_timestamp_is_set(t))
4118 fprintf(f, "%s=%llu %llu\n",
4120 (unsigned long long) t->realtime,
4121 (unsigned long long) t->monotonic);
4124 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4125 unsigned long long a, b;
4130 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4131 log_debug("Failed to parse finish timestamp value %s", value);
4138 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4142 /* FIXME: to follow udev's logic 100% we need to leave valid
4143 * UTF8 chars unescaped */
4145 u = unquote(tagvalue, "\"\'");
4149 t = xescape(u, "/ ");
4155 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4164 char *fstab_node_to_udev_node(const char *p) {
4167 if (startswith(p, "LABEL="))
4168 return tag_to_udev_node(p+6, "label");
4170 if (startswith(p, "UUID="))
4171 return tag_to_udev_node(p+5, "uuid");
4173 if (startswith(p, "PARTUUID="))
4174 return tag_to_udev_node(p+9, "partuuid");
4176 if (startswith(p, "PARTLABEL="))
4177 return tag_to_udev_node(p+10, "partlabel");
4182 bool tty_is_vc(const char *tty) {
4185 if (startswith(tty, "/dev/"))
4188 return vtnr_from_tty(tty) >= 0;
4191 bool tty_is_console(const char *tty) {
4194 if (startswith(tty, "/dev/"))
4197 return streq(tty, "console");
4200 int vtnr_from_tty(const char *tty) {
4205 if (startswith(tty, "/dev/"))
4208 if (!startswith(tty, "tty") )
4211 if (tty[3] < '0' || tty[3] > '9')
4214 r = safe_atoi(tty+3, &i);
4218 if (i < 0 || i > 63)
4224 bool tty_is_vc_resolve(const char *tty) {
4225 char *active = NULL;
4230 if (startswith(tty, "/dev/"))
4233 /* Resolve where /dev/console is pointing to, if /sys is
4234 * actually ours (i.e. not read-only-mounted which is a sign
4235 * for container setups) */
4236 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4237 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4238 /* If multiple log outputs are configured the
4239 * last one is what /dev/console points to */
4240 tty = strrchr(active, ' ');
4253 const char *default_term_for_tty(const char *tty) {
4256 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4259 bool dirent_is_file(const struct dirent *de) {
4262 if (ignore_file(de->d_name))
4265 if (de->d_type != DT_REG &&
4266 de->d_type != DT_LNK &&
4267 de->d_type != DT_UNKNOWN)
4273 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4276 if (de->d_type != DT_REG &&
4277 de->d_type != DT_LNK &&
4278 de->d_type != DT_UNKNOWN)
4281 if (ignore_file_allow_backup(de->d_name))
4284 return endswith(de->d_name, suffix);
4287 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4290 Hashmap *pids = NULL;
4294 /* Executes all binaries in a directory in parallel and waits
4295 * until all they all finished. */
4298 if (!(_d = opendir(directory))) {
4300 if (errno == ENOENT)
4303 log_error("Failed to enumerate directory %s: %m", directory);
4310 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4311 log_error("Failed to allocate set.");
4315 while ((de = readdir(d))) {
4320 if (!dirent_is_file(de))
4323 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4328 if ((pid = fork()) < 0) {
4329 log_error("Failed to fork: %m");
4347 log_error("Failed to execute %s: %m", path);
4348 _exit(EXIT_FAILURE);
4351 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4353 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4354 log_error("Failed to add PID to set: %s", strerror(-k));
4359 while (!hashmap_isempty(pids)) {
4360 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4365 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4370 log_error("waitid() failed: %m");
4374 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4375 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4376 if (si.si_code == CLD_EXITED)
4377 log_error("%s exited with exit status %i.", path, si.si_status);
4379 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4381 log_debug("%s exited successfully.", path);
4392 hashmap_free_free(pids);
4395 int kill_and_sigcont(pid_t pid, int sig) {
4398 r = kill(pid, sig) < 0 ? -errno : 0;
4406 bool nulstr_contains(const char*nulstr, const char *needle) {
4412 NULSTR_FOREACH(i, nulstr)
4413 if (streq(i, needle))
4419 bool plymouth_running(void) {
4420 return access("/run/plymouth/pid", F_OK) >= 0;
4423 char* strshorten(char *s, size_t l) {
4432 static bool hostname_valid_char(char c) {
4434 (c >= 'a' && c <= 'z') ||
4435 (c >= 'A' && c <= 'Z') ||
4436 (c >= '0' && c <= '9') ||
4442 bool hostname_is_valid(const char *s) {
4448 for (p = s; *p; p++)
4449 if (!hostname_valid_char(*p))
4452 if (p-s > HOST_NAME_MAX)
4458 char* hostname_cleanup(char *s) {
4461 for (p = s, d = s; *p; p++)
4462 if ((*p >= 'a' && *p <= 'z') ||
4463 (*p >= 'A' && *p <= 'Z') ||
4464 (*p >= '0' && *p <= '9') ||
4472 strshorten(s, HOST_NAME_MAX);
4476 int pipe_eof(int fd) {
4477 struct pollfd pollfd;
4482 pollfd.events = POLLIN|POLLHUP;
4484 r = poll(&pollfd, 1, 0);
4491 return pollfd.revents & POLLHUP;
4494 int fd_wait_for_event(int fd, int event, usec_t t) {
4495 struct pollfd pollfd;
4500 pollfd.events = event;
4502 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4509 return pollfd.revents;
4512 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4523 t = new(char, strlen(path) + 1 + 6 + 1);
4527 fn = path_get_file_name(path);
4531 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4533 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4539 f = fdopen(fd, "we");
4552 int terminal_vhangup_fd(int fd) {
4555 if (ioctl(fd, TIOCVHANGUP) < 0)
4561 int terminal_vhangup(const char *name) {
4564 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4568 r = terminal_vhangup_fd(fd);
4569 close_nointr_nofail(fd);
4574 int vt_disallocate(const char *name) {
4578 /* Deallocate the VT if possible. If not possible
4579 * (i.e. because it is the active one), at least clear it
4580 * entirely (including the scrollback buffer) */
4582 if (!startswith(name, "/dev/"))
4585 if (!tty_is_vc(name)) {
4586 /* So this is not a VT. I guess we cannot deallocate
4587 * it then. But let's at least clear the screen */
4589 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4594 "\033[r" /* clear scrolling region */
4595 "\033[H" /* move home */
4596 "\033[2J", /* clear screen */
4598 close_nointr_nofail(fd);
4603 if (!startswith(name, "/dev/tty"))
4606 r = safe_atou(name+8, &u);
4613 /* Try to deallocate */
4614 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4618 r = ioctl(fd, VT_DISALLOCATE, u);
4619 close_nointr_nofail(fd);
4627 /* Couldn't deallocate, so let's clear it fully with
4629 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4634 "\033[r" /* clear scrolling region */
4635 "\033[H" /* move home */
4636 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4638 close_nointr_nofail(fd);
4643 int copy_file(const char *from, const char *to) {
4649 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4653 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4655 close_nointr_nofail(fdf);
4663 n = read(fdf, buf, sizeof(buf));
4667 close_nointr_nofail(fdf);
4678 k = loop_write(fdt, buf, n, false);
4680 r = k < 0 ? k : (errno ? -errno : -EIO);
4682 close_nointr_nofail(fdf);
4690 close_nointr_nofail(fdf);
4691 r = close_nointr(fdt);
4701 int symlink_atomic(const char *from, const char *to) {
4703 _cleanup_free_ char *t;
4706 unsigned long long ull;
4713 t = new(char, strlen(to) + 1 + 16 + 1);
4717 fn = path_get_file_name(to);
4721 x = stpcpy(t+k+1, fn);
4724 for (i = 0; i < 16; i++) {
4725 *(x++) = hexchar(ull & 0xF);
4731 if (symlink(from, t) < 0)
4734 if (rename(t, to) < 0) {
4743 bool display_is_local(const char *display) {
4747 display[0] == ':' &&
4748 display[1] >= '0' &&
4752 int socket_from_display(const char *display, char **path) {
4759 if (!display_is_local(display))
4762 k = strspn(display+1, "0123456789");
4764 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4768 c = stpcpy(f, "/tmp/.X11-unix/X");
4769 memcpy(c, display+1, k);
4778 const char **username,
4779 uid_t *uid, gid_t *gid,
4781 const char **shell) {
4789 /* We enforce some special rules for uid=0: in order to avoid
4790 * NSS lookups for root we hardcode its data. */
4792 if (streq(*username, "root") || streq(*username, "0")) {
4810 if (parse_uid(*username, &u) >= 0) {
4814 /* If there are multiple users with the same id, make
4815 * sure to leave $USER to the configured value instead
4816 * of the first occurrence in the database. However if
4817 * the uid was configured by a numeric uid, then let's
4818 * pick the real username from /etc/passwd. */
4820 *username = p->pw_name;
4823 p = getpwnam(*username);
4827 return errno != 0 ? -errno : -ESRCH;
4839 *shell = p->pw_shell;
4844 int get_group_creds(const char **groupname, gid_t *gid) {
4850 /* We enforce some special rules for gid=0: in order to avoid
4851 * NSS lookups for root we hardcode its data. */
4853 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4854 *groupname = "root";
4862 if (parse_gid(*groupname, &id) >= 0) {
4867 *groupname = g->gr_name;
4870 g = getgrnam(*groupname);
4874 return errno != 0 ? -errno : -ESRCH;
4882 int in_group(const char *name) {
4884 int ngroups_max, r, i;
4886 r = get_group_creds(&name, &gid);
4890 if (getgid() == gid)
4893 if (getegid() == gid)
4896 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4897 assert(ngroups_max > 0);
4899 gids = alloca(sizeof(gid_t) * ngroups_max);
4901 r = getgroups(ngroups_max, gids);
4905 for (i = 0; i < r; i++)
4912 int glob_exists(const char *path) {
4920 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4922 if (k == GLOB_NOMATCH)
4924 else if (k == GLOB_NOSPACE)
4927 r = !strv_isempty(g.gl_pathv);
4929 r = errno ? -errno : -EIO;
4936 int dirent_ensure_type(DIR *d, struct dirent *de) {
4942 if (de->d_type != DT_UNKNOWN)
4945 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4949 S_ISREG(st.st_mode) ? DT_REG :
4950 S_ISDIR(st.st_mode) ? DT_DIR :
4951 S_ISLNK(st.st_mode) ? DT_LNK :
4952 S_ISFIFO(st.st_mode) ? DT_FIFO :
4953 S_ISSOCK(st.st_mode) ? DT_SOCK :
4954 S_ISCHR(st.st_mode) ? DT_CHR :
4955 S_ISBLK(st.st_mode) ? DT_BLK :
4961 int in_search_path(const char *path, char **search) {
4965 r = path_get_parent(path, &parent);
4971 STRV_FOREACH(i, search) {
4972 if (path_equal(parent, *i)) {
4983 int get_files_in_directory(const char *path, char ***list) {
4991 /* Returns all files in a directory in *list, and the number
4992 * of files as return value. If list is NULL returns only the
5001 union dirent_storage buf;
5004 k = readdir_r(d, &buf.de, &de);
5013 dirent_ensure_type(d, de);
5015 if (!dirent_is_file(de))
5019 if ((unsigned) r >= n) {
5023 t = realloc(l, sizeof(char*) * n);
5032 assert((unsigned) r < n);
5034 l[r] = strdup(de->d_name);
5058 char *strjoin(const char *x, ...) {
5072 t = va_arg(ap, const char *);
5077 if (n > ((size_t) -1) - l) {
5101 t = va_arg(ap, const char *);
5115 bool is_main_thread(void) {
5116 static __thread int cached = 0;
5118 if (_unlikely_(cached == 0))
5119 cached = getpid() == gettid() ? 1 : -1;
5124 int block_get_whole_disk(dev_t d, dev_t *ret) {
5131 /* If it has a queue this is good enough for us */
5132 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5135 r = access(p, F_OK);
5143 /* If it is a partition find the originating device */
5144 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5147 r = access(p, F_OK);
5153 /* Get parent dev_t */
5154 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5157 r = read_one_line_file(p, &s);
5163 r = sscanf(s, "%u:%u", &m, &n);
5169 /* Only return this if it is really good enough for us. */
5170 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5173 r = access(p, F_OK);
5177 *ret = makedev(m, n);
5184 int file_is_priv_sticky(const char *p) {
5189 if (lstat(p, &st) < 0)
5193 (st.st_uid == 0 || st.st_uid == getuid()) &&
5194 (st.st_mode & S_ISVTX);
5197 static const char *const ioprio_class_table[] = {
5198 [IOPRIO_CLASS_NONE] = "none",
5199 [IOPRIO_CLASS_RT] = "realtime",
5200 [IOPRIO_CLASS_BE] = "best-effort",
5201 [IOPRIO_CLASS_IDLE] = "idle"
5204 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5206 static const char *const sigchld_code_table[] = {
5207 [CLD_EXITED] = "exited",
5208 [CLD_KILLED] = "killed",
5209 [CLD_DUMPED] = "dumped",
5210 [CLD_TRAPPED] = "trapped",
5211 [CLD_STOPPED] = "stopped",
5212 [CLD_CONTINUED] = "continued",
5215 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5217 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5218 [LOG_FAC(LOG_KERN)] = "kern",
5219 [LOG_FAC(LOG_USER)] = "user",
5220 [LOG_FAC(LOG_MAIL)] = "mail",
5221 [LOG_FAC(LOG_DAEMON)] = "daemon",
5222 [LOG_FAC(LOG_AUTH)] = "auth",
5223 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5224 [LOG_FAC(LOG_LPR)] = "lpr",
5225 [LOG_FAC(LOG_NEWS)] = "news",
5226 [LOG_FAC(LOG_UUCP)] = "uucp",
5227 [LOG_FAC(LOG_CRON)] = "cron",
5228 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5229 [LOG_FAC(LOG_FTP)] = "ftp",
5230 [LOG_FAC(LOG_LOCAL0)] = "local0",
5231 [LOG_FAC(LOG_LOCAL1)] = "local1",
5232 [LOG_FAC(LOG_LOCAL2)] = "local2",
5233 [LOG_FAC(LOG_LOCAL3)] = "local3",
5234 [LOG_FAC(LOG_LOCAL4)] = "local4",
5235 [LOG_FAC(LOG_LOCAL5)] = "local5",
5236 [LOG_FAC(LOG_LOCAL6)] = "local6",
5237 [LOG_FAC(LOG_LOCAL7)] = "local7"
5240 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5242 static const char *const log_level_table[] = {
5243 [LOG_EMERG] = "emerg",
5244 [LOG_ALERT] = "alert",
5245 [LOG_CRIT] = "crit",
5247 [LOG_WARNING] = "warning",
5248 [LOG_NOTICE] = "notice",
5249 [LOG_INFO] = "info",
5250 [LOG_DEBUG] = "debug"
5253 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5255 static const char* const sched_policy_table[] = {
5256 [SCHED_OTHER] = "other",
5257 [SCHED_BATCH] = "batch",
5258 [SCHED_IDLE] = "idle",
5259 [SCHED_FIFO] = "fifo",
5263 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5265 static const char* const rlimit_table[] = {
5266 [RLIMIT_CPU] = "LimitCPU",
5267 [RLIMIT_FSIZE] = "LimitFSIZE",
5268 [RLIMIT_DATA] = "LimitDATA",
5269 [RLIMIT_STACK] = "LimitSTACK",
5270 [RLIMIT_CORE] = "LimitCORE",
5271 [RLIMIT_RSS] = "LimitRSS",
5272 [RLIMIT_NOFILE] = "LimitNOFILE",
5273 [RLIMIT_AS] = "LimitAS",
5274 [RLIMIT_NPROC] = "LimitNPROC",
5275 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5276 [RLIMIT_LOCKS] = "LimitLOCKS",
5277 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5278 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5279 [RLIMIT_NICE] = "LimitNICE",
5280 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5281 [RLIMIT_RTTIME] = "LimitRTTIME"
5284 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5286 static const char* const ip_tos_table[] = {
5287 [IPTOS_LOWDELAY] = "low-delay",
5288 [IPTOS_THROUGHPUT] = "throughput",
5289 [IPTOS_RELIABILITY] = "reliability",
5290 [IPTOS_LOWCOST] = "low-cost",
5293 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5295 static const char *const __signal_table[] = {
5312 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5323 [SIGVTALRM] = "VTALRM",
5325 [SIGWINCH] = "WINCH",
5331 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5333 const char *signal_to_string(int signo) {
5334 static __thread char buf[12];
5337 name = __signal_to_string(signo);
5341 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5342 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5344 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5349 int signal_from_string(const char *s) {
5354 signo = __signal_from_string(s);
5358 if (startswith(s, "RTMIN+")) {
5362 if (safe_atou(s, &u) >= 0) {
5363 signo = (int) u + offset;
5364 if (signo > 0 && signo < _NSIG)
5370 bool kexec_loaded(void) {
5371 bool loaded = false;
5374 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5382 int strdup_or_null(const char *a, char **b) {
5400 int prot_from_flags(int flags) {
5402 switch (flags & O_ACCMODE) {
5411 return PROT_READ|PROT_WRITE;
5418 char *format_bytes(char *buf, size_t l, off_t t) {
5421 static const struct {
5425 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5426 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5427 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5428 { "G", 1024ULL*1024ULL*1024ULL },
5429 { "M", 1024ULL*1024ULL },
5433 for (i = 0; i < ELEMENTSOF(table); i++) {
5435 if (t >= table[i].factor) {
5438 (unsigned long long) (t / table[i].factor),
5439 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5446 snprintf(buf, l, "%lluB", (unsigned long long) t);
5454 void* memdup(const void *p, size_t l) {
5467 int fd_inc_sndbuf(int fd, size_t n) {
5469 socklen_t l = sizeof(value);
5471 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5473 l == sizeof(value) &&
5474 (size_t) value >= n*2)
5478 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5485 int fd_inc_rcvbuf(int fd, size_t n) {
5487 socklen_t l = sizeof(value);
5489 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5491 l == sizeof(value) &&
5492 (size_t) value >= n*2)
5496 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5503 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5504 pid_t parent_pid, agent_pid;
5506 bool stdout_is_tty, stderr_is_tty;
5514 parent_pid = getpid();
5516 /* Spawns a temporary TTY agent, making sure it goes away when
5523 if (agent_pid != 0) {
5530 * Make sure the agent goes away when the parent dies */
5531 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5532 _exit(EXIT_FAILURE);
5534 /* Check whether our parent died before we were able
5535 * to set the death signal */
5536 if (getppid() != parent_pid)
5537 _exit(EXIT_SUCCESS);
5539 /* Don't leak fds to the agent */
5540 close_all_fds(except, n_except);
5542 stdout_is_tty = isatty(STDOUT_FILENO);
5543 stderr_is_tty = isatty(STDERR_FILENO);
5545 if (!stdout_is_tty || !stderr_is_tty) {
5546 /* Detach from stdout/stderr. and reopen
5547 * /dev/tty for them. This is important to
5548 * ensure that when systemctl is started via
5549 * popen() or a similar call that expects to
5550 * read EOF we actually do generate EOF and
5551 * not delay this indefinitely by because we
5552 * keep an unused copy of stdin around. */
5553 fd = open("/dev/tty", O_WRONLY);
5555 log_error("Failed to open /dev/tty: %m");
5556 _exit(EXIT_FAILURE);
5560 dup2(fd, STDOUT_FILENO);
5563 dup2(fd, STDERR_FILENO);
5569 /* Count arguments */
5571 for (n = 0; va_arg(ap, char*); n++)
5576 l = alloca(sizeof(char *) * (n + 1));
5578 /* Fill in arguments */
5580 for (i = 0; i <= n; i++)
5581 l[i] = va_arg(ap, char*);
5585 _exit(EXIT_FAILURE);
5588 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5589 struct rlimit highest, fixed;
5593 if (setrlimit(resource, rlim) >= 0)
5599 /* So we failed to set the desired setrlimit, then let's try
5600 * to get as close as we can */
5601 assert_se(getrlimit(resource, &highest) == 0);
5603 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5604 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5606 if (setrlimit(resource, &fixed) < 0)
5612 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5613 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5625 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5628 f = fopen(path, "re");
5636 char line[LINE_MAX];
5639 for (i = 0; i < sizeof(line)-1; i++) {
5643 if (_unlikely_(c == EOF)) {
5653 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5654 value = strdup(line + l + 1);
5674 int can_sleep(const char *type) {
5678 _cleanup_free_ char *p = NULL;
5682 r = read_one_line_file("/sys/power/state", &p);
5684 return r == -ENOENT ? 0 : r;
5687 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5688 if (l == k && memcmp(w, type, l) == 0)
5694 bool is_valid_documentation_url(const char *url) {
5697 if (startswith(url, "http://") && url[7])
5700 if (startswith(url, "https://") && url[8])
5703 if (startswith(url, "file:") && url[5])
5706 if (startswith(url, "info:") && url[5])
5709 if (startswith(url, "man:") && url[4])
5715 bool in_initrd(void) {
5716 static __thread int saved = -1;
5722 /* We make two checks here:
5724 * 1. the flag file /etc/initrd-release must exist
5725 * 2. the root file system must be a memory file system
5727 * The second check is extra paranoia, since misdetecting an
5728 * initrd can have bad bad consequences due the initrd
5729 * emptying when transititioning to the main systemd.
5732 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5733 statfs("/", &s) >= 0 &&
5734 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5739 void warn_melody(void) {
5740 _cleanup_close_ int fd = -1;
5742 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5746 /* Yeah, this is synchronous. Kinda sucks. But well... */
5748 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5749 usleep(125*USEC_PER_MSEC);
5751 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5752 usleep(125*USEC_PER_MSEC);
5754 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5755 usleep(125*USEC_PER_MSEC);
5757 ioctl(fd, KIOCSOUND, 0);
5760 int make_console_stdio(void) {
5763 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5765 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5767 log_error("Failed to acquire terminal: %s", strerror(-fd));
5773 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5780 int get_home_dir(char **_h) {
5788 /* Take the user specified one */
5799 /* Hardcode home directory for root to avoid NSS */
5802 h = strdup("/root");
5810 /* Check the database... */
5814 return errno ? -errno : -ESRCH;
5816 if (!path_is_absolute(p->pw_dir))
5819 h = strdup(p->pw_dir);
5827 int get_shell(char **_sh) {
5835 /* Take the user specified one */
5836 e = getenv("SHELL");
5846 /* Hardcode home directory for root to avoid NSS */
5849 sh = strdup("/bin/sh");
5857 /* Check the database... */
5861 return errno ? -errno : -ESRCH;
5863 if (!path_is_absolute(p->pw_shell))
5866 sh = strdup(p->pw_shell);
5874 void freep(void *p) {
5878 void fclosep(FILE **f) {
5883 void closep(int *fd) {
5885 close_nointr_nofail(*fd);
5888 void closedirp(DIR **d) {
5893 void umaskp(mode_t *u) {
5897 bool filename_is_safe(const char *p) {
5911 if (strlen(p) > FILENAME_MAX)
5917 bool string_is_safe(const char *p) {
5922 for (t = p; *t; t++) {
5923 if (*t > 0 && *t < ' ')
5926 if (strchr("\\\"\'", *t))
5933 int parse_timestamp(const char *t, usec_t *usec) {
5937 usec_t plus = 0, minus = 0, ret;
5943 * 2012-09-22 16:34:22
5944 * 2012-09-22 16:34 (seconds will be set to 0)
5945 * 2012-09-22 (time will be set to 00:00:00)
5946 * 16:34:22 (date will be set to today)
5947 * 16:34 (date will be set to today, seconds to 0)
5949 * yesterday (time is set to 00:00:00)
5950 * today (time is set to 00:00:00)
5951 * tomorrow (time is set to 00:00:00)
5961 assert_se(localtime_r(&x, &tm));
5963 if (streq(t, "now"))
5966 else if (streq(t, "today")) {
5967 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5970 } else if (streq(t, "yesterday")) {
5972 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5975 } else if (streq(t, "tomorrow")) {
5977 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5980 } else if (t[0] == '+') {
5982 r = parse_usec(t+1, &plus);
5987 } else if (t[0] == '-') {
5989 r = parse_usec(t+1, &minus);
5997 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6002 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6007 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6014 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6021 k = strptime(t, "%y-%m-%d", &tm);
6023 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6028 k = strptime(t, "%Y-%m-%d", &tm);
6030 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6035 k = strptime(t, "%H:%M:%S", &tm);
6040 k = strptime(t, "%H:%M", &tm);
6050 if (x == (time_t) -1)
6053 ret = (usec_t) x * USEC_PER_SEC;