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 size_t page_size(void) {
75 static __thread size_t pgsz = 0;
78 if (_likely_(pgsz > 0))
81 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
88 bool streq_ptr(const char *a, const char *b) {
90 /* Like streq(), but tries to make sense of NULL pointers */
101 usec_t now(clockid_t clock_id) {
104 assert_se(clock_gettime(clock_id, &ts) == 0);
106 return timespec_load(&ts);
109 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
112 ts->realtime = now(CLOCK_REALTIME);
113 ts->monotonic = now(CLOCK_MONOTONIC);
118 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
127 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
129 ts->monotonic = now(CLOCK_MONOTONIC);
131 if ((int64_t) ts->monotonic > delta)
132 ts->monotonic -= delta;
140 usec_t timespec_load(const struct timespec *ts) {
144 (usec_t) ts->tv_sec * USEC_PER_SEC +
145 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
148 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
151 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
152 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
157 usec_t timeval_load(const struct timeval *tv) {
161 (usec_t) tv->tv_sec * USEC_PER_SEC +
162 (usec_t) tv->tv_usec;
165 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
168 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
169 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
174 bool endswith(const char *s, const char *postfix) {
181 pl = strlen(postfix);
189 return memcmp(s + sl - pl, postfix, pl) == 0;
192 bool startswith(const char *s, const char *prefix) {
207 return memcmp(s, prefix, pl) == 0;
210 bool startswith_no_case(const char *s, const char *prefix) {
226 for(i = 0; i < pl; ++i) {
227 if (tolower(s[i]) != tolower(prefix[i]))
234 bool first_word(const char *s, const char *word) {
249 if (memcmp(s, word, wl) != 0)
253 strchr(WHITESPACE, s[wl]);
256 int close_nointr(int fd) {
271 void close_nointr_nofail(int fd) {
272 int saved_errno = errno;
274 /* like close_nointr() but cannot fail, and guarantees errno
277 assert_se(close_nointr(fd) == 0);
282 void close_many(const int fds[], unsigned n_fd) {
285 for (i = 0; i < n_fd; i++)
286 close_nointr_nofail(fds[i]);
289 int parse_boolean(const char *v) {
292 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
294 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
300 int parse_pid(const char *s, pid_t* ret_pid) {
301 unsigned long ul = 0;
308 if ((r = safe_atolu(s, &ul)) < 0)
313 if ((unsigned long) pid != ul)
323 int parse_uid(const char *s, uid_t* ret_uid) {
324 unsigned long ul = 0;
331 if ((r = safe_atolu(s, &ul)) < 0)
336 if ((unsigned long) uid != ul)
343 int safe_atou(const char *s, unsigned *ret_u) {
351 l = strtoul(s, &x, 0);
353 if (!x || *x || errno)
354 return errno ? -errno : -EINVAL;
356 if ((unsigned long) (unsigned) l != l)
359 *ret_u = (unsigned) l;
363 int safe_atoi(const char *s, int *ret_i) {
371 l = strtol(s, &x, 0);
373 if (!x || *x || errno)
374 return errno ? -errno : -EINVAL;
376 if ((long) (int) l != l)
383 int safe_atollu(const char *s, long long unsigned *ret_llu) {
385 unsigned long long l;
391 l = strtoull(s, &x, 0);
393 if (!x || *x || errno)
394 return errno ? -errno : -EINVAL;
400 int safe_atolli(const char *s, long long int *ret_lli) {
408 l = strtoll(s, &x, 0);
410 if (!x || *x || errno)
411 return errno ? -errno : -EINVAL;
417 /* Split a string into words. */
418 char *split(const char *c, size_t *l, const char *separator, char **state) {
421 current = *state ? *state : (char*) c;
423 if (!*current || *c == 0)
426 current += strspn(current, separator);
427 *l = strcspn(current, separator);
430 return (char*) current;
433 /* Split a string into words, but consider strings enclosed in '' and
434 * "" as words even if they include spaces. */
435 char *split_quoted(const char *c, size_t *l, char **state) {
437 bool escaped = false;
439 current = *state ? *state : (char*) c;
441 if (!*current || *c == 0)
444 current += strspn(current, WHITESPACE);
446 if (*current == '\'') {
449 for (e = current; *e; e++) {
459 *state = *e == 0 ? e : e+1;
460 } else if (*current == '\"') {
463 for (e = current; *e; e++) {
473 *state = *e == 0 ? e : e+1;
475 for (e = current; *e; e++) {
480 else if (strchr(WHITESPACE, *e))
487 return (char*) current;
490 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
492 _cleanup_fclose_ FILE *f = NULL;
493 char fn[PATH_MAX], line[LINE_MAX], *p;
499 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
506 if (!fgets(line, sizeof(line), f)) {
507 r = feof(f) ? -EIO : -errno;
512 /* Let's skip the pid and comm fields. The latter is enclosed
513 * in () but does not escape any () in its value, so let's
514 * skip over it manually */
516 p = strrchr(line, ')');
528 if ((long unsigned) (pid_t) ppid != ppid)
531 *_ppid = (pid_t) ppid;
536 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
539 char fn[PATH_MAX], line[LINE_MAX], *p;
544 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
547 if (!(f = fopen(fn, "re")))
550 if (!(fgets(line, sizeof(line), f))) {
551 r = feof(f) ? -EIO : -errno;
558 /* Let's skip the pid and comm fields. The latter is enclosed
559 * in () but does not escape any () in its value, so let's
560 * skip over it manually */
562 if (!(p = strrchr(line, ')')))
583 "%*d " /* priority */
585 "%*d " /* num_threads */
586 "%*d " /* itrealvalue */
587 "%llu " /* starttime */,
594 int write_one_line_file(const char *fn, const char *line) {
606 if (fputs(line, f) < 0) {
611 if (!endswith(line, "\n"))
629 int fchmod_umask(int fd, mode_t m) {
634 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
640 int write_one_line_file_atomic(const char *fn, const char *line) {
648 r = fopen_temporary(fn, &f, &p);
652 fchmod_umask(fileno(f), 0644);
655 if (fputs(line, f) < 0) {
660 if (!endswith(line, "\n"))
671 if (rename(p, fn) < 0)
687 int read_one_line_file(const char *fn, char **line) {
688 _cleanup_fclose_ FILE *f = NULL;
689 char t[LINE_MAX], *c;
698 if (!fgets(t, sizeof(t), f)) {
715 int read_full_file(const char *fn, char **contents, size_t *size) {
716 _cleanup_fclose_ FILE *f = NULL;
718 _cleanup_free_ char *buf = NULL;
725 if (fstat(fileno(f), &st) < 0)
729 if (st.st_size > 4*1024*1024)
732 n = st.st_size > 0 ? st.st_size : LINE_MAX;
739 t = realloc(buf, n+1);
744 k = fread(buf + l, 1, n - l, f);
773 const char *separator, ...) {
776 char *contents = NULL, *p;
781 if ((r = read_full_file(fname, &contents, NULL)) < 0)
786 const char *key = NULL;
788 p += strspn(p, separator);
789 p += strspn(p, WHITESPACE);
794 if (!strchr(COMMENTS, *p)) {
798 va_start(ap, separator);
799 while ((key = va_arg(ap, char *))) {
803 value = va_arg(ap, char **);
806 if (strncmp(p, key, n) != 0 ||
811 n = strcspn(p, separator);
814 strchr(QUOTES, p[0]) &&
816 v = strndup(p+1, n-2);
827 /* return empty value strings as NULL */
844 p += strcspn(p, separator);
863 if (!(f = fopen(fname, "re")))
867 char l[LINE_MAX], *p, *u;
870 if (!fgets(l, sizeof(l), f)) {
883 if (strchr(COMMENTS, *p))
886 if (!(u = normalize_env_assignment(p))) {
891 t = strv_append(m, u);
917 int write_env_file(const char *fname, char **l) {
922 r = fopen_temporary(fname, &f, &p);
926 fchmod_umask(fileno(f), 0644);
942 if (rename(p, fname) < 0)
957 char *truncate_nl(char *s) {
960 s[strcspn(s, NEWLINE)] = 0;
964 int get_process_comm(pid_t pid, char **name) {
970 r = read_one_line_file("/proc/self/comm", name);
973 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
976 r = read_one_line_file(p, name);
983 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
990 assert(max_length > 0);
994 f = fopen("/proc/self/cmdline", "re");
997 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1007 r = new(char, max_length);
1015 while ((c = getc(f)) != EOF) {
1037 size_t n = MIN(left-1, 3U);
1038 memcpy(k, "...", n);
1045 /* Kernel threads have no argv[] */
1055 h = get_process_comm(pid, &t);
1059 r = strjoin("[", t, "]", NULL);
1070 int is_kernel_thread(pid_t pid) {
1080 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1089 count = fread(&c, 1, 1, f);
1093 /* Kernel threads have an empty cmdline */
1096 return eof ? 1 : -errno;
1101 int get_process_exe(pid_t pid, char **name) {
1107 r = readlink_malloc("/proc/self/exe", name);
1110 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1113 r = readlink_malloc(p, name);
1120 int get_process_uid(pid_t pid, uid_t *uid) {
1130 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1140 char line[LINE_MAX], *l;
1142 if (!fgets(line, sizeof(line), f)) {
1152 if (startswith(l, "Uid:")) {
1154 l += strspn(l, WHITESPACE);
1156 l[strcspn(l, WHITESPACE)] = 0;
1158 r = parse_uid(l, uid);
1171 char *strnappend(const char *s, const char *suffix, size_t b) {
1179 return strndup(suffix, b);
1189 if (!(r = new(char, a+b+1)))
1193 memcpy(r+a, suffix, b);
1199 char *strappend(const char *s, const char *suffix) {
1200 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1203 int readlink_malloc(const char *p, char **r) {
1213 if (!(c = new(char, l)))
1216 if ((n = readlink(p, c, l-1)) < 0) {
1222 if ((size_t) n < l-1) {
1233 int readlink_and_make_absolute(const char *p, char **r) {
1240 if ((j = readlink_malloc(p, &target)) < 0)
1243 k = file_in_same_dir(p, target);
1253 int readlink_and_canonicalize(const char *p, char **r) {
1260 j = readlink_and_make_absolute(p, &t);
1264 s = canonicalize_file_name(t);
1271 path_kill_slashes(*r);
1276 int reset_all_signal_handlers(void) {
1279 for (sig = 1; sig < _NSIG; sig++) {
1280 struct sigaction sa;
1282 if (sig == SIGKILL || sig == SIGSTOP)
1286 sa.sa_handler = SIG_DFL;
1287 sa.sa_flags = SA_RESTART;
1289 /* On Linux the first two RT signals are reserved by
1290 * glibc, and sigaction() will return EINVAL for them. */
1291 if ((sigaction(sig, &sa, NULL) < 0))
1292 if (errno != EINVAL)
1299 char *strstrip(char *s) {
1302 /* Drops trailing whitespace. Modifies the string in
1303 * place. Returns pointer to first non-space character */
1305 s += strspn(s, WHITESPACE);
1307 for (e = strchr(s, 0); e > s; e --)
1308 if (!strchr(WHITESPACE, e[-1]))
1316 char *delete_chars(char *s, const char *bad) {
1319 /* Drops all whitespace, regardless where in the string */
1321 for (f = s, t = s; *f; f++) {
1322 if (strchr(bad, *f))
1333 bool in_charset(const char *s, const char* charset) {
1339 for (i = s; *i; i++)
1340 if (!strchr(charset, *i))
1346 char *file_in_same_dir(const char *path, const char *filename) {
1353 /* This removes the last component of path and appends
1354 * filename, unless the latter is absolute anyway or the
1357 if (path_is_absolute(filename))
1358 return strdup(filename);
1360 if (!(e = strrchr(path, '/')))
1361 return strdup(filename);
1363 k = strlen(filename);
1364 if (!(r = new(char, e-path+1+k+1)))
1367 memcpy(r, path, e-path+1);
1368 memcpy(r+(e-path)+1, filename, k+1);
1373 int rmdir_parents(const char *path, const char *stop) {
1382 /* Skip trailing slashes */
1383 while (l > 0 && path[l-1] == '/')
1389 /* Skip last component */
1390 while (l > 0 && path[l-1] != '/')
1393 /* Skip trailing slashes */
1394 while (l > 0 && path[l-1] == '/')
1400 if (!(t = strndup(path, l)))
1403 if (path_startswith(stop, t)) {
1412 if (errno != ENOENT)
1420 char hexchar(int x) {
1421 static const char table[16] = "0123456789abcdef";
1423 return table[x & 15];
1426 int unhexchar(char c) {
1428 if (c >= '0' && c <= '9')
1431 if (c >= 'a' && c <= 'f')
1432 return c - 'a' + 10;
1434 if (c >= 'A' && c <= 'F')
1435 return c - 'A' + 10;
1440 char octchar(int x) {
1441 return '0' + (x & 7);
1444 int unoctchar(char c) {
1446 if (c >= '0' && c <= '7')
1452 char decchar(int x) {
1453 return '0' + (x % 10);
1456 int undecchar(char c) {
1458 if (c >= '0' && c <= '9')
1464 char *cescape(const char *s) {
1470 /* Does C style string escaping. */
1472 r = new(char, strlen(s)*4 + 1);
1476 for (f = s, t = r; *f; f++)
1522 /* For special chars we prefer octal over
1523 * hexadecimal encoding, simply because glib's
1524 * g_strescape() does the same */
1525 if ((*f < ' ') || (*f >= 127)) {
1527 *(t++) = octchar((unsigned char) *f >> 6);
1528 *(t++) = octchar((unsigned char) *f >> 3);
1529 *(t++) = octchar((unsigned char) *f);
1540 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1547 /* Undoes C style string escaping, and optionally prefixes it. */
1549 pl = prefix ? strlen(prefix) : 0;
1551 r = new(char, pl+length+1);
1556 memcpy(r, prefix, pl);
1558 for (f = s, t = r + pl; f < s + length; f++) {
1601 /* This is an extension of the XDG syntax files */
1606 /* hexadecimal encoding */
1609 a = unhexchar(f[1]);
1610 b = unhexchar(f[2]);
1612 if (a < 0 || b < 0) {
1613 /* Invalid escape code, let's take it literal then */
1617 *(t++) = (char) ((a << 4) | b);
1632 /* octal encoding */
1635 a = unoctchar(f[0]);
1636 b = unoctchar(f[1]);
1637 c = unoctchar(f[2]);
1639 if (a < 0 || b < 0 || c < 0) {
1640 /* Invalid escape code, let's take it literal then */
1644 *(t++) = (char) ((a << 6) | (b << 3) | c);
1652 /* premature end of string.*/
1657 /* Invalid escape code, let's take it literal then */
1669 char *cunescape_length(const char *s, size_t length) {
1670 return cunescape_length_with_prefix(s, length, NULL);
1673 char *cunescape(const char *s) {
1676 return cunescape_length(s, strlen(s));
1679 char *xescape(const char *s, const char *bad) {
1683 /* Escapes all chars in bad, in addition to \ and all special
1684 * chars, in \xFF style escaping. May be reversed with
1687 if (!(r = new(char, strlen(s)*4+1)))
1690 for (f = s, t = r; *f; f++) {
1692 if ((*f < ' ') || (*f >= 127) ||
1693 (*f == '\\') || strchr(bad, *f)) {
1696 *(t++) = hexchar(*f >> 4);
1697 *(t++) = hexchar(*f);
1707 char *bus_path_escape(const char *s) {
1713 /* Escapes all chars that D-Bus' object path cannot deal
1714 * with. Can be reverse with bus_path_unescape() */
1716 if (!(r = new(char, strlen(s)*3+1)))
1719 for (f = s, t = r; *f; f++) {
1721 if (!(*f >= 'A' && *f <= 'Z') &&
1722 !(*f >= 'a' && *f <= 'z') &&
1723 !(*f >= '0' && *f <= '9')) {
1725 *(t++) = hexchar(*f >> 4);
1726 *(t++) = hexchar(*f);
1736 char *bus_path_unescape(const char *f) {
1741 if (!(r = strdup(f)))
1744 for (t = r; *f; f++) {
1749 if ((a = unhexchar(f[1])) < 0 ||
1750 (b = unhexchar(f[2])) < 0) {
1751 /* Invalid escape code, let's take it literal then */
1754 *(t++) = (char) ((a << 4) | b);
1766 char *ascii_strlower(char *t) {
1771 for (p = t; *p; p++)
1772 if (*p >= 'A' && *p <= 'Z')
1773 *p = *p - 'A' + 'a';
1778 static bool ignore_file_allow_backup(const char *filename) {
1782 filename[0] == '.' ||
1783 streq(filename, "lost+found") ||
1784 streq(filename, "aquota.user") ||
1785 streq(filename, "aquota.group") ||
1786 endswith(filename, ".rpmnew") ||
1787 endswith(filename, ".rpmsave") ||
1788 endswith(filename, ".rpmorig") ||
1789 endswith(filename, ".dpkg-old") ||
1790 endswith(filename, ".dpkg-new") ||
1791 endswith(filename, ".swp");
1794 bool ignore_file(const char *filename) {
1797 if (endswith(filename, "~"))
1800 return ignore_file_allow_backup(filename);
1803 int fd_nonblock(int fd, bool nonblock) {
1808 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1812 flags |= O_NONBLOCK;
1814 flags &= ~O_NONBLOCK;
1816 if (fcntl(fd, F_SETFL, flags) < 0)
1822 int fd_cloexec(int fd, bool cloexec) {
1827 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1831 flags |= FD_CLOEXEC;
1833 flags &= ~FD_CLOEXEC;
1835 if (fcntl(fd, F_SETFD, flags) < 0)
1841 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1844 assert(n_fdset == 0 || fdset);
1846 for (i = 0; i < n_fdset; i++)
1853 int close_all_fds(const int except[], unsigned n_except) {
1858 assert(n_except == 0 || except);
1860 d = opendir("/proc/self/fd");
1865 /* When /proc isn't available (for example in chroots)
1866 * the fallback is brute forcing through the fd
1869 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1870 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1872 if (fd_in_set(fd, except, n_except))
1875 if (close_nointr(fd) < 0)
1876 if (errno != EBADF && r == 0)
1883 while ((de = readdir(d))) {
1886 if (ignore_file(de->d_name))
1889 if (safe_atoi(de->d_name, &fd) < 0)
1890 /* Let's better ignore this, just in case */
1899 if (fd_in_set(fd, except, n_except))
1902 if (close_nointr(fd) < 0) {
1903 /* Valgrind has its own FD and doesn't want to have it closed */
1904 if (errno != EBADF && r == 0)
1913 bool chars_intersect(const char *a, const char *b) {
1916 /* Returns true if any of the chars in a are in b. */
1917 for (p = a; *p; p++)
1924 char *format_timestamp(char *buf, size_t l, usec_t t) {
1934 sec = (time_t) (t / USEC_PER_SEC);
1936 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1942 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1945 n = now(CLOCK_REALTIME);
1947 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1952 if (d >= USEC_PER_YEAR)
1953 snprintf(buf, l, "%llu years and %llu months ago",
1954 (unsigned long long) (d / USEC_PER_YEAR),
1955 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1956 else if (d >= USEC_PER_MONTH)
1957 snprintf(buf, l, "%llu months and %llu days ago",
1958 (unsigned long long) (d / USEC_PER_MONTH),
1959 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1960 else if (d >= USEC_PER_WEEK)
1961 snprintf(buf, l, "%llu weeks and %llu days ago",
1962 (unsigned long long) (d / USEC_PER_WEEK),
1963 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1964 else if (d >= 2*USEC_PER_DAY)
1965 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1966 else if (d >= 25*USEC_PER_HOUR)
1967 snprintf(buf, l, "1 day and %lluh ago",
1968 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1969 else if (d >= 6*USEC_PER_HOUR)
1970 snprintf(buf, l, "%lluh ago",
1971 (unsigned long long) (d / USEC_PER_HOUR));
1972 else if (d >= USEC_PER_HOUR)
1973 snprintf(buf, l, "%lluh %llumin ago",
1974 (unsigned long long) (d / USEC_PER_HOUR),
1975 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1976 else if (d >= 5*USEC_PER_MINUTE)
1977 snprintf(buf, l, "%llumin ago",
1978 (unsigned long long) (d / USEC_PER_MINUTE));
1979 else if (d >= USEC_PER_MINUTE)
1980 snprintf(buf, l, "%llumin %llus ago",
1981 (unsigned long long) (d / USEC_PER_MINUTE),
1982 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1983 else if (d >= USEC_PER_SEC)
1984 snprintf(buf, l, "%llus ago",
1985 (unsigned long long) (d / USEC_PER_SEC));
1986 else if (d >= USEC_PER_MSEC)
1987 snprintf(buf, l, "%llums ago",
1988 (unsigned long long) (d / USEC_PER_MSEC));
1990 snprintf(buf, l, "%lluus ago",
1991 (unsigned long long) d);
1993 snprintf(buf, l, "now");
1999 char *format_timespan(char *buf, size_t l, usec_t t) {
2000 static const struct {
2004 { "w", USEC_PER_WEEK },
2005 { "d", USEC_PER_DAY },
2006 { "h", USEC_PER_HOUR },
2007 { "min", USEC_PER_MINUTE },
2008 { "s", USEC_PER_SEC },
2009 { "ms", USEC_PER_MSEC },
2019 if (t == (usec_t) -1)
2023 snprintf(p, l, "0");
2028 /* The result of this function can be parsed with parse_usec */
2030 for (i = 0; i < ELEMENTSOF(table); i++) {
2034 if (t < table[i].usec)
2040 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2041 n = MIN((size_t) k, l);
2054 bool fstype_is_network(const char *fstype) {
2055 static const char * const table[] = {
2067 for (i = 0; i < ELEMENTSOF(table); i++)
2068 if (streq(table[i], fstype))
2077 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2082 TIOCL_GETKMSGREDIRECT,
2086 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2091 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2094 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2098 close_nointr_nofail(fd);
2102 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2103 struct termios old_termios, new_termios;
2105 char line[LINE_MAX];
2110 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2111 new_termios = old_termios;
2113 new_termios.c_lflag &= ~ICANON;
2114 new_termios.c_cc[VMIN] = 1;
2115 new_termios.c_cc[VTIME] = 0;
2117 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2120 if (t != (usec_t) -1) {
2121 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2122 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2127 k = fread(&c, 1, 1, f);
2129 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2135 *need_nl = c != '\n';
2142 if (t != (usec_t) -1)
2143 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2146 if (!fgets(line, sizeof(line), f))
2151 if (strlen(line) != 1)
2161 int ask(char *ret, const char *replies, const char *text, ...) {
2168 on_tty = isatty(STDOUT_FILENO);
2174 bool need_nl = true;
2177 fputs(ANSI_HIGHLIGHT_ON, stdout);
2184 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2188 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2191 if (r == -EBADMSG) {
2192 puts("Bad input, please try again.");
2203 if (strchr(replies, c)) {
2208 puts("Read unexpected character, please try again.");
2212 int reset_terminal_fd(int fd, bool switch_to_text) {
2213 struct termios termios;
2216 /* Set terminal to some sane defaults */
2220 /* We leave locked terminal attributes untouched, so that
2221 * Plymouth may set whatever it wants to set, and we don't
2222 * interfere with that. */
2224 /* Disable exclusive mode, just in case */
2225 ioctl(fd, TIOCNXCL);
2227 /* Switch to text mode */
2229 ioctl(fd, KDSETMODE, KD_TEXT);
2231 /* Enable console unicode mode */
2232 ioctl(fd, KDSKBMODE, K_UNICODE);
2234 if (tcgetattr(fd, &termios) < 0) {
2239 /* We only reset the stuff that matters to the software. How
2240 * hardware is set up we don't touch assuming that somebody
2241 * else will do that for us */
2243 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2244 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2245 termios.c_oflag |= ONLCR;
2246 termios.c_cflag |= CREAD;
2247 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2249 termios.c_cc[VINTR] = 03; /* ^C */
2250 termios.c_cc[VQUIT] = 034; /* ^\ */
2251 termios.c_cc[VERASE] = 0177;
2252 termios.c_cc[VKILL] = 025; /* ^X */
2253 termios.c_cc[VEOF] = 04; /* ^D */
2254 termios.c_cc[VSTART] = 021; /* ^Q */
2255 termios.c_cc[VSTOP] = 023; /* ^S */
2256 termios.c_cc[VSUSP] = 032; /* ^Z */
2257 termios.c_cc[VLNEXT] = 026; /* ^V */
2258 termios.c_cc[VWERASE] = 027; /* ^W */
2259 termios.c_cc[VREPRINT] = 022; /* ^R */
2260 termios.c_cc[VEOL] = 0;
2261 termios.c_cc[VEOL2] = 0;
2263 termios.c_cc[VTIME] = 0;
2264 termios.c_cc[VMIN] = 1;
2266 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2270 /* Just in case, flush all crap out */
2271 tcflush(fd, TCIOFLUSH);
2276 int reset_terminal(const char *name) {
2279 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2283 r = reset_terminal_fd(fd, true);
2284 close_nointr_nofail(fd);
2289 int open_terminal(const char *name, int mode) {
2294 * If a TTY is in the process of being closed opening it might
2295 * cause EIO. This is horribly awful, but unlikely to be
2296 * changed in the kernel. Hence we work around this problem by
2297 * retrying a couple of times.
2299 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2303 fd = open(name, mode);
2310 /* Max 1s in total */
2314 usleep(50 * USEC_PER_MSEC);
2323 close_nointr_nofail(fd);
2328 close_nointr_nofail(fd);
2335 int flush_fd(int fd) {
2336 struct pollfd pollfd;
2340 pollfd.events = POLLIN;
2347 if ((r = poll(&pollfd, 1, 0)) < 0) {
2358 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2363 if (errno == EAGAIN)
2374 int acquire_terminal(
2378 bool ignore_tiocstty_eperm,
2381 int fd = -1, notify = -1, r = 0, wd = -1;
2383 struct sigaction sa_old, sa_new;
2387 /* We use inotify to be notified when the tty is closed. We
2388 * create the watch before checking if we can actually acquire
2389 * it, so that we don't lose any event.
2391 * Note: strictly speaking this actually watches for the
2392 * device being closed, it does *not* really watch whether a
2393 * tty loses its controlling process. However, unless some
2394 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2395 * its tty otherwise this will not become a problem. As long
2396 * as the administrator makes sure not configure any service
2397 * on the same tty as an untrusted user this should not be a
2398 * problem. (Which he probably should not do anyway.) */
2400 if (timeout != (usec_t) -1)
2401 ts = now(CLOCK_MONOTONIC);
2403 if (!fail && !force) {
2404 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2410 wd = inotify_add_watch(notify, name, IN_CLOSE);
2419 r = flush_fd(notify);
2424 /* We pass here O_NOCTTY only so that we can check the return
2425 * value TIOCSCTTY and have a reliable way to figure out if we
2426 * successfully became the controlling process of the tty */
2427 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2431 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2432 * if we already own the tty. */
2434 sa_new.sa_handler = SIG_IGN;
2435 sa_new.sa_flags = SA_RESTART;
2436 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2438 /* First, try to get the tty */
2439 if (ioctl(fd, TIOCSCTTY, force) < 0)
2442 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2444 /* Sometimes it makes sense to ignore TIOCSCTTY
2445 * returning EPERM, i.e. when very likely we already
2446 * are have this controlling terminal. */
2447 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2450 if (r < 0 && (force || fail || r != -EPERM)) {
2459 assert(notify >= 0);
2462 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2464 struct inotify_event *e;
2466 if (timeout != (usec_t) -1) {
2469 n = now(CLOCK_MONOTONIC);
2470 if (ts + timeout < n) {
2475 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2485 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2488 if (errno == EINTR || errno == EAGAIN)
2495 e = (struct inotify_event*) inotify_buffer;
2500 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2505 step = sizeof(struct inotify_event) + e->len;
2506 assert(step <= (size_t) l);
2508 e = (struct inotify_event*) ((uint8_t*) e + step);
2515 /* We close the tty fd here since if the old session
2516 * ended our handle will be dead. It's important that
2517 * we do this after sleeping, so that we don't enter
2518 * an endless loop. */
2519 close_nointr_nofail(fd);
2523 close_nointr_nofail(notify);
2525 r = reset_terminal_fd(fd, true);
2527 log_warning("Failed to reset terminal: %s", strerror(-r));
2533 close_nointr_nofail(fd);
2536 close_nointr_nofail(notify);
2541 int release_terminal(void) {
2543 struct sigaction sa_old, sa_new;
2545 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2548 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2549 * by our own TIOCNOTTY */
2552 sa_new.sa_handler = SIG_IGN;
2553 sa_new.sa_flags = SA_RESTART;
2554 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2556 if (ioctl(fd, TIOCNOTTY) < 0)
2559 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2561 close_nointr_nofail(fd);
2565 int sigaction_many(const struct sigaction *sa, ...) {
2570 while ((sig = va_arg(ap, int)) > 0)
2571 if (sigaction(sig, sa, NULL) < 0)
2578 int ignore_signals(int sig, ...) {
2579 struct sigaction sa;
2584 sa.sa_handler = SIG_IGN;
2585 sa.sa_flags = SA_RESTART;
2587 if (sigaction(sig, &sa, NULL) < 0)
2591 while ((sig = va_arg(ap, int)) > 0)
2592 if (sigaction(sig, &sa, NULL) < 0)
2599 int default_signals(int sig, ...) {
2600 struct sigaction sa;
2605 sa.sa_handler = SIG_DFL;
2606 sa.sa_flags = SA_RESTART;
2608 if (sigaction(sig, &sa, NULL) < 0)
2612 while ((sig = va_arg(ap, int)) > 0)
2613 if (sigaction(sig, &sa, NULL) < 0)
2620 int close_pipe(int p[]) {
2626 a = close_nointr(p[0]);
2631 b = close_nointr(p[1]);
2635 return a < 0 ? a : b;
2638 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2647 while (nbytes > 0) {
2650 if ((k = read(fd, p, nbytes)) <= 0) {
2652 if (k < 0 && errno == EINTR)
2655 if (k < 0 && errno == EAGAIN && do_poll) {
2656 struct pollfd pollfd;
2660 pollfd.events = POLLIN;
2662 if (poll(&pollfd, 1, -1) < 0) {
2666 return n > 0 ? n : -errno;
2669 if (pollfd.revents != POLLIN)
2670 return n > 0 ? n : -EIO;
2675 return n > 0 ? n : (k < 0 ? -errno : 0);
2686 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2695 while (nbytes > 0) {
2698 k = write(fd, p, nbytes);
2701 if (k < 0 && errno == EINTR)
2704 if (k < 0 && errno == EAGAIN && do_poll) {
2705 struct pollfd pollfd;
2709 pollfd.events = POLLOUT;
2711 if (poll(&pollfd, 1, -1) < 0) {
2715 return n > 0 ? n : -errno;
2718 if (pollfd.revents != POLLOUT)
2719 return n > 0 ? n : -EIO;
2724 return n > 0 ? n : (k < 0 ? -errno : 0);
2735 int parse_usec(const char *t, usec_t *usec) {
2736 static const struct {
2740 { "sec", USEC_PER_SEC },
2741 { "s", USEC_PER_SEC },
2742 { "min", USEC_PER_MINUTE },
2743 { "hr", USEC_PER_HOUR },
2744 { "h", USEC_PER_HOUR },
2745 { "d", USEC_PER_DAY },
2746 { "w", USEC_PER_WEEK },
2747 { "msec", USEC_PER_MSEC },
2748 { "ms", USEC_PER_MSEC },
2749 { "m", USEC_PER_MINUTE },
2752 { "", USEC_PER_SEC }, /* default is sec */
2768 l = strtoll(p, &e, 10);
2779 e += strspn(e, WHITESPACE);
2781 for (i = 0; i < ELEMENTSOF(table); i++)
2782 if (startswith(e, table[i].suffix)) {
2783 r += (usec_t) l * table[i].usec;
2784 p = e + strlen(table[i].suffix);
2788 if (i >= ELEMENTSOF(table))
2798 int parse_nsec(const char *t, nsec_t *nsec) {
2799 static const struct {
2803 { "sec", NSEC_PER_SEC },
2804 { "s", NSEC_PER_SEC },
2805 { "min", NSEC_PER_MINUTE },
2806 { "hr", NSEC_PER_HOUR },
2807 { "h", NSEC_PER_HOUR },
2808 { "d", NSEC_PER_DAY },
2809 { "w", NSEC_PER_WEEK },
2810 { "msec", NSEC_PER_MSEC },
2811 { "ms", NSEC_PER_MSEC },
2812 { "m", NSEC_PER_MINUTE },
2813 { "usec", NSEC_PER_USEC },
2814 { "us", NSEC_PER_USEC },
2817 { "", 1ULL }, /* default is nsec */
2833 l = strtoll(p, &e, 10);
2844 e += strspn(e, WHITESPACE);
2846 for (i = 0; i < ELEMENTSOF(table); i++)
2847 if (startswith(e, table[i].suffix)) {
2848 r += (nsec_t) l * table[i].nsec;
2849 p = e + strlen(table[i].suffix);
2853 if (i >= ELEMENTSOF(table))
2863 int parse_bytes(const char *t, off_t *bytes) {
2864 static const struct {
2870 { "M", 1024ULL*1024ULL },
2871 { "G", 1024ULL*1024ULL*1024ULL },
2872 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2873 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2874 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2891 l = strtoll(p, &e, 10);
2902 e += strspn(e, WHITESPACE);
2904 for (i = 0; i < ELEMENTSOF(table); i++)
2905 if (startswith(e, table[i].suffix)) {
2906 r += (off_t) l * table[i].factor;
2907 p = e + strlen(table[i].suffix);
2911 if (i >= ELEMENTSOF(table))
2921 int make_stdio(int fd) {
2926 r = dup2(fd, STDIN_FILENO);
2927 s = dup2(fd, STDOUT_FILENO);
2928 t = dup2(fd, STDERR_FILENO);
2931 close_nointr_nofail(fd);
2933 if (r < 0 || s < 0 || t < 0)
2936 fd_cloexec(STDIN_FILENO, false);
2937 fd_cloexec(STDOUT_FILENO, false);
2938 fd_cloexec(STDERR_FILENO, false);
2943 int make_null_stdio(void) {
2946 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2950 return make_stdio(null_fd);
2953 bool is_device_path(const char *path) {
2955 /* Returns true on paths that refer to a device, either in
2956 * sysfs or in /dev */
2959 path_startswith(path, "/dev/") ||
2960 path_startswith(path, "/sys/");
2963 int dir_is_empty(const char *path) {
2966 struct dirent buf, *de;
2968 if (!(d = opendir(path)))
2972 if ((r = readdir_r(d, &buf, &de)) > 0) {
2982 if (!ignore_file(de->d_name)) {
2992 unsigned long long random_ull(void) {
2997 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3001 r = loop_read(fd, &ull, sizeof(ull), true);
3002 close_nointr_nofail(fd);
3004 if (r != sizeof(ull))
3010 return random() * RAND_MAX + random();
3013 void rename_process(const char name[8]) {
3016 /* This is a like a poor man's setproctitle(). It changes the
3017 * comm field, argv[0], and also the glibc's internally used
3018 * name of the process. For the first one a limit of 16 chars
3019 * applies, to the second one usually one of 10 (i.e. length
3020 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3021 * "systemd"). If you pass a longer string it will be
3024 prctl(PR_SET_NAME, name);
3026 if (program_invocation_name)
3027 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3029 if (saved_argc > 0) {
3033 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3035 for (i = 1; i < saved_argc; i++) {
3039 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3044 void sigset_add_many(sigset_t *ss, ...) {
3051 while ((sig = va_arg(ap, int)) > 0)
3052 assert_se(sigaddset(ss, sig) == 0);
3056 char* gethostname_malloc(void) {
3059 assert_se(uname(&u) >= 0);
3061 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3062 return strdup(u.nodename);
3064 return strdup(u.sysname);
3067 bool hostname_is_set(void) {
3070 assert_se(uname(&u) >= 0);
3072 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3075 static char *lookup_uid(uid_t uid) {
3078 struct passwd pwbuf, *pw = NULL;
3080 /* Shortcut things to avoid NSS lookups */
3082 return strdup("root");
3084 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3088 buf = malloc(bufsize);
3092 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3093 name = strdup(pw->pw_name);
3100 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3106 char* getlogname_malloc(void) {
3110 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3115 return lookup_uid(uid);
3118 char *getusername_malloc(void) {
3125 return lookup_uid(getuid());
3128 int getttyname_malloc(int fd, char **r) {
3129 char path[PATH_MAX], *c;
3134 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3139 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3146 int getttyname_harder(int fd, char **r) {
3150 if ((k = getttyname_malloc(fd, &s)) < 0)
3153 if (streq(s, "tty")) {
3155 return get_ctty(0, NULL, r);
3162 int get_ctty_devnr(pid_t pid, dev_t *d) {
3164 char line[LINE_MAX], *p, *fn;
3165 unsigned long ttynr;
3168 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3171 f = fopen(fn, "re");
3176 if (!fgets(line, sizeof(line), f)) {
3177 k = feof(f) ? -EIO : -errno;
3184 p = strrchr(line, ')');
3194 "%*d " /* session */
3203 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3205 char fn[PATH_MAX], *s, *b, *p;
3210 k = get_ctty_devnr(pid, &devnr);
3214 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3217 if ((k = readlink_malloc(fn, &s)) < 0) {
3222 /* This is an ugly hack */
3223 if (major(devnr) == 136) {
3224 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3234 /* Probably something like the ptys which have no
3235 * symlink in /dev/char. Let's return something
3236 * vaguely useful. */
3238 if (!(b = strdup(fn + 5)))
3248 if (startswith(s, "/dev/"))
3250 else if (startswith(s, "../"))
3268 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3274 /* This returns the first error we run into, but nevertheless
3275 * tries to go on. This closes the passed fd. */
3279 close_nointr_nofail(fd);
3281 return errno == ENOENT ? 0 : -errno;
3285 struct dirent buf, *de;
3286 bool is_dir, keep_around;
3290 r = readdir_r(d, &buf, &de);
3291 if (r != 0 && ret == 0) {
3299 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3302 if (de->d_type == DT_UNKNOWN ||
3304 (de->d_type == DT_DIR && root_dev)) {
3305 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3306 if (ret == 0 && errno != ENOENT)
3311 is_dir = S_ISDIR(st.st_mode);
3314 (st.st_uid == 0 || st.st_uid == getuid()) &&
3315 (st.st_mode & S_ISVTX);
3317 is_dir = de->d_type == DT_DIR;
3318 keep_around = false;
3324 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3325 if (root_dev && st.st_dev != root_dev->st_dev)
3328 subdir_fd = openat(fd, de->d_name,
3329 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3330 if (subdir_fd < 0) {
3331 if (ret == 0 && errno != ENOENT)
3336 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3337 if (r < 0 && ret == 0)
3341 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3342 if (ret == 0 && errno != ENOENT)
3346 } else if (!only_dirs && !keep_around) {
3348 if (unlinkat(fd, de->d_name, 0) < 0) {
3349 if (ret == 0 && errno != ENOENT)
3360 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3365 if (fstatfs(fd, &s) < 0) {
3366 close_nointr_nofail(fd);
3370 /* We refuse to clean disk file systems with this call. This
3371 * is extra paranoia just to be sure we never ever remove
3374 if (s.f_type != TMPFS_MAGIC &&
3375 s.f_type != RAMFS_MAGIC) {
3376 log_error("Attempted to remove disk file system, and we can't allow that.");
3377 close_nointr_nofail(fd);
3381 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3384 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3390 /* We refuse to clean the root file system with this
3391 * call. This is extra paranoia to never cause a really
3392 * seriously broken system. */
3393 if (path_equal(path, "/")) {
3394 log_error("Attempted to remove entire root file system, and we can't allow that.");
3398 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3401 if (errno != ENOTDIR)
3405 if (statfs(path, &s) < 0)
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.");
3415 if (delete_root && !only_dirs)
3416 if (unlink(path) < 0 && errno != ENOENT)
3423 if (fstatfs(fd, &s) < 0) {
3424 close_nointr_nofail(fd);
3428 if (s.f_type != TMPFS_MAGIC &&
3429 s.f_type != RAMFS_MAGIC) {
3430 log_error("Attempted to remove disk file system, and we can't allow that.");
3431 close_nointr_nofail(fd);
3436 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3439 if (honour_sticky && file_is_priv_sticky(path) > 0)
3442 if (rmdir(path) < 0 && errno != ENOENT) {
3451 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3452 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3455 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3456 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3459 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3462 /* Under the assumption that we are running privileged we
3463 * first change the access mode and only then hand out
3464 * ownership to avoid a window where access is too open. */
3466 if (mode != (mode_t) -1)
3467 if (chmod(path, mode) < 0)
3470 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3471 if (chown(path, uid, gid) < 0)
3477 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3480 /* Under the assumption that we are running privileged we
3481 * first change the access mode and only then hand out
3482 * ownership to avoid a window where access is too open. */
3484 if (fchmod(fd, mode) < 0)
3487 if (fchown(fd, uid, gid) < 0)
3493 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3497 /* Allocates the cpuset in the right size */
3500 if (!(r = CPU_ALLOC(n)))
3503 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3504 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3514 if (errno != EINVAL)
3521 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3523 static const char status_indent[] = " "; /* "[" STATUS "] " */
3525 struct iovec iovec[5];
3530 /* This is independent of logging, as status messages are
3531 * optional and go exclusively to the console. */
3533 if (vasprintf(&s, format, ap) < 0)
3536 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3549 sl = status ? strlen(status_indent) : 0;
3555 e = ellipsize(s, emax, 75);
3565 if (!isempty(status)) {
3566 IOVEC_SET_STRING(iovec[n++], "[");
3567 IOVEC_SET_STRING(iovec[n++], status);
3568 IOVEC_SET_STRING(iovec[n++], "] ");
3570 IOVEC_SET_STRING(iovec[n++], status_indent);
3573 IOVEC_SET_STRING(iovec[n++], s);
3574 IOVEC_SET_STRING(iovec[n++], "\n");
3576 writev(fd, iovec, n);
3582 close_nointr_nofail(fd);
3585 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3590 va_start(ap, format);
3591 status_vprintf(status, ellipse, format, ap);
3595 void status_welcome(void) {
3596 char *pretty_name = NULL, *ansi_color = NULL;
3597 const char *const_pretty = NULL, *const_color = NULL;
3600 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3601 "PRETTY_NAME", &pretty_name,
3602 "ANSI_COLOR", &ansi_color,
3606 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3609 if (!pretty_name && !const_pretty)
3610 const_pretty = "Linux";
3612 if (!ansi_color && !const_color)
3617 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3618 const_color ? const_color : ansi_color,
3619 const_pretty ? const_pretty : pretty_name);
3625 char *replace_env(const char *format, char **env) {
3632 const char *e, *word = format;
3637 for (e = format; *e; e ++) {
3648 if (!(k = strnappend(r, word, e-word-1)))
3657 } else if (*e == '$') {
3658 if (!(k = strnappend(r, word, e-word)))
3674 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3677 if (!(k = strappend(r, t)))
3690 if (!(k = strnappend(r, word, e-word)))
3701 char **replace_env_argv(char **argv, char **env) {
3703 unsigned k = 0, l = 0;
3705 l = strv_length(argv);
3707 if (!(r = new(char*, l+1)))
3710 STRV_FOREACH(i, argv) {
3712 /* If $FOO appears as single word, replace it by the split up variable */
3713 if ((*i)[0] == '$' && (*i)[1] != '{') {
3718 if ((e = strv_env_get(env, *i+1))) {
3720 if (!(m = strv_split_quoted(e))) {
3731 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3740 memcpy(r + k, m, q * sizeof(char*));
3748 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3749 if (!(r[k++] = replace_env(*i, env))) {
3759 int fd_columns(int fd) {
3763 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3772 static unsigned columns_cached(bool cached) {
3773 static __thread int parsed_columns = 0, env_columns = -1;
3776 if (_likely_(parsed_columns > 0 && cached))
3777 return parsed_columns;
3779 if (_unlikely_(env_columns == -1)) {
3780 e = getenv("COLUMNS");
3782 env_columns = atoi(e);
3787 if (env_columns > 0) {
3788 parsed_columns = env_columns;
3789 return parsed_columns;
3792 if (parsed_columns <= 0 || !cached)
3793 parsed_columns = fd_columns(STDOUT_FILENO);
3795 if (parsed_columns <= 0)
3796 parsed_columns = 80;
3798 return parsed_columns;
3801 unsigned columns(void) {
3802 return columns_cached(true);
3805 unsigned columns_uncached(void) {
3806 return columns_cached(false);
3809 int fd_lines(int fd) {
3813 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3822 unsigned lines(void) {
3823 static __thread int parsed_lines = 0;
3826 if (_likely_(parsed_lines > 0))
3827 return parsed_lines;
3829 e = getenv("LINES");
3831 parsed_lines = atoi(e);
3833 if (parsed_lines <= 0)
3834 parsed_lines = fd_lines(STDOUT_FILENO);
3836 if (parsed_lines <= 0)
3839 return parsed_lines;
3842 int running_in_chroot(void) {
3848 /* Only works as root */
3850 if (stat("/proc/1/root", &a) < 0)
3853 if (stat("/", &b) < 0)
3857 a.st_dev != b.st_dev ||
3858 a.st_ino != b.st_ino;
3861 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3866 assert(percent <= 100);
3867 assert(new_length >= 3);
3869 if (old_length <= 3 || old_length <= new_length)
3870 return strndup(s, old_length);
3872 r = new0(char, new_length+1);
3876 x = (new_length * percent) / 100;
3878 if (x > new_length - 3)
3886 s + old_length - (new_length - x - 3),
3887 new_length - x - 3);
3892 char *ellipsize(const char *s, size_t length, unsigned percent) {
3893 return ellipsize_mem(s, strlen(s), length, percent);
3896 int touch(const char *path) {
3901 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3904 close_nointr_nofail(fd);
3908 char *unquote(const char *s, const char* quotes) {
3916 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3917 return strndup(s+1, l-2);
3922 char *normalize_env_assignment(const char *s) {
3923 char *name, *value, *p, *r;
3928 if (!(r = strdup(s)))
3934 if (!(name = strndup(s, p - s)))
3937 if (!(p = strdup(p+1))) {
3942 value = unquote(strstrip(p), QUOTES);
3950 if (asprintf(&r, "%s=%s", name, value) < 0)
3959 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3970 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3982 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3989 r = wait_for_terminate(pid, &status);
3991 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3995 if (status.si_code == CLD_EXITED) {
3996 if (status.si_status != 0) {
3997 log_warning("%s failed with error code %i.", name, status.si_status);
3998 return status.si_status;
4001 log_debug("%s succeeded.", name);
4004 } else if (status.si_code == CLD_KILLED ||
4005 status.si_code == CLD_DUMPED) {
4007 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4011 log_warning("%s failed due to unknown reason.", name);
4015 _noreturn_ void freeze(void) {
4017 /* Make sure nobody waits for us on a socket anymore */
4018 close_all_fds(NULL, 0);
4026 bool null_or_empty(struct stat *st) {
4029 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4032 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4038 int null_or_empty_path(const char *fn) {
4043 if (stat(fn, &st) < 0)
4046 return null_or_empty(&st);
4049 DIR *xopendirat(int fd, const char *name, int flags) {
4053 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4056 if (!(d = fdopendir(nfd))) {
4057 close_nointr_nofail(nfd);
4064 int signal_from_string_try_harder(const char *s) {
4068 if ((signo = signal_from_string(s)) <= 0)
4069 if (startswith(s, "SIG"))
4070 return signal_from_string(s+3);
4075 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4081 if (!dual_timestamp_is_set(t))
4084 fprintf(f, "%s=%llu %llu\n",
4086 (unsigned long long) t->realtime,
4087 (unsigned long long) t->monotonic);
4090 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4091 unsigned long long a, b;
4096 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4097 log_debug("Failed to parse finish timestamp value %s", value);
4104 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4108 /* FIXME: to follow udev's logic 100% we need to leave valid
4109 * UTF8 chars unescaped */
4111 u = unquote(tagvalue, "\"\'");
4115 t = xescape(u, "/ ");
4121 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4130 char *fstab_node_to_udev_node(const char *p) {
4131 if (startswith(p, "LABEL="))
4132 return tag_to_udev_node(p+6, "label");
4134 if (startswith(p, "UUID="))
4135 return tag_to_udev_node(p+5, "uuid");
4137 if (startswith(p, "PARTUUID="))
4138 return tag_to_udev_node(p+9, "partuuid");
4140 if (startswith(p, "PARTLABEL="))
4141 return tag_to_udev_node(p+10, "partlabel");
4146 bool tty_is_vc(const char *tty) {
4149 if (startswith(tty, "/dev/"))
4152 return vtnr_from_tty(tty) >= 0;
4155 bool tty_is_console(const char *tty) {
4158 if (startswith(tty, "/dev/"))
4161 return streq(tty, "console");
4164 int vtnr_from_tty(const char *tty) {
4169 if (startswith(tty, "/dev/"))
4172 if (!startswith(tty, "tty") )
4175 if (tty[3] < '0' || tty[3] > '9')
4178 r = safe_atoi(tty+3, &i);
4182 if (i < 0 || i > 63)
4188 bool tty_is_vc_resolve(const char *tty) {
4189 char *active = NULL;
4194 if (startswith(tty, "/dev/"))
4197 /* Resolve where /dev/console is pointing to, if /sys is
4198 * actually ours (i.e. not read-only-mounted which is a sign
4199 * for container setups) */
4200 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4201 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4202 /* If multiple log outputs are configured the
4203 * last one is what /dev/console points to */
4204 tty = strrchr(active, ' ');
4217 const char *default_term_for_tty(const char *tty) {
4220 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4223 bool dirent_is_file(const struct dirent *de) {
4226 if (ignore_file(de->d_name))
4229 if (de->d_type != DT_REG &&
4230 de->d_type != DT_LNK &&
4231 de->d_type != DT_UNKNOWN)
4237 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4240 if (de->d_type != DT_REG &&
4241 de->d_type != DT_LNK &&
4242 de->d_type != DT_UNKNOWN)
4245 if (ignore_file_allow_backup(de->d_name))
4248 return endswith(de->d_name, suffix);
4251 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4254 Hashmap *pids = NULL;
4258 /* Executes all binaries in a directory in parallel and waits
4259 * until all they all finished. */
4262 if (!(_d = opendir(directory))) {
4264 if (errno == ENOENT)
4267 log_error("Failed to enumerate directory %s: %m", directory);
4274 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4275 log_error("Failed to allocate set.");
4279 while ((de = readdir(d))) {
4284 if (!dirent_is_file(de))
4287 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4292 if ((pid = fork()) < 0) {
4293 log_error("Failed to fork: %m");
4311 log_error("Failed to execute %s: %m", path);
4312 _exit(EXIT_FAILURE);
4315 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4317 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4318 log_error("Failed to add PID to set: %s", strerror(-k));
4323 while (!hashmap_isempty(pids)) {
4324 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4329 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4334 log_error("waitid() failed: %m");
4338 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4339 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4340 if (si.si_code == CLD_EXITED)
4341 log_error("%s exited with exit status %i.", path, si.si_status);
4343 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4345 log_debug("%s exited successfully.", path);
4356 hashmap_free_free(pids);
4359 int kill_and_sigcont(pid_t pid, int sig) {
4362 r = kill(pid, sig) < 0 ? -errno : 0;
4370 bool nulstr_contains(const char*nulstr, const char *needle) {
4376 NULSTR_FOREACH(i, nulstr)
4377 if (streq(i, needle))
4383 bool plymouth_running(void) {
4384 return access("/run/plymouth/pid", F_OK) >= 0;
4387 char* strshorten(char *s, size_t l) {
4396 static bool hostname_valid_char(char c) {
4398 (c >= 'a' && c <= 'z') ||
4399 (c >= 'A' && c <= 'Z') ||
4400 (c >= '0' && c <= '9') ||
4406 bool hostname_is_valid(const char *s) {
4412 for (p = s; *p; p++)
4413 if (!hostname_valid_char(*p))
4416 if (p-s > HOST_NAME_MAX)
4422 char* hostname_cleanup(char *s) {
4425 for (p = s, d = s; *p; p++)
4426 if ((*p >= 'a' && *p <= 'z') ||
4427 (*p >= 'A' && *p <= 'Z') ||
4428 (*p >= '0' && *p <= '9') ||
4436 strshorten(s, HOST_NAME_MAX);
4440 int pipe_eof(int fd) {
4441 struct pollfd pollfd;
4446 pollfd.events = POLLIN|POLLHUP;
4448 r = poll(&pollfd, 1, 0);
4455 return pollfd.revents & POLLHUP;
4458 int fd_wait_for_event(int fd, int event, usec_t t) {
4459 struct pollfd pollfd;
4464 pollfd.events = event;
4466 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4473 return pollfd.revents;
4476 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4487 t = new(char, strlen(path) + 1 + 6 + 1);
4491 fn = path_get_file_name(path);
4495 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4497 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4503 f = fdopen(fd, "we");
4516 int terminal_vhangup_fd(int fd) {
4519 if (ioctl(fd, TIOCVHANGUP) < 0)
4525 int terminal_vhangup(const char *name) {
4528 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4532 r = terminal_vhangup_fd(fd);
4533 close_nointr_nofail(fd);
4538 int vt_disallocate(const char *name) {
4542 /* Deallocate the VT if possible. If not possible
4543 * (i.e. because it is the active one), at least clear it
4544 * entirely (including the scrollback buffer) */
4546 if (!startswith(name, "/dev/"))
4549 if (!tty_is_vc(name)) {
4550 /* So this is not a VT. I guess we cannot deallocate
4551 * it then. But let's at least clear the screen */
4553 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4558 "\033[r" /* clear scrolling region */
4559 "\033[H" /* move home */
4560 "\033[2J", /* clear screen */
4562 close_nointr_nofail(fd);
4567 if (!startswith(name, "/dev/tty"))
4570 r = safe_atou(name+8, &u);
4577 /* Try to deallocate */
4578 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4582 r = ioctl(fd, VT_DISALLOCATE, u);
4583 close_nointr_nofail(fd);
4591 /* Couldn't deallocate, so let's clear it fully with
4593 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4598 "\033[r" /* clear scrolling region */
4599 "\033[H" /* move home */
4600 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4602 close_nointr_nofail(fd);
4607 int copy_file(const char *from, const char *to) {
4613 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4617 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4619 close_nointr_nofail(fdf);
4627 n = read(fdf, buf, sizeof(buf));
4631 close_nointr_nofail(fdf);
4642 k = loop_write(fdt, buf, n, false);
4644 r = k < 0 ? k : (errno ? -errno : -EIO);
4646 close_nointr_nofail(fdf);
4654 close_nointr_nofail(fdf);
4655 r = close_nointr(fdt);
4665 int symlink_or_copy(const char *from, const char *to) {
4666 char *pf = NULL, *pt = NULL;
4673 if (path_get_parent(from, &pf) < 0 ||
4674 path_get_parent(to, &pt) < 0) {
4679 if (stat(pf, &a) < 0 ||
4685 if (a.st_dev != b.st_dev) {
4689 return copy_file(from, to);
4692 if (symlink(from, to) < 0) {
4706 int symlink_or_copy_atomic(const char *from, const char *to) {
4710 unsigned long long ull;
4717 t = new(char, strlen(to) + 1 + 16 + 1);
4721 fn = path_get_file_name(to);
4725 x = stpcpy(t+k+1, fn);
4728 for (i = 0; i < 16; i++) {
4729 *(x++) = hexchar(ull & 0xF);
4735 r = symlink_or_copy(from, t);
4742 if (rename(t, to) < 0) {
4753 bool display_is_local(const char *display) {
4757 display[0] == ':' &&
4758 display[1] >= '0' &&
4762 int socket_from_display(const char *display, char **path) {
4769 if (!display_is_local(display))
4772 k = strspn(display+1, "0123456789");
4774 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4778 c = stpcpy(f, "/tmp/.X11-unix/X");
4779 memcpy(c, display+1, k);
4788 const char **username,
4789 uid_t *uid, gid_t *gid,
4791 const char **shell) {
4799 /* We enforce some special rules for uid=0: in order to avoid
4800 * NSS lookups for root we hardcode its data. */
4802 if (streq(*username, "root") || streq(*username, "0")) {
4820 if (parse_uid(*username, &u) >= 0) {
4824 /* If there are multiple users with the same id, make
4825 * sure to leave $USER to the configured value instead
4826 * of the first occurrence in the database. However if
4827 * the uid was configured by a numeric uid, then let's
4828 * pick the real username from /etc/passwd. */
4830 *username = p->pw_name;
4833 p = getpwnam(*username);
4837 return errno != 0 ? -errno : -ESRCH;
4849 *shell = p->pw_shell;
4854 int get_group_creds(const char **groupname, gid_t *gid) {
4860 /* We enforce some special rules for gid=0: in order to avoid
4861 * NSS lookups for root we hardcode its data. */
4863 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4864 *groupname = "root";
4872 if (parse_gid(*groupname, &id) >= 0) {
4877 *groupname = g->gr_name;
4880 g = getgrnam(*groupname);
4884 return errno != 0 ? -errno : -ESRCH;
4892 int in_group(const char *name) {
4894 int ngroups_max, r, i;
4896 r = get_group_creds(&name, &gid);
4900 if (getgid() == gid)
4903 if (getegid() == gid)
4906 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4907 assert(ngroups_max > 0);
4909 gids = alloca(sizeof(gid_t) * ngroups_max);
4911 r = getgroups(ngroups_max, gids);
4915 for (i = 0; i < r; i++)
4922 int glob_exists(const char *path) {
4930 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4932 if (k == GLOB_NOMATCH)
4934 else if (k == GLOB_NOSPACE)
4937 r = !strv_isempty(g.gl_pathv);
4939 r = errno ? -errno : -EIO;
4946 int dirent_ensure_type(DIR *d, struct dirent *de) {
4952 if (de->d_type != DT_UNKNOWN)
4955 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4959 S_ISREG(st.st_mode) ? DT_REG :
4960 S_ISDIR(st.st_mode) ? DT_DIR :
4961 S_ISLNK(st.st_mode) ? DT_LNK :
4962 S_ISFIFO(st.st_mode) ? DT_FIFO :
4963 S_ISSOCK(st.st_mode) ? DT_SOCK :
4964 S_ISCHR(st.st_mode) ? DT_CHR :
4965 S_ISBLK(st.st_mode) ? DT_BLK :
4971 int in_search_path(const char *path, char **search) {
4975 r = path_get_parent(path, &parent);
4981 STRV_FOREACH(i, search) {
4982 if (path_equal(parent, *i)) {
4993 int get_files_in_directory(const char *path, char ***list) {
5001 /* Returns all files in a directory in *list, and the number
5002 * of files as return value. If list is NULL returns only the
5010 struct dirent buffer, *de;
5013 k = readdir_r(d, &buffer, &de);
5022 dirent_ensure_type(d, de);
5024 if (!dirent_is_file(de))
5028 if ((unsigned) r >= n) {
5032 t = realloc(l, sizeof(char*) * n);
5041 assert((unsigned) r < n);
5043 l[r] = strdup(de->d_name);
5067 char *strjoin(const char *x, ...) {
5080 t = va_arg(ap, const char *);
5103 t = va_arg(ap, const char *);
5117 bool is_main_thread(void) {
5118 static __thread int cached = 0;
5120 if (_unlikely_(cached == 0))
5121 cached = getpid() == gettid() ? 1 : -1;
5126 int block_get_whole_disk(dev_t d, dev_t *ret) {
5133 /* If it has a queue this is good enough for us */
5134 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5137 r = access(p, F_OK);
5145 /* If it is a partition find the originating device */
5146 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5149 r = access(p, F_OK);
5155 /* Get parent dev_t */
5156 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5159 r = read_one_line_file(p, &s);
5165 r = sscanf(s, "%u:%u", &m, &n);
5171 /* Only return this if it is really good enough for us. */
5172 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5175 r = access(p, F_OK);
5179 *ret = makedev(m, n);
5186 int file_is_priv_sticky(const char *p) {
5191 if (lstat(p, &st) < 0)
5195 (st.st_uid == 0 || st.st_uid == getuid()) &&
5196 (st.st_mode & S_ISVTX);
5199 static const char *const ioprio_class_table[] = {
5200 [IOPRIO_CLASS_NONE] = "none",
5201 [IOPRIO_CLASS_RT] = "realtime",
5202 [IOPRIO_CLASS_BE] = "best-effort",
5203 [IOPRIO_CLASS_IDLE] = "idle"
5206 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5208 static const char *const sigchld_code_table[] = {
5209 [CLD_EXITED] = "exited",
5210 [CLD_KILLED] = "killed",
5211 [CLD_DUMPED] = "dumped",
5212 [CLD_TRAPPED] = "trapped",
5213 [CLD_STOPPED] = "stopped",
5214 [CLD_CONTINUED] = "continued",
5217 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5219 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5220 [LOG_FAC(LOG_KERN)] = "kern",
5221 [LOG_FAC(LOG_USER)] = "user",
5222 [LOG_FAC(LOG_MAIL)] = "mail",
5223 [LOG_FAC(LOG_DAEMON)] = "daemon",
5224 [LOG_FAC(LOG_AUTH)] = "auth",
5225 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5226 [LOG_FAC(LOG_LPR)] = "lpr",
5227 [LOG_FAC(LOG_NEWS)] = "news",
5228 [LOG_FAC(LOG_UUCP)] = "uucp",
5229 [LOG_FAC(LOG_CRON)] = "cron",
5230 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5231 [LOG_FAC(LOG_FTP)] = "ftp",
5232 [LOG_FAC(LOG_LOCAL0)] = "local0",
5233 [LOG_FAC(LOG_LOCAL1)] = "local1",
5234 [LOG_FAC(LOG_LOCAL2)] = "local2",
5235 [LOG_FAC(LOG_LOCAL3)] = "local3",
5236 [LOG_FAC(LOG_LOCAL4)] = "local4",
5237 [LOG_FAC(LOG_LOCAL5)] = "local5",
5238 [LOG_FAC(LOG_LOCAL6)] = "local6",
5239 [LOG_FAC(LOG_LOCAL7)] = "local7"
5242 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5244 static const char *const log_level_table[] = {
5245 [LOG_EMERG] = "emerg",
5246 [LOG_ALERT] = "alert",
5247 [LOG_CRIT] = "crit",
5249 [LOG_WARNING] = "warning",
5250 [LOG_NOTICE] = "notice",
5251 [LOG_INFO] = "info",
5252 [LOG_DEBUG] = "debug"
5255 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5257 static const char* const sched_policy_table[] = {
5258 [SCHED_OTHER] = "other",
5259 [SCHED_BATCH] = "batch",
5260 [SCHED_IDLE] = "idle",
5261 [SCHED_FIFO] = "fifo",
5265 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5267 static const char* const rlimit_table[] = {
5268 [RLIMIT_CPU] = "LimitCPU",
5269 [RLIMIT_FSIZE] = "LimitFSIZE",
5270 [RLIMIT_DATA] = "LimitDATA",
5271 [RLIMIT_STACK] = "LimitSTACK",
5272 [RLIMIT_CORE] = "LimitCORE",
5273 [RLIMIT_RSS] = "LimitRSS",
5274 [RLIMIT_NOFILE] = "LimitNOFILE",
5275 [RLIMIT_AS] = "LimitAS",
5276 [RLIMIT_NPROC] = "LimitNPROC",
5277 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5278 [RLIMIT_LOCKS] = "LimitLOCKS",
5279 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5280 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5281 [RLIMIT_NICE] = "LimitNICE",
5282 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5283 [RLIMIT_RTTIME] = "LimitRTTIME"
5286 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5288 static const char* const ip_tos_table[] = {
5289 [IPTOS_LOWDELAY] = "low-delay",
5290 [IPTOS_THROUGHPUT] = "throughput",
5291 [IPTOS_RELIABILITY] = "reliability",
5292 [IPTOS_LOWCOST] = "low-cost",
5295 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5297 static const char *const __signal_table[] = {
5314 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5325 [SIGVTALRM] = "VTALRM",
5327 [SIGWINCH] = "WINCH",
5333 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5335 const char *signal_to_string(int signo) {
5336 static __thread char buf[12];
5339 name = __signal_to_string(signo);
5343 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5344 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5346 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5351 int signal_from_string(const char *s) {
5356 signo =__signal_from_string(s);
5360 if (startswith(s, "RTMIN+")) {
5364 if (safe_atou(s, &u) >= 0) {
5365 signo = (int) u + offset;
5366 if (signo > 0 && signo < _NSIG)
5372 bool kexec_loaded(void) {
5373 bool loaded = false;
5376 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5384 int strdup_or_null(const char *a, char **b) {
5402 int prot_from_flags(int flags) {
5404 switch (flags & O_ACCMODE) {
5413 return PROT_READ|PROT_WRITE;
5420 char *format_bytes(char *buf, size_t l, off_t t) {
5423 static const struct {
5427 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5428 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5429 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5430 { "G", 1024ULL*1024ULL*1024ULL },
5431 { "M", 1024ULL*1024ULL },
5435 for (i = 0; i < ELEMENTSOF(table); i++) {
5437 if (t >= table[i].factor) {
5440 (unsigned long long) (t / table[i].factor),
5441 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5448 snprintf(buf, l, "%lluB", (unsigned long long) t);
5456 void* memdup(const void *p, size_t l) {
5469 int fd_inc_sndbuf(int fd, size_t n) {
5471 socklen_t l = sizeof(value);
5473 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5475 l == sizeof(value) &&
5476 (size_t) value >= n*2)
5480 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5487 int fd_inc_rcvbuf(int fd, size_t n) {
5489 socklen_t l = sizeof(value);
5491 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5493 l == sizeof(value) &&
5494 (size_t) value >= n*2)
5498 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5505 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5506 pid_t parent_pid, agent_pid;
5508 bool stdout_is_tty, stderr_is_tty;
5516 parent_pid = getpid();
5518 /* Spawns a temporary TTY agent, making sure it goes away when
5525 if (agent_pid != 0) {
5532 * Make sure the agent goes away when the parent dies */
5533 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5534 _exit(EXIT_FAILURE);
5536 /* Check whether our parent died before we were able
5537 * to set the death signal */
5538 if (getppid() != parent_pid)
5539 _exit(EXIT_SUCCESS);
5541 /* Don't leak fds to the agent */
5542 close_all_fds(except, n_except);
5544 stdout_is_tty = isatty(STDOUT_FILENO);
5545 stderr_is_tty = isatty(STDERR_FILENO);
5547 if (!stdout_is_tty || !stderr_is_tty) {
5548 /* Detach from stdout/stderr. and reopen
5549 * /dev/tty for them. This is important to
5550 * ensure that when systemctl is started via
5551 * popen() or a similar call that expects to
5552 * read EOF we actually do generate EOF and
5553 * not delay this indefinitely by because we
5554 * keep an unused copy of stdin around. */
5555 fd = open("/dev/tty", O_WRONLY);
5557 log_error("Failed to open /dev/tty: %m");
5558 _exit(EXIT_FAILURE);
5562 dup2(fd, STDOUT_FILENO);
5565 dup2(fd, STDERR_FILENO);
5571 /* Count arguments */
5573 for (n = 0; va_arg(ap, char*); n++)
5578 l = alloca(sizeof(char *) * (n + 1));
5580 /* Fill in arguments */
5582 for (i = 0; i <= n; i++)
5583 l[i] = va_arg(ap, char*);
5587 _exit(EXIT_FAILURE);
5590 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5591 struct rlimit highest, fixed;
5595 if (setrlimit(resource, rlim) >= 0)
5601 /* So we failed to set the desired setrlimit, then let's try
5602 * to get as close as we can */
5603 assert_se(getrlimit(resource, &highest) == 0);
5605 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5606 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5608 if (setrlimit(resource, &fixed) < 0)
5614 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5615 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5627 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5630 f = fopen(path, "re");
5638 char line[LINE_MAX];
5641 for (i = 0; i < sizeof(line)-1; i++) {
5645 if (_unlikely_(c == EOF)) {
5655 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5656 value = strdup(line + l + 1);
5676 int can_sleep(const char *type) {
5677 char *p, *w, *state;
5684 r = read_one_line_file("/sys/power/state", &p);
5686 return r == -ENOENT ? 0 : r;
5690 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5691 if (l == k && strncmp(w, type, l) == 0) {
5701 bool is_valid_documentation_url(const char *url) {
5704 if (startswith(url, "http://") && url[7])
5707 if (startswith(url, "https://") && url[8])
5710 if (startswith(url, "file:") && url[5])
5713 if (startswith(url, "info:") && url[5])
5716 if (startswith(url, "man:") && url[4])
5722 bool in_initrd(void) {
5723 static int saved = -1;
5729 /* We make two checks here:
5731 * 1. the flag file /etc/initrd-release must exist
5732 * 2. the root file system must be a memory file system
5734 * The second check is extra paranoia, since misdetecting an
5735 * initrd can have bad bad consequences due the initrd
5736 * emptying when transititioning to the main systemd.
5739 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5740 statfs("/", &s) >= 0 &&
5741 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5746 void warn_melody(void) {
5749 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5753 /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5755 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5756 usleep(125*USEC_PER_MSEC);
5758 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5759 usleep(125*USEC_PER_MSEC);
5761 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5762 usleep(125*USEC_PER_MSEC);
5764 ioctl(fd, KIOCSOUND, 0);
5765 close_nointr_nofail(fd);
5768 int make_console_stdio(void) {
5771 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5773 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5775 log_error("Failed to acquire terminal: %s", strerror(-fd));
5781 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5788 int get_home_dir(char **_h) {
5796 /* Take the user specified one */
5807 /* Hardcode home directory for root to avoid NSS */
5810 h = strdup("/root");
5818 /* Check the database... */
5822 return errno ? -errno : -ENOENT;
5824 if (!path_is_absolute(p->pw_dir))
5827 h = strdup(p->pw_dir);
5835 int get_shell(char **_sh) {
5843 /* Take the user specified one */
5844 e = getenv("SHELL");
5854 /* Hardcode home directory for root to avoid NSS */
5857 sh = strdup("/bin/sh");
5865 /* Check the database... */
5869 return errno ? -errno : -ESRCH;
5871 if (!path_is_absolute(p->pw_shell))
5874 sh = strdup(p->pw_shell);
5882 void freep(void *p) {
5886 void fclosep(FILE **f) {