1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
67 #include "path-util.h"
68 #include "exit-status.h"
72 char **saved_argv = NULL;
74 static int parsed_columns = 0;
76 size_t page_size(void) {
77 static __thread size_t pgsz = 0;
80 if (_likely_(pgsz > 0))
83 r = sysconf(_SC_PAGESIZE);
90 bool streq_ptr(const char *a, const char *b) {
92 /* Like streq(), but tries to make sense of NULL pointers */
103 usec_t now(clockid_t clock_id) {
106 assert_se(clock_gettime(clock_id, &ts) == 0);
108 return timespec_load(&ts);
111 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
114 ts->realtime = now(CLOCK_REALTIME);
115 ts->monotonic = now(CLOCK_MONOTONIC);
120 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
129 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
131 ts->monotonic = now(CLOCK_MONOTONIC);
133 if ((int64_t) ts->monotonic > delta)
134 ts->monotonic -= delta;
142 usec_t timespec_load(const struct timespec *ts) {
146 (usec_t) ts->tv_sec * USEC_PER_SEC +
147 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
150 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
153 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
154 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
159 usec_t timeval_load(const struct timeval *tv) {
163 (usec_t) tv->tv_sec * USEC_PER_SEC +
164 (usec_t) tv->tv_usec;
167 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
170 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
171 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
176 bool endswith(const char *s, const char *postfix) {
183 pl = strlen(postfix);
191 return memcmp(s + sl - pl, postfix, pl) == 0;
194 bool startswith(const char *s, const char *prefix) {
209 return memcmp(s, prefix, pl) == 0;
212 bool startswith_no_case(const char *s, const char *prefix) {
228 for(i = 0; i < pl; ++i)
229 if (tolower(s[i]) != tolower(prefix[i]))
235 bool first_word(const char *s, const char *word) {
250 if (memcmp(s, word, wl) != 0)
254 strchr(WHITESPACE, s[wl]);
257 int close_nointr(int fd) {
272 void close_nointr_nofail(int fd) {
273 int saved_errno = errno;
275 /* like close_nointr() but cannot fail, and guarantees errno
278 assert_se(close_nointr(fd) == 0);
283 void close_many(const int fds[], unsigned n_fd) {
286 for (i = 0; i < n_fd; i++)
287 close_nointr_nofail(fds[i]);
290 int parse_boolean(const char *v) {
293 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
295 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
301 int parse_pid(const char *s, pid_t* ret_pid) {
302 unsigned long ul = 0;
309 r = safe_atolu(s, &ul);
315 if ((unsigned long) pid != ul)
325 int parse_uid(const char *s, uid_t* ret_uid) {
326 unsigned long ul = 0;
333 r = safe_atolu(s, &ul);
339 if ((unsigned long) uid != ul)
346 int safe_atou(const char *s, unsigned *ret_u) {
354 l = strtoul(s, &x, 0);
356 if (!x || *x || errno)
357 return errno ? -errno : -EINVAL;
359 if ((unsigned long) (unsigned) l != l)
362 *ret_u = (unsigned) l;
366 int safe_atoi(const char *s, int *ret_i) {
374 l = strtol(s, &x, 0);
376 if (!x || *x || errno)
377 return errno ? -errno : -EINVAL;
379 if ((long) (int) l != l)
386 int safe_atollu(const char *s, long long unsigned *ret_llu) {
388 unsigned long long l;
394 l = strtoull(s, &x, 0);
396 if (!x || *x || errno)
397 return errno ? -errno : -EINVAL;
403 int safe_atolli(const char *s, long long int *ret_lli) {
411 l = strtoll(s, &x, 0);
413 if (!x || *x || errno)
414 return errno ? -errno : -EINVAL;
420 /* Split a string into words. */
421 char *split(const char *c, size_t *l, const char *separator, char **state) {
424 current = *state ? *state : (char*) c;
426 if (!*current || *c == 0)
429 current += strspn(current, separator);
430 *l = strcspn(current, separator);
433 return (char*) current;
436 /* Split a string into words, but consider strings enclosed in '' and
437 * "" as words even if they include spaces. */
438 char *split_quoted(const char *c, size_t *l, char **state) {
440 bool escaped = false;
442 current = *state ? *state : (char*) c;
444 if (!*current || *c == 0)
447 current += strspn(current, WHITESPACE);
449 if (*current == '\'') {
452 for (e = current; *e; e++) {
462 *state = *e == 0 ? e : e+1;
463 } else if (*current == '\"') {
466 for (e = current; *e; e++) {
476 *state = *e == 0 ? e : e+1;
478 for (e = current; *e; e++) {
483 else if (strchr(WHITESPACE, *e))
490 return (char*) current;
493 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
495 _cleanup_fclose_ FILE *f = NULL;
496 char fn[PATH_MAX], line[LINE_MAX], *p;
502 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
509 if (!fgets(line, sizeof(line), f)) {
510 r = feof(f) ? -EIO : -errno;
515 /* Let's skip the pid and comm fields. The latter is enclosed
516 * in () but does not escape any () in its value, so let's
517 * skip over it manually */
519 p = strrchr(line, ')');
531 if ((long unsigned) (pid_t) ppid != ppid)
534 *_ppid = (pid_t) ppid;
539 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
540 _cleanup_fclose_ FILE *f = NULL;
541 char fn[PATH_MAX], line[LINE_MAX], *p;
546 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
553 if (!fgets(line, sizeof(line), f)) {
560 /* Let's skip the pid and comm fields. The latter is enclosed
561 * in () but does not escape any () in its value, so let's
562 * skip over it manually */
564 p = strrchr(line, ')');
586 "%*d " /* priority */
588 "%*d " /* num_threads */
589 "%*d " /* itrealvalue */
590 "%llu " /* starttime */,
597 int write_one_line_file(const char *fn, const char *line) {
598 _cleanup_fclose_ FILE *f = NULL;
608 if (fputs(line, f) < 0)
609 return errno ? -errno : -EIO;
611 if (!endswith(line, "\n"))
617 return errno ? -errno : -EIO;
622 int fchmod_umask(int fd, mode_t m) {
627 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
633 int write_one_line_file_atomic(const char *fn, const char *line) {
641 r = fopen_temporary(fn, &f, &p);
645 fchmod_umask(fileno(f), 0644);
648 if (fputs(line, f) < 0) {
653 if (!endswith(line, "\n"))
664 if (rename(p, fn) < 0)
680 int read_one_line_file(const char *fn, char **line) {
681 _cleanup_fclose_ FILE *f = NULL;
682 char t[LINE_MAX], *c;
691 if (!fgets(t, sizeof(t), f)) {
694 return errno ? -errno : -EIO;
708 int read_full_file(const char *fn, char **contents, size_t *size) {
709 _cleanup_fclose_ FILE *f = NULL;
711 _cleanup_free_ char *buf = NULL;
718 if (fstat(fileno(f), &st) < 0)
722 if (st.st_size > 4*1024*1024)
725 n = st.st_size > 0 ? st.st_size : LINE_MAX;
732 t = realloc(buf, n+1);
737 k = fread(buf + l, 1, n - l, f);
766 const char *separator, ...) {
769 char *contents = NULL, *p;
774 if ((r = read_full_file(fname, &contents, NULL)) < 0)
779 const char *key = NULL;
781 p += strspn(p, separator);
782 p += strspn(p, WHITESPACE);
787 if (!strchr(COMMENTS, *p)) {
791 va_start(ap, separator);
792 while ((key = va_arg(ap, char *))) {
796 value = va_arg(ap, char **);
799 if (strncmp(p, key, n) != 0 ||
804 n = strcspn(p, separator);
807 strchr(QUOTES, p[0]) &&
809 v = strndup(p+1, n-2);
820 /* return empty value strings as NULL */
837 p += strcspn(p, separator);
856 if (!(f = fopen(fname, "re")))
860 char l[LINE_MAX], *p, *u;
863 if (!fgets(l, sizeof(l), f)) {
876 if (strchr(COMMENTS, *p))
879 if (!(u = normalize_env_assignment(p))) {
884 t = strv_append(m, u);
910 int write_env_file(const char *fname, char **l) {
915 r = fopen_temporary(fname, &f, &p);
919 fchmod_umask(fileno(f), 0644);
935 if (rename(p, fname) < 0)
950 char *truncate_nl(char *s) {
953 s[strcspn(s, NEWLINE)] = 0;
957 int get_process_comm(pid_t pid, char **name) {
963 r = read_one_line_file("/proc/self/comm", name);
966 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
969 r = read_one_line_file(p, name);
976 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
983 assert(max_length > 0);
987 f = fopen("/proc/self/cmdline", "re");
990 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1000 r = new(char, max_length);
1008 while ((c = getc(f)) != EOF) {
1030 size_t n = MIN(left-1, 3U);
1031 memcpy(k, "...", n);
1038 /* Kernel threads have no argv[] */
1048 h = get_process_comm(pid, &t);
1052 r = strjoin("[", t, "]", NULL);
1063 int is_kernel_thread(pid_t pid) {
1073 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1082 count = fread(&c, 1, 1, f);
1086 /* Kernel threads have an empty cmdline */
1089 return eof ? 1 : -errno;
1094 int get_process_exe(pid_t pid, char **name) {
1100 r = readlink_malloc("/proc/self/exe", name);
1103 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1106 r = readlink_malloc(p, name);
1113 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1123 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1133 char line[LINE_MAX], *l;
1135 if (!fgets(line, sizeof(line), f)) {
1145 if (startswith(l, field)) {
1147 l += strspn(l, WHITESPACE);
1149 l[strcspn(l, WHITESPACE)] = 0;
1151 r = parse_uid(l, uid);
1164 int get_process_uid(pid_t pid, uid_t *uid) {
1165 return get_process_id(pid, "Uid:", uid);
1168 int get_process_gid(pid_t pid, gid_t *gid) {
1169 return get_process_id(pid, "Gid:", gid);
1172 char *strnappend(const char *s, const char *suffix, size_t b) {
1180 return strndup(suffix, b);
1189 if (b > ((size_t) -1) - a)
1192 r = new(char, a+b+1);
1197 memcpy(r+a, suffix, b);
1203 char *strappend(const char *s, const char *suffix) {
1204 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1207 int readlink_malloc(const char *p, char **r) {
1217 if (!(c = new(char, l)))
1220 if ((n = readlink(p, c, l-1)) < 0) {
1226 if ((size_t) n < l-1) {
1237 int readlink_and_make_absolute(const char *p, char **r) {
1244 if ((j = readlink_malloc(p, &target)) < 0)
1247 k = file_in_same_dir(p, target);
1257 int readlink_and_canonicalize(const char *p, char **r) {
1264 j = readlink_and_make_absolute(p, &t);
1268 s = canonicalize_file_name(t);
1275 path_kill_slashes(*r);
1280 int reset_all_signal_handlers(void) {
1283 for (sig = 1; sig < _NSIG; sig++) {
1284 struct sigaction sa;
1286 if (sig == SIGKILL || sig == SIGSTOP)
1290 sa.sa_handler = SIG_DFL;
1291 sa.sa_flags = SA_RESTART;
1293 /* On Linux the first two RT signals are reserved by
1294 * glibc, and sigaction() will return EINVAL for them. */
1295 if ((sigaction(sig, &sa, NULL) < 0))
1296 if (errno != EINVAL)
1303 char *strstrip(char *s) {
1306 /* Drops trailing whitespace. Modifies the string in
1307 * place. Returns pointer to first non-space character */
1309 s += strspn(s, WHITESPACE);
1311 for (e = strchr(s, 0); e > s; e --)
1312 if (!strchr(WHITESPACE, e[-1]))
1320 char *delete_chars(char *s, const char *bad) {
1323 /* Drops all whitespace, regardless where in the string */
1325 for (f = s, t = s; *f; f++) {
1326 if (strchr(bad, *f))
1337 bool in_charset(const char *s, const char* charset) {
1343 for (i = s; *i; i++)
1344 if (!strchr(charset, *i))
1350 char *file_in_same_dir(const char *path, const char *filename) {
1357 /* This removes the last component of path and appends
1358 * filename, unless the latter is absolute anyway or the
1361 if (path_is_absolute(filename))
1362 return strdup(filename);
1364 if (!(e = strrchr(path, '/')))
1365 return strdup(filename);
1367 k = strlen(filename);
1368 if (!(r = new(char, e-path+1+k+1)))
1371 memcpy(r, path, e-path+1);
1372 memcpy(r+(e-path)+1, filename, k+1);
1377 int rmdir_parents(const char *path, const char *stop) {
1386 /* Skip trailing slashes */
1387 while (l > 0 && path[l-1] == '/')
1393 /* Skip last component */
1394 while (l > 0 && path[l-1] != '/')
1397 /* Skip trailing slashes */
1398 while (l > 0 && path[l-1] == '/')
1404 if (!(t = strndup(path, l)))
1407 if (path_startswith(stop, t)) {
1416 if (errno != ENOENT)
1424 char hexchar(int x) {
1425 static const char table[16] = "0123456789abcdef";
1427 return table[x & 15];
1430 int unhexchar(char c) {
1432 if (c >= '0' && c <= '9')
1435 if (c >= 'a' && c <= 'f')
1436 return c - 'a' + 10;
1438 if (c >= 'A' && c <= 'F')
1439 return c - 'A' + 10;
1444 char octchar(int x) {
1445 return '0' + (x & 7);
1448 int unoctchar(char c) {
1450 if (c >= '0' && c <= '7')
1456 char decchar(int x) {
1457 return '0' + (x % 10);
1460 int undecchar(char c) {
1462 if (c >= '0' && c <= '9')
1468 char *cescape(const char *s) {
1474 /* Does C style string escaping. */
1476 r = new(char, strlen(s)*4 + 1);
1480 for (f = s, t = r; *f; f++)
1526 /* For special chars we prefer octal over
1527 * hexadecimal encoding, simply because glib's
1528 * g_strescape() does the same */
1529 if ((*f < ' ') || (*f >= 127)) {
1531 *(t++) = octchar((unsigned char) *f >> 6);
1532 *(t++) = octchar((unsigned char) *f >> 3);
1533 *(t++) = octchar((unsigned char) *f);
1544 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1551 /* Undoes C style string escaping, and optionally prefixes it. */
1553 pl = prefix ? strlen(prefix) : 0;
1555 r = new(char, pl+length+1);
1560 memcpy(r, prefix, pl);
1562 for (f = s, t = r + pl; f < s + length; f++) {
1605 /* This is an extension of the XDG syntax files */
1610 /* hexadecimal encoding */
1613 a = unhexchar(f[1]);
1614 b = unhexchar(f[2]);
1616 if (a < 0 || b < 0) {
1617 /* Invalid escape code, let's take it literal then */
1621 *(t++) = (char) ((a << 4) | b);
1636 /* octal encoding */
1639 a = unoctchar(f[0]);
1640 b = unoctchar(f[1]);
1641 c = unoctchar(f[2]);
1643 if (a < 0 || b < 0 || c < 0) {
1644 /* Invalid escape code, let's take it literal then */
1648 *(t++) = (char) ((a << 6) | (b << 3) | c);
1656 /* premature end of string.*/
1661 /* Invalid escape code, let's take it literal then */
1673 char *cunescape_length(const char *s, size_t length) {
1674 return cunescape_length_with_prefix(s, length, NULL);
1677 char *cunescape(const char *s) {
1680 return cunescape_length(s, strlen(s));
1683 char *xescape(const char *s, const char *bad) {
1687 /* Escapes all chars in bad, in addition to \ and all special
1688 * chars, in \xFF style escaping. May be reversed with
1691 if (!(r = new(char, strlen(s)*4+1)))
1694 for (f = s, t = r; *f; f++) {
1696 if ((*f < ' ') || (*f >= 127) ||
1697 (*f == '\\') || strchr(bad, *f)) {
1700 *(t++) = hexchar(*f >> 4);
1701 *(t++) = hexchar(*f);
1711 char *bus_path_escape(const char *s) {
1717 /* Escapes all chars that D-Bus' object path cannot deal
1718 * with. Can be reverse with bus_path_unescape() */
1720 if (!(r = new(char, strlen(s)*3+1)))
1723 for (f = s, t = r; *f; f++) {
1725 if (!(*f >= 'A' && *f <= 'Z') &&
1726 !(*f >= 'a' && *f <= 'z') &&
1727 !(*f >= '0' && *f <= '9')) {
1729 *(t++) = hexchar(*f >> 4);
1730 *(t++) = hexchar(*f);
1740 char *bus_path_unescape(const char *f) {
1745 if (!(r = strdup(f)))
1748 for (t = r; *f; f++) {
1753 if ((a = unhexchar(f[1])) < 0 ||
1754 (b = unhexchar(f[2])) < 0) {
1755 /* Invalid escape code, let's take it literal then */
1758 *(t++) = (char) ((a << 4) | b);
1770 char *ascii_strlower(char *t) {
1775 for (p = t; *p; p++)
1776 if (*p >= 'A' && *p <= 'Z')
1777 *p = *p - 'A' + 'a';
1782 static bool ignore_file_allow_backup(const char *filename) {
1786 filename[0] == '.' ||
1787 streq(filename, "lost+found") ||
1788 streq(filename, "aquota.user") ||
1789 streq(filename, "aquota.group") ||
1790 endswith(filename, ".rpmnew") ||
1791 endswith(filename, ".rpmsave") ||
1792 endswith(filename, ".rpmorig") ||
1793 endswith(filename, ".dpkg-old") ||
1794 endswith(filename, ".dpkg-new") ||
1795 endswith(filename, ".swp");
1798 bool ignore_file(const char *filename) {
1801 if (endswith(filename, "~"))
1804 return ignore_file_allow_backup(filename);
1807 int fd_nonblock(int fd, bool nonblock) {
1812 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1816 flags |= O_NONBLOCK;
1818 flags &= ~O_NONBLOCK;
1820 if (fcntl(fd, F_SETFL, flags) < 0)
1826 int fd_cloexec(int fd, bool cloexec) {
1831 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1835 flags |= FD_CLOEXEC;
1837 flags &= ~FD_CLOEXEC;
1839 if (fcntl(fd, F_SETFD, flags) < 0)
1845 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1848 assert(n_fdset == 0 || fdset);
1850 for (i = 0; i < n_fdset; i++)
1857 int close_all_fds(const int except[], unsigned n_except) {
1862 assert(n_except == 0 || except);
1864 d = opendir("/proc/self/fd");
1869 /* When /proc isn't available (for example in chroots)
1870 * the fallback is brute forcing through the fd
1873 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1874 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1876 if (fd_in_set(fd, except, n_except))
1879 if (close_nointr(fd) < 0)
1880 if (errno != EBADF && r == 0)
1887 while ((de = readdir(d))) {
1890 if (ignore_file(de->d_name))
1893 if (safe_atoi(de->d_name, &fd) < 0)
1894 /* Let's better ignore this, just in case */
1903 if (fd_in_set(fd, except, n_except))
1906 if (close_nointr(fd) < 0) {
1907 /* Valgrind has its own FD and doesn't want to have it closed */
1908 if (errno != EBADF && r == 0)
1917 bool chars_intersect(const char *a, const char *b) {
1920 /* Returns true if any of the chars in a are in b. */
1921 for (p = a; *p; p++)
1928 char *format_timestamp(char *buf, size_t l, usec_t t) {
1938 sec = (time_t) (t / USEC_PER_SEC);
1940 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1946 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1949 n = now(CLOCK_REALTIME);
1951 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1956 if (d >= USEC_PER_YEAR)
1957 snprintf(buf, l, "%llu years and %llu months ago",
1958 (unsigned long long) (d / USEC_PER_YEAR),
1959 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1960 else if (d >= USEC_PER_MONTH)
1961 snprintf(buf, l, "%llu months and %llu days ago",
1962 (unsigned long long) (d / USEC_PER_MONTH),
1963 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1964 else if (d >= USEC_PER_WEEK)
1965 snprintf(buf, l, "%llu weeks and %llu days ago",
1966 (unsigned long long) (d / USEC_PER_WEEK),
1967 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1968 else if (d >= 2*USEC_PER_DAY)
1969 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1970 else if (d >= 25*USEC_PER_HOUR)
1971 snprintf(buf, l, "1 day and %lluh ago",
1972 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1973 else if (d >= 6*USEC_PER_HOUR)
1974 snprintf(buf, l, "%lluh ago",
1975 (unsigned long long) (d / USEC_PER_HOUR));
1976 else if (d >= USEC_PER_HOUR)
1977 snprintf(buf, l, "%lluh %llumin ago",
1978 (unsigned long long) (d / USEC_PER_HOUR),
1979 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1980 else if (d >= 5*USEC_PER_MINUTE)
1981 snprintf(buf, l, "%llumin ago",
1982 (unsigned long long) (d / USEC_PER_MINUTE));
1983 else if (d >= USEC_PER_MINUTE)
1984 snprintf(buf, l, "%llumin %llus ago",
1985 (unsigned long long) (d / USEC_PER_MINUTE),
1986 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1987 else if (d >= USEC_PER_SEC)
1988 snprintf(buf, l, "%llus ago",
1989 (unsigned long long) (d / USEC_PER_SEC));
1990 else if (d >= USEC_PER_MSEC)
1991 snprintf(buf, l, "%llums ago",
1992 (unsigned long long) (d / USEC_PER_MSEC));
1994 snprintf(buf, l, "%lluus ago",
1995 (unsigned long long) d);
1997 snprintf(buf, l, "now");
2003 char *format_timespan(char *buf, size_t l, usec_t t) {
2004 static const struct {
2008 { "w", USEC_PER_WEEK },
2009 { "d", USEC_PER_DAY },
2010 { "h", USEC_PER_HOUR },
2011 { "min", USEC_PER_MINUTE },
2012 { "s", USEC_PER_SEC },
2013 { "ms", USEC_PER_MSEC },
2023 if (t == (usec_t) -1)
2027 snprintf(p, l, "0");
2032 /* The result of this function can be parsed with parse_usec */
2034 for (i = 0; i < ELEMENTSOF(table); i++) {
2038 if (t < table[i].usec)
2044 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2045 n = MIN((size_t) k, l);
2058 bool fstype_is_network(const char *fstype) {
2059 static const char table[] =
2068 return nulstr_contains(table, fstype);
2072 _cleanup_close_ int fd;
2074 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2080 TIOCL_GETKMSGREDIRECT,
2084 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2087 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2090 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2096 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2097 struct termios old_termios, new_termios;
2099 char line[LINE_MAX];
2104 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2105 new_termios = old_termios;
2107 new_termios.c_lflag &= ~ICANON;
2108 new_termios.c_cc[VMIN] = 1;
2109 new_termios.c_cc[VTIME] = 0;
2111 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2114 if (t != (usec_t) -1) {
2115 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2116 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2121 k = fread(&c, 1, 1, f);
2123 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2129 *need_nl = c != '\n';
2136 if (t != (usec_t) -1)
2137 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2140 if (!fgets(line, sizeof(line), f))
2145 if (strlen(line) != 1)
2155 int ask(char *ret, const char *replies, const char *text, ...) {
2162 on_tty = isatty(STDOUT_FILENO);
2168 bool need_nl = true;
2171 fputs(ANSI_HIGHLIGHT_ON, stdout);
2178 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2182 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2185 if (r == -EBADMSG) {
2186 puts("Bad input, please try again.");
2197 if (strchr(replies, c)) {
2202 puts("Read unexpected character, please try again.");
2206 int reset_terminal_fd(int fd, bool switch_to_text) {
2207 struct termios termios;
2210 /* Set terminal to some sane defaults */
2214 /* We leave locked terminal attributes untouched, so that
2215 * Plymouth may set whatever it wants to set, and we don't
2216 * interfere with that. */
2218 /* Disable exclusive mode, just in case */
2219 ioctl(fd, TIOCNXCL);
2221 /* Switch to text mode */
2223 ioctl(fd, KDSETMODE, KD_TEXT);
2225 /* Enable console unicode mode */
2226 ioctl(fd, KDSKBMODE, K_UNICODE);
2228 if (tcgetattr(fd, &termios) < 0) {
2233 /* We only reset the stuff that matters to the software. How
2234 * hardware is set up we don't touch assuming that somebody
2235 * else will do that for us */
2237 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2238 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2239 termios.c_oflag |= ONLCR;
2240 termios.c_cflag |= CREAD;
2241 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2243 termios.c_cc[VINTR] = 03; /* ^C */
2244 termios.c_cc[VQUIT] = 034; /* ^\ */
2245 termios.c_cc[VERASE] = 0177;
2246 termios.c_cc[VKILL] = 025; /* ^X */
2247 termios.c_cc[VEOF] = 04; /* ^D */
2248 termios.c_cc[VSTART] = 021; /* ^Q */
2249 termios.c_cc[VSTOP] = 023; /* ^S */
2250 termios.c_cc[VSUSP] = 032; /* ^Z */
2251 termios.c_cc[VLNEXT] = 026; /* ^V */
2252 termios.c_cc[VWERASE] = 027; /* ^W */
2253 termios.c_cc[VREPRINT] = 022; /* ^R */
2254 termios.c_cc[VEOL] = 0;
2255 termios.c_cc[VEOL2] = 0;
2257 termios.c_cc[VTIME] = 0;
2258 termios.c_cc[VMIN] = 1;
2260 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2264 /* Just in case, flush all crap out */
2265 tcflush(fd, TCIOFLUSH);
2270 int reset_terminal(const char *name) {
2273 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2277 r = reset_terminal_fd(fd, true);
2278 close_nointr_nofail(fd);
2283 int open_terminal(const char *name, int mode) {
2288 * If a TTY is in the process of being closed opening it might
2289 * cause EIO. This is horribly awful, but unlikely to be
2290 * changed in the kernel. Hence we work around this problem by
2291 * retrying a couple of times.
2293 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2297 fd = open(name, mode);
2304 /* Max 1s in total */
2308 usleep(50 * USEC_PER_MSEC);
2317 close_nointr_nofail(fd);
2322 close_nointr_nofail(fd);
2329 int flush_fd(int fd) {
2330 struct pollfd pollfd;
2334 pollfd.events = POLLIN;
2341 if ((r = poll(&pollfd, 1, 0)) < 0) {
2352 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2357 if (errno == EAGAIN)
2368 int acquire_terminal(
2372 bool ignore_tiocstty_eperm,
2375 int fd = -1, notify = -1, r = 0, wd = -1;
2377 struct sigaction sa_old, sa_new;
2381 /* We use inotify to be notified when the tty is closed. We
2382 * create the watch before checking if we can actually acquire
2383 * it, so that we don't lose any event.
2385 * Note: strictly speaking this actually watches for the
2386 * device being closed, it does *not* really watch whether a
2387 * tty loses its controlling process. However, unless some
2388 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2389 * its tty otherwise this will not become a problem. As long
2390 * as the administrator makes sure not configure any service
2391 * on the same tty as an untrusted user this should not be a
2392 * problem. (Which he probably should not do anyway.) */
2394 if (timeout != (usec_t) -1)
2395 ts = now(CLOCK_MONOTONIC);
2397 if (!fail && !force) {
2398 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2404 wd = inotify_add_watch(notify, name, IN_CLOSE);
2413 r = flush_fd(notify);
2418 /* We pass here O_NOCTTY only so that we can check the return
2419 * value TIOCSCTTY and have a reliable way to figure out if we
2420 * successfully became the controlling process of the tty */
2421 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2425 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2426 * if we already own the tty. */
2428 sa_new.sa_handler = SIG_IGN;
2429 sa_new.sa_flags = SA_RESTART;
2430 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2432 /* First, try to get the tty */
2433 if (ioctl(fd, TIOCSCTTY, force) < 0)
2436 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2438 /* Sometimes it makes sense to ignore TIOCSCTTY
2439 * returning EPERM, i.e. when very likely we already
2440 * are have this controlling terminal. */
2441 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2444 if (r < 0 && (force || fail || r != -EPERM)) {
2453 assert(notify >= 0);
2456 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2458 struct inotify_event *e;
2460 if (timeout != (usec_t) -1) {
2463 n = now(CLOCK_MONOTONIC);
2464 if (ts + timeout < n) {
2469 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2479 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2482 if (errno == EINTR || errno == EAGAIN)
2489 e = (struct inotify_event*) inotify_buffer;
2494 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2499 step = sizeof(struct inotify_event) + e->len;
2500 assert(step <= (size_t) l);
2502 e = (struct inotify_event*) ((uint8_t*) e + step);
2509 /* We close the tty fd here since if the old session
2510 * ended our handle will be dead. It's important that
2511 * we do this after sleeping, so that we don't enter
2512 * an endless loop. */
2513 close_nointr_nofail(fd);
2517 close_nointr_nofail(notify);
2519 r = reset_terminal_fd(fd, true);
2521 log_warning("Failed to reset terminal: %s", strerror(-r));
2527 close_nointr_nofail(fd);
2530 close_nointr_nofail(notify);
2535 int release_terminal(void) {
2537 struct sigaction sa_old, sa_new;
2539 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2542 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2543 * by our own TIOCNOTTY */
2546 sa_new.sa_handler = SIG_IGN;
2547 sa_new.sa_flags = SA_RESTART;
2548 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2550 if (ioctl(fd, TIOCNOTTY) < 0)
2553 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2555 close_nointr_nofail(fd);
2559 int sigaction_many(const struct sigaction *sa, ...) {
2564 while ((sig = va_arg(ap, int)) > 0)
2565 if (sigaction(sig, sa, NULL) < 0)
2572 int ignore_signals(int sig, ...) {
2573 struct sigaction sa;
2578 sa.sa_handler = SIG_IGN;
2579 sa.sa_flags = SA_RESTART;
2581 if (sigaction(sig, &sa, NULL) < 0)
2585 while ((sig = va_arg(ap, int)) > 0)
2586 if (sigaction(sig, &sa, NULL) < 0)
2593 int default_signals(int sig, ...) {
2594 struct sigaction sa;
2599 sa.sa_handler = SIG_DFL;
2600 sa.sa_flags = SA_RESTART;
2602 if (sigaction(sig, &sa, NULL) < 0)
2606 while ((sig = va_arg(ap, int)) > 0)
2607 if (sigaction(sig, &sa, NULL) < 0)
2614 int close_pipe(int p[]) {
2620 a = close_nointr(p[0]);
2625 b = close_nointr(p[1]);
2629 return a < 0 ? a : b;
2632 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2641 while (nbytes > 0) {
2644 if ((k = read(fd, p, nbytes)) <= 0) {
2646 if (k < 0 && errno == EINTR)
2649 if (k < 0 && errno == EAGAIN && do_poll) {
2650 struct pollfd pollfd;
2654 pollfd.events = POLLIN;
2656 if (poll(&pollfd, 1, -1) < 0) {
2660 return n > 0 ? n : -errno;
2663 if (pollfd.revents != POLLIN)
2664 return n > 0 ? n : -EIO;
2669 return n > 0 ? n : (k < 0 ? -errno : 0);
2680 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2689 while (nbytes > 0) {
2692 k = write(fd, p, nbytes);
2695 if (k < 0 && errno == EINTR)
2698 if (k < 0 && errno == EAGAIN && do_poll) {
2699 struct pollfd pollfd;
2703 pollfd.events = POLLOUT;
2705 if (poll(&pollfd, 1, -1) < 0) {
2709 return n > 0 ? n : -errno;
2712 if (pollfd.revents != POLLOUT)
2713 return n > 0 ? n : -EIO;
2718 return n > 0 ? n : (k < 0 ? -errno : 0);
2729 int parse_usec(const char *t, usec_t *usec) {
2730 static const struct {
2734 { "sec", USEC_PER_SEC },
2735 { "s", USEC_PER_SEC },
2736 { "min", USEC_PER_MINUTE },
2737 { "hr", USEC_PER_HOUR },
2738 { "h", USEC_PER_HOUR },
2739 { "d", USEC_PER_DAY },
2740 { "w", USEC_PER_WEEK },
2741 { "msec", USEC_PER_MSEC },
2742 { "ms", USEC_PER_MSEC },
2743 { "m", USEC_PER_MINUTE },
2746 { "", USEC_PER_SEC }, /* default is sec */
2762 l = strtoll(p, &e, 10);
2773 e += strspn(e, WHITESPACE);
2775 for (i = 0; i < ELEMENTSOF(table); i++)
2776 if (startswith(e, table[i].suffix)) {
2777 r += (usec_t) l * table[i].usec;
2778 p = e + strlen(table[i].suffix);
2782 if (i >= ELEMENTSOF(table))
2792 int parse_nsec(const char *t, nsec_t *nsec) {
2793 static const struct {
2797 { "sec", NSEC_PER_SEC },
2798 { "s", NSEC_PER_SEC },
2799 { "min", NSEC_PER_MINUTE },
2800 { "hr", NSEC_PER_HOUR },
2801 { "h", NSEC_PER_HOUR },
2802 { "d", NSEC_PER_DAY },
2803 { "w", NSEC_PER_WEEK },
2804 { "msec", NSEC_PER_MSEC },
2805 { "ms", NSEC_PER_MSEC },
2806 { "m", NSEC_PER_MINUTE },
2807 { "usec", NSEC_PER_USEC },
2808 { "us", NSEC_PER_USEC },
2811 { "", 1ULL }, /* default is nsec */
2827 l = strtoll(p, &e, 10);
2838 e += strspn(e, WHITESPACE);
2840 for (i = 0; i < ELEMENTSOF(table); i++)
2841 if (startswith(e, table[i].suffix)) {
2842 r += (nsec_t) l * table[i].nsec;
2843 p = e + strlen(table[i].suffix);
2847 if (i >= ELEMENTSOF(table))
2857 int parse_bytes(const char *t, off_t *bytes) {
2858 static const struct {
2864 { "M", 1024ULL*1024ULL },
2865 { "G", 1024ULL*1024ULL*1024ULL },
2866 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2867 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2868 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2885 l = strtoll(p, &e, 10);
2896 e += strspn(e, WHITESPACE);
2898 for (i = 0; i < ELEMENTSOF(table); i++)
2899 if (startswith(e, table[i].suffix)) {
2900 r += (off_t) l * table[i].factor;
2901 p = e + strlen(table[i].suffix);
2905 if (i >= ELEMENTSOF(table))
2915 int make_stdio(int fd) {
2920 r = dup3(fd, STDIN_FILENO, 0);
2921 s = dup3(fd, STDOUT_FILENO, 0);
2922 t = dup3(fd, STDERR_FILENO, 0);
2925 close_nointr_nofail(fd);
2927 if (r < 0 || s < 0 || t < 0)
2930 /* We rely here that the new fd has O_CLOEXEC not set */
2935 int make_null_stdio(void) {
2938 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2942 return make_stdio(null_fd);
2945 bool is_device_path(const char *path) {
2947 /* Returns true on paths that refer to a device, either in
2948 * sysfs or in /dev */
2951 path_startswith(path, "/dev/") ||
2952 path_startswith(path, "/sys/");
2955 int dir_is_empty(const char *path) {
2956 _cleanup_closedir_ DIR *d;
2965 union dirent_storage buf;
2967 r = readdir_r(d, &buf.de, &de);
2974 if (!ignore_file(de->d_name))
2979 unsigned long long random_ull(void) {
2980 _cleanup_close_ int fd;
2984 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2988 r = loop_read(fd, &ull, sizeof(ull), true);
2989 if (r != sizeof(ull))
2995 return random() * RAND_MAX + random();
2998 void rename_process(const char name[8]) {
3001 /* This is a like a poor man's setproctitle(). It changes the
3002 * comm field, argv[0], and also the glibc's internally used
3003 * name of the process. For the first one a limit of 16 chars
3004 * applies, to the second one usually one of 10 (i.e. length
3005 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3006 * "systemd"). If you pass a longer string it will be
3009 prctl(PR_SET_NAME, name);
3011 if (program_invocation_name)
3012 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3014 if (saved_argc > 0) {
3018 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3020 for (i = 1; i < saved_argc; i++) {
3024 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3029 void sigset_add_many(sigset_t *ss, ...) {
3036 while ((sig = va_arg(ap, int)) > 0)
3037 assert_se(sigaddset(ss, sig) == 0);
3041 char* gethostname_malloc(void) {
3044 assert_se(uname(&u) >= 0);
3046 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3047 return strdup(u.nodename);
3049 return strdup(u.sysname);
3052 bool hostname_is_set(void) {
3055 assert_se(uname(&u) >= 0);
3057 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3060 static char *lookup_uid(uid_t uid) {
3063 _cleanup_free_ char *buf = NULL;
3064 struct passwd pwbuf, *pw = NULL;
3066 /* Shortcut things to avoid NSS lookups */
3068 return strdup("root");
3070 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3074 buf = malloc(bufsize);
3078 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3079 return strdup(pw->pw_name);
3081 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3087 char* getlogname_malloc(void) {
3091 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3096 return lookup_uid(uid);
3099 char *getusername_malloc(void) {
3106 return lookup_uid(getuid());
3109 int getttyname_malloc(int fd, char **r) {
3110 char path[PATH_MAX], *c;
3115 k = ttyname_r(fd, path, sizeof(path));
3121 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3129 int getttyname_harder(int fd, char **r) {
3133 k = getttyname_malloc(fd, &s);
3137 if (streq(s, "tty")) {
3139 return get_ctty(0, NULL, r);
3146 int get_ctty_devnr(pid_t pid, dev_t *d) {
3148 char line[LINE_MAX], *p, *fn;
3149 unsigned long ttynr;
3152 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3155 f = fopen(fn, "re");
3160 if (!fgets(line, sizeof(line), f)) {
3161 k = feof(f) ? -EIO : -errno;
3168 p = strrchr(line, ')');
3178 "%*d " /* session */
3187 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3189 char fn[PATH_MAX], *s, *b, *p;
3194 k = get_ctty_devnr(pid, &devnr);
3198 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3201 if ((k = readlink_malloc(fn, &s)) < 0) {
3206 /* This is an ugly hack */
3207 if (major(devnr) == 136) {
3208 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3218 /* Probably something like the ptys which have no
3219 * symlink in /dev/char. Let's return something
3220 * vaguely useful. */
3222 if (!(b = strdup(fn + 5)))
3232 if (startswith(s, "/dev/"))
3234 else if (startswith(s, "../"))
3252 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3258 /* This returns the first error we run into, but nevertheless
3259 * tries to go on. This closes the passed fd. */
3263 close_nointr_nofail(fd);
3265 return errno == ENOENT ? 0 : -errno;
3270 union dirent_storage buf;
3271 bool is_dir, keep_around;
3275 r = readdir_r(d, &buf.de, &de);
3276 if (r != 0 && ret == 0) {
3284 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3287 if (de->d_type == DT_UNKNOWN ||
3289 (de->d_type == DT_DIR && root_dev)) {
3290 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3291 if (ret == 0 && errno != ENOENT)
3296 is_dir = S_ISDIR(st.st_mode);
3299 (st.st_uid == 0 || st.st_uid == getuid()) &&
3300 (st.st_mode & S_ISVTX);
3302 is_dir = de->d_type == DT_DIR;
3303 keep_around = false;
3309 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3310 if (root_dev && st.st_dev != root_dev->st_dev)
3313 subdir_fd = openat(fd, de->d_name,
3314 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3315 if (subdir_fd < 0) {
3316 if (ret == 0 && errno != ENOENT)
3321 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3322 if (r < 0 && ret == 0)
3326 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3327 if (ret == 0 && errno != ENOENT)
3331 } else if (!only_dirs && !keep_around) {
3333 if (unlinkat(fd, de->d_name, 0) < 0) {
3334 if (ret == 0 && errno != ENOENT)
3345 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3350 if (fstatfs(fd, &s) < 0) {
3351 close_nointr_nofail(fd);
3355 /* We refuse to clean disk file systems with this call. This
3356 * is extra paranoia just to be sure we never ever remove
3359 if (s.f_type != TMPFS_MAGIC &&
3360 s.f_type != RAMFS_MAGIC) {
3361 log_error("Attempted to remove disk file system, and we can't allow that.");
3362 close_nointr_nofail(fd);
3366 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3369 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3375 /* We refuse to clean the root file system with this
3376 * call. This is extra paranoia to never cause a really
3377 * seriously broken system. */
3378 if (path_equal(path, "/")) {
3379 log_error("Attempted to remove entire root file system, and we can't allow that.");
3383 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3386 if (errno != ENOTDIR)
3390 if (statfs(path, &s) < 0)
3393 if (s.f_type != TMPFS_MAGIC &&
3394 s.f_type != RAMFS_MAGIC) {
3395 log_error("Attempted to remove disk file system, and we can't allow that.");
3400 if (delete_root && !only_dirs)
3401 if (unlink(path) < 0 && errno != ENOENT)
3408 if (fstatfs(fd, &s) < 0) {
3409 close_nointr_nofail(fd);
3413 if (s.f_type != TMPFS_MAGIC &&
3414 s.f_type != RAMFS_MAGIC) {
3415 log_error("Attempted to remove disk file system, and we can't allow that.");
3416 close_nointr_nofail(fd);
3421 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3424 if (honour_sticky && file_is_priv_sticky(path) > 0)
3427 if (rmdir(path) < 0 && errno != ENOENT) {
3436 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3437 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3440 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3441 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3444 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3447 /* Under the assumption that we are running privileged we
3448 * first change the access mode and only then hand out
3449 * ownership to avoid a window where access is too open. */
3451 if (mode != (mode_t) -1)
3452 if (chmod(path, mode) < 0)
3455 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3456 if (chown(path, uid, gid) < 0)
3462 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3465 /* Under the assumption that we are running privileged we
3466 * first change the access mode and only then hand out
3467 * ownership to avoid a window where access is too open. */
3469 if (fchmod(fd, mode) < 0)
3472 if (fchown(fd, uid, gid) < 0)
3478 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3482 /* Allocates the cpuset in the right size */
3485 if (!(r = CPU_ALLOC(n)))
3488 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3489 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3499 if (errno != EINVAL)
3506 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3507 static const char status_indent[] = " "; /* "[" STATUS "] " */
3508 _cleanup_free_ char *s = NULL;
3509 _cleanup_close_ int fd = -1;
3510 struct iovec iovec[5];
3515 /* This is independent of logging, as status messages are
3516 * optional and go exclusively to the console. */
3518 if (vasprintf(&s, format, ap) < 0)
3521 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3534 sl = status ? sizeof(status_indent)-1 : 0;
3540 e = ellipsize(s, emax, 75);
3550 if (!isempty(status)) {
3551 IOVEC_SET_STRING(iovec[n++], "[");
3552 IOVEC_SET_STRING(iovec[n++], status);
3553 IOVEC_SET_STRING(iovec[n++], "] ");
3555 IOVEC_SET_STRING(iovec[n++], status_indent);
3558 IOVEC_SET_STRING(iovec[n++], s);
3559 IOVEC_SET_STRING(iovec[n++], "\n");
3561 if (writev(fd, iovec, n) < 0)
3567 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3573 va_start(ap, format);
3574 r = status_vprintf(status, ellipse, format, ap);
3580 int status_welcome(void) {
3582 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3584 r = parse_env_file("/etc/os-release", NEWLINE,
3585 "PRETTY_NAME", &pretty_name,
3586 "ANSI_COLOR", &ansi_color,
3588 if (r < 0 && r != -ENOENT)
3589 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3591 return status_printf(NULL, false,
3592 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3593 isempty(ansi_color) ? "1" : ansi_color,
3594 isempty(pretty_name) ? "Linux" : pretty_name);
3597 char *replace_env(const char *format, char **env) {
3604 const char *e, *word = format;
3609 for (e = format; *e; e ++) {
3620 if (!(k = strnappend(r, word, e-word-1)))
3629 } else if (*e == '$') {
3630 if (!(k = strnappend(r, word, e-word)))
3646 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3649 if (!(k = strappend(r, t)))
3662 if (!(k = strnappend(r, word, e-word)))
3673 char **replace_env_argv(char **argv, char **env) {
3675 unsigned k = 0, l = 0;
3677 l = strv_length(argv);
3679 if (!(r = new(char*, l+1)))
3682 STRV_FOREACH(i, argv) {
3684 /* If $FOO appears as single word, replace it by the split up variable */
3685 if ((*i)[0] == '$' && (*i)[1] != '{') {
3690 if ((e = strv_env_get(env, *i+1))) {
3692 if (!(m = strv_split_quoted(e))) {
3703 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3712 memcpy(r + k, m, q * sizeof(char*));
3720 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3721 if (!(r[k++] = replace_env(*i, env))) {
3731 int fd_columns(int fd) {
3735 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3744 static unsigned columns_cached(bool cached) {
3745 static __thread int env_columns = -1;
3748 if (_likely_(parsed_columns > 0 && cached))
3749 return parsed_columns;
3751 if (_unlikely_(env_columns == -1)) {
3752 e = getenv("COLUMNS");
3754 env_columns = atoi(e);
3759 if (env_columns > 0) {
3760 parsed_columns = env_columns;
3761 return parsed_columns;
3764 if (parsed_columns <= 0 || !cached)
3765 parsed_columns = fd_columns(STDOUT_FILENO);
3767 if (parsed_columns <= 0)
3768 parsed_columns = 80;
3770 return parsed_columns;
3773 unsigned columns(void) {
3774 return columns_cached(true);
3777 unsigned columns_uncached(void) {
3778 return columns_cached(false);
3781 /* intended to be used as a SIGWINCH sighandler */
3782 void columns_cache_reset(int signum) {
3786 int fd_lines(int fd) {
3790 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3799 unsigned lines(void) {
3800 static __thread int parsed_lines = 0;
3803 if (_likely_(parsed_lines > 0))
3804 return parsed_lines;
3806 e = getenv("LINES");
3808 parsed_lines = atoi(e);
3810 if (parsed_lines <= 0)
3811 parsed_lines = fd_lines(STDOUT_FILENO);
3813 if (parsed_lines <= 0)
3816 return parsed_lines;
3819 int running_in_chroot(void) {
3825 /* Only works as root */
3827 if (stat("/proc/1/root", &a) < 0)
3830 if (stat("/", &b) < 0)
3834 a.st_dev != b.st_dev ||
3835 a.st_ino != b.st_ino;
3838 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3843 assert(percent <= 100);
3844 assert(new_length >= 3);
3846 if (old_length <= 3 || old_length <= new_length)
3847 return strndup(s, old_length);
3849 r = new0(char, new_length+1);
3853 x = (new_length * percent) / 100;
3855 if (x > new_length - 3)
3863 s + old_length - (new_length - x - 3),
3864 new_length - x - 3);
3869 char *ellipsize(const char *s, size_t length, unsigned percent) {
3870 return ellipsize_mem(s, strlen(s), length, percent);
3873 int touch(const char *path) {
3878 /* This just opens the file for writing, ensuring it
3879 * exists. It doesn't call utimensat() the way /usr/bin/touch
3882 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3886 close_nointr_nofail(fd);
3890 char *unquote(const char *s, const char* quotes) {
3894 /* This is rather stupid, simply removes the heading and
3895 * trailing quotes if there is one. Doesn't care about
3896 * escaping or anything. We should make this smarter one
3903 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3904 return strndup(s+1, l-2);
3909 char *normalize_env_assignment(const char *s) {
3910 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3913 eq = strchr(s, '=');
3925 memmove(r, t, strlen(t) + 1);
3929 name = strndup(s, eq - s);
3937 value = unquote(strstrip(p), QUOTES);
3941 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3947 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3958 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3970 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3977 r = wait_for_terminate(pid, &status);
3979 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3983 if (status.si_code == CLD_EXITED) {
3984 if (status.si_status != 0) {
3985 log_warning("%s failed with error code %i.", name, status.si_status);
3986 return status.si_status;
3989 log_debug("%s succeeded.", name);
3992 } else if (status.si_code == CLD_KILLED ||
3993 status.si_code == CLD_DUMPED) {
3995 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3999 log_warning("%s failed due to unknown reason.", name);
4003 _noreturn_ void freeze(void) {
4005 /* Make sure nobody waits for us on a socket anymore */
4006 close_all_fds(NULL, 0);
4014 bool null_or_empty(struct stat *st) {
4017 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4020 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4026 int null_or_empty_path(const char *fn) {
4031 if (stat(fn, &st) < 0)
4034 return null_or_empty(&st);
4037 DIR *xopendirat(int fd, const char *name, int flags) {
4041 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4047 close_nointr_nofail(nfd);
4054 int signal_from_string_try_harder(const char *s) {
4058 signo = signal_from_string(s);
4060 if (startswith(s, "SIG"))
4061 return signal_from_string(s+3);
4066 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4072 if (!dual_timestamp_is_set(t))
4075 fprintf(f, "%s=%llu %llu\n",
4077 (unsigned long long) t->realtime,
4078 (unsigned long long) t->monotonic);
4081 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4082 unsigned long long a, b;
4087 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4088 log_debug("Failed to parse finish timestamp value %s", value);
4095 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4099 /* FIXME: to follow udev's logic 100% we need to leave valid
4100 * UTF8 chars unescaped */
4102 u = unquote(tagvalue, "\"\'");
4106 t = xescape(u, "/ ");
4112 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4121 char *fstab_node_to_udev_node(const char *p) {
4124 if (startswith(p, "LABEL="))
4125 return tag_to_udev_node(p+6, "label");
4127 if (startswith(p, "UUID="))
4128 return tag_to_udev_node(p+5, "uuid");
4130 if (startswith(p, "PARTUUID="))
4131 return tag_to_udev_node(p+9, "partuuid");
4133 if (startswith(p, "PARTLABEL="))
4134 return tag_to_udev_node(p+10, "partlabel");
4139 bool tty_is_vc(const char *tty) {
4142 if (startswith(tty, "/dev/"))
4145 return vtnr_from_tty(tty) >= 0;
4148 bool tty_is_console(const char *tty) {
4151 if (startswith(tty, "/dev/"))
4154 return streq(tty, "console");
4157 int vtnr_from_tty(const char *tty) {
4162 if (startswith(tty, "/dev/"))
4165 if (!startswith(tty, "tty") )
4168 if (tty[3] < '0' || tty[3] > '9')
4171 r = safe_atoi(tty+3, &i);
4175 if (i < 0 || i > 63)
4181 bool tty_is_vc_resolve(const char *tty) {
4182 char *active = NULL;
4187 if (startswith(tty, "/dev/"))
4190 /* Resolve where /dev/console is pointing to, if /sys is
4191 * actually ours (i.e. not read-only-mounted which is a sign
4192 * for container setups) */
4193 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4194 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4195 /* If multiple log outputs are configured the
4196 * last one is what /dev/console points to */
4197 tty = strrchr(active, ' ');
4210 const char *default_term_for_tty(const char *tty) {
4213 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4216 bool dirent_is_file(const struct dirent *de) {
4219 if (ignore_file(de->d_name))
4222 if (de->d_type != DT_REG &&
4223 de->d_type != DT_LNK &&
4224 de->d_type != DT_UNKNOWN)
4230 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4233 if (de->d_type != DT_REG &&
4234 de->d_type != DT_LNK &&
4235 de->d_type != DT_UNKNOWN)
4238 if (ignore_file_allow_backup(de->d_name))
4241 return endswith(de->d_name, suffix);
4244 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4247 Hashmap *pids = NULL;
4251 /* Executes all binaries in a directory in parallel and waits
4252 * until all they all finished. */
4255 if (!(_d = opendir(directory))) {
4257 if (errno == ENOENT)
4260 log_error("Failed to enumerate directory %s: %m", directory);
4267 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4268 log_error("Failed to allocate set.");
4272 while ((de = readdir(d))) {
4277 if (!dirent_is_file(de))
4280 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4285 if ((pid = fork()) < 0) {
4286 log_error("Failed to fork: %m");
4304 log_error("Failed to execute %s: %m", path);
4305 _exit(EXIT_FAILURE);
4308 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4310 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4311 log_error("Failed to add PID to set: %s", strerror(-k));
4316 while (!hashmap_isempty(pids)) {
4317 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4322 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4327 log_error("waitid() failed: %m");
4331 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4332 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4333 if (si.si_code == CLD_EXITED)
4334 log_error("%s exited with exit status %i.", path, si.si_status);
4336 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4338 log_debug("%s exited successfully.", path);
4349 hashmap_free_free(pids);
4352 int kill_and_sigcont(pid_t pid, int sig) {
4355 r = kill(pid, sig) < 0 ? -errno : 0;
4363 bool nulstr_contains(const char*nulstr, const char *needle) {
4369 NULSTR_FOREACH(i, nulstr)
4370 if (streq(i, needle))
4376 bool plymouth_running(void) {
4377 return access("/run/plymouth/pid", F_OK) >= 0;
4380 char* strshorten(char *s, size_t l) {
4389 static bool hostname_valid_char(char c) {
4391 (c >= 'a' && c <= 'z') ||
4392 (c >= 'A' && c <= 'Z') ||
4393 (c >= '0' && c <= '9') ||
4399 bool hostname_is_valid(const char *s) {
4405 for (p = s; *p; p++)
4406 if (!hostname_valid_char(*p))
4409 if (p-s > HOST_NAME_MAX)
4415 char* hostname_cleanup(char *s) {
4418 for (p = s, d = s; *p; p++)
4419 if ((*p >= 'a' && *p <= 'z') ||
4420 (*p >= 'A' && *p <= 'Z') ||
4421 (*p >= '0' && *p <= '9') ||
4429 strshorten(s, HOST_NAME_MAX);
4433 int pipe_eof(int fd) {
4434 struct pollfd pollfd;
4439 pollfd.events = POLLIN|POLLHUP;
4441 r = poll(&pollfd, 1, 0);
4448 return pollfd.revents & POLLHUP;
4451 int fd_wait_for_event(int fd, int event, usec_t t) {
4452 struct pollfd pollfd;
4457 pollfd.events = event;
4459 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4466 return pollfd.revents;
4469 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4480 t = new(char, strlen(path) + 1 + 6 + 1);
4484 fn = path_get_file_name(path);
4488 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4490 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4496 f = fdopen(fd, "we");
4509 int terminal_vhangup_fd(int fd) {
4512 if (ioctl(fd, TIOCVHANGUP) < 0)
4518 int terminal_vhangup(const char *name) {
4521 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4525 r = terminal_vhangup_fd(fd);
4526 close_nointr_nofail(fd);
4531 int vt_disallocate(const char *name) {
4535 /* Deallocate the VT if possible. If not possible
4536 * (i.e. because it is the active one), at least clear it
4537 * entirely (including the scrollback buffer) */
4539 if (!startswith(name, "/dev/"))
4542 if (!tty_is_vc(name)) {
4543 /* So this is not a VT. I guess we cannot deallocate
4544 * it then. But let's at least clear the screen */
4546 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4551 "\033[r" /* clear scrolling region */
4552 "\033[H" /* move home */
4553 "\033[2J", /* clear screen */
4555 close_nointr_nofail(fd);
4560 if (!startswith(name, "/dev/tty"))
4563 r = safe_atou(name+8, &u);
4570 /* Try to deallocate */
4571 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4575 r = ioctl(fd, VT_DISALLOCATE, u);
4576 close_nointr_nofail(fd);
4584 /* Couldn't deallocate, so let's clear it fully with
4586 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4591 "\033[r" /* clear scrolling region */
4592 "\033[H" /* move home */
4593 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4595 close_nointr_nofail(fd);
4600 int copy_file(const char *from, const char *to) {
4606 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4610 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4612 close_nointr_nofail(fdf);
4620 n = read(fdf, buf, sizeof(buf));
4624 close_nointr_nofail(fdf);
4635 k = loop_write(fdt, buf, n, false);
4637 r = k < 0 ? k : (errno ? -errno : -EIO);
4639 close_nointr_nofail(fdf);
4647 close_nointr_nofail(fdf);
4648 r = close_nointr(fdt);
4658 int symlink_atomic(const char *from, const char *to) {
4660 _cleanup_free_ char *t;
4663 unsigned long long ull;
4670 t = new(char, strlen(to) + 1 + 16 + 1);
4674 fn = path_get_file_name(to);
4678 x = stpcpy(t+k+1, fn);
4681 for (i = 0; i < 16; i++) {
4682 *(x++) = hexchar(ull & 0xF);
4688 if (symlink(from, t) < 0)
4691 if (rename(t, to) < 0) {
4700 bool display_is_local(const char *display) {
4704 display[0] == ':' &&
4705 display[1] >= '0' &&
4709 int socket_from_display(const char *display, char **path) {
4716 if (!display_is_local(display))
4719 k = strspn(display+1, "0123456789");
4721 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4725 c = stpcpy(f, "/tmp/.X11-unix/X");
4726 memcpy(c, display+1, k);
4735 const char **username,
4736 uid_t *uid, gid_t *gid,
4738 const char **shell) {
4746 /* We enforce some special rules for uid=0: in order to avoid
4747 * NSS lookups for root we hardcode its data. */
4749 if (streq(*username, "root") || streq(*username, "0")) {
4767 if (parse_uid(*username, &u) >= 0) {
4771 /* If there are multiple users with the same id, make
4772 * sure to leave $USER to the configured value instead
4773 * of the first occurrence in the database. However if
4774 * the uid was configured by a numeric uid, then let's
4775 * pick the real username from /etc/passwd. */
4777 *username = p->pw_name;
4780 p = getpwnam(*username);
4784 return errno != 0 ? -errno : -ESRCH;
4796 *shell = p->pw_shell;
4801 int get_group_creds(const char **groupname, gid_t *gid) {
4807 /* We enforce some special rules for gid=0: in order to avoid
4808 * NSS lookups for root we hardcode its data. */
4810 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4811 *groupname = "root";
4819 if (parse_gid(*groupname, &id) >= 0) {
4824 *groupname = g->gr_name;
4827 g = getgrnam(*groupname);
4831 return errno != 0 ? -errno : -ESRCH;
4839 int in_group(const char *name) {
4841 int ngroups_max, r, i;
4843 r = get_group_creds(&name, &gid);
4847 if (getgid() == gid)
4850 if (getegid() == gid)
4853 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4854 assert(ngroups_max > 0);
4856 gids = alloca(sizeof(gid_t) * ngroups_max);
4858 r = getgroups(ngroups_max, gids);
4862 for (i = 0; i < r; i++)
4869 int glob_exists(const char *path) {
4877 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4879 if (k == GLOB_NOMATCH)
4881 else if (k == GLOB_NOSPACE)
4884 r = !strv_isempty(g.gl_pathv);
4886 r = errno ? -errno : -EIO;
4893 int dirent_ensure_type(DIR *d, struct dirent *de) {
4899 if (de->d_type != DT_UNKNOWN)
4902 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4906 S_ISREG(st.st_mode) ? DT_REG :
4907 S_ISDIR(st.st_mode) ? DT_DIR :
4908 S_ISLNK(st.st_mode) ? DT_LNK :
4909 S_ISFIFO(st.st_mode) ? DT_FIFO :
4910 S_ISSOCK(st.st_mode) ? DT_SOCK :
4911 S_ISCHR(st.st_mode) ? DT_CHR :
4912 S_ISBLK(st.st_mode) ? DT_BLK :
4918 int in_search_path(const char *path, char **search) {
4922 r = path_get_parent(path, &parent);
4928 STRV_FOREACH(i, search) {
4929 if (path_equal(parent, *i)) {
4940 int get_files_in_directory(const char *path, char ***list) {
4948 /* Returns all files in a directory in *list, and the number
4949 * of files as return value. If list is NULL returns only the
4958 union dirent_storage buf;
4961 k = readdir_r(d, &buf.de, &de);
4970 dirent_ensure_type(d, de);
4972 if (!dirent_is_file(de))
4976 if ((unsigned) r >= n) {
4980 t = realloc(l, sizeof(char*) * n);
4989 assert((unsigned) r < n);
4991 l[r] = strdup(de->d_name);
5015 char *strjoin(const char *x, ...) {
5029 t = va_arg(ap, const char *);
5034 if (n > ((size_t) -1) - l) {
5058 t = va_arg(ap, const char *);
5072 bool is_main_thread(void) {
5073 static __thread int cached = 0;
5075 if (_unlikely_(cached == 0))
5076 cached = getpid() == gettid() ? 1 : -1;
5081 int block_get_whole_disk(dev_t d, dev_t *ret) {
5088 /* If it has a queue this is good enough for us */
5089 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5092 r = access(p, F_OK);
5100 /* If it is a partition find the originating device */
5101 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5104 r = access(p, F_OK);
5110 /* Get parent dev_t */
5111 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5114 r = read_one_line_file(p, &s);
5120 r = sscanf(s, "%u:%u", &m, &n);
5126 /* Only return this if it is really good enough for us. */
5127 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5130 r = access(p, F_OK);
5134 *ret = makedev(m, n);
5141 int file_is_priv_sticky(const char *p) {
5146 if (lstat(p, &st) < 0)
5150 (st.st_uid == 0 || st.st_uid == getuid()) &&
5151 (st.st_mode & S_ISVTX);
5154 static const char *const ioprio_class_table[] = {
5155 [IOPRIO_CLASS_NONE] = "none",
5156 [IOPRIO_CLASS_RT] = "realtime",
5157 [IOPRIO_CLASS_BE] = "best-effort",
5158 [IOPRIO_CLASS_IDLE] = "idle"
5161 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5163 static const char *const sigchld_code_table[] = {
5164 [CLD_EXITED] = "exited",
5165 [CLD_KILLED] = "killed",
5166 [CLD_DUMPED] = "dumped",
5167 [CLD_TRAPPED] = "trapped",
5168 [CLD_STOPPED] = "stopped",
5169 [CLD_CONTINUED] = "continued",
5172 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5174 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5175 [LOG_FAC(LOG_KERN)] = "kern",
5176 [LOG_FAC(LOG_USER)] = "user",
5177 [LOG_FAC(LOG_MAIL)] = "mail",
5178 [LOG_FAC(LOG_DAEMON)] = "daemon",
5179 [LOG_FAC(LOG_AUTH)] = "auth",
5180 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5181 [LOG_FAC(LOG_LPR)] = "lpr",
5182 [LOG_FAC(LOG_NEWS)] = "news",
5183 [LOG_FAC(LOG_UUCP)] = "uucp",
5184 [LOG_FAC(LOG_CRON)] = "cron",
5185 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5186 [LOG_FAC(LOG_FTP)] = "ftp",
5187 [LOG_FAC(LOG_LOCAL0)] = "local0",
5188 [LOG_FAC(LOG_LOCAL1)] = "local1",
5189 [LOG_FAC(LOG_LOCAL2)] = "local2",
5190 [LOG_FAC(LOG_LOCAL3)] = "local3",
5191 [LOG_FAC(LOG_LOCAL4)] = "local4",
5192 [LOG_FAC(LOG_LOCAL5)] = "local5",
5193 [LOG_FAC(LOG_LOCAL6)] = "local6",
5194 [LOG_FAC(LOG_LOCAL7)] = "local7"
5197 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5199 static const char *const log_level_table[] = {
5200 [LOG_EMERG] = "emerg",
5201 [LOG_ALERT] = "alert",
5202 [LOG_CRIT] = "crit",
5204 [LOG_WARNING] = "warning",
5205 [LOG_NOTICE] = "notice",
5206 [LOG_INFO] = "info",
5207 [LOG_DEBUG] = "debug"
5210 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5212 static const char* const sched_policy_table[] = {
5213 [SCHED_OTHER] = "other",
5214 [SCHED_BATCH] = "batch",
5215 [SCHED_IDLE] = "idle",
5216 [SCHED_FIFO] = "fifo",
5220 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5222 static const char* const rlimit_table[] = {
5223 [RLIMIT_CPU] = "LimitCPU",
5224 [RLIMIT_FSIZE] = "LimitFSIZE",
5225 [RLIMIT_DATA] = "LimitDATA",
5226 [RLIMIT_STACK] = "LimitSTACK",
5227 [RLIMIT_CORE] = "LimitCORE",
5228 [RLIMIT_RSS] = "LimitRSS",
5229 [RLIMIT_NOFILE] = "LimitNOFILE",
5230 [RLIMIT_AS] = "LimitAS",
5231 [RLIMIT_NPROC] = "LimitNPROC",
5232 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5233 [RLIMIT_LOCKS] = "LimitLOCKS",
5234 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5235 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5236 [RLIMIT_NICE] = "LimitNICE",
5237 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5238 [RLIMIT_RTTIME] = "LimitRTTIME"
5241 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5243 static const char* const ip_tos_table[] = {
5244 [IPTOS_LOWDELAY] = "low-delay",
5245 [IPTOS_THROUGHPUT] = "throughput",
5246 [IPTOS_RELIABILITY] = "reliability",
5247 [IPTOS_LOWCOST] = "low-cost",
5250 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5252 static const char *const __signal_table[] = {
5269 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5280 [SIGVTALRM] = "VTALRM",
5282 [SIGWINCH] = "WINCH",
5288 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5290 const char *signal_to_string(int signo) {
5291 static __thread char buf[12];
5294 name = __signal_to_string(signo);
5298 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5299 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5301 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5306 int signal_from_string(const char *s) {
5311 signo = __signal_from_string(s);
5315 if (startswith(s, "RTMIN+")) {
5319 if (safe_atou(s, &u) >= 0) {
5320 signo = (int) u + offset;
5321 if (signo > 0 && signo < _NSIG)
5327 bool kexec_loaded(void) {
5328 bool loaded = false;
5331 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5339 int strdup_or_null(const char *a, char **b) {
5357 int prot_from_flags(int flags) {
5359 switch (flags & O_ACCMODE) {
5368 return PROT_READ|PROT_WRITE;
5375 char *format_bytes(char *buf, size_t l, off_t t) {
5378 static const struct {
5382 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5383 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5384 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5385 { "G", 1024ULL*1024ULL*1024ULL },
5386 { "M", 1024ULL*1024ULL },
5390 for (i = 0; i < ELEMENTSOF(table); i++) {
5392 if (t >= table[i].factor) {
5395 (unsigned long long) (t / table[i].factor),
5396 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5403 snprintf(buf, l, "%lluB", (unsigned long long) t);
5411 void* memdup(const void *p, size_t l) {
5424 int fd_inc_sndbuf(int fd, size_t n) {
5426 socklen_t l = sizeof(value);
5428 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5430 l == sizeof(value) &&
5431 (size_t) value >= n*2)
5435 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5442 int fd_inc_rcvbuf(int fd, size_t n) {
5444 socklen_t l = sizeof(value);
5446 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5448 l == sizeof(value) &&
5449 (size_t) value >= n*2)
5453 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5460 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5461 pid_t parent_pid, agent_pid;
5463 bool stdout_is_tty, stderr_is_tty;
5471 parent_pid = getpid();
5473 /* Spawns a temporary TTY agent, making sure it goes away when
5480 if (agent_pid != 0) {
5487 * Make sure the agent goes away when the parent dies */
5488 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5489 _exit(EXIT_FAILURE);
5491 /* Check whether our parent died before we were able
5492 * to set the death signal */
5493 if (getppid() != parent_pid)
5494 _exit(EXIT_SUCCESS);
5496 /* Don't leak fds to the agent */
5497 close_all_fds(except, n_except);
5499 stdout_is_tty = isatty(STDOUT_FILENO);
5500 stderr_is_tty = isatty(STDERR_FILENO);
5502 if (!stdout_is_tty || !stderr_is_tty) {
5503 /* Detach from stdout/stderr. and reopen
5504 * /dev/tty for them. This is important to
5505 * ensure that when systemctl is started via
5506 * popen() or a similar call that expects to
5507 * read EOF we actually do generate EOF and
5508 * not delay this indefinitely by because we
5509 * keep an unused copy of stdin around. */
5510 fd = open("/dev/tty", O_WRONLY);
5512 log_error("Failed to open /dev/tty: %m");
5513 _exit(EXIT_FAILURE);
5517 dup2(fd, STDOUT_FILENO);
5520 dup2(fd, STDERR_FILENO);
5526 /* Count arguments */
5528 for (n = 0; va_arg(ap, char*); n++)
5533 l = alloca(sizeof(char *) * (n + 1));
5535 /* Fill in arguments */
5537 for (i = 0; i <= n; i++)
5538 l[i] = va_arg(ap, char*);
5542 _exit(EXIT_FAILURE);
5545 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5546 struct rlimit highest, fixed;
5550 if (setrlimit(resource, rlim) >= 0)
5556 /* So we failed to set the desired setrlimit, then let's try
5557 * to get as close as we can */
5558 assert_se(getrlimit(resource, &highest) == 0);
5560 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5561 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5563 if (setrlimit(resource, &fixed) < 0)
5569 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5570 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5582 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5585 f = fopen(path, "re");
5593 char line[LINE_MAX];
5596 for (i = 0; i < sizeof(line)-1; i++) {
5600 if (_unlikely_(c == EOF)) {
5610 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5611 value = strdup(line + l + 1);
5631 int can_sleep(const char *type) {
5635 _cleanup_free_ char *p = NULL;
5639 r = read_one_line_file("/sys/power/state", &p);
5641 return r == -ENOENT ? 0 : r;
5644 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5645 if (l == k && memcmp(w, type, l) == 0)
5651 bool is_valid_documentation_url(const char *url) {
5654 if (startswith(url, "http://") && url[7])
5657 if (startswith(url, "https://") && url[8])
5660 if (startswith(url, "file:") && url[5])
5663 if (startswith(url, "info:") && url[5])
5666 if (startswith(url, "man:") && url[4])
5672 bool in_initrd(void) {
5673 static __thread int saved = -1;
5679 /* We make two checks here:
5681 * 1. the flag file /etc/initrd-release must exist
5682 * 2. the root file system must be a memory file system
5684 * The second check is extra paranoia, since misdetecting an
5685 * initrd can have bad bad consequences due the initrd
5686 * emptying when transititioning to the main systemd.
5689 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5690 statfs("/", &s) >= 0 &&
5691 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5696 void warn_melody(void) {
5697 _cleanup_close_ int fd = -1;
5699 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5703 /* Yeah, this is synchronous. Kinda sucks. But well... */
5705 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5706 usleep(125*USEC_PER_MSEC);
5708 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5709 usleep(125*USEC_PER_MSEC);
5711 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5712 usleep(125*USEC_PER_MSEC);
5714 ioctl(fd, KIOCSOUND, 0);
5717 int make_console_stdio(void) {
5720 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5722 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5724 log_error("Failed to acquire terminal: %s", strerror(-fd));
5730 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5737 int get_home_dir(char **_h) {
5745 /* Take the user specified one */
5756 /* Hardcode home directory for root to avoid NSS */
5759 h = strdup("/root");
5767 /* Check the database... */
5771 return errno ? -errno : -ESRCH;
5773 if (!path_is_absolute(p->pw_dir))
5776 h = strdup(p->pw_dir);
5784 int get_shell(char **_sh) {
5792 /* Take the user specified one */
5793 e = getenv("SHELL");
5803 /* Hardcode home directory for root to avoid NSS */
5806 sh = strdup("/bin/sh");
5814 /* Check the database... */
5818 return errno ? -errno : -ESRCH;
5820 if (!path_is_absolute(p->pw_shell))
5823 sh = strdup(p->pw_shell);
5831 void freep(void *p) {
5835 void fclosep(FILE **f) {
5840 void closep(int *fd) {
5842 close_nointr_nofail(*fd);
5845 void closedirp(DIR **d) {
5850 void umaskp(mode_t *u) {