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>
53 #include <sys/capability.h>
66 #include "path-util.h"
67 #include "exit-status.h"
71 char **saved_argv = NULL;
73 size_t page_size(void) {
74 static __thread size_t pgsz = 0;
77 if (_likely_(pgsz > 0))
80 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
87 bool streq_ptr(const char *a, const char *b) {
89 /* Like streq(), but tries to make sense of NULL pointers */
100 usec_t now(clockid_t clock_id) {
103 assert_se(clock_gettime(clock_id, &ts) == 0);
105 return timespec_load(&ts);
108 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
111 ts->realtime = now(CLOCK_REALTIME);
112 ts->monotonic = now(CLOCK_MONOTONIC);
117 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
126 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
128 ts->monotonic = now(CLOCK_MONOTONIC);
130 if ((int64_t) ts->monotonic > delta)
131 ts->monotonic -= delta;
139 usec_t timespec_load(const struct timespec *ts) {
143 (usec_t) ts->tv_sec * USEC_PER_SEC +
144 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
147 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
150 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
151 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
156 usec_t timeval_load(const struct timeval *tv) {
160 (usec_t) tv->tv_sec * USEC_PER_SEC +
161 (usec_t) tv->tv_usec;
164 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
167 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
168 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
173 bool endswith(const char *s, const char *postfix) {
180 pl = strlen(postfix);
188 return memcmp(s + sl - pl, postfix, pl) == 0;
191 bool startswith(const char *s, const char *prefix) {
206 return memcmp(s, prefix, pl) == 0;
209 bool startswith_no_case(const char *s, const char *prefix) {
225 for(i = 0; i < pl; ++i) {
226 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 if ((r = safe_atolu(s, &ul)) < 0)
312 if ((unsigned long) pid != ul)
322 int parse_uid(const char *s, uid_t* ret_uid) {
323 unsigned long ul = 0;
330 if ((r = safe_atolu(s, &ul)) < 0)
335 if ((unsigned long) uid != ul)
342 int safe_atou(const char *s, unsigned *ret_u) {
350 l = strtoul(s, &x, 0);
352 if (!x || *x || errno)
353 return errno ? -errno : -EINVAL;
355 if ((unsigned long) (unsigned) l != l)
358 *ret_u = (unsigned) l;
362 int safe_atoi(const char *s, int *ret_i) {
370 l = strtol(s, &x, 0);
372 if (!x || *x || errno)
373 return errno ? -errno : -EINVAL;
375 if ((long) (int) l != l)
382 int safe_atollu(const char *s, long long unsigned *ret_llu) {
384 unsigned long long l;
390 l = strtoull(s, &x, 0);
392 if (!x || *x || errno)
393 return errno ? -errno : -EINVAL;
399 int safe_atolli(const char *s, long long int *ret_lli) {
407 l = strtoll(s, &x, 0);
409 if (!x || *x || errno)
410 return errno ? -errno : -EINVAL;
416 /* Split a string into words. */
417 char *split(const char *c, size_t *l, const char *separator, char **state) {
420 current = *state ? *state : (char*) c;
422 if (!*current || *c == 0)
425 current += strspn(current, separator);
426 *l = strcspn(current, separator);
429 return (char*) current;
432 /* Split a string into words, but consider strings enclosed in '' and
433 * "" as words even if they include spaces. */
434 char *split_quoted(const char *c, size_t *l, char **state) {
436 bool escaped = false;
438 current = *state ? *state : (char*) c;
440 if (!*current || *c == 0)
443 current += strspn(current, WHITESPACE);
445 if (*current == '\'') {
448 for (e = current; *e; e++) {
458 *state = *e == 0 ? e : e+1;
459 } else if (*current == '\"') {
462 for (e = current; *e; e++) {
472 *state = *e == 0 ? e : e+1;
474 for (e = current; *e; e++) {
479 else if (strchr(WHITESPACE, *e))
486 return (char*) current;
489 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
492 char fn[PATH_MAX], line[LINE_MAX], *p;
498 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
501 if (!(f = fopen(fn, "re")))
504 if (!(fgets(line, sizeof(line), f))) {
505 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 if (!(p = strrchr(line, ')')))
527 if ((long unsigned) (pid_t) ppid != ppid)
530 *_ppid = (pid_t) ppid;
535 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
538 char fn[PATH_MAX], line[LINE_MAX], *p;
543 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
546 if (!(f = fopen(fn, "re")))
549 if (!(fgets(line, sizeof(line), f))) {
550 r = feof(f) ? -EIO : -errno;
557 /* Let's skip the pid and comm fields. The latter is enclosed
558 * in () but does not escape any () in its value, so let's
559 * skip over it manually */
561 if (!(p = strrchr(line, ')')))
582 "%*d " /* priority */
584 "%*d " /* num_threads */
585 "%*d " /* itrealvalue */
586 "%llu " /* starttime */,
593 int write_one_line_file(const char *fn, const char *line) {
605 if (fputs(line, f) < 0) {
610 if (!endswith(line, "\n"))
628 int fchmod_umask(int fd, mode_t m) {
633 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
639 int write_one_line_file_atomic(const char *fn, const char *line) {
647 r = fopen_temporary(fn, &f, &p);
651 fchmod_umask(fileno(f), 0644);
654 if (fputs(line, f) < 0) {
659 if (!endswith(line, "\n"))
670 if (rename(p, fn) < 0)
686 int read_one_line_file(const char *fn, char **line) {
689 char t[LINE_MAX], *c;
698 if (!fgets(t, sizeof(t), f)) {
724 int read_full_file(const char *fn, char **contents, size_t *size) {
731 if (!(f = fopen(fn, "re")))
734 if (fstat(fileno(f), &st) < 0) {
740 if (st.st_size > 4*1024*1024) {
745 n = st.st_size > 0 ? st.st_size : LINE_MAX;
752 if (!(t = realloc(buf, n+1))) {
758 k = fread(buf + l, 1, n - l, f);
773 if (n > 4*1024*1024) {
797 const char *separator, ...) {
800 char *contents = NULL, *p;
805 if ((r = read_full_file(fname, &contents, NULL)) < 0)
810 const char *key = NULL;
812 p += strspn(p, separator);
813 p += strspn(p, WHITESPACE);
818 if (!strchr(COMMENTS, *p)) {
822 va_start(ap, separator);
823 while ((key = va_arg(ap, char *))) {
827 value = va_arg(ap, char **);
830 if (strncmp(p, key, n) != 0 ||
835 n = strcspn(p, separator);
838 strchr(QUOTES, p[0]) &&
840 v = strndup(p+1, n-2);
851 /* return empty value strings as NULL */
868 p += strcspn(p, separator);
887 if (!(f = fopen(fname, "re")))
891 char l[LINE_MAX], *p, *u;
894 if (!fgets(l, sizeof(l), f)) {
907 if (strchr(COMMENTS, *p))
910 if (!(u = normalize_env_assignment(p))) {
911 log_error("Out of memory");
916 t = strv_append(m, u);
920 log_error("Out of memory");
943 int write_env_file(const char *fname, char **l) {
948 r = fopen_temporary(fname, &f, &p);
952 fchmod_umask(fileno(f), 0644);
968 if (rename(p, fname) < 0)
983 char *truncate_nl(char *s) {
986 s[strcspn(s, NEWLINE)] = 0;
990 int get_process_comm(pid_t pid, char **name) {
996 r = read_one_line_file("/proc/self/comm", name);
999 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1002 r = read_one_line_file(p, name);
1009 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1016 assert(max_length > 0);
1020 f = fopen("/proc/self/cmdline", "re");
1023 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1033 r = new(char, max_length);
1041 while ((c = getc(f)) != EOF) {
1063 size_t n = MIN(left-1, 3U);
1064 memcpy(k, "...", n);
1071 /* Kernel threads have no argv[] */
1081 h = get_process_comm(pid, &t);
1085 r = join("[", t, "]", NULL);
1096 int is_kernel_thread(pid_t pid) {
1106 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1115 count = fread(&c, 1, 1, f);
1119 /* Kernel threads have an empty cmdline */
1122 return eof ? 1 : -errno;
1127 int get_process_exe(pid_t pid, char **name) {
1133 r = readlink_malloc("/proc/self/exe", name);
1136 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1139 r = readlink_malloc(p, name);
1146 int get_process_uid(pid_t pid, uid_t *uid) {
1156 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1166 char line[LINE_MAX], *l;
1168 if (!fgets(line, sizeof(line), f)) {
1178 if (startswith(l, "Uid:")) {
1180 l += strspn(l, WHITESPACE);
1182 l[strcspn(l, WHITESPACE)] = 0;
1184 r = parse_uid(l, uid);
1197 char *strnappend(const char *s, const char *suffix, size_t b) {
1205 return strndup(suffix, b);
1215 if (!(r = new(char, a+b+1)))
1219 memcpy(r+a, suffix, b);
1225 char *strappend(const char *s, const char *suffix) {
1226 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1229 int readlink_malloc(const char *p, char **r) {
1239 if (!(c = new(char, l)))
1242 if ((n = readlink(p, c, l-1)) < 0) {
1248 if ((size_t) n < l-1) {
1259 int readlink_and_make_absolute(const char *p, char **r) {
1266 if ((j = readlink_malloc(p, &target)) < 0)
1269 k = file_in_same_dir(p, target);
1279 int readlink_and_canonicalize(const char *p, char **r) {
1286 j = readlink_and_make_absolute(p, &t);
1290 s = canonicalize_file_name(t);
1297 path_kill_slashes(*r);
1302 int reset_all_signal_handlers(void) {
1305 for (sig = 1; sig < _NSIG; sig++) {
1306 struct sigaction sa;
1308 if (sig == SIGKILL || sig == SIGSTOP)
1312 sa.sa_handler = SIG_DFL;
1313 sa.sa_flags = SA_RESTART;
1315 /* On Linux the first two RT signals are reserved by
1316 * glibc, and sigaction() will return EINVAL for them. */
1317 if ((sigaction(sig, &sa, NULL) < 0))
1318 if (errno != EINVAL)
1325 char *strstrip(char *s) {
1328 /* Drops trailing whitespace. Modifies the string in
1329 * place. Returns pointer to first non-space character */
1331 s += strspn(s, WHITESPACE);
1333 for (e = strchr(s, 0); e > s; e --)
1334 if (!strchr(WHITESPACE, e[-1]))
1342 char *delete_chars(char *s, const char *bad) {
1345 /* Drops all whitespace, regardless where in the string */
1347 for (f = s, t = s; *f; f++) {
1348 if (strchr(bad, *f))
1359 bool in_charset(const char *s, const char* charset) {
1365 for (i = s; *i; i++)
1366 if (!strchr(charset, *i))
1372 char *file_in_same_dir(const char *path, const char *filename) {
1379 /* This removes the last component of path and appends
1380 * filename, unless the latter is absolute anyway or the
1383 if (path_is_absolute(filename))
1384 return strdup(filename);
1386 if (!(e = strrchr(path, '/')))
1387 return strdup(filename);
1389 k = strlen(filename);
1390 if (!(r = new(char, e-path+1+k+1)))
1393 memcpy(r, path, e-path+1);
1394 memcpy(r+(e-path)+1, filename, k+1);
1399 int rmdir_parents(const char *path, const char *stop) {
1408 /* Skip trailing slashes */
1409 while (l > 0 && path[l-1] == '/')
1415 /* Skip last component */
1416 while (l > 0 && path[l-1] != '/')
1419 /* Skip trailing slashes */
1420 while (l > 0 && path[l-1] == '/')
1426 if (!(t = strndup(path, l)))
1429 if (path_startswith(stop, t)) {
1438 if (errno != ENOENT)
1446 char hexchar(int x) {
1447 static const char table[16] = "0123456789abcdef";
1449 return table[x & 15];
1452 int unhexchar(char c) {
1454 if (c >= '0' && c <= '9')
1457 if (c >= 'a' && c <= 'f')
1458 return c - 'a' + 10;
1460 if (c >= 'A' && c <= 'F')
1461 return c - 'A' + 10;
1466 char octchar(int x) {
1467 return '0' + (x & 7);
1470 int unoctchar(char c) {
1472 if (c >= '0' && c <= '7')
1478 char decchar(int x) {
1479 return '0' + (x % 10);
1482 int undecchar(char c) {
1484 if (c >= '0' && c <= '9')
1490 char *cescape(const char *s) {
1496 /* Does C style string escaping. */
1498 r = new(char, strlen(s)*4 + 1);
1502 for (f = s, t = r; *f; f++)
1548 /* For special chars we prefer octal over
1549 * hexadecimal encoding, simply because glib's
1550 * g_strescape() does the same */
1551 if ((*f < ' ') || (*f >= 127)) {
1553 *(t++) = octchar((unsigned char) *f >> 6);
1554 *(t++) = octchar((unsigned char) *f >> 3);
1555 *(t++) = octchar((unsigned char) *f);
1566 char *cunescape_length(const char *s, size_t length) {
1572 /* Undoes C style string escaping */
1574 r = new(char, length+1);
1578 for (f = s, t = r; f < s + length; f++) {
1621 /* This is an extension of the XDG syntax files */
1626 /* hexadecimal encoding */
1629 a = unhexchar(f[1]);
1630 b = unhexchar(f[2]);
1632 if (a < 0 || b < 0) {
1633 /* Invalid escape code, let's take it literal then */
1637 *(t++) = (char) ((a << 4) | b);
1652 /* octal encoding */
1655 a = unoctchar(f[0]);
1656 b = unoctchar(f[1]);
1657 c = unoctchar(f[2]);
1659 if (a < 0 || b < 0 || c < 0) {
1660 /* Invalid escape code, let's take it literal then */
1664 *(t++) = (char) ((a << 6) | (b << 3) | c);
1672 /* premature end of string.*/
1677 /* Invalid escape code, let's take it literal then */
1689 char *cunescape(const char *s) {
1690 return cunescape_length(s, strlen(s));
1693 char *xescape(const char *s, const char *bad) {
1697 /* Escapes all chars in bad, in addition to \ and all special
1698 * chars, in \xFF style escaping. May be reversed with
1701 if (!(r = new(char, strlen(s)*4+1)))
1704 for (f = s, t = r; *f; f++) {
1706 if ((*f < ' ') || (*f >= 127) ||
1707 (*f == '\\') || strchr(bad, *f)) {
1710 *(t++) = hexchar(*f >> 4);
1711 *(t++) = hexchar(*f);
1721 char *bus_path_escape(const char *s) {
1727 /* Escapes all chars that D-Bus' object path cannot deal
1728 * with. Can be reverse with bus_path_unescape() */
1730 if (!(r = new(char, strlen(s)*3+1)))
1733 for (f = s, t = r; *f; f++) {
1735 if (!(*f >= 'A' && *f <= 'Z') &&
1736 !(*f >= 'a' && *f <= 'z') &&
1737 !(*f >= '0' && *f <= '9')) {
1739 *(t++) = hexchar(*f >> 4);
1740 *(t++) = hexchar(*f);
1750 char *bus_path_unescape(const char *f) {
1755 if (!(r = strdup(f)))
1758 for (t = r; *f; f++) {
1763 if ((a = unhexchar(f[1])) < 0 ||
1764 (b = unhexchar(f[2])) < 0) {
1765 /* Invalid escape code, let's take it literal then */
1768 *(t++) = (char) ((a << 4) | b);
1780 char *ascii_strlower(char *t) {
1785 for (p = t; *p; p++)
1786 if (*p >= 'A' && *p <= 'Z')
1787 *p = *p - 'A' + 'a';
1792 bool ignore_file(const char *filename) {
1796 filename[0] == '.' ||
1797 streq(filename, "lost+found") ||
1798 streq(filename, "aquota.user") ||
1799 streq(filename, "aquota.group") ||
1800 endswith(filename, "~") ||
1801 endswith(filename, ".rpmnew") ||
1802 endswith(filename, ".rpmsave") ||
1803 endswith(filename, ".rpmorig") ||
1804 endswith(filename, ".dpkg-old") ||
1805 endswith(filename, ".dpkg-new") ||
1806 endswith(filename, ".swp");
1809 int fd_nonblock(int fd, bool nonblock) {
1814 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1818 flags |= O_NONBLOCK;
1820 flags &= ~O_NONBLOCK;
1822 if (fcntl(fd, F_SETFL, flags) < 0)
1828 int fd_cloexec(int fd, bool cloexec) {
1833 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1837 flags |= FD_CLOEXEC;
1839 flags &= ~FD_CLOEXEC;
1841 if (fcntl(fd, F_SETFD, flags) < 0)
1847 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1850 assert(n_fdset == 0 || fdset);
1852 for (i = 0; i < n_fdset; i++)
1859 int close_all_fds(const int except[], unsigned n_except) {
1864 assert(n_except == 0 || except);
1866 d = opendir("/proc/self/fd");
1871 /* When /proc isn't available (for example in chroots)
1872 * the fallback is brute forcing through the fd
1875 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1876 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1878 if (fd_in_set(fd, except, n_except))
1881 if (close_nointr(fd) < 0)
1882 if (errno != EBADF && r == 0)
1889 while ((de = readdir(d))) {
1892 if (ignore_file(de->d_name))
1895 if (safe_atoi(de->d_name, &fd) < 0)
1896 /* Let's better ignore this, just in case */
1905 if (fd_in_set(fd, except, n_except))
1908 if (close_nointr(fd) < 0) {
1909 /* Valgrind has its own FD and doesn't want to have it closed */
1910 if (errno != EBADF && r == 0)
1919 bool chars_intersect(const char *a, const char *b) {
1922 /* Returns true if any of the chars in a are in b. */
1923 for (p = a; *p; p++)
1930 char *format_timestamp(char *buf, size_t l, usec_t t) {
1940 sec = (time_t) (t / USEC_PER_SEC);
1942 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1948 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1951 n = now(CLOCK_REALTIME);
1953 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1958 if (d >= USEC_PER_YEAR)
1959 snprintf(buf, l, "%llu years and %llu months ago",
1960 (unsigned long long) (d / USEC_PER_YEAR),
1961 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1962 else if (d >= USEC_PER_MONTH)
1963 snprintf(buf, l, "%llu months and %llu days ago",
1964 (unsigned long long) (d / USEC_PER_MONTH),
1965 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1966 else if (d >= USEC_PER_WEEK)
1967 snprintf(buf, l, "%llu weeks and %llu days ago",
1968 (unsigned long long) (d / USEC_PER_WEEK),
1969 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1970 else if (d >= 2*USEC_PER_DAY)
1971 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1972 else if (d >= 25*USEC_PER_HOUR)
1973 snprintf(buf, l, "1 day and %lluh ago",
1974 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1975 else if (d >= 6*USEC_PER_HOUR)
1976 snprintf(buf, l, "%lluh ago",
1977 (unsigned long long) (d / USEC_PER_HOUR));
1978 else if (d >= USEC_PER_HOUR)
1979 snprintf(buf, l, "%lluh %llumin ago",
1980 (unsigned long long) (d / USEC_PER_HOUR),
1981 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1982 else if (d >= 5*USEC_PER_MINUTE)
1983 snprintf(buf, l, "%llumin ago",
1984 (unsigned long long) (d / USEC_PER_MINUTE));
1985 else if (d >= USEC_PER_MINUTE)
1986 snprintf(buf, l, "%llumin %llus ago",
1987 (unsigned long long) (d / USEC_PER_MINUTE),
1988 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1989 else if (d >= USEC_PER_SEC)
1990 snprintf(buf, l, "%llus ago",
1991 (unsigned long long) (d / USEC_PER_SEC));
1992 else if (d >= USEC_PER_MSEC)
1993 snprintf(buf, l, "%llums ago",
1994 (unsigned long long) (d / USEC_PER_MSEC));
1996 snprintf(buf, l, "%lluus ago",
1997 (unsigned long long) d);
1999 snprintf(buf, l, "now");
2005 char *format_timespan(char *buf, size_t l, usec_t t) {
2006 static const struct {
2010 { "w", USEC_PER_WEEK },
2011 { "d", USEC_PER_DAY },
2012 { "h", USEC_PER_HOUR },
2013 { "min", USEC_PER_MINUTE },
2014 { "s", USEC_PER_SEC },
2015 { "ms", USEC_PER_MSEC },
2025 if (t == (usec_t) -1)
2029 snprintf(p, l, "0");
2034 /* The result of this function can be parsed with parse_usec */
2036 for (i = 0; i < ELEMENTSOF(table); i++) {
2040 if (t < table[i].usec)
2046 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2047 n = MIN((size_t) k, l);
2060 bool fstype_is_network(const char *fstype) {
2061 static const char * const table[] = {
2073 for (i = 0; i < ELEMENTSOF(table); i++)
2074 if (streq(table[i], fstype))
2083 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2088 TIOCL_GETKMSGREDIRECT,
2092 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2097 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2100 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2104 close_nointr_nofail(fd);
2108 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2109 struct termios old_termios, new_termios;
2111 char line[LINE_MAX];
2116 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2117 new_termios = old_termios;
2119 new_termios.c_lflag &= ~ICANON;
2120 new_termios.c_cc[VMIN] = 1;
2121 new_termios.c_cc[VTIME] = 0;
2123 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2126 if (t != (usec_t) -1) {
2127 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2128 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2133 k = fread(&c, 1, 1, f);
2135 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2141 *need_nl = c != '\n';
2148 if (t != (usec_t) -1)
2149 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2152 if (!fgets(line, sizeof(line), f))
2157 if (strlen(line) != 1)
2167 int ask(char *ret, const char *replies, const char *text, ...) {
2174 on_tty = isatty(STDOUT_FILENO);
2180 bool need_nl = true;
2183 fputs(ANSI_HIGHLIGHT_ON, stdout);
2190 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2194 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2197 if (r == -EBADMSG) {
2198 puts("Bad input, please try again.");
2209 if (strchr(replies, c)) {
2214 puts("Read unexpected character, please try again.");
2218 int reset_terminal_fd(int fd, bool switch_to_text) {
2219 struct termios termios;
2222 /* Set terminal to some sane defaults */
2226 /* We leave locked terminal attributes untouched, so that
2227 * Plymouth may set whatever it wants to set, and we don't
2228 * interfere with that. */
2230 /* Disable exclusive mode, just in case */
2231 ioctl(fd, TIOCNXCL);
2233 /* Switch to text mode */
2235 ioctl(fd, KDSETMODE, KD_TEXT);
2237 /* Enable console unicode mode */
2238 ioctl(fd, KDSKBMODE, K_UNICODE);
2240 if (tcgetattr(fd, &termios) < 0) {
2245 /* We only reset the stuff that matters to the software. How
2246 * hardware is set up we don't touch assuming that somebody
2247 * else will do that for us */
2249 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2250 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2251 termios.c_oflag |= ONLCR;
2252 termios.c_cflag |= CREAD;
2253 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2255 termios.c_cc[VINTR] = 03; /* ^C */
2256 termios.c_cc[VQUIT] = 034; /* ^\ */
2257 termios.c_cc[VERASE] = 0177;
2258 termios.c_cc[VKILL] = 025; /* ^X */
2259 termios.c_cc[VEOF] = 04; /* ^D */
2260 termios.c_cc[VSTART] = 021; /* ^Q */
2261 termios.c_cc[VSTOP] = 023; /* ^S */
2262 termios.c_cc[VSUSP] = 032; /* ^Z */
2263 termios.c_cc[VLNEXT] = 026; /* ^V */
2264 termios.c_cc[VWERASE] = 027; /* ^W */
2265 termios.c_cc[VREPRINT] = 022; /* ^R */
2266 termios.c_cc[VEOL] = 0;
2267 termios.c_cc[VEOL2] = 0;
2269 termios.c_cc[VTIME] = 0;
2270 termios.c_cc[VMIN] = 1;
2272 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2276 /* Just in case, flush all crap out */
2277 tcflush(fd, TCIOFLUSH);
2282 int reset_terminal(const char *name) {
2285 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2289 r = reset_terminal_fd(fd, true);
2290 close_nointr_nofail(fd);
2295 int open_terminal(const char *name, int mode) {
2300 * If a TTY is in the process of being closed opening it might
2301 * cause EIO. This is horribly awful, but unlikely to be
2302 * changed in the kernel. Hence we work around this problem by
2303 * retrying a couple of times.
2305 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2309 if ((fd = open(name, mode)) >= 0)
2318 usleep(50 * USEC_PER_MSEC);
2325 if ((r = isatty(fd)) < 0) {
2326 close_nointr_nofail(fd);
2331 close_nointr_nofail(fd);
2338 int flush_fd(int fd) {
2339 struct pollfd pollfd;
2343 pollfd.events = POLLIN;
2350 if ((r = poll(&pollfd, 1, 0)) < 0) {
2361 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2366 if (errno == EAGAIN)
2377 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2378 int fd = -1, notify = -1, r, wd = -1;
2382 /* We use inotify to be notified when the tty is closed. We
2383 * create the watch before checking if we can actually acquire
2384 * it, so that we don't lose any event.
2386 * Note: strictly speaking this actually watches for the
2387 * device being closed, it does *not* really watch whether a
2388 * tty loses its controlling process. However, unless some
2389 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2390 * its tty otherwise this will not become a problem. As long
2391 * as the administrator makes sure not configure any service
2392 * on the same tty as an untrusted user this should not be a
2393 * problem. (Which he probably should not do anyway.) */
2395 if (!fail && !force) {
2396 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2401 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2409 if ((r = flush_fd(notify)) < 0)
2412 /* We pass here O_NOCTTY only so that we can check the return
2413 * value TIOCSCTTY and have a reliable way to figure out if we
2414 * successfully became the controlling process of the tty */
2415 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2418 /* First, try to get the tty */
2419 r = ioctl(fd, TIOCSCTTY, force);
2421 /* Sometimes it makes sense to ignore TIOCSCTTY
2422 * returning EPERM, i.e. when very likely we already
2423 * are have this controlling terminal. */
2424 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2427 if (r < 0 && (force || fail || errno != EPERM)) {
2437 assert(notify >= 0);
2440 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2442 struct inotify_event *e;
2444 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2453 e = (struct inotify_event*) inotify_buffer;
2458 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2463 step = sizeof(struct inotify_event) + e->len;
2464 assert(step <= (size_t) l);
2466 e = (struct inotify_event*) ((uint8_t*) e + step);
2473 /* We close the tty fd here since if the old session
2474 * ended our handle will be dead. It's important that
2475 * we do this after sleeping, so that we don't enter
2476 * an endless loop. */
2477 close_nointr_nofail(fd);
2481 close_nointr_nofail(notify);
2483 r = reset_terminal_fd(fd, true);
2485 log_warning("Failed to reset terminal: %s", strerror(-r));
2491 close_nointr_nofail(fd);
2494 close_nointr_nofail(notify);
2499 int release_terminal(void) {
2501 struct sigaction sa_old, sa_new;
2503 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2506 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2507 * by our own TIOCNOTTY */
2510 sa_new.sa_handler = SIG_IGN;
2511 sa_new.sa_flags = SA_RESTART;
2512 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2514 if (ioctl(fd, TIOCNOTTY) < 0)
2517 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2519 close_nointr_nofail(fd);
2523 int sigaction_many(const struct sigaction *sa, ...) {
2528 while ((sig = va_arg(ap, int)) > 0)
2529 if (sigaction(sig, sa, NULL) < 0)
2536 int ignore_signals(int sig, ...) {
2537 struct sigaction sa;
2542 sa.sa_handler = SIG_IGN;
2543 sa.sa_flags = SA_RESTART;
2545 if (sigaction(sig, &sa, NULL) < 0)
2549 while ((sig = va_arg(ap, int)) > 0)
2550 if (sigaction(sig, &sa, NULL) < 0)
2557 int default_signals(int sig, ...) {
2558 struct sigaction sa;
2563 sa.sa_handler = SIG_DFL;
2564 sa.sa_flags = SA_RESTART;
2566 if (sigaction(sig, &sa, NULL) < 0)
2570 while ((sig = va_arg(ap, int)) > 0)
2571 if (sigaction(sig, &sa, NULL) < 0)
2578 int close_pipe(int p[]) {
2584 a = close_nointr(p[0]);
2589 b = close_nointr(p[1]);
2593 return a < 0 ? a : b;
2596 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2605 while (nbytes > 0) {
2608 if ((k = read(fd, p, nbytes)) <= 0) {
2610 if (k < 0 && errno == EINTR)
2613 if (k < 0 && errno == EAGAIN && do_poll) {
2614 struct pollfd pollfd;
2618 pollfd.events = POLLIN;
2620 if (poll(&pollfd, 1, -1) < 0) {
2624 return n > 0 ? n : -errno;
2627 if (pollfd.revents != POLLIN)
2628 return n > 0 ? n : -EIO;
2633 return n > 0 ? n : (k < 0 ? -errno : 0);
2644 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2653 while (nbytes > 0) {
2656 k = write(fd, p, nbytes);
2659 if (k < 0 && errno == EINTR)
2662 if (k < 0 && errno == EAGAIN && do_poll) {
2663 struct pollfd pollfd;
2667 pollfd.events = POLLOUT;
2669 if (poll(&pollfd, 1, -1) < 0) {
2673 return n > 0 ? n : -errno;
2676 if (pollfd.revents != POLLOUT)
2677 return n > 0 ? n : -EIO;
2682 return n > 0 ? n : (k < 0 ? -errno : 0);
2693 int parse_usec(const char *t, usec_t *usec) {
2694 static const struct {
2698 { "sec", USEC_PER_SEC },
2699 { "s", USEC_PER_SEC },
2700 { "min", USEC_PER_MINUTE },
2701 { "hr", USEC_PER_HOUR },
2702 { "h", USEC_PER_HOUR },
2703 { "d", USEC_PER_DAY },
2704 { "w", USEC_PER_WEEK },
2705 { "msec", USEC_PER_MSEC },
2706 { "ms", USEC_PER_MSEC },
2707 { "m", USEC_PER_MINUTE },
2710 { "", USEC_PER_SEC }, /* default is sec */
2726 l = strtoll(p, &e, 10);
2737 e += strspn(e, WHITESPACE);
2739 for (i = 0; i < ELEMENTSOF(table); i++)
2740 if (startswith(e, table[i].suffix)) {
2741 r += (usec_t) l * table[i].usec;
2742 p = e + strlen(table[i].suffix);
2746 if (i >= ELEMENTSOF(table))
2756 int parse_nsec(const char *t, nsec_t *nsec) {
2757 static const struct {
2761 { "sec", NSEC_PER_SEC },
2762 { "s", NSEC_PER_SEC },
2763 { "min", NSEC_PER_MINUTE },
2764 { "hr", NSEC_PER_HOUR },
2765 { "h", NSEC_PER_HOUR },
2766 { "d", NSEC_PER_DAY },
2767 { "w", NSEC_PER_WEEK },
2768 { "msec", NSEC_PER_MSEC },
2769 { "ms", NSEC_PER_MSEC },
2770 { "m", NSEC_PER_MINUTE },
2771 { "usec", NSEC_PER_USEC },
2772 { "us", NSEC_PER_USEC },
2775 { "", 1ULL }, /* default is nsec */
2791 l = strtoll(p, &e, 10);
2802 e += strspn(e, WHITESPACE);
2804 for (i = 0; i < ELEMENTSOF(table); i++)
2805 if (startswith(e, table[i].suffix)) {
2806 r += (nsec_t) l * table[i].nsec;
2807 p = e + strlen(table[i].suffix);
2811 if (i >= ELEMENTSOF(table))
2821 int parse_bytes(const char *t, off_t *bytes) {
2822 static const struct {
2828 { "M", 1024ULL*1024ULL },
2829 { "G", 1024ULL*1024ULL*1024ULL },
2830 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2831 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2832 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2849 l = strtoll(p, &e, 10);
2860 e += strspn(e, WHITESPACE);
2862 for (i = 0; i < ELEMENTSOF(table); i++)
2863 if (startswith(e, table[i].suffix)) {
2864 r += (off_t) l * table[i].factor;
2865 p = e + strlen(table[i].suffix);
2869 if (i >= ELEMENTSOF(table))
2879 int make_stdio(int fd) {
2884 r = dup2(fd, STDIN_FILENO);
2885 s = dup2(fd, STDOUT_FILENO);
2886 t = dup2(fd, STDERR_FILENO);
2889 close_nointr_nofail(fd);
2891 if (r < 0 || s < 0 || t < 0)
2894 fd_cloexec(STDIN_FILENO, false);
2895 fd_cloexec(STDOUT_FILENO, false);
2896 fd_cloexec(STDERR_FILENO, false);
2901 int make_null_stdio(void) {
2904 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2907 return make_stdio(null_fd);
2910 bool is_device_path(const char *path) {
2912 /* Returns true on paths that refer to a device, either in
2913 * sysfs or in /dev */
2916 path_startswith(path, "/dev/") ||
2917 path_startswith(path, "/sys/");
2920 int dir_is_empty(const char *path) {
2923 struct dirent buf, *de;
2925 if (!(d = opendir(path)))
2929 if ((r = readdir_r(d, &buf, &de)) > 0) {
2939 if (!ignore_file(de->d_name)) {
2949 unsigned long long random_ull(void) {
2954 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2957 r = loop_read(fd, &ull, sizeof(ull), true);
2958 close_nointr_nofail(fd);
2960 if (r != sizeof(ull))
2966 return random() * RAND_MAX + random();
2969 void rename_process(const char name[8]) {
2972 /* This is a like a poor man's setproctitle(). It changes the
2973 * comm field, argv[0], and also the glibc's internally used
2974 * name of the process. For the first one a limit of 16 chars
2975 * applies, to the second one usually one of 10 (i.e. length
2976 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2977 * "systemd"). If you pass a longer string it will be
2980 prctl(PR_SET_NAME, name);
2982 if (program_invocation_name)
2983 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2985 if (saved_argc > 0) {
2989 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2991 for (i = 1; i < saved_argc; i++) {
2995 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3000 void sigset_add_many(sigset_t *ss, ...) {
3007 while ((sig = va_arg(ap, int)) > 0)
3008 assert_se(sigaddset(ss, sig) == 0);
3012 char* gethostname_malloc(void) {
3015 assert_se(uname(&u) >= 0);
3017 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3018 return strdup(u.nodename);
3020 return strdup(u.sysname);
3023 bool hostname_is_set(void) {
3026 assert_se(uname(&u) >= 0);
3028 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3031 char* getlogname_malloc(void) {
3035 struct passwd pwbuf, *pw = NULL;
3038 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3043 /* Shortcut things to avoid NSS lookups */
3045 return strdup("root");
3047 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3050 if (!(buf = malloc(bufsize)))
3053 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3054 name = strdup(pw->pw_name);
3061 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3067 int getttyname_malloc(int fd, char **r) {
3068 char path[PATH_MAX], *c;
3073 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3078 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3085 int getttyname_harder(int fd, char **r) {
3089 if ((k = getttyname_malloc(fd, &s)) < 0)
3092 if (streq(s, "tty")) {
3094 return get_ctty(0, NULL, r);
3101 int get_ctty_devnr(pid_t pid, dev_t *d) {
3103 char line[LINE_MAX], *p, *fn;
3104 unsigned long ttynr;
3107 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3110 f = fopen(fn, "re");
3115 if (!fgets(line, sizeof(line), f)) {
3116 k = feof(f) ? -EIO : -errno;
3123 p = strrchr(line, ')');
3133 "%*d " /* session */
3142 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3144 char fn[PATH_MAX], *s, *b, *p;
3149 k = get_ctty_devnr(pid, &devnr);
3153 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3156 if ((k = readlink_malloc(fn, &s)) < 0) {
3161 /* This is an ugly hack */
3162 if (major(devnr) == 136) {
3163 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3173 /* Probably something like the ptys which have no
3174 * symlink in /dev/char. Let's return something
3175 * vaguely useful. */
3177 if (!(b = strdup(fn + 5)))
3187 if (startswith(s, "/dev/"))
3189 else if (startswith(s, "../"))
3207 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3213 /* This returns the first error we run into, but nevertheless
3214 * tries to go on. This closes the passed fd. */
3218 close_nointr_nofail(fd);
3220 return errno == ENOENT ? 0 : -errno;
3224 struct dirent buf, *de;
3225 bool is_dir, keep_around;
3229 r = readdir_r(d, &buf, &de);
3230 if (r != 0 && ret == 0) {
3238 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3241 if (de->d_type == DT_UNKNOWN ||
3243 (de->d_type == DT_DIR && root_dev)) {
3244 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3245 if (ret == 0 && errno != ENOENT)
3250 is_dir = S_ISDIR(st.st_mode);
3253 (st.st_uid == 0 || st.st_uid == getuid()) &&
3254 (st.st_mode & S_ISVTX);
3256 is_dir = de->d_type == DT_DIR;
3257 keep_around = false;
3263 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3264 if (root_dev && st.st_dev != root_dev->st_dev)
3267 subdir_fd = openat(fd, de->d_name,
3268 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3269 if (subdir_fd < 0) {
3270 if (ret == 0 && errno != ENOENT)
3275 r = rm_rf_children(subdir_fd, only_dirs, honour_sticky, root_dev);
3276 if (r < 0 && ret == 0)
3280 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3281 if (ret == 0 && errno != ENOENT)
3285 } else if (!only_dirs && !keep_around) {
3287 if (unlinkat(fd, de->d_name, 0) < 0) {
3288 if (ret == 0 && errno != ENOENT)
3299 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3305 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3308 if (errno != ENOTDIR)
3311 if (delete_root && !only_dirs)
3312 if (unlink(path) < 0 && errno != ENOENT)
3318 r = rm_rf_children(fd, only_dirs, honour_sticky, NULL);
3322 if (honour_sticky && file_is_priv_sticky(path) > 0)
3325 if (rmdir(path) < 0 && errno != ENOENT) {
3334 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3337 /* Under the assumption that we are running privileged we
3338 * first change the access mode and only then hand out
3339 * ownership to avoid a window where access is too open. */
3341 if (mode != (mode_t) -1)
3342 if (chmod(path, mode) < 0)
3345 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3346 if (chown(path, uid, gid) < 0)
3352 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3355 /* Under the assumption that we are running privileged we
3356 * first change the access mode and only then hand out
3357 * ownership to avoid a window where access is too open. */
3359 if (fchmod(fd, mode) < 0)
3362 if (fchown(fd, uid, gid) < 0)
3368 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3372 /* Allocates the cpuset in the right size */
3375 if (!(r = CPU_ALLOC(n)))
3378 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3379 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3389 if (errno != EINVAL)
3396 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3398 static const char status_indent[] = " "; /* "[" STATUS "] " */
3400 struct iovec iovec[5];
3405 /* This is independent of logging, as status messages are
3406 * optional and go exclusively to the console. */
3408 if (vasprintf(&s, format, ap) < 0)
3411 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3424 sl = status ? strlen(status_indent) : 0;
3430 e = ellipsize(s, emax, 75);
3440 if (!isempty(status)) {
3441 IOVEC_SET_STRING(iovec[n++], "[");
3442 IOVEC_SET_STRING(iovec[n++], status);
3443 IOVEC_SET_STRING(iovec[n++], "] ");
3445 IOVEC_SET_STRING(iovec[n++], status_indent);
3448 IOVEC_SET_STRING(iovec[n++], s);
3449 IOVEC_SET_STRING(iovec[n++], "\n");
3451 writev(fd, iovec, n);
3457 close_nointr_nofail(fd);
3460 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3465 va_start(ap, format);
3466 status_vprintf(status, ellipse, format, ap);
3470 void status_welcome(void) {
3471 char *pretty_name = NULL, *ansi_color = NULL;
3472 const char *const_pretty = NULL, *const_color = NULL;
3475 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3476 "PRETTY_NAME", &pretty_name,
3477 "ANSI_COLOR", &ansi_color,
3481 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3484 if (!pretty_name && !const_pretty)
3485 const_pretty = "Linux";
3487 if (!ansi_color && !const_color)
3492 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3493 const_color ? const_color : ansi_color,
3494 const_pretty ? const_pretty : pretty_name);
3500 char *replace_env(const char *format, char **env) {
3507 const char *e, *word = format;
3512 for (e = format; *e; e ++) {
3523 if (!(k = strnappend(r, word, e-word-1)))
3532 } else if (*e == '$') {
3533 if (!(k = strnappend(r, word, e-word)))
3549 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3552 if (!(k = strappend(r, t)))
3565 if (!(k = strnappend(r, word, e-word)))
3576 char **replace_env_argv(char **argv, char **env) {
3578 unsigned k = 0, l = 0;
3580 l = strv_length(argv);
3582 if (!(r = new(char*, l+1)))
3585 STRV_FOREACH(i, argv) {
3587 /* If $FOO appears as single word, replace it by the split up variable */
3588 if ((*i)[0] == '$' && (*i)[1] != '{') {
3593 if ((e = strv_env_get(env, *i+1))) {
3595 if (!(m = strv_split_quoted(e))) {
3606 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3615 memcpy(r + k, m, q * sizeof(char*));
3623 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3624 if (!(r[k++] = replace_env(*i, env))) {
3634 int fd_columns(int fd) {
3638 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3647 unsigned columns(void) {
3648 static __thread int parsed_columns = 0;
3651 if (_likely_(parsed_columns > 0))
3652 return parsed_columns;
3654 e = getenv("COLUMNS");
3656 parsed_columns = atoi(e);
3658 if (parsed_columns <= 0)
3659 parsed_columns = fd_columns(STDOUT_FILENO);
3661 if (parsed_columns <= 0)
3662 parsed_columns = 80;
3664 return parsed_columns;
3667 int fd_lines(int fd) {
3671 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3680 unsigned lines(void) {
3681 static __thread int parsed_lines = 0;
3684 if (_likely_(parsed_lines > 0))
3685 return parsed_lines;
3687 e = getenv("LINES");
3689 parsed_lines = atoi(e);
3691 if (parsed_lines <= 0)
3692 parsed_lines = fd_lines(STDOUT_FILENO);
3694 if (parsed_lines <= 0)
3697 return parsed_lines;
3700 int running_in_chroot(void) {
3706 /* Only works as root */
3708 if (stat("/proc/1/root", &a) < 0)
3711 if (stat("/", &b) < 0)
3715 a.st_dev != b.st_dev ||
3716 a.st_ino != b.st_ino;
3719 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3724 assert(percent <= 100);
3725 assert(new_length >= 3);
3727 if (old_length <= 3 || old_length <= new_length)
3728 return strndup(s, old_length);
3730 r = new0(char, new_length+1);
3734 x = (new_length * percent) / 100;
3736 if (x > new_length - 3)
3744 s + old_length - (new_length - x - 3),
3745 new_length - x - 3);
3750 char *ellipsize(const char *s, size_t length, unsigned percent) {
3751 return ellipsize_mem(s, strlen(s), length, percent);
3754 int touch(const char *path) {
3759 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3762 close_nointr_nofail(fd);
3766 char *unquote(const char *s, const char* quotes) {
3774 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3775 return strndup(s+1, l-2);
3780 char *normalize_env_assignment(const char *s) {
3781 char *name, *value, *p, *r;
3786 if (!(r = strdup(s)))
3792 if (!(name = strndup(s, p - s)))
3795 if (!(p = strdup(p+1))) {
3800 value = unquote(strstrip(p), QUOTES);
3808 if (asprintf(&r, "%s=%s", name, value) < 0)
3817 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3828 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3840 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3847 if ((r = wait_for_terminate(pid, &status)) < 0) {
3848 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3852 if (status.si_code == CLD_EXITED) {
3853 if (status.si_status != 0) {
3854 log_warning("%s failed with error code %i.", name, status.si_status);
3855 return status.si_status;
3858 log_debug("%s succeeded.", name);
3861 } else if (status.si_code == CLD_KILLED ||
3862 status.si_code == CLD_DUMPED) {
3864 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3868 log_warning("%s failed due to unknown reason.", name);
3873 _noreturn_ void freeze(void) {
3875 /* Make sure nobody waits for us on a socket anymore */
3876 close_all_fds(NULL, 0);
3884 bool null_or_empty(struct stat *st) {
3887 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3890 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3896 int null_or_empty_path(const char *fn) {
3901 if (stat(fn, &st) < 0)
3904 return null_or_empty(&st);
3907 DIR *xopendirat(int fd, const char *name, int flags) {
3911 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3914 if (!(d = fdopendir(nfd))) {
3915 close_nointr_nofail(nfd);
3922 int signal_from_string_try_harder(const char *s) {
3926 if ((signo = signal_from_string(s)) <= 0)
3927 if (startswith(s, "SIG"))
3928 return signal_from_string(s+3);
3933 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3939 if (!dual_timestamp_is_set(t))
3942 fprintf(f, "%s=%llu %llu\n",
3944 (unsigned long long) t->realtime,
3945 (unsigned long long) t->monotonic);
3948 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3949 unsigned long long a, b;
3954 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3955 log_debug("Failed to parse finish timestamp value %s", value);
3962 char *fstab_node_to_udev_node(const char *p) {
3966 /* FIXME: to follow udev's logic 100% we need to leave valid
3967 * UTF8 chars unescaped */
3969 if (startswith(p, "LABEL=")) {
3971 if (!(u = unquote(p+6, "\"\'")))
3974 t = xescape(u, "/ ");
3980 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3989 if (startswith(p, "UUID=")) {
3991 if (!(u = unquote(p+5, "\"\'")))
3994 t = xescape(u, "/ ");
4000 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4012 bool tty_is_vc(const char *tty) {
4015 if (startswith(tty, "/dev/"))
4018 return vtnr_from_tty(tty) >= 0;
4021 bool tty_is_console(const char *tty) {
4024 if (startswith(tty, "/dev/"))
4027 return streq(tty, "console");
4030 int vtnr_from_tty(const char *tty) {
4035 if (startswith(tty, "/dev/"))
4038 if (!startswith(tty, "tty") )
4041 if (tty[3] < '0' || tty[3] > '9')
4044 r = safe_atoi(tty+3, &i);
4048 if (i < 0 || i > 63)
4054 bool tty_is_vc_resolve(const char *tty) {
4055 char *active = NULL;
4060 if (startswith(tty, "/dev/"))
4063 /* Resolve where /dev/console is pointing to, if /sys is
4064 * actually ours (i.e. not read-only-mounted which is a sign
4065 * for container setups) */
4066 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4067 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4068 /* If multiple log outputs are configured the
4069 * last one is what /dev/console points to */
4070 tty = strrchr(active, ' ');
4083 const char *default_term_for_tty(const char *tty) {
4086 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4089 bool dirent_is_file(const struct dirent *de) {
4092 if (ignore_file(de->d_name))
4095 if (de->d_type != DT_REG &&
4096 de->d_type != DT_LNK &&
4097 de->d_type != DT_UNKNOWN)
4103 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4106 if (!dirent_is_file(de))
4109 return endswith(de->d_name, suffix);
4112 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4115 Hashmap *pids = NULL;
4119 /* Executes all binaries in a directory in parallel and waits
4120 * until all they all finished. */
4123 if (!(_d = opendir(directory))) {
4125 if (errno == ENOENT)
4128 log_error("Failed to enumerate directory %s: %m", directory);
4135 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4136 log_error("Failed to allocate set.");
4140 while ((de = readdir(d))) {
4145 if (!dirent_is_file(de))
4148 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4149 log_error("Out of memory");
4153 if ((pid = fork()) < 0) {
4154 log_error("Failed to fork: %m");
4172 log_error("Failed to execute %s: %m", path);
4173 _exit(EXIT_FAILURE);
4176 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4178 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4179 log_error("Failed to add PID to set: %s", strerror(-k));
4184 while (!hashmap_isempty(pids)) {
4185 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4190 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4195 log_error("waitid() failed: %m");
4199 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4200 if (!is_clean_exit(si.si_code, si.si_status)) {
4201 if (si.si_code == CLD_EXITED)
4202 log_error("%s exited with exit status %i.", path, si.si_status);
4204 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4206 log_debug("%s exited successfully.", path);
4217 hashmap_free_free(pids);
4220 int kill_and_sigcont(pid_t pid, int sig) {
4223 r = kill(pid, sig) < 0 ? -errno : 0;
4231 bool nulstr_contains(const char*nulstr, const char *needle) {
4237 NULSTR_FOREACH(i, nulstr)
4238 if (streq(i, needle))
4244 bool plymouth_running(void) {
4245 return access("/run/plymouth/pid", F_OK) >= 0;
4248 void parse_syslog_priority(char **p, int *priority) {
4249 int a = 0, b = 0, c = 0;
4259 if (!strchr(*p, '>'))
4262 if ((*p)[2] == '>') {
4263 c = undecchar((*p)[1]);
4265 } else if ((*p)[3] == '>') {
4266 b = undecchar((*p)[1]);
4267 c = undecchar((*p)[2]);
4269 } else if ((*p)[4] == '>') {
4270 a = undecchar((*p)[1]);
4271 b = undecchar((*p)[2]);
4272 c = undecchar((*p)[3]);
4277 if (a < 0 || b < 0 || c < 0)
4280 *priority = a*100+b*10+c;
4284 void skip_syslog_pid(char **buf) {
4296 p += strspn(p, "0123456789");
4306 void skip_syslog_date(char **buf) {
4314 LETTER, LETTER, LETTER,
4316 SPACE_OR_NUMBER, NUMBER,
4318 SPACE_OR_NUMBER, NUMBER,
4320 SPACE_OR_NUMBER, NUMBER,
4322 SPACE_OR_NUMBER, NUMBER,
4334 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4339 switch (sequence[i]) {
4346 case SPACE_OR_NUMBER:
4353 if (*p < '0' || *p > '9')
4359 if (!(*p >= 'A' && *p <= 'Z') &&
4360 !(*p >= 'a' && *p <= 'z'))
4376 char* strshorten(char *s, size_t l) {
4385 static bool hostname_valid_char(char c) {
4387 (c >= 'a' && c <= 'z') ||
4388 (c >= 'A' && c <= 'Z') ||
4389 (c >= '0' && c <= '9') ||
4395 bool hostname_is_valid(const char *s) {
4401 for (p = s; *p; p++)
4402 if (!hostname_valid_char(*p))
4405 if (p-s > HOST_NAME_MAX)
4411 char* hostname_cleanup(char *s) {
4414 for (p = s, d = s; *p; p++)
4415 if ((*p >= 'a' && *p <= 'z') ||
4416 (*p >= 'A' && *p <= 'Z') ||
4417 (*p >= '0' && *p <= '9') ||
4425 strshorten(s, HOST_NAME_MAX);
4429 int pipe_eof(int fd) {
4430 struct pollfd pollfd;
4435 pollfd.events = POLLIN|POLLHUP;
4437 r = poll(&pollfd, 1, 0);
4444 return pollfd.revents & POLLHUP;
4447 int fd_wait_for_event(int fd, int event, usec_t t) {
4448 struct pollfd pollfd;
4453 pollfd.events = event;
4455 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4462 return pollfd.revents;
4465 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4476 t = new(char, strlen(path) + 1 + 6 + 1);
4480 fn = path_get_file_name(path);
4484 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4486 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4492 f = fdopen(fd, "we");
4505 int terminal_vhangup_fd(int fd) {
4508 if (ioctl(fd, TIOCVHANGUP) < 0)
4514 int terminal_vhangup(const char *name) {
4517 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4521 r = terminal_vhangup_fd(fd);
4522 close_nointr_nofail(fd);
4527 int vt_disallocate(const char *name) {
4531 /* Deallocate the VT if possible. If not possible
4532 * (i.e. because it is the active one), at least clear it
4533 * entirely (including the scrollback buffer) */
4535 if (!startswith(name, "/dev/"))
4538 if (!tty_is_vc(name)) {
4539 /* So this is not a VT. I guess we cannot deallocate
4540 * it then. But let's at least clear the screen */
4542 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4547 "\033[r" /* clear scrolling region */
4548 "\033[H" /* move home */
4549 "\033[2J", /* clear screen */
4551 close_nointr_nofail(fd);
4556 if (!startswith(name, "/dev/tty"))
4559 r = safe_atou(name+8, &u);
4566 /* Try to deallocate */
4567 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4571 r = ioctl(fd, VT_DISALLOCATE, u);
4572 close_nointr_nofail(fd);
4580 /* Couldn't deallocate, so let's clear it fully with
4582 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4587 "\033[r" /* clear scrolling region */
4588 "\033[H" /* move home */
4589 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4591 close_nointr_nofail(fd);
4596 int copy_file(const char *from, const char *to) {
4602 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4606 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4608 close_nointr_nofail(fdf);
4616 n = read(fdf, buf, sizeof(buf));
4620 close_nointr_nofail(fdf);
4631 k = loop_write(fdt, buf, n, false);
4633 r = k < 0 ? k : (errno ? -errno : -EIO);
4635 close_nointr_nofail(fdf);
4643 close_nointr_nofail(fdf);
4644 r = close_nointr(fdt);
4654 int symlink_or_copy(const char *from, const char *to) {
4655 char *pf = NULL, *pt = NULL;
4662 if (path_get_parent(from, &pf) < 0 ||
4663 path_get_parent(to, &pt) < 0) {
4668 if (stat(pf, &a) < 0 ||
4674 if (a.st_dev != b.st_dev) {
4678 return copy_file(from, to);
4681 if (symlink(from, to) < 0) {
4695 int symlink_or_copy_atomic(const char *from, const char *to) {
4699 unsigned long long ull;
4706 t = new(char, strlen(to) + 1 + 16 + 1);
4710 fn = path_get_file_name(to);
4714 x = stpcpy(t+k+1, fn);
4717 for (i = 0; i < 16; i++) {
4718 *(x++) = hexchar(ull & 0xF);
4724 r = symlink_or_copy(from, t);
4731 if (rename(t, to) < 0) {
4742 bool display_is_local(const char *display) {
4746 display[0] == ':' &&
4747 display[1] >= '0' &&
4751 int socket_from_display(const char *display, char **path) {
4758 if (!display_is_local(display))
4761 k = strspn(display+1, "0123456789");
4763 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4767 c = stpcpy(f, "/tmp/.X11-unix/X");
4768 memcpy(c, display+1, k);
4776 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
4783 /* We enforce some special rules for uid=0: in order to avoid
4784 * NSS lookups for root we hardcode its data. */
4786 if (streq(*username, "root") || streq(*username, "0")) {
4800 if (parse_uid(*username, &u) >= 0) {
4804 /* If there are multiple users with the same id, make
4805 * sure to leave $USER to the configured value instead
4806 * of the first occurrence in the database. However if
4807 * the uid was configured by a numeric uid, then let's
4808 * pick the real username from /etc/passwd. */
4810 *username = p->pw_name;
4813 p = getpwnam(*username);
4817 return errno != 0 ? -errno : -ESRCH;
4831 int get_group_creds(const char **groupname, gid_t *gid) {
4837 /* We enforce some special rules for gid=0: in order to avoid
4838 * NSS lookups for root we hardcode its data. */
4840 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4841 *groupname = "root";
4849 if (parse_gid(*groupname, &id) >= 0) {
4854 *groupname = g->gr_name;
4857 g = getgrnam(*groupname);
4861 return errno != 0 ? -errno : -ESRCH;
4869 int in_group(const char *name) {
4871 int ngroups_max, r, i;
4873 r = get_group_creds(&name, &gid);
4877 if (getgid() == gid)
4880 if (getegid() == gid)
4883 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4884 assert(ngroups_max > 0);
4886 gids = alloca(sizeof(gid_t) * ngroups_max);
4888 r = getgroups(ngroups_max, gids);
4892 for (i = 0; i < r; i++)
4899 int glob_exists(const char *path) {
4907 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4909 if (k == GLOB_NOMATCH)
4911 else if (k == GLOB_NOSPACE)
4914 r = !strv_isempty(g.gl_pathv);
4916 r = errno ? -errno : -EIO;
4923 int dirent_ensure_type(DIR *d, struct dirent *de) {
4929 if (de->d_type != DT_UNKNOWN)
4932 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4936 S_ISREG(st.st_mode) ? DT_REG :
4937 S_ISDIR(st.st_mode) ? DT_DIR :
4938 S_ISLNK(st.st_mode) ? DT_LNK :
4939 S_ISFIFO(st.st_mode) ? DT_FIFO :
4940 S_ISSOCK(st.st_mode) ? DT_SOCK :
4941 S_ISCHR(st.st_mode) ? DT_CHR :
4942 S_ISBLK(st.st_mode) ? DT_BLK :
4948 int in_search_path(const char *path, char **search) {
4952 r = path_get_parent(path, &parent);
4958 STRV_FOREACH(i, search) {
4959 if (path_equal(parent, *i)) {
4970 int get_files_in_directory(const char *path, char ***list) {
4978 /* Returns all files in a directory in *list, and the number
4979 * of files as return value. If list is NULL returns only the
4987 struct dirent buffer, *de;
4990 k = readdir_r(d, &buffer, &de);
4999 dirent_ensure_type(d, de);
5001 if (!dirent_is_file(de))
5005 if ((unsigned) r >= n) {
5009 t = realloc(l, sizeof(char*) * n);
5018 assert((unsigned) r < n);
5020 l[r] = strdup(de->d_name);
5044 char *join(const char *x, ...) {
5057 t = va_arg(ap, const char *);
5080 t = va_arg(ap, const char *);
5094 bool is_main_thread(void) {
5095 static __thread int cached = 0;
5097 if (_unlikely_(cached == 0))
5098 cached = getpid() == gettid() ? 1 : -1;
5103 int block_get_whole_disk(dev_t d, dev_t *ret) {
5110 /* If it has a queue this is good enough for us */
5111 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5114 r = access(p, F_OK);
5122 /* If it is a partition find the originating device */
5123 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5126 r = access(p, F_OK);
5132 /* Get parent dev_t */
5133 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5136 r = read_one_line_file(p, &s);
5142 r = sscanf(s, "%u:%u", &m, &n);
5148 /* Only return this if it is really good enough for us. */
5149 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5152 r = access(p, F_OK);
5156 *ret = makedev(m, n);
5163 int file_is_priv_sticky(const char *p) {
5168 if (lstat(p, &st) < 0)
5172 (st.st_uid == 0 || st.st_uid == getuid()) &&
5173 (st.st_mode & S_ISVTX);
5176 static const char *const ioprio_class_table[] = {
5177 [IOPRIO_CLASS_NONE] = "none",
5178 [IOPRIO_CLASS_RT] = "realtime",
5179 [IOPRIO_CLASS_BE] = "best-effort",
5180 [IOPRIO_CLASS_IDLE] = "idle"
5183 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5185 static const char *const sigchld_code_table[] = {
5186 [CLD_EXITED] = "exited",
5187 [CLD_KILLED] = "killed",
5188 [CLD_DUMPED] = "dumped",
5189 [CLD_TRAPPED] = "trapped",
5190 [CLD_STOPPED] = "stopped",
5191 [CLD_CONTINUED] = "continued",
5194 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5196 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5197 [LOG_FAC(LOG_KERN)] = "kern",
5198 [LOG_FAC(LOG_USER)] = "user",
5199 [LOG_FAC(LOG_MAIL)] = "mail",
5200 [LOG_FAC(LOG_DAEMON)] = "daemon",
5201 [LOG_FAC(LOG_AUTH)] = "auth",
5202 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5203 [LOG_FAC(LOG_LPR)] = "lpr",
5204 [LOG_FAC(LOG_NEWS)] = "news",
5205 [LOG_FAC(LOG_UUCP)] = "uucp",
5206 [LOG_FAC(LOG_CRON)] = "cron",
5207 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5208 [LOG_FAC(LOG_FTP)] = "ftp",
5209 [LOG_FAC(LOG_LOCAL0)] = "local0",
5210 [LOG_FAC(LOG_LOCAL1)] = "local1",
5211 [LOG_FAC(LOG_LOCAL2)] = "local2",
5212 [LOG_FAC(LOG_LOCAL3)] = "local3",
5213 [LOG_FAC(LOG_LOCAL4)] = "local4",
5214 [LOG_FAC(LOG_LOCAL5)] = "local5",
5215 [LOG_FAC(LOG_LOCAL6)] = "local6",
5216 [LOG_FAC(LOG_LOCAL7)] = "local7"
5219 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5221 static const char *const log_level_table[] = {
5222 [LOG_EMERG] = "emerg",
5223 [LOG_ALERT] = "alert",
5224 [LOG_CRIT] = "crit",
5226 [LOG_WARNING] = "warning",
5227 [LOG_NOTICE] = "notice",
5228 [LOG_INFO] = "info",
5229 [LOG_DEBUG] = "debug"
5232 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5234 static const char* const sched_policy_table[] = {
5235 [SCHED_OTHER] = "other",
5236 [SCHED_BATCH] = "batch",
5237 [SCHED_IDLE] = "idle",
5238 [SCHED_FIFO] = "fifo",
5242 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5244 static const char* const rlimit_table[] = {
5245 [RLIMIT_CPU] = "LimitCPU",
5246 [RLIMIT_FSIZE] = "LimitFSIZE",
5247 [RLIMIT_DATA] = "LimitDATA",
5248 [RLIMIT_STACK] = "LimitSTACK",
5249 [RLIMIT_CORE] = "LimitCORE",
5250 [RLIMIT_RSS] = "LimitRSS",
5251 [RLIMIT_NOFILE] = "LimitNOFILE",
5252 [RLIMIT_AS] = "LimitAS",
5253 [RLIMIT_NPROC] = "LimitNPROC",
5254 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5255 [RLIMIT_LOCKS] = "LimitLOCKS",
5256 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5257 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5258 [RLIMIT_NICE] = "LimitNICE",
5259 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5260 [RLIMIT_RTTIME] = "LimitRTTIME"
5263 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5265 static const char* const ip_tos_table[] = {
5266 [IPTOS_LOWDELAY] = "low-delay",
5267 [IPTOS_THROUGHPUT] = "throughput",
5268 [IPTOS_RELIABILITY] = "reliability",
5269 [IPTOS_LOWCOST] = "low-cost",
5272 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5274 static const char *const __signal_table[] = {
5291 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5302 [SIGVTALRM] = "VTALRM",
5304 [SIGWINCH] = "WINCH",
5310 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5312 const char *signal_to_string(int signo) {
5313 static __thread char buf[12];
5316 name = __signal_to_string(signo);
5320 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5321 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5323 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5328 int signal_from_string(const char *s) {
5333 signo =__signal_from_string(s);
5337 if (startswith(s, "RTMIN+")) {
5341 if (safe_atou(s, &u) >= 0) {
5342 signo = (int) u + offset;
5343 if (signo > 0 && signo < _NSIG)
5349 bool kexec_loaded(void) {
5350 bool loaded = false;
5353 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5361 int strdup_or_null(const char *a, char **b) {
5379 int prot_from_flags(int flags) {
5381 switch (flags & O_ACCMODE) {
5390 return PROT_READ|PROT_WRITE;
5397 char *format_bytes(char *buf, size_t l, off_t t) {
5400 static const struct {
5404 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5405 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5406 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5407 { "G", 1024ULL*1024ULL*1024ULL },
5408 { "M", 1024ULL*1024ULL },
5412 for (i = 0; i < ELEMENTSOF(table); i++) {
5414 if (t >= table[i].factor) {
5417 (unsigned long long) (t / table[i].factor),
5418 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5425 snprintf(buf, l, "%lluB", (unsigned long long) t);
5433 void* memdup(const void *p, size_t l) {
5446 int fd_inc_sndbuf(int fd, size_t n) {
5448 socklen_t l = sizeof(value);
5450 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5452 l == sizeof(value) &&
5453 (size_t) value >= n*2)
5457 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5464 int fd_inc_rcvbuf(int fd, size_t n) {
5466 socklen_t l = sizeof(value);
5468 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5470 l == sizeof(value) &&
5471 (size_t) value >= n*2)
5475 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5482 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5483 pid_t parent_pid, agent_pid;
5485 bool stdout_is_tty, stderr_is_tty;
5493 parent_pid = getpid();
5495 /* Spawns a temporary TTY agent, making sure it goes away when
5502 if (agent_pid != 0) {
5509 * Make sure the agent goes away when the parent dies */
5510 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5511 _exit(EXIT_FAILURE);
5513 /* Check whether our parent died before we were able
5514 * to set the death signal */
5515 if (getppid() != parent_pid)
5516 _exit(EXIT_SUCCESS);
5518 /* Don't leak fds to the agent */
5519 close_all_fds(except, n_except);
5521 stdout_is_tty = isatty(STDOUT_FILENO);
5522 stderr_is_tty = isatty(STDERR_FILENO);
5524 if (!stdout_is_tty || !stderr_is_tty) {
5525 /* Detach from stdout/stderr. and reopen
5526 * /dev/tty for them. This is important to
5527 * ensure that when systemctl is started via
5528 * popen() or a similar call that expects to
5529 * read EOF we actually do generate EOF and
5530 * not delay this indefinitely by because we
5531 * keep an unused copy of stdin around. */
5532 fd = open("/dev/tty", O_WRONLY);
5534 log_error("Failed to open /dev/tty: %m");
5535 _exit(EXIT_FAILURE);
5539 dup2(fd, STDOUT_FILENO);
5542 dup2(fd, STDERR_FILENO);
5548 /* Count arguments */
5550 for (n = 0; va_arg(ap, char*); n++)
5555 l = alloca(sizeof(char *) * (n + 1));
5557 /* Fill in arguments */
5559 for (i = 0; i <= n; i++)
5560 l[i] = va_arg(ap, char*);
5564 _exit(EXIT_FAILURE);
5567 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5568 struct rlimit highest, fixed;
5572 if (setrlimit(resource, rlim) >= 0)
5578 /* So we failed to set the desired setrlimit, then let's try
5579 * to get as close as we can */
5580 assert_se(getrlimit(resource, &highest) == 0);
5582 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5583 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5585 if (setrlimit(resource, &fixed) < 0)
5591 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5592 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5604 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5607 f = fopen(path, "re");
5615 char line[LINE_MAX];
5618 for (i = 0; i < sizeof(line)-1; i++) {
5622 if (_unlikely_(c == EOF)) {
5632 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5633 value = strdup(line + l + 1);
5653 int can_sleep(const char *type) {
5654 char *p, *w, *state;
5661 r = read_one_line_file("/sys/power/state", &p);
5663 return r == -ENOENT ? 0 : r;
5667 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5668 if (l == k && strncmp(w, type, l) == 0) {
5678 bool is_valid_documentation_url(const char *url) {
5681 if (startswith(url, "http://") && url[7])
5684 if (startswith(url, "https://") && url[8])
5687 if (startswith(url, "file:") && url[5])
5690 if (startswith(url, "info:") && url[5])
5693 if (startswith(url, "man:") && url[4])
5699 bool in_initrd(void) {
5700 static int saved = -1;
5703 saved = access("/etc/initrd-release", F_OK) >= 0;
5708 void warn_melody(void) {
5711 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5715 /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5717 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5718 usleep(125*USEC_PER_MSEC);
5720 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5721 usleep(125*USEC_PER_MSEC);
5723 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5724 usleep(125*USEC_PER_MSEC);
5726 ioctl(fd, KIOCSOUND, 0);
5727 close_nointr_nofail(fd);