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 r = sysconf(_SC_PAGESIZE);
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]))
233 bool first_word(const char *s, const char *word) {
248 if (memcmp(s, word, wl) != 0)
252 strchr(WHITESPACE, s[wl]);
255 int close_nointr(int fd) {
270 void close_nointr_nofail(int fd) {
271 int saved_errno = errno;
273 /* like close_nointr() but cannot fail, and guarantees errno
276 assert_se(close_nointr(fd) == 0);
281 void close_many(const int fds[], unsigned n_fd) {
284 for (i = 0; i < n_fd; i++)
285 close_nointr_nofail(fds[i]);
288 int parse_boolean(const char *v) {
291 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
293 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
299 int parse_pid(const char *s, pid_t* ret_pid) {
300 unsigned long ul = 0;
307 r = safe_atolu(s, &ul);
313 if ((unsigned long) pid != ul)
323 int parse_uid(const char *s, uid_t* ret_uid) {
324 unsigned long ul = 0;
331 r = safe_atolu(s, &ul);
337 if ((unsigned long) uid != ul)
344 int safe_atou(const char *s, unsigned *ret_u) {
352 l = strtoul(s, &x, 0);
354 if (!x || *x || errno)
355 return errno ? -errno : -EINVAL;
357 if ((unsigned long) (unsigned) l != l)
360 *ret_u = (unsigned) l;
364 int safe_atoi(const char *s, int *ret_i) {
372 l = strtol(s, &x, 0);
374 if (!x || *x || errno)
375 return errno ? -errno : -EINVAL;
377 if ((long) (int) l != l)
384 int safe_atollu(const char *s, long long unsigned *ret_llu) {
386 unsigned long long l;
392 l = strtoull(s, &x, 0);
394 if (!x || *x || errno)
395 return errno ? -errno : -EINVAL;
401 int safe_atolli(const char *s, long long int *ret_lli) {
409 l = strtoll(s, &x, 0);
411 if (!x || *x || errno)
412 return errno ? -errno : -EINVAL;
418 /* Split a string into words. */
419 char *split(const char *c, size_t *l, const char *separator, char **state) {
422 current = *state ? *state : (char*) c;
424 if (!*current || *c == 0)
427 current += strspn(current, separator);
428 *l = strcspn(current, separator);
431 return (char*) current;
434 /* Split a string into words, but consider strings enclosed in '' and
435 * "" as words even if they include spaces. */
436 char *split_quoted(const char *c, size_t *l, char **state) {
438 bool escaped = false;
440 current = *state ? *state : (char*) c;
442 if (!*current || *c == 0)
445 current += strspn(current, WHITESPACE);
447 if (*current == '\'') {
450 for (e = current; *e; e++) {
460 *state = *e == 0 ? e : e+1;
461 } else if (*current == '\"') {
464 for (e = current; *e; e++) {
474 *state = *e == 0 ? e : e+1;
476 for (e = current; *e; e++) {
481 else if (strchr(WHITESPACE, *e))
488 return (char*) current;
491 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
493 _cleanup_fclose_ FILE *f = NULL;
494 char fn[PATH_MAX], line[LINE_MAX], *p;
500 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
507 if (!fgets(line, sizeof(line), f)) {
508 r = feof(f) ? -EIO : -errno;
513 /* Let's skip the pid and comm fields. The latter is enclosed
514 * in () but does not escape any () in its value, so let's
515 * skip over it manually */
517 p = strrchr(line, ')');
529 if ((long unsigned) (pid_t) ppid != ppid)
532 *_ppid = (pid_t) ppid;
537 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
538 _cleanup_fclose_ FILE *f = NULL;
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));
551 if (!fgets(line, sizeof(line), f)) {
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 p = strrchr(line, ')');
584 "%*d " /* priority */
586 "%*d " /* num_threads */
587 "%*d " /* itrealvalue */
588 "%llu " /* starttime */,
595 int write_one_line_file(const char *fn, const char *line) {
596 _cleanup_fclose_ FILE *f = NULL;
606 if (fputs(line, f) < 0)
607 return errno ? -errno : -EIO;
609 if (!endswith(line, "\n"))
615 return errno ? -errno : -EIO;
620 int fchmod_umask(int fd, mode_t m) {
625 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
631 int write_one_line_file_atomic(const char *fn, const char *line) {
639 r = fopen_temporary(fn, &f, &p);
643 fchmod_umask(fileno(f), 0644);
646 if (fputs(line, f) < 0) {
651 if (!endswith(line, "\n"))
662 if (rename(p, fn) < 0)
678 int read_one_line_file(const char *fn, char **line) {
679 _cleanup_fclose_ FILE *f = NULL;
680 char t[LINE_MAX], *c;
689 if (!fgets(t, sizeof(t), f)) {
692 return errno ? -errno : -EIO;
706 int read_full_file(const char *fn, char **contents, size_t *size) {
707 _cleanup_fclose_ FILE *f = NULL;
709 _cleanup_free_ char *buf = NULL;
716 if (fstat(fileno(f), &st) < 0)
720 if (st.st_size > 4*1024*1024)
723 n = st.st_size > 0 ? st.st_size : LINE_MAX;
730 t = realloc(buf, n+1);
735 k = fread(buf + l, 1, n - l, f);
764 const char *separator, ...) {
767 char *contents = NULL, *p;
772 if ((r = read_full_file(fname, &contents, NULL)) < 0)
777 const char *key = NULL;
779 p += strspn(p, separator);
780 p += strspn(p, WHITESPACE);
785 if (!strchr(COMMENTS, *p)) {
789 va_start(ap, separator);
790 while ((key = va_arg(ap, char *))) {
794 value = va_arg(ap, char **);
797 if (strncmp(p, key, n) != 0 ||
802 n = strcspn(p, separator);
805 strchr(QUOTES, p[0]) &&
807 v = strndup(p+1, n-2);
818 /* return empty value strings as NULL */
835 p += strcspn(p, separator);
854 if (!(f = fopen(fname, "re")))
858 char l[LINE_MAX], *p, *u;
861 if (!fgets(l, sizeof(l), f)) {
874 if (strchr(COMMENTS, *p))
877 if (!(u = normalize_env_assignment(p))) {
882 t = strv_append(m, u);
908 int write_env_file(const char *fname, char **l) {
913 r = fopen_temporary(fname, &f, &p);
917 fchmod_umask(fileno(f), 0644);
933 if (rename(p, fname) < 0)
948 char *truncate_nl(char *s) {
951 s[strcspn(s, NEWLINE)] = 0;
955 int get_process_comm(pid_t pid, char **name) {
961 r = read_one_line_file("/proc/self/comm", name);
964 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
967 r = read_one_line_file(p, name);
974 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
981 assert(max_length > 0);
985 f = fopen("/proc/self/cmdline", "re");
988 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
998 r = new(char, max_length);
1006 while ((c = getc(f)) != EOF) {
1028 size_t n = MIN(left-1, 3U);
1029 memcpy(k, "...", n);
1036 /* Kernel threads have no argv[] */
1046 h = get_process_comm(pid, &t);
1050 r = strjoin("[", t, "]", NULL);
1061 int is_kernel_thread(pid_t pid) {
1071 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1080 count = fread(&c, 1, 1, f);
1084 /* Kernel threads have an empty cmdline */
1087 return eof ? 1 : -errno;
1092 int get_process_exe(pid_t pid, char **name) {
1098 r = readlink_malloc("/proc/self/exe", name);
1101 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1104 r = readlink_malloc(p, name);
1111 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1121 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1131 char line[LINE_MAX], *l;
1133 if (!fgets(line, sizeof(line), f)) {
1143 if (startswith(l, field)) {
1145 l += strspn(l, WHITESPACE);
1147 l[strcspn(l, WHITESPACE)] = 0;
1149 r = parse_uid(l, uid);
1162 int get_process_uid(pid_t pid, uid_t *uid) {
1163 return get_process_id(pid, "Uid:", uid);
1166 int get_process_gid(pid_t pid, gid_t *gid) {
1167 return get_process_id(pid, "Gid:", gid);
1170 char *strnappend(const char *s, const char *suffix, size_t b) {
1178 return strndup(suffix, b);
1187 if (b > ((size_t) -1) - a)
1190 r = new(char, a+b+1);
1195 memcpy(r+a, suffix, b);
1201 char *strappend(const char *s, const char *suffix) {
1202 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1205 int readlink_malloc(const char *p, char **r) {
1215 if (!(c = new(char, l)))
1218 if ((n = readlink(p, c, l-1)) < 0) {
1224 if ((size_t) n < l-1) {
1235 int readlink_and_make_absolute(const char *p, char **r) {
1242 if ((j = readlink_malloc(p, &target)) < 0)
1245 k = file_in_same_dir(p, target);
1255 int readlink_and_canonicalize(const char *p, char **r) {
1262 j = readlink_and_make_absolute(p, &t);
1266 s = canonicalize_file_name(t);
1273 path_kill_slashes(*r);
1278 int reset_all_signal_handlers(void) {
1281 for (sig = 1; sig < _NSIG; sig++) {
1282 struct sigaction sa;
1284 if (sig == SIGKILL || sig == SIGSTOP)
1288 sa.sa_handler = SIG_DFL;
1289 sa.sa_flags = SA_RESTART;
1291 /* On Linux the first two RT signals are reserved by
1292 * glibc, and sigaction() will return EINVAL for them. */
1293 if ((sigaction(sig, &sa, NULL) < 0))
1294 if (errno != EINVAL)
1301 char *strstrip(char *s) {
1304 /* Drops trailing whitespace. Modifies the string in
1305 * place. Returns pointer to first non-space character */
1307 s += strspn(s, WHITESPACE);
1309 for (e = strchr(s, 0); e > s; e --)
1310 if (!strchr(WHITESPACE, e[-1]))
1318 char *delete_chars(char *s, const char *bad) {
1321 /* Drops all whitespace, regardless where in the string */
1323 for (f = s, t = s; *f; f++) {
1324 if (strchr(bad, *f))
1335 bool in_charset(const char *s, const char* charset) {
1341 for (i = s; *i; i++)
1342 if (!strchr(charset, *i))
1348 char *file_in_same_dir(const char *path, const char *filename) {
1355 /* This removes the last component of path and appends
1356 * filename, unless the latter is absolute anyway or the
1359 if (path_is_absolute(filename))
1360 return strdup(filename);
1362 if (!(e = strrchr(path, '/')))
1363 return strdup(filename);
1365 k = strlen(filename);
1366 if (!(r = new(char, e-path+1+k+1)))
1369 memcpy(r, path, e-path+1);
1370 memcpy(r+(e-path)+1, filename, k+1);
1375 int rmdir_parents(const char *path, const char *stop) {
1384 /* Skip trailing slashes */
1385 while (l > 0 && path[l-1] == '/')
1391 /* Skip last component */
1392 while (l > 0 && path[l-1] != '/')
1395 /* Skip trailing slashes */
1396 while (l > 0 && path[l-1] == '/')
1402 if (!(t = strndup(path, l)))
1405 if (path_startswith(stop, t)) {
1414 if (errno != ENOENT)
1422 char hexchar(int x) {
1423 static const char table[16] = "0123456789abcdef";
1425 return table[x & 15];
1428 int unhexchar(char c) {
1430 if (c >= '0' && c <= '9')
1433 if (c >= 'a' && c <= 'f')
1434 return c - 'a' + 10;
1436 if (c >= 'A' && c <= 'F')
1437 return c - 'A' + 10;
1442 char octchar(int x) {
1443 return '0' + (x & 7);
1446 int unoctchar(char c) {
1448 if (c >= '0' && c <= '7')
1454 char decchar(int x) {
1455 return '0' + (x % 10);
1458 int undecchar(char c) {
1460 if (c >= '0' && c <= '9')
1466 char *cescape(const char *s) {
1472 /* Does C style string escaping. */
1474 r = new(char, strlen(s)*4 + 1);
1478 for (f = s, t = r; *f; f++)
1524 /* For special chars we prefer octal over
1525 * hexadecimal encoding, simply because glib's
1526 * g_strescape() does the same */
1527 if ((*f < ' ') || (*f >= 127)) {
1529 *(t++) = octchar((unsigned char) *f >> 6);
1530 *(t++) = octchar((unsigned char) *f >> 3);
1531 *(t++) = octchar((unsigned char) *f);
1542 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1549 /* Undoes C style string escaping, and optionally prefixes it. */
1551 pl = prefix ? strlen(prefix) : 0;
1553 r = new(char, pl+length+1);
1558 memcpy(r, prefix, pl);
1560 for (f = s, t = r + pl; f < s + length; f++) {
1603 /* This is an extension of the XDG syntax files */
1608 /* hexadecimal encoding */
1611 a = unhexchar(f[1]);
1612 b = unhexchar(f[2]);
1614 if (a < 0 || b < 0) {
1615 /* Invalid escape code, let's take it literal then */
1619 *(t++) = (char) ((a << 4) | b);
1634 /* octal encoding */
1637 a = unoctchar(f[0]);
1638 b = unoctchar(f[1]);
1639 c = unoctchar(f[2]);
1641 if (a < 0 || b < 0 || c < 0) {
1642 /* Invalid escape code, let's take it literal then */
1646 *(t++) = (char) ((a << 6) | (b << 3) | c);
1654 /* premature end of string.*/
1659 /* Invalid escape code, let's take it literal then */
1671 char *cunescape_length(const char *s, size_t length) {
1672 return cunescape_length_with_prefix(s, length, NULL);
1675 char *cunescape(const char *s) {
1678 return cunescape_length(s, strlen(s));
1681 char *xescape(const char *s, const char *bad) {
1685 /* Escapes all chars in bad, in addition to \ and all special
1686 * chars, in \xFF style escaping. May be reversed with
1689 if (!(r = new(char, strlen(s)*4+1)))
1692 for (f = s, t = r; *f; f++) {
1694 if ((*f < ' ') || (*f >= 127) ||
1695 (*f == '\\') || strchr(bad, *f)) {
1698 *(t++) = hexchar(*f >> 4);
1699 *(t++) = hexchar(*f);
1709 char *bus_path_escape(const char *s) {
1715 /* Escapes all chars that D-Bus' object path cannot deal
1716 * with. Can be reverse with bus_path_unescape() */
1718 if (!(r = new(char, strlen(s)*3+1)))
1721 for (f = s, t = r; *f; f++) {
1723 if (!(*f >= 'A' && *f <= 'Z') &&
1724 !(*f >= 'a' && *f <= 'z') &&
1725 !(*f >= '0' && *f <= '9')) {
1727 *(t++) = hexchar(*f >> 4);
1728 *(t++) = hexchar(*f);
1738 char *bus_path_unescape(const char *f) {
1743 if (!(r = strdup(f)))
1746 for (t = r; *f; f++) {
1751 if ((a = unhexchar(f[1])) < 0 ||
1752 (b = unhexchar(f[2])) < 0) {
1753 /* Invalid escape code, let's take it literal then */
1756 *(t++) = (char) ((a << 4) | b);
1768 char *ascii_strlower(char *t) {
1773 for (p = t; *p; p++)
1774 if (*p >= 'A' && *p <= 'Z')
1775 *p = *p - 'A' + 'a';
1780 static bool ignore_file_allow_backup(const char *filename) {
1784 filename[0] == '.' ||
1785 streq(filename, "lost+found") ||
1786 streq(filename, "aquota.user") ||
1787 streq(filename, "aquota.group") ||
1788 endswith(filename, ".rpmnew") ||
1789 endswith(filename, ".rpmsave") ||
1790 endswith(filename, ".rpmorig") ||
1791 endswith(filename, ".dpkg-old") ||
1792 endswith(filename, ".dpkg-new") ||
1793 endswith(filename, ".swp");
1796 bool ignore_file(const char *filename) {
1799 if (endswith(filename, "~"))
1802 return ignore_file_allow_backup(filename);
1805 int fd_nonblock(int fd, bool nonblock) {
1810 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1814 flags |= O_NONBLOCK;
1816 flags &= ~O_NONBLOCK;
1818 if (fcntl(fd, F_SETFL, flags) < 0)
1824 int fd_cloexec(int fd, bool cloexec) {
1829 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1833 flags |= FD_CLOEXEC;
1835 flags &= ~FD_CLOEXEC;
1837 if (fcntl(fd, F_SETFD, flags) < 0)
1843 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1846 assert(n_fdset == 0 || fdset);
1848 for (i = 0; i < n_fdset; i++)
1855 int close_all_fds(const int except[], unsigned n_except) {
1860 assert(n_except == 0 || except);
1862 d = opendir("/proc/self/fd");
1867 /* When /proc isn't available (for example in chroots)
1868 * the fallback is brute forcing through the fd
1871 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1872 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1874 if (fd_in_set(fd, except, n_except))
1877 if (close_nointr(fd) < 0)
1878 if (errno != EBADF && r == 0)
1885 while ((de = readdir(d))) {
1888 if (ignore_file(de->d_name))
1891 if (safe_atoi(de->d_name, &fd) < 0)
1892 /* Let's better ignore this, just in case */
1901 if (fd_in_set(fd, except, n_except))
1904 if (close_nointr(fd) < 0) {
1905 /* Valgrind has its own FD and doesn't want to have it closed */
1906 if (errno != EBADF && r == 0)
1915 bool chars_intersect(const char *a, const char *b) {
1918 /* Returns true if any of the chars in a are in b. */
1919 for (p = a; *p; p++)
1926 char *format_timestamp(char *buf, size_t l, usec_t t) {
1936 sec = (time_t) (t / USEC_PER_SEC);
1938 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1944 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1947 n = now(CLOCK_REALTIME);
1949 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1954 if (d >= USEC_PER_YEAR)
1955 snprintf(buf, l, "%llu years and %llu months ago",
1956 (unsigned long long) (d / USEC_PER_YEAR),
1957 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1958 else if (d >= USEC_PER_MONTH)
1959 snprintf(buf, l, "%llu months and %llu days ago",
1960 (unsigned long long) (d / USEC_PER_MONTH),
1961 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1962 else if (d >= USEC_PER_WEEK)
1963 snprintf(buf, l, "%llu weeks and %llu days ago",
1964 (unsigned long long) (d / USEC_PER_WEEK),
1965 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1966 else if (d >= 2*USEC_PER_DAY)
1967 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1968 else if (d >= 25*USEC_PER_HOUR)
1969 snprintf(buf, l, "1 day and %lluh ago",
1970 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1971 else if (d >= 6*USEC_PER_HOUR)
1972 snprintf(buf, l, "%lluh ago",
1973 (unsigned long long) (d / USEC_PER_HOUR));
1974 else if (d >= USEC_PER_HOUR)
1975 snprintf(buf, l, "%lluh %llumin ago",
1976 (unsigned long long) (d / USEC_PER_HOUR),
1977 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1978 else if (d >= 5*USEC_PER_MINUTE)
1979 snprintf(buf, l, "%llumin ago",
1980 (unsigned long long) (d / USEC_PER_MINUTE));
1981 else if (d >= USEC_PER_MINUTE)
1982 snprintf(buf, l, "%llumin %llus ago",
1983 (unsigned long long) (d / USEC_PER_MINUTE),
1984 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1985 else if (d >= USEC_PER_SEC)
1986 snprintf(buf, l, "%llus ago",
1987 (unsigned long long) (d / USEC_PER_SEC));
1988 else if (d >= USEC_PER_MSEC)
1989 snprintf(buf, l, "%llums ago",
1990 (unsigned long long) (d / USEC_PER_MSEC));
1992 snprintf(buf, l, "%lluus ago",
1993 (unsigned long long) d);
1995 snprintf(buf, l, "now");
2001 char *format_timespan(char *buf, size_t l, usec_t t) {
2002 static const struct {
2006 { "w", USEC_PER_WEEK },
2007 { "d", USEC_PER_DAY },
2008 { "h", USEC_PER_HOUR },
2009 { "min", USEC_PER_MINUTE },
2010 { "s", USEC_PER_SEC },
2011 { "ms", USEC_PER_MSEC },
2021 if (t == (usec_t) -1)
2025 snprintf(p, l, "0");
2030 /* The result of this function can be parsed with parse_usec */
2032 for (i = 0; i < ELEMENTSOF(table); i++) {
2036 if (t < table[i].usec)
2042 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2043 n = MIN((size_t) k, l);
2056 bool fstype_is_network(const char *fstype) {
2057 static const char table[] =
2066 return nulstr_contains(table, fstype);
2070 _cleanup_close_ int fd;
2072 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2078 TIOCL_GETKMSGREDIRECT,
2082 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2085 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2088 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2094 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2095 struct termios old_termios, new_termios;
2097 char line[LINE_MAX];
2102 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2103 new_termios = old_termios;
2105 new_termios.c_lflag &= ~ICANON;
2106 new_termios.c_cc[VMIN] = 1;
2107 new_termios.c_cc[VTIME] = 0;
2109 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2112 if (t != (usec_t) -1) {
2113 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2114 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2119 k = fread(&c, 1, 1, f);
2121 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2127 *need_nl = c != '\n';
2134 if (t != (usec_t) -1)
2135 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2138 if (!fgets(line, sizeof(line), f))
2143 if (strlen(line) != 1)
2153 int ask(char *ret, const char *replies, const char *text, ...) {
2160 on_tty = isatty(STDOUT_FILENO);
2166 bool need_nl = true;
2169 fputs(ANSI_HIGHLIGHT_ON, stdout);
2176 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2180 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2183 if (r == -EBADMSG) {
2184 puts("Bad input, please try again.");
2195 if (strchr(replies, c)) {
2200 puts("Read unexpected character, please try again.");
2204 int reset_terminal_fd(int fd, bool switch_to_text) {
2205 struct termios termios;
2208 /* Set terminal to some sane defaults */
2212 /* We leave locked terminal attributes untouched, so that
2213 * Plymouth may set whatever it wants to set, and we don't
2214 * interfere with that. */
2216 /* Disable exclusive mode, just in case */
2217 ioctl(fd, TIOCNXCL);
2219 /* Switch to text mode */
2221 ioctl(fd, KDSETMODE, KD_TEXT);
2223 /* Enable console unicode mode */
2224 ioctl(fd, KDSKBMODE, K_UNICODE);
2226 if (tcgetattr(fd, &termios) < 0) {
2231 /* We only reset the stuff that matters to the software. How
2232 * hardware is set up we don't touch assuming that somebody
2233 * else will do that for us */
2235 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2236 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2237 termios.c_oflag |= ONLCR;
2238 termios.c_cflag |= CREAD;
2239 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2241 termios.c_cc[VINTR] = 03; /* ^C */
2242 termios.c_cc[VQUIT] = 034; /* ^\ */
2243 termios.c_cc[VERASE] = 0177;
2244 termios.c_cc[VKILL] = 025; /* ^X */
2245 termios.c_cc[VEOF] = 04; /* ^D */
2246 termios.c_cc[VSTART] = 021; /* ^Q */
2247 termios.c_cc[VSTOP] = 023; /* ^S */
2248 termios.c_cc[VSUSP] = 032; /* ^Z */
2249 termios.c_cc[VLNEXT] = 026; /* ^V */
2250 termios.c_cc[VWERASE] = 027; /* ^W */
2251 termios.c_cc[VREPRINT] = 022; /* ^R */
2252 termios.c_cc[VEOL] = 0;
2253 termios.c_cc[VEOL2] = 0;
2255 termios.c_cc[VTIME] = 0;
2256 termios.c_cc[VMIN] = 1;
2258 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2262 /* Just in case, flush all crap out */
2263 tcflush(fd, TCIOFLUSH);
2268 int reset_terminal(const char *name) {
2271 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2275 r = reset_terminal_fd(fd, true);
2276 close_nointr_nofail(fd);
2281 int open_terminal(const char *name, int mode) {
2286 * If a TTY is in the process of being closed opening it might
2287 * cause EIO. This is horribly awful, but unlikely to be
2288 * changed in the kernel. Hence we work around this problem by
2289 * retrying a couple of times.
2291 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2295 fd = open(name, mode);
2302 /* Max 1s in total */
2306 usleep(50 * USEC_PER_MSEC);
2315 close_nointr_nofail(fd);
2320 close_nointr_nofail(fd);
2327 int flush_fd(int fd) {
2328 struct pollfd pollfd;
2332 pollfd.events = POLLIN;
2339 if ((r = poll(&pollfd, 1, 0)) < 0) {
2350 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2355 if (errno == EAGAIN)
2366 int acquire_terminal(
2370 bool ignore_tiocstty_eperm,
2373 int fd = -1, notify = -1, r = 0, wd = -1;
2375 struct sigaction sa_old, sa_new;
2379 /* We use inotify to be notified when the tty is closed. We
2380 * create the watch before checking if we can actually acquire
2381 * it, so that we don't lose any event.
2383 * Note: strictly speaking this actually watches for the
2384 * device being closed, it does *not* really watch whether a
2385 * tty loses its controlling process. However, unless some
2386 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2387 * its tty otherwise this will not become a problem. As long
2388 * as the administrator makes sure not configure any service
2389 * on the same tty as an untrusted user this should not be a
2390 * problem. (Which he probably should not do anyway.) */
2392 if (timeout != (usec_t) -1)
2393 ts = now(CLOCK_MONOTONIC);
2395 if (!fail && !force) {
2396 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2402 wd = inotify_add_watch(notify, name, IN_CLOSE);
2411 r = flush_fd(notify);
2416 /* We pass here O_NOCTTY only so that we can check the return
2417 * value TIOCSCTTY and have a reliable way to figure out if we
2418 * successfully became the controlling process of the tty */
2419 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2423 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2424 * if we already own the tty. */
2426 sa_new.sa_handler = SIG_IGN;
2427 sa_new.sa_flags = SA_RESTART;
2428 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2430 /* First, try to get the tty */
2431 if (ioctl(fd, TIOCSCTTY, force) < 0)
2434 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2436 /* Sometimes it makes sense to ignore TIOCSCTTY
2437 * returning EPERM, i.e. when very likely we already
2438 * are have this controlling terminal. */
2439 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2442 if (r < 0 && (force || fail || r != -EPERM)) {
2451 assert(notify >= 0);
2454 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2456 struct inotify_event *e;
2458 if (timeout != (usec_t) -1) {
2461 n = now(CLOCK_MONOTONIC);
2462 if (ts + timeout < n) {
2467 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2477 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2480 if (errno == EINTR || errno == EAGAIN)
2487 e = (struct inotify_event*) inotify_buffer;
2492 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2497 step = sizeof(struct inotify_event) + e->len;
2498 assert(step <= (size_t) l);
2500 e = (struct inotify_event*) ((uint8_t*) e + step);
2507 /* We close the tty fd here since if the old session
2508 * ended our handle will be dead. It's important that
2509 * we do this after sleeping, so that we don't enter
2510 * an endless loop. */
2511 close_nointr_nofail(fd);
2515 close_nointr_nofail(notify);
2517 r = reset_terminal_fd(fd, true);
2519 log_warning("Failed to reset terminal: %s", strerror(-r));
2525 close_nointr_nofail(fd);
2528 close_nointr_nofail(notify);
2533 int release_terminal(void) {
2535 struct sigaction sa_old, sa_new;
2537 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2540 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2541 * by our own TIOCNOTTY */
2544 sa_new.sa_handler = SIG_IGN;
2545 sa_new.sa_flags = SA_RESTART;
2546 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2548 if (ioctl(fd, TIOCNOTTY) < 0)
2551 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2553 close_nointr_nofail(fd);
2557 int sigaction_many(const struct sigaction *sa, ...) {
2562 while ((sig = va_arg(ap, int)) > 0)
2563 if (sigaction(sig, sa, NULL) < 0)
2570 int ignore_signals(int sig, ...) {
2571 struct sigaction sa;
2576 sa.sa_handler = SIG_IGN;
2577 sa.sa_flags = SA_RESTART;
2579 if (sigaction(sig, &sa, NULL) < 0)
2583 while ((sig = va_arg(ap, int)) > 0)
2584 if (sigaction(sig, &sa, NULL) < 0)
2591 int default_signals(int sig, ...) {
2592 struct sigaction sa;
2597 sa.sa_handler = SIG_DFL;
2598 sa.sa_flags = SA_RESTART;
2600 if (sigaction(sig, &sa, NULL) < 0)
2604 while ((sig = va_arg(ap, int)) > 0)
2605 if (sigaction(sig, &sa, NULL) < 0)
2612 int close_pipe(int p[]) {
2618 a = close_nointr(p[0]);
2623 b = close_nointr(p[1]);
2627 return a < 0 ? a : b;
2630 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2639 while (nbytes > 0) {
2642 if ((k = read(fd, p, nbytes)) <= 0) {
2644 if (k < 0 && errno == EINTR)
2647 if (k < 0 && errno == EAGAIN && do_poll) {
2648 struct pollfd pollfd;
2652 pollfd.events = POLLIN;
2654 if (poll(&pollfd, 1, -1) < 0) {
2658 return n > 0 ? n : -errno;
2661 if (pollfd.revents != POLLIN)
2662 return n > 0 ? n : -EIO;
2667 return n > 0 ? n : (k < 0 ? -errno : 0);
2678 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2687 while (nbytes > 0) {
2690 k = write(fd, p, nbytes);
2693 if (k < 0 && errno == EINTR)
2696 if (k < 0 && errno == EAGAIN && do_poll) {
2697 struct pollfd pollfd;
2701 pollfd.events = POLLOUT;
2703 if (poll(&pollfd, 1, -1) < 0) {
2707 return n > 0 ? n : -errno;
2710 if (pollfd.revents != POLLOUT)
2711 return n > 0 ? n : -EIO;
2716 return n > 0 ? n : (k < 0 ? -errno : 0);
2727 int parse_usec(const char *t, usec_t *usec) {
2728 static const struct {
2732 { "sec", USEC_PER_SEC },
2733 { "s", USEC_PER_SEC },
2734 { "min", USEC_PER_MINUTE },
2735 { "hr", USEC_PER_HOUR },
2736 { "h", USEC_PER_HOUR },
2737 { "d", USEC_PER_DAY },
2738 { "w", USEC_PER_WEEK },
2739 { "msec", USEC_PER_MSEC },
2740 { "ms", USEC_PER_MSEC },
2741 { "m", USEC_PER_MINUTE },
2744 { "", USEC_PER_SEC }, /* default is sec */
2760 l = strtoll(p, &e, 10);
2771 e += strspn(e, WHITESPACE);
2773 for (i = 0; i < ELEMENTSOF(table); i++)
2774 if (startswith(e, table[i].suffix)) {
2775 r += (usec_t) l * table[i].usec;
2776 p = e + strlen(table[i].suffix);
2780 if (i >= ELEMENTSOF(table))
2790 int parse_nsec(const char *t, nsec_t *nsec) {
2791 static const struct {
2795 { "sec", NSEC_PER_SEC },
2796 { "s", NSEC_PER_SEC },
2797 { "min", NSEC_PER_MINUTE },
2798 { "hr", NSEC_PER_HOUR },
2799 { "h", NSEC_PER_HOUR },
2800 { "d", NSEC_PER_DAY },
2801 { "w", NSEC_PER_WEEK },
2802 { "msec", NSEC_PER_MSEC },
2803 { "ms", NSEC_PER_MSEC },
2804 { "m", NSEC_PER_MINUTE },
2805 { "usec", NSEC_PER_USEC },
2806 { "us", NSEC_PER_USEC },
2809 { "", 1ULL }, /* default is nsec */
2825 l = strtoll(p, &e, 10);
2836 e += strspn(e, WHITESPACE);
2838 for (i = 0; i < ELEMENTSOF(table); i++)
2839 if (startswith(e, table[i].suffix)) {
2840 r += (nsec_t) l * table[i].nsec;
2841 p = e + strlen(table[i].suffix);
2845 if (i >= ELEMENTSOF(table))
2855 int parse_bytes(const char *t, off_t *bytes) {
2856 static const struct {
2862 { "M", 1024ULL*1024ULL },
2863 { "G", 1024ULL*1024ULL*1024ULL },
2864 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2865 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2866 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2883 l = strtoll(p, &e, 10);
2894 e += strspn(e, WHITESPACE);
2896 for (i = 0; i < ELEMENTSOF(table); i++)
2897 if (startswith(e, table[i].suffix)) {
2898 r += (off_t) l * table[i].factor;
2899 p = e + strlen(table[i].suffix);
2903 if (i >= ELEMENTSOF(table))
2913 int make_stdio(int fd) {
2918 r = dup3(fd, STDIN_FILENO, 0);
2919 s = dup3(fd, STDOUT_FILENO, 0);
2920 t = dup3(fd, STDERR_FILENO, 0);
2923 close_nointr_nofail(fd);
2925 if (r < 0 || s < 0 || t < 0)
2928 /* We rely here that the new fd has O_CLOEXEC not set */
2933 int make_null_stdio(void) {
2936 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2940 return make_stdio(null_fd);
2943 bool is_device_path(const char *path) {
2945 /* Returns true on paths that refer to a device, either in
2946 * sysfs or in /dev */
2949 path_startswith(path, "/dev/") ||
2950 path_startswith(path, "/sys/");
2953 int dir_is_empty(const char *path) {
2954 _cleanup_closedir_ DIR *d;
2963 union dirent_storage buf;
2965 r = readdir_r(d, &buf.de, &de);
2972 if (!ignore_file(de->d_name))
2977 unsigned long long random_ull(void) {
2978 _cleanup_close_ int fd;
2982 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2986 r = loop_read(fd, &ull, sizeof(ull), true);
2987 if (r != sizeof(ull))
2993 return random() * RAND_MAX + random();
2996 void rename_process(const char name[8]) {
2999 /* This is a like a poor man's setproctitle(). It changes the
3000 * comm field, argv[0], and also the glibc's internally used
3001 * name of the process. For the first one a limit of 16 chars
3002 * applies, to the second one usually one of 10 (i.e. length
3003 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3004 * "systemd"). If you pass a longer string it will be
3007 prctl(PR_SET_NAME, name);
3009 if (program_invocation_name)
3010 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3012 if (saved_argc > 0) {
3016 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3018 for (i = 1; i < saved_argc; i++) {
3022 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3027 void sigset_add_many(sigset_t *ss, ...) {
3034 while ((sig = va_arg(ap, int)) > 0)
3035 assert_se(sigaddset(ss, sig) == 0);
3039 char* gethostname_malloc(void) {
3042 assert_se(uname(&u) >= 0);
3044 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3045 return strdup(u.nodename);
3047 return strdup(u.sysname);
3050 bool hostname_is_set(void) {
3053 assert_se(uname(&u) >= 0);
3055 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3058 static char *lookup_uid(uid_t uid) {
3061 _cleanup_free_ char *buf = NULL;
3062 struct passwd pwbuf, *pw = NULL;
3064 /* Shortcut things to avoid NSS lookups */
3066 return strdup("root");
3068 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3072 buf = malloc(bufsize);
3076 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3077 return strdup(pw->pw_name);
3079 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3085 char* getlogname_malloc(void) {
3089 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3094 return lookup_uid(uid);
3097 char *getusername_malloc(void) {
3104 return lookup_uid(getuid());
3107 int getttyname_malloc(int fd, char **r) {
3108 char path[PATH_MAX], *c;
3113 k = ttyname_r(fd, path, sizeof(path));
3119 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3127 int getttyname_harder(int fd, char **r) {
3131 k = getttyname_malloc(fd, &s);
3135 if (streq(s, "tty")) {
3137 return get_ctty(0, NULL, r);
3144 int get_ctty_devnr(pid_t pid, dev_t *d) {
3146 char line[LINE_MAX], *p, *fn;
3147 unsigned long ttynr;
3150 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3153 f = fopen(fn, "re");
3158 if (!fgets(line, sizeof(line), f)) {
3159 k = feof(f) ? -EIO : -errno;
3166 p = strrchr(line, ')');
3176 "%*d " /* session */
3185 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3187 char fn[PATH_MAX], *s, *b, *p;
3192 k = get_ctty_devnr(pid, &devnr);
3196 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3199 if ((k = readlink_malloc(fn, &s)) < 0) {
3204 /* This is an ugly hack */
3205 if (major(devnr) == 136) {
3206 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3216 /* Probably something like the ptys which have no
3217 * symlink in /dev/char. Let's return something
3218 * vaguely useful. */
3220 if (!(b = strdup(fn + 5)))
3230 if (startswith(s, "/dev/"))
3232 else if (startswith(s, "../"))
3250 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3256 /* This returns the first error we run into, but nevertheless
3257 * tries to go on. This closes the passed fd. */
3261 close_nointr_nofail(fd);
3263 return errno == ENOENT ? 0 : -errno;
3268 union dirent_storage buf;
3269 bool is_dir, keep_around;
3273 r = readdir_r(d, &buf.de, &de);
3274 if (r != 0 && ret == 0) {
3282 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3285 if (de->d_type == DT_UNKNOWN ||
3287 (de->d_type == DT_DIR && root_dev)) {
3288 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3289 if (ret == 0 && errno != ENOENT)
3294 is_dir = S_ISDIR(st.st_mode);
3297 (st.st_uid == 0 || st.st_uid == getuid()) &&
3298 (st.st_mode & S_ISVTX);
3300 is_dir = de->d_type == DT_DIR;
3301 keep_around = false;
3307 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3308 if (root_dev && st.st_dev != root_dev->st_dev)
3311 subdir_fd = openat(fd, de->d_name,
3312 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3313 if (subdir_fd < 0) {
3314 if (ret == 0 && errno != ENOENT)
3319 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3320 if (r < 0 && ret == 0)
3324 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3325 if (ret == 0 && errno != ENOENT)
3329 } else if (!only_dirs && !keep_around) {
3331 if (unlinkat(fd, de->d_name, 0) < 0) {
3332 if (ret == 0 && errno != ENOENT)
3343 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3348 if (fstatfs(fd, &s) < 0) {
3349 close_nointr_nofail(fd);
3353 /* We refuse to clean disk file systems with this call. This
3354 * is extra paranoia just to be sure we never ever remove
3357 if (s.f_type != TMPFS_MAGIC &&
3358 s.f_type != RAMFS_MAGIC) {
3359 log_error("Attempted to remove disk file system, and we can't allow that.");
3360 close_nointr_nofail(fd);
3364 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3367 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3373 /* We refuse to clean the root file system with this
3374 * call. This is extra paranoia to never cause a really
3375 * seriously broken system. */
3376 if (path_equal(path, "/")) {
3377 log_error("Attempted to remove entire root file system, and we can't allow that.");
3381 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3384 if (errno != ENOTDIR)
3388 if (statfs(path, &s) < 0)
3391 if (s.f_type != TMPFS_MAGIC &&
3392 s.f_type != RAMFS_MAGIC) {
3393 log_error("Attempted to remove disk file system, and we can't allow that.");
3398 if (delete_root && !only_dirs)
3399 if (unlink(path) < 0 && errno != ENOENT)
3406 if (fstatfs(fd, &s) < 0) {
3407 close_nointr_nofail(fd);
3411 if (s.f_type != TMPFS_MAGIC &&
3412 s.f_type != RAMFS_MAGIC) {
3413 log_error("Attempted to remove disk file system, and we can't allow that.");
3414 close_nointr_nofail(fd);
3419 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3422 if (honour_sticky && file_is_priv_sticky(path) > 0)
3425 if (rmdir(path) < 0 && errno != ENOENT) {
3434 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3435 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3438 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3439 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3442 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3445 /* Under the assumption that we are running privileged we
3446 * first change the access mode and only then hand out
3447 * ownership to avoid a window where access is too open. */
3449 if (mode != (mode_t) -1)
3450 if (chmod(path, mode) < 0)
3453 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3454 if (chown(path, uid, gid) < 0)
3460 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3463 /* Under the assumption that we are running privileged we
3464 * first change the access mode and only then hand out
3465 * ownership to avoid a window where access is too open. */
3467 if (fchmod(fd, mode) < 0)
3470 if (fchown(fd, uid, gid) < 0)
3476 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3480 /* Allocates the cpuset in the right size */
3483 if (!(r = CPU_ALLOC(n)))
3486 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3487 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3497 if (errno != EINVAL)
3504 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3505 static const char status_indent[] = " "; /* "[" STATUS "] " */
3506 _cleanup_free_ char *s = NULL;
3507 _cleanup_close_ int fd = -1;
3508 struct iovec iovec[5];
3513 /* This is independent of logging, as status messages are
3514 * optional and go exclusively to the console. */
3516 if (vasprintf(&s, format, ap) < 0)
3519 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3532 sl = status ? sizeof(status_indent)-1 : 0;
3538 e = ellipsize(s, emax, 75);
3548 if (!isempty(status)) {
3549 IOVEC_SET_STRING(iovec[n++], "[");
3550 IOVEC_SET_STRING(iovec[n++], status);
3551 IOVEC_SET_STRING(iovec[n++], "] ");
3553 IOVEC_SET_STRING(iovec[n++], status_indent);
3556 IOVEC_SET_STRING(iovec[n++], s);
3557 IOVEC_SET_STRING(iovec[n++], "\n");
3559 if (writev(fd, iovec, n) < 0)
3565 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3571 va_start(ap, format);
3572 r = status_vprintf(status, ellipse, format, ap);
3578 int status_welcome(void) {
3580 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3582 r = parse_env_file("/etc/os-release", NEWLINE,
3583 "PRETTY_NAME", &pretty_name,
3584 "ANSI_COLOR", &ansi_color,
3586 if (r < 0 && r != -ENOENT)
3587 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3589 return status_printf(NULL, false,
3590 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3591 isempty(ansi_color) ? "1" : ansi_color,
3592 isempty(pretty_name) ? "Linux" : pretty_name);
3595 char *replace_env(const char *format, char **env) {
3602 const char *e, *word = format;
3607 for (e = format; *e; e ++) {
3618 if (!(k = strnappend(r, word, e-word-1)))
3627 } else if (*e == '$') {
3628 if (!(k = strnappend(r, word, e-word)))
3644 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3647 if (!(k = strappend(r, t)))
3660 if (!(k = strnappend(r, word, e-word)))
3671 char **replace_env_argv(char **argv, char **env) {
3673 unsigned k = 0, l = 0;
3675 l = strv_length(argv);
3677 if (!(r = new(char*, l+1)))
3680 STRV_FOREACH(i, argv) {
3682 /* If $FOO appears as single word, replace it by the split up variable */
3683 if ((*i)[0] == '$' && (*i)[1] != '{') {
3688 if ((e = strv_env_get(env, *i+1))) {
3690 if (!(m = strv_split_quoted(e))) {
3701 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3710 memcpy(r + k, m, q * sizeof(char*));
3718 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3719 if (!(r[k++] = replace_env(*i, env))) {
3729 int fd_columns(int fd) {
3733 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3742 static unsigned columns_cached(bool cached) {
3743 static __thread int parsed_columns = 0, env_columns = -1;
3746 if (_likely_(parsed_columns > 0 && cached))
3747 return parsed_columns;
3749 if (_unlikely_(env_columns == -1)) {
3750 e = getenv("COLUMNS");
3752 env_columns = atoi(e);
3757 if (env_columns > 0) {
3758 parsed_columns = env_columns;
3759 return parsed_columns;
3762 if (parsed_columns <= 0 || !cached)
3763 parsed_columns = fd_columns(STDOUT_FILENO);
3765 if (parsed_columns <= 0)
3766 parsed_columns = 80;
3768 return parsed_columns;
3771 unsigned columns(void) {
3772 return columns_cached(true);
3775 unsigned columns_uncached(void) {
3776 return columns_cached(false);
3779 int fd_lines(int fd) {
3783 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3792 unsigned lines(void) {
3793 static __thread int parsed_lines = 0;
3796 if (_likely_(parsed_lines > 0))
3797 return parsed_lines;
3799 e = getenv("LINES");
3801 parsed_lines = atoi(e);
3803 if (parsed_lines <= 0)
3804 parsed_lines = fd_lines(STDOUT_FILENO);
3806 if (parsed_lines <= 0)
3809 return parsed_lines;
3812 int running_in_chroot(void) {
3818 /* Only works as root */
3820 if (stat("/proc/1/root", &a) < 0)
3823 if (stat("/", &b) < 0)
3827 a.st_dev != b.st_dev ||
3828 a.st_ino != b.st_ino;
3831 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3836 assert(percent <= 100);
3837 assert(new_length >= 3);
3839 if (old_length <= 3 || old_length <= new_length)
3840 return strndup(s, old_length);
3842 r = new0(char, new_length+1);
3846 x = (new_length * percent) / 100;
3848 if (x > new_length - 3)
3856 s + old_length - (new_length - x - 3),
3857 new_length - x - 3);
3862 char *ellipsize(const char *s, size_t length, unsigned percent) {
3863 return ellipsize_mem(s, strlen(s), length, percent);
3866 int touch(const char *path) {
3871 /* This just opens the file for writing, ensuring it
3872 * exists. It doesn't call utimensat() the way /usr/bin/touch
3875 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3879 close_nointr_nofail(fd);
3883 char *unquote(const char *s, const char* quotes) {
3887 /* This is rather stupid, simply removes the heading and
3888 * trailing quotes if there is one. Doesn't care about
3889 * escaping or anything. We should make this smarter one
3896 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3897 return strndup(s+1, l-2);
3902 char *normalize_env_assignment(const char *s) {
3903 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3906 eq = strchr(s, '=');
3918 memmove(r, t, strlen(t) + 1);
3922 name = strndup(s, eq - s);
3930 value = unquote(strstrip(p), QUOTES);
3934 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3940 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3951 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3963 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3970 r = wait_for_terminate(pid, &status);
3972 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3976 if (status.si_code == CLD_EXITED) {
3977 if (status.si_status != 0) {
3978 log_warning("%s failed with error code %i.", name, status.si_status);
3979 return status.si_status;
3982 log_debug("%s succeeded.", name);
3985 } else if (status.si_code == CLD_KILLED ||
3986 status.si_code == CLD_DUMPED) {
3988 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3992 log_warning("%s failed due to unknown reason.", name);
3996 _noreturn_ void freeze(void) {
3998 /* Make sure nobody waits for us on a socket anymore */
3999 close_all_fds(NULL, 0);
4007 bool null_or_empty(struct stat *st) {
4010 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4013 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4019 int null_or_empty_path(const char *fn) {
4024 if (stat(fn, &st) < 0)
4027 return null_or_empty(&st);
4030 DIR *xopendirat(int fd, const char *name, int flags) {
4034 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4040 close_nointr_nofail(nfd);
4047 int signal_from_string_try_harder(const char *s) {
4051 signo = signal_from_string(s);
4053 if (startswith(s, "SIG"))
4054 return signal_from_string(s+3);
4059 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4065 if (!dual_timestamp_is_set(t))
4068 fprintf(f, "%s=%llu %llu\n",
4070 (unsigned long long) t->realtime,
4071 (unsigned long long) t->monotonic);
4074 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4075 unsigned long long a, b;
4080 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4081 log_debug("Failed to parse finish timestamp value %s", value);
4088 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4092 /* FIXME: to follow udev's logic 100% we need to leave valid
4093 * UTF8 chars unescaped */
4095 u = unquote(tagvalue, "\"\'");
4099 t = xescape(u, "/ ");
4105 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4114 char *fstab_node_to_udev_node(const char *p) {
4117 if (startswith(p, "LABEL="))
4118 return tag_to_udev_node(p+6, "label");
4120 if (startswith(p, "UUID="))
4121 return tag_to_udev_node(p+5, "uuid");
4123 if (startswith(p, "PARTUUID="))
4124 return tag_to_udev_node(p+9, "partuuid");
4126 if (startswith(p, "PARTLABEL="))
4127 return tag_to_udev_node(p+10, "partlabel");
4132 bool tty_is_vc(const char *tty) {
4135 if (startswith(tty, "/dev/"))
4138 return vtnr_from_tty(tty) >= 0;
4141 bool tty_is_console(const char *tty) {
4144 if (startswith(tty, "/dev/"))
4147 return streq(tty, "console");
4150 int vtnr_from_tty(const char *tty) {
4155 if (startswith(tty, "/dev/"))
4158 if (!startswith(tty, "tty") )
4161 if (tty[3] < '0' || tty[3] > '9')
4164 r = safe_atoi(tty+3, &i);
4168 if (i < 0 || i > 63)
4174 bool tty_is_vc_resolve(const char *tty) {
4175 char *active = NULL;
4180 if (startswith(tty, "/dev/"))
4183 /* Resolve where /dev/console is pointing to, if /sys is
4184 * actually ours (i.e. not read-only-mounted which is a sign
4185 * for container setups) */
4186 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4187 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4188 /* If multiple log outputs are configured the
4189 * last one is what /dev/console points to */
4190 tty = strrchr(active, ' ');
4203 const char *default_term_for_tty(const char *tty) {
4206 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4209 bool dirent_is_file(const struct dirent *de) {
4212 if (ignore_file(de->d_name))
4215 if (de->d_type != DT_REG &&
4216 de->d_type != DT_LNK &&
4217 de->d_type != DT_UNKNOWN)
4223 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4226 if (de->d_type != DT_REG &&
4227 de->d_type != DT_LNK &&
4228 de->d_type != DT_UNKNOWN)
4231 if (ignore_file_allow_backup(de->d_name))
4234 return endswith(de->d_name, suffix);
4237 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4240 Hashmap *pids = NULL;
4244 /* Executes all binaries in a directory in parallel and waits
4245 * until all they all finished. */
4248 if (!(_d = opendir(directory))) {
4250 if (errno == ENOENT)
4253 log_error("Failed to enumerate directory %s: %m", directory);
4260 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4261 log_error("Failed to allocate set.");
4265 while ((de = readdir(d))) {
4270 if (!dirent_is_file(de))
4273 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4278 if ((pid = fork()) < 0) {
4279 log_error("Failed to fork: %m");
4297 log_error("Failed to execute %s: %m", path);
4298 _exit(EXIT_FAILURE);
4301 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4303 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4304 log_error("Failed to add PID to set: %s", strerror(-k));
4309 while (!hashmap_isempty(pids)) {
4310 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4315 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4320 log_error("waitid() failed: %m");
4324 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4325 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4326 if (si.si_code == CLD_EXITED)
4327 log_error("%s exited with exit status %i.", path, si.si_status);
4329 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4331 log_debug("%s exited successfully.", path);
4342 hashmap_free_free(pids);
4345 int kill_and_sigcont(pid_t pid, int sig) {
4348 r = kill(pid, sig) < 0 ? -errno : 0;
4356 bool nulstr_contains(const char*nulstr, const char *needle) {
4362 NULSTR_FOREACH(i, nulstr)
4363 if (streq(i, needle))
4369 bool plymouth_running(void) {
4370 return access("/run/plymouth/pid", F_OK) >= 0;
4373 char* strshorten(char *s, size_t l) {
4382 static bool hostname_valid_char(char c) {
4384 (c >= 'a' && c <= 'z') ||
4385 (c >= 'A' && c <= 'Z') ||
4386 (c >= '0' && c <= '9') ||
4392 bool hostname_is_valid(const char *s) {
4398 for (p = s; *p; p++)
4399 if (!hostname_valid_char(*p))
4402 if (p-s > HOST_NAME_MAX)
4408 char* hostname_cleanup(char *s) {
4411 for (p = s, d = s; *p; p++)
4412 if ((*p >= 'a' && *p <= 'z') ||
4413 (*p >= 'A' && *p <= 'Z') ||
4414 (*p >= '0' && *p <= '9') ||
4422 strshorten(s, HOST_NAME_MAX);
4426 int pipe_eof(int fd) {
4427 struct pollfd pollfd;
4432 pollfd.events = POLLIN|POLLHUP;
4434 r = poll(&pollfd, 1, 0);
4441 return pollfd.revents & POLLHUP;
4444 int fd_wait_for_event(int fd, int event, usec_t t) {
4445 struct pollfd pollfd;
4450 pollfd.events = event;
4452 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4459 return pollfd.revents;
4462 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4473 t = new(char, strlen(path) + 1 + 6 + 1);
4477 fn = path_get_file_name(path);
4481 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4483 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4489 f = fdopen(fd, "we");
4502 int terminal_vhangup_fd(int fd) {
4505 if (ioctl(fd, TIOCVHANGUP) < 0)
4511 int terminal_vhangup(const char *name) {
4514 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4518 r = terminal_vhangup_fd(fd);
4519 close_nointr_nofail(fd);
4524 int vt_disallocate(const char *name) {
4528 /* Deallocate the VT if possible. If not possible
4529 * (i.e. because it is the active one), at least clear it
4530 * entirely (including the scrollback buffer) */
4532 if (!startswith(name, "/dev/"))
4535 if (!tty_is_vc(name)) {
4536 /* So this is not a VT. I guess we cannot deallocate
4537 * it then. But let's at least clear the screen */
4539 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4544 "\033[r" /* clear scrolling region */
4545 "\033[H" /* move home */
4546 "\033[2J", /* clear screen */
4548 close_nointr_nofail(fd);
4553 if (!startswith(name, "/dev/tty"))
4556 r = safe_atou(name+8, &u);
4563 /* Try to deallocate */
4564 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4568 r = ioctl(fd, VT_DISALLOCATE, u);
4569 close_nointr_nofail(fd);
4577 /* Couldn't deallocate, so let's clear it fully with
4579 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4584 "\033[r" /* clear scrolling region */
4585 "\033[H" /* move home */
4586 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4588 close_nointr_nofail(fd);
4593 int copy_file(const char *from, const char *to) {
4599 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4603 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4605 close_nointr_nofail(fdf);
4613 n = read(fdf, buf, sizeof(buf));
4617 close_nointr_nofail(fdf);
4628 k = loop_write(fdt, buf, n, false);
4630 r = k < 0 ? k : (errno ? -errno : -EIO);
4632 close_nointr_nofail(fdf);
4640 close_nointr_nofail(fdf);
4641 r = close_nointr(fdt);
4651 int symlink_atomic(const char *from, const char *to) {
4653 _cleanup_free_ char *t;
4656 unsigned long long ull;
4663 t = new(char, strlen(to) + 1 + 16 + 1);
4667 fn = path_get_file_name(to);
4671 x = stpcpy(t+k+1, fn);
4674 for (i = 0; i < 16; i++) {
4675 *(x++) = hexchar(ull & 0xF);
4681 if (symlink(from, t) < 0)
4684 if (rename(t, to) < 0) {
4693 bool display_is_local(const char *display) {
4697 display[0] == ':' &&
4698 display[1] >= '0' &&
4702 int socket_from_display(const char *display, char **path) {
4709 if (!display_is_local(display))
4712 k = strspn(display+1, "0123456789");
4714 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4718 c = stpcpy(f, "/tmp/.X11-unix/X");
4719 memcpy(c, display+1, k);
4728 const char **username,
4729 uid_t *uid, gid_t *gid,
4731 const char **shell) {
4739 /* We enforce some special rules for uid=0: in order to avoid
4740 * NSS lookups for root we hardcode its data. */
4742 if (streq(*username, "root") || streq(*username, "0")) {
4760 if (parse_uid(*username, &u) >= 0) {
4764 /* If there are multiple users with the same id, make
4765 * sure to leave $USER to the configured value instead
4766 * of the first occurrence in the database. However if
4767 * the uid was configured by a numeric uid, then let's
4768 * pick the real username from /etc/passwd. */
4770 *username = p->pw_name;
4773 p = getpwnam(*username);
4777 return errno != 0 ? -errno : -ESRCH;
4789 *shell = p->pw_shell;
4794 int get_group_creds(const char **groupname, gid_t *gid) {
4800 /* We enforce some special rules for gid=0: in order to avoid
4801 * NSS lookups for root we hardcode its data. */
4803 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4804 *groupname = "root";
4812 if (parse_gid(*groupname, &id) >= 0) {
4817 *groupname = g->gr_name;
4820 g = getgrnam(*groupname);
4824 return errno != 0 ? -errno : -ESRCH;
4832 int in_group(const char *name) {
4834 int ngroups_max, r, i;
4836 r = get_group_creds(&name, &gid);
4840 if (getgid() == gid)
4843 if (getegid() == gid)
4846 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4847 assert(ngroups_max > 0);
4849 gids = alloca(sizeof(gid_t) * ngroups_max);
4851 r = getgroups(ngroups_max, gids);
4855 for (i = 0; i < r; i++)
4862 int glob_exists(const char *path) {
4870 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4872 if (k == GLOB_NOMATCH)
4874 else if (k == GLOB_NOSPACE)
4877 r = !strv_isempty(g.gl_pathv);
4879 r = errno ? -errno : -EIO;
4886 int dirent_ensure_type(DIR *d, struct dirent *de) {
4892 if (de->d_type != DT_UNKNOWN)
4895 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4899 S_ISREG(st.st_mode) ? DT_REG :
4900 S_ISDIR(st.st_mode) ? DT_DIR :
4901 S_ISLNK(st.st_mode) ? DT_LNK :
4902 S_ISFIFO(st.st_mode) ? DT_FIFO :
4903 S_ISSOCK(st.st_mode) ? DT_SOCK :
4904 S_ISCHR(st.st_mode) ? DT_CHR :
4905 S_ISBLK(st.st_mode) ? DT_BLK :
4911 int in_search_path(const char *path, char **search) {
4915 r = path_get_parent(path, &parent);
4921 STRV_FOREACH(i, search) {
4922 if (path_equal(parent, *i)) {
4933 int get_files_in_directory(const char *path, char ***list) {
4941 /* Returns all files in a directory in *list, and the number
4942 * of files as return value. If list is NULL returns only the
4951 union dirent_storage buf;
4954 k = readdir_r(d, &buf.de, &de);
4963 dirent_ensure_type(d, de);
4965 if (!dirent_is_file(de))
4969 if ((unsigned) r >= n) {
4973 t = realloc(l, sizeof(char*) * n);
4982 assert((unsigned) r < n);
4984 l[r] = strdup(de->d_name);
5008 char *strjoin(const char *x, ...) {
5022 t = va_arg(ap, const char *);
5027 if (n > ((size_t) -1) - l)
5049 t = va_arg(ap, const char *);
5063 bool is_main_thread(void) {
5064 static __thread int cached = 0;
5066 if (_unlikely_(cached == 0))
5067 cached = getpid() == gettid() ? 1 : -1;
5072 int block_get_whole_disk(dev_t d, dev_t *ret) {
5079 /* If it has a queue this is good enough for us */
5080 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5083 r = access(p, F_OK);
5091 /* If it is a partition find the originating device */
5092 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5095 r = access(p, F_OK);
5101 /* Get parent dev_t */
5102 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5105 r = read_one_line_file(p, &s);
5111 r = sscanf(s, "%u:%u", &m, &n);
5117 /* Only return this if it is really good enough for us. */
5118 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5121 r = access(p, F_OK);
5125 *ret = makedev(m, n);
5132 int file_is_priv_sticky(const char *p) {
5137 if (lstat(p, &st) < 0)
5141 (st.st_uid == 0 || st.st_uid == getuid()) &&
5142 (st.st_mode & S_ISVTX);
5145 static const char *const ioprio_class_table[] = {
5146 [IOPRIO_CLASS_NONE] = "none",
5147 [IOPRIO_CLASS_RT] = "realtime",
5148 [IOPRIO_CLASS_BE] = "best-effort",
5149 [IOPRIO_CLASS_IDLE] = "idle"
5152 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5154 static const char *const sigchld_code_table[] = {
5155 [CLD_EXITED] = "exited",
5156 [CLD_KILLED] = "killed",
5157 [CLD_DUMPED] = "dumped",
5158 [CLD_TRAPPED] = "trapped",
5159 [CLD_STOPPED] = "stopped",
5160 [CLD_CONTINUED] = "continued",
5163 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5165 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5166 [LOG_FAC(LOG_KERN)] = "kern",
5167 [LOG_FAC(LOG_USER)] = "user",
5168 [LOG_FAC(LOG_MAIL)] = "mail",
5169 [LOG_FAC(LOG_DAEMON)] = "daemon",
5170 [LOG_FAC(LOG_AUTH)] = "auth",
5171 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5172 [LOG_FAC(LOG_LPR)] = "lpr",
5173 [LOG_FAC(LOG_NEWS)] = "news",
5174 [LOG_FAC(LOG_UUCP)] = "uucp",
5175 [LOG_FAC(LOG_CRON)] = "cron",
5176 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5177 [LOG_FAC(LOG_FTP)] = "ftp",
5178 [LOG_FAC(LOG_LOCAL0)] = "local0",
5179 [LOG_FAC(LOG_LOCAL1)] = "local1",
5180 [LOG_FAC(LOG_LOCAL2)] = "local2",
5181 [LOG_FAC(LOG_LOCAL3)] = "local3",
5182 [LOG_FAC(LOG_LOCAL4)] = "local4",
5183 [LOG_FAC(LOG_LOCAL5)] = "local5",
5184 [LOG_FAC(LOG_LOCAL6)] = "local6",
5185 [LOG_FAC(LOG_LOCAL7)] = "local7"
5188 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5190 static const char *const log_level_table[] = {
5191 [LOG_EMERG] = "emerg",
5192 [LOG_ALERT] = "alert",
5193 [LOG_CRIT] = "crit",
5195 [LOG_WARNING] = "warning",
5196 [LOG_NOTICE] = "notice",
5197 [LOG_INFO] = "info",
5198 [LOG_DEBUG] = "debug"
5201 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5203 static const char* const sched_policy_table[] = {
5204 [SCHED_OTHER] = "other",
5205 [SCHED_BATCH] = "batch",
5206 [SCHED_IDLE] = "idle",
5207 [SCHED_FIFO] = "fifo",
5211 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5213 static const char* const rlimit_table[] = {
5214 [RLIMIT_CPU] = "LimitCPU",
5215 [RLIMIT_FSIZE] = "LimitFSIZE",
5216 [RLIMIT_DATA] = "LimitDATA",
5217 [RLIMIT_STACK] = "LimitSTACK",
5218 [RLIMIT_CORE] = "LimitCORE",
5219 [RLIMIT_RSS] = "LimitRSS",
5220 [RLIMIT_NOFILE] = "LimitNOFILE",
5221 [RLIMIT_AS] = "LimitAS",
5222 [RLIMIT_NPROC] = "LimitNPROC",
5223 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5224 [RLIMIT_LOCKS] = "LimitLOCKS",
5225 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5226 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5227 [RLIMIT_NICE] = "LimitNICE",
5228 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5229 [RLIMIT_RTTIME] = "LimitRTTIME"
5232 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5234 static const char* const ip_tos_table[] = {
5235 [IPTOS_LOWDELAY] = "low-delay",
5236 [IPTOS_THROUGHPUT] = "throughput",
5237 [IPTOS_RELIABILITY] = "reliability",
5238 [IPTOS_LOWCOST] = "low-cost",
5241 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5243 static const char *const __signal_table[] = {
5260 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5271 [SIGVTALRM] = "VTALRM",
5273 [SIGWINCH] = "WINCH",
5279 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5281 const char *signal_to_string(int signo) {
5282 static __thread char buf[12];
5285 name = __signal_to_string(signo);
5289 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5290 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5292 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5297 int signal_from_string(const char *s) {
5302 signo = __signal_from_string(s);
5306 if (startswith(s, "RTMIN+")) {
5310 if (safe_atou(s, &u) >= 0) {
5311 signo = (int) u + offset;
5312 if (signo > 0 && signo < _NSIG)
5318 bool kexec_loaded(void) {
5319 bool loaded = false;
5322 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5330 int strdup_or_null(const char *a, char **b) {
5348 int prot_from_flags(int flags) {
5350 switch (flags & O_ACCMODE) {
5359 return PROT_READ|PROT_WRITE;
5366 char *format_bytes(char *buf, size_t l, off_t t) {
5369 static const struct {
5373 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5374 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5375 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5376 { "G", 1024ULL*1024ULL*1024ULL },
5377 { "M", 1024ULL*1024ULL },
5381 for (i = 0; i < ELEMENTSOF(table); i++) {
5383 if (t >= table[i].factor) {
5386 (unsigned long long) (t / table[i].factor),
5387 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5394 snprintf(buf, l, "%lluB", (unsigned long long) t);
5402 void* memdup(const void *p, size_t l) {
5415 int fd_inc_sndbuf(int fd, size_t n) {
5417 socklen_t l = sizeof(value);
5419 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5421 l == sizeof(value) &&
5422 (size_t) value >= n*2)
5426 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5433 int fd_inc_rcvbuf(int fd, size_t n) {
5435 socklen_t l = sizeof(value);
5437 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5439 l == sizeof(value) &&
5440 (size_t) value >= n*2)
5444 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5451 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5452 pid_t parent_pid, agent_pid;
5454 bool stdout_is_tty, stderr_is_tty;
5462 parent_pid = getpid();
5464 /* Spawns a temporary TTY agent, making sure it goes away when
5471 if (agent_pid != 0) {
5478 * Make sure the agent goes away when the parent dies */
5479 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5480 _exit(EXIT_FAILURE);
5482 /* Check whether our parent died before we were able
5483 * to set the death signal */
5484 if (getppid() != parent_pid)
5485 _exit(EXIT_SUCCESS);
5487 /* Don't leak fds to the agent */
5488 close_all_fds(except, n_except);
5490 stdout_is_tty = isatty(STDOUT_FILENO);
5491 stderr_is_tty = isatty(STDERR_FILENO);
5493 if (!stdout_is_tty || !stderr_is_tty) {
5494 /* Detach from stdout/stderr. and reopen
5495 * /dev/tty for them. This is important to
5496 * ensure that when systemctl is started via
5497 * popen() or a similar call that expects to
5498 * read EOF we actually do generate EOF and
5499 * not delay this indefinitely by because we
5500 * keep an unused copy of stdin around. */
5501 fd = open("/dev/tty", O_WRONLY);
5503 log_error("Failed to open /dev/tty: %m");
5504 _exit(EXIT_FAILURE);
5508 dup2(fd, STDOUT_FILENO);
5511 dup2(fd, STDERR_FILENO);
5517 /* Count arguments */
5519 for (n = 0; va_arg(ap, char*); n++)
5524 l = alloca(sizeof(char *) * (n + 1));
5526 /* Fill in arguments */
5528 for (i = 0; i <= n; i++)
5529 l[i] = va_arg(ap, char*);
5533 _exit(EXIT_FAILURE);
5536 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5537 struct rlimit highest, fixed;
5541 if (setrlimit(resource, rlim) >= 0)
5547 /* So we failed to set the desired setrlimit, then let's try
5548 * to get as close as we can */
5549 assert_se(getrlimit(resource, &highest) == 0);
5551 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5552 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5554 if (setrlimit(resource, &fixed) < 0)
5560 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5561 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5573 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5576 f = fopen(path, "re");
5584 char line[LINE_MAX];
5587 for (i = 0; i < sizeof(line)-1; i++) {
5591 if (_unlikely_(c == EOF)) {
5601 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5602 value = strdup(line + l + 1);
5622 int can_sleep(const char *type) {
5626 _cleanup_free_ char *p = NULL;
5630 r = read_one_line_file("/sys/power/state", &p);
5632 return r == -ENOENT ? 0 : r;
5635 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5636 if (l == k && memcmp(w, type, l) == 0)
5642 bool is_valid_documentation_url(const char *url) {
5645 if (startswith(url, "http://") && url[7])
5648 if (startswith(url, "https://") && url[8])
5651 if (startswith(url, "file:") && url[5])
5654 if (startswith(url, "info:") && url[5])
5657 if (startswith(url, "man:") && url[4])
5663 bool in_initrd(void) {
5664 static __thread int saved = -1;
5670 /* We make two checks here:
5672 * 1. the flag file /etc/initrd-release must exist
5673 * 2. the root file system must be a memory file system
5675 * The second check is extra paranoia, since misdetecting an
5676 * initrd can have bad bad consequences due the initrd
5677 * emptying when transititioning to the main systemd.
5680 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5681 statfs("/", &s) >= 0 &&
5682 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5687 void warn_melody(void) {
5688 _cleanup_close_ int fd = -1;
5690 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5694 /* Yeah, this is synchronous. Kinda sucks. But well... */
5696 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5697 usleep(125*USEC_PER_MSEC);
5699 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5700 usleep(125*USEC_PER_MSEC);
5702 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5703 usleep(125*USEC_PER_MSEC);
5705 ioctl(fd, KIOCSOUND, 0);
5708 int make_console_stdio(void) {
5711 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5713 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5715 log_error("Failed to acquire terminal: %s", strerror(-fd));
5721 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5728 int get_home_dir(char **_h) {
5736 /* Take the user specified one */
5747 /* Hardcode home directory for root to avoid NSS */
5750 h = strdup("/root");
5758 /* Check the database... */
5762 return errno ? -errno : -ESRCH;
5764 if (!path_is_absolute(p->pw_dir))
5767 h = strdup(p->pw_dir);
5775 int get_shell(char **_sh) {
5783 /* Take the user specified one */
5784 e = getenv("SHELL");
5794 /* Hardcode home directory for root to avoid NSS */
5797 sh = strdup("/bin/sh");
5805 /* Check the database... */
5809 return errno ? -errno : -ESRCH;
5811 if (!path_is_absolute(p->pw_shell))
5814 sh = strdup(p->pw_shell);
5822 void freep(void *p) {
5826 void fclosep(FILE **f) {
5831 void closep(int *fd) {
5833 close_nointr_nofail(*fd);
5836 void closedirp(DIR **d) {
5841 void umaskp(mode_t *u) {