1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
68 #include "path-util.h"
69 #include "exit-status.h"
73 char **saved_argv = NULL;
75 static int parsed_columns = 0;
77 size_t page_size(void) {
78 static __thread size_t pgsz = 0;
81 if (_likely_(pgsz > 0))
84 r = sysconf(_SC_PAGESIZE);
91 bool streq_ptr(const char *a, const char *b) {
93 /* Like streq(), but tries to make sense of NULL pointers */
104 usec_t now(clockid_t clock_id) {
107 assert_se(clock_gettime(clock_id, &ts) == 0);
109 return timespec_load(&ts);
112 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
115 ts->realtime = now(CLOCK_REALTIME);
116 ts->monotonic = now(CLOCK_MONOTONIC);
121 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
130 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
132 ts->monotonic = now(CLOCK_MONOTONIC);
134 if ((int64_t) ts->monotonic > delta)
135 ts->monotonic -= delta;
143 usec_t timespec_load(const struct timespec *ts) {
147 (usec_t) ts->tv_sec * USEC_PER_SEC +
148 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
151 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
154 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
155 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
160 usec_t timeval_load(const struct timeval *tv) {
164 (usec_t) tv->tv_sec * USEC_PER_SEC +
165 (usec_t) tv->tv_usec;
168 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
171 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
172 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
177 bool endswith(const char *s, const char *postfix) {
184 pl = strlen(postfix);
192 return memcmp(s + sl - pl, postfix, pl) == 0;
195 bool startswith(const char *s, const char *prefix) {
210 return memcmp(s, prefix, pl) == 0;
213 bool startswith_no_case(const char *s, const char *prefix) {
229 for(i = 0; i < pl; ++i)
230 if (tolower(s[i]) != tolower(prefix[i]))
236 bool first_word(const char *s, const char *word) {
251 if (memcmp(s, word, wl) != 0)
255 strchr(WHITESPACE, s[wl]);
258 int close_nointr(int fd) {
273 void close_nointr_nofail(int fd) {
274 int saved_errno = errno;
276 /* like close_nointr() but cannot fail, and guarantees errno
279 assert_se(close_nointr(fd) == 0);
284 void close_many(const int fds[], unsigned n_fd) {
287 for (i = 0; i < n_fd; i++)
288 close_nointr_nofail(fds[i]);
291 int parse_boolean(const char *v) {
294 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
296 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
302 int parse_pid(const char *s, pid_t* ret_pid) {
303 unsigned long ul = 0;
310 r = safe_atolu(s, &ul);
316 if ((unsigned long) pid != ul)
326 int parse_uid(const char *s, uid_t* ret_uid) {
327 unsigned long ul = 0;
334 r = safe_atolu(s, &ul);
340 if ((unsigned long) uid != ul)
347 int safe_atou(const char *s, unsigned *ret_u) {
355 l = strtoul(s, &x, 0);
357 if (!x || *x || errno)
358 return errno ? -errno : -EINVAL;
360 if ((unsigned long) (unsigned) l != l)
363 *ret_u = (unsigned) l;
367 int safe_atoi(const char *s, int *ret_i) {
375 l = strtol(s, &x, 0);
377 if (!x || *x || errno)
378 return errno ? -errno : -EINVAL;
380 if ((long) (int) l != l)
387 int safe_atollu(const char *s, long long unsigned *ret_llu) {
389 unsigned long long l;
395 l = strtoull(s, &x, 0);
397 if (!x || *x || errno)
398 return errno ? -errno : -EINVAL;
404 int safe_atolli(const char *s, long long int *ret_lli) {
412 l = strtoll(s, &x, 0);
414 if (!x || *x || errno)
415 return errno ? -errno : -EINVAL;
421 /* Split a string into words. */
422 char *split(const char *c, size_t *l, const char *separator, char **state) {
425 current = *state ? *state : (char*) c;
427 if (!*current || *c == 0)
430 current += strspn(current, separator);
431 *l = strcspn(current, separator);
434 return (char*) current;
437 /* Split a string into words, but consider strings enclosed in '' and
438 * "" as words even if they include spaces. */
439 char *split_quoted(const char *c, size_t *l, char **state) {
441 bool escaped = false;
443 current = *state ? *state : (char*) c;
445 if (!*current || *c == 0)
448 current += strspn(current, WHITESPACE);
450 if (*current == '\'') {
453 for (e = current; *e; e++) {
463 *state = *e == 0 ? e : e+1;
464 } else if (*current == '\"') {
467 for (e = current; *e; e++) {
477 *state = *e == 0 ? e : e+1;
479 for (e = current; *e; e++) {
484 else if (strchr(WHITESPACE, *e))
491 return (char*) current;
494 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
496 _cleanup_fclose_ FILE *f = NULL;
497 char fn[PATH_MAX], line[LINE_MAX], *p;
503 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
510 if (!fgets(line, sizeof(line), f)) {
511 r = feof(f) ? -EIO : -errno;
516 /* Let's skip the pid and comm fields. The latter is enclosed
517 * in () but does not escape any () in its value, so let's
518 * skip over it manually */
520 p = strrchr(line, ')');
532 if ((long unsigned) (pid_t) ppid != ppid)
535 *_ppid = (pid_t) ppid;
540 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
541 _cleanup_fclose_ FILE *f = NULL;
542 char fn[PATH_MAX], line[LINE_MAX], *p;
547 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
554 if (!fgets(line, sizeof(line), f)) {
561 /* Let's skip the pid and comm fields. The latter is enclosed
562 * in () but does not escape any () in its value, so let's
563 * skip over it manually */
565 p = strrchr(line, ')');
587 "%*d " /* priority */
589 "%*d " /* num_threads */
590 "%*d " /* itrealvalue */
591 "%llu " /* starttime */,
598 int write_one_line_file(const char *fn, const char *line) {
599 _cleanup_fclose_ FILE *f = NULL;
609 if (fputs(line, f) < 0)
610 return errno ? -errno : -EIO;
612 if (!endswith(line, "\n"))
618 return errno ? -errno : -EIO;
623 int fchmod_umask(int fd, mode_t m) {
628 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
634 int write_one_line_file_atomic(const char *fn, const char *line) {
642 r = fopen_temporary(fn, &f, &p);
646 fchmod_umask(fileno(f), 0644);
649 if (fputs(line, f) < 0) {
654 if (!endswith(line, "\n"))
665 if (rename(p, fn) < 0)
681 int read_one_line_file(const char *fn, char **line) {
682 _cleanup_fclose_ FILE *f = NULL;
683 char t[LINE_MAX], *c;
692 if (!fgets(t, sizeof(t), f)) {
695 return errno ? -errno : -EIO;
709 int read_full_file(const char *fn, char **contents, size_t *size) {
710 _cleanup_fclose_ FILE *f = NULL;
712 _cleanup_free_ char *buf = NULL;
719 if (fstat(fileno(f), &st) < 0)
723 if (st.st_size > 4*1024*1024)
726 n = st.st_size > 0 ? st.st_size : LINE_MAX;
733 t = realloc(buf, n+1);
738 k = fread(buf + l, 1, n - l, f);
767 const char *separator, ...) {
770 char *contents = NULL, *p;
775 if ((r = read_full_file(fname, &contents, NULL)) < 0)
780 const char *key = NULL;
782 p += strspn(p, separator);
783 p += strspn(p, WHITESPACE);
788 if (!strchr(COMMENTS, *p)) {
792 va_start(ap, separator);
793 while ((key = va_arg(ap, char *))) {
797 value = va_arg(ap, char **);
800 if (strncmp(p, key, n) != 0 ||
805 n = strcspn(p, separator);
808 strchr(QUOTES, p[0]) &&
810 v = strndup(p+1, n-2);
821 /* return empty value strings as NULL */
838 p += strcspn(p, separator);
857 if (!(f = fopen(fname, "re")))
861 char l[LINE_MAX], *p, *u;
864 if (!fgets(l, sizeof(l), f)) {
877 if (strchr(COMMENTS, *p))
880 if (!(u = normalize_env_assignment(p))) {
885 t = strv_append(m, u);
911 int write_env_file(const char *fname, char **l) {
916 r = fopen_temporary(fname, &f, &p);
920 fchmod_umask(fileno(f), 0644);
936 if (rename(p, fname) < 0)
951 char *truncate_nl(char *s) {
954 s[strcspn(s, NEWLINE)] = 0;
958 int get_process_comm(pid_t pid, char **name) {
964 r = read_one_line_file("/proc/self/comm", name);
967 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
970 r = read_one_line_file(p, name);
977 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
984 assert(max_length > 0);
988 f = fopen("/proc/self/cmdline", "re");
991 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1001 r = new(char, max_length);
1009 while ((c = getc(f)) != EOF) {
1031 size_t n = MIN(left-1, 3U);
1032 memcpy(k, "...", n);
1039 /* Kernel threads have no argv[] */
1049 h = get_process_comm(pid, &t);
1053 r = strjoin("[", t, "]", NULL);
1064 int is_kernel_thread(pid_t pid) {
1074 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1083 count = fread(&c, 1, 1, f);
1087 /* Kernel threads have an empty cmdline */
1090 return eof ? 1 : -errno;
1095 int get_process_exe(pid_t pid, char **name) {
1101 r = readlink_malloc("/proc/self/exe", name);
1104 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1107 r = readlink_malloc(p, name);
1114 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1124 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1134 char line[LINE_MAX], *l;
1136 if (!fgets(line, sizeof(line), f)) {
1146 if (startswith(l, field)) {
1148 l += strspn(l, WHITESPACE);
1150 l[strcspn(l, WHITESPACE)] = 0;
1152 r = parse_uid(l, uid);
1165 int get_process_uid(pid_t pid, uid_t *uid) {
1166 return get_process_id(pid, "Uid:", uid);
1169 int get_process_gid(pid_t pid, gid_t *gid) {
1170 return get_process_id(pid, "Gid:", gid);
1173 char *strnappend(const char *s, const char *suffix, size_t b) {
1181 return strndup(suffix, b);
1190 if (b > ((size_t) -1) - a)
1193 r = new(char, a+b+1);
1198 memcpy(r+a, suffix, b);
1204 char *strappend(const char *s, const char *suffix) {
1205 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1208 int readlink_malloc(const char *p, char **r) {
1218 if (!(c = new(char, l)))
1221 if ((n = readlink(p, c, l-1)) < 0) {
1227 if ((size_t) n < l-1) {
1238 int readlink_and_make_absolute(const char *p, char **r) {
1245 if ((j = readlink_malloc(p, &target)) < 0)
1248 k = file_in_same_dir(p, target);
1258 int readlink_and_canonicalize(const char *p, char **r) {
1265 j = readlink_and_make_absolute(p, &t);
1269 s = canonicalize_file_name(t);
1276 path_kill_slashes(*r);
1281 int reset_all_signal_handlers(void) {
1284 for (sig = 1; sig < _NSIG; sig++) {
1285 struct sigaction sa;
1287 if (sig == SIGKILL || sig == SIGSTOP)
1291 sa.sa_handler = SIG_DFL;
1292 sa.sa_flags = SA_RESTART;
1294 /* On Linux the first two RT signals are reserved by
1295 * glibc, and sigaction() will return EINVAL for them. */
1296 if ((sigaction(sig, &sa, NULL) < 0))
1297 if (errno != EINVAL)
1304 char *strstrip(char *s) {
1307 /* Drops trailing whitespace. Modifies the string in
1308 * place. Returns pointer to first non-space character */
1310 s += strspn(s, WHITESPACE);
1312 for (e = strchr(s, 0); e > s; e --)
1313 if (!strchr(WHITESPACE, e[-1]))
1321 char *delete_chars(char *s, const char *bad) {
1324 /* Drops all whitespace, regardless where in the string */
1326 for (f = s, t = s; *f; f++) {
1327 if (strchr(bad, *f))
1338 bool in_charset(const char *s, const char* charset) {
1344 for (i = s; *i; i++)
1345 if (!strchr(charset, *i))
1351 char *file_in_same_dir(const char *path, const char *filename) {
1358 /* This removes the last component of path and appends
1359 * filename, unless the latter is absolute anyway or the
1362 if (path_is_absolute(filename))
1363 return strdup(filename);
1365 if (!(e = strrchr(path, '/')))
1366 return strdup(filename);
1368 k = strlen(filename);
1369 if (!(r = new(char, e-path+1+k+1)))
1372 memcpy(r, path, e-path+1);
1373 memcpy(r+(e-path)+1, filename, k+1);
1378 int rmdir_parents(const char *path, const char *stop) {
1387 /* Skip trailing slashes */
1388 while (l > 0 && path[l-1] == '/')
1394 /* Skip last component */
1395 while (l > 0 && path[l-1] != '/')
1398 /* Skip trailing slashes */
1399 while (l > 0 && path[l-1] == '/')
1405 if (!(t = strndup(path, l)))
1408 if (path_startswith(stop, t)) {
1417 if (errno != ENOENT)
1425 char hexchar(int x) {
1426 static const char table[16] = "0123456789abcdef";
1428 return table[x & 15];
1431 int unhexchar(char c) {
1433 if (c >= '0' && c <= '9')
1436 if (c >= 'a' && c <= 'f')
1437 return c - 'a' + 10;
1439 if (c >= 'A' && c <= 'F')
1440 return c - 'A' + 10;
1445 char octchar(int x) {
1446 return '0' + (x & 7);
1449 int unoctchar(char c) {
1451 if (c >= '0' && c <= '7')
1457 char decchar(int x) {
1458 return '0' + (x % 10);
1461 int undecchar(char c) {
1463 if (c >= '0' && c <= '9')
1469 char *cescape(const char *s) {
1475 /* Does C style string escaping. */
1477 r = new(char, strlen(s)*4 + 1);
1481 for (f = s, t = r; *f; f++)
1527 /* For special chars we prefer octal over
1528 * hexadecimal encoding, simply because glib's
1529 * g_strescape() does the same */
1530 if ((*f < ' ') || (*f >= 127)) {
1532 *(t++) = octchar((unsigned char) *f >> 6);
1533 *(t++) = octchar((unsigned char) *f >> 3);
1534 *(t++) = octchar((unsigned char) *f);
1545 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1552 /* Undoes C style string escaping, and optionally prefixes it. */
1554 pl = prefix ? strlen(prefix) : 0;
1556 r = new(char, pl+length+1);
1561 memcpy(r, prefix, pl);
1563 for (f = s, t = r + pl; f < s + length; f++) {
1606 /* This is an extension of the XDG syntax files */
1611 /* hexadecimal encoding */
1614 a = unhexchar(f[1]);
1615 b = unhexchar(f[2]);
1617 if (a < 0 || b < 0) {
1618 /* Invalid escape code, let's take it literal then */
1622 *(t++) = (char) ((a << 4) | b);
1637 /* octal encoding */
1640 a = unoctchar(f[0]);
1641 b = unoctchar(f[1]);
1642 c = unoctchar(f[2]);
1644 if (a < 0 || b < 0 || c < 0) {
1645 /* Invalid escape code, let's take it literal then */
1649 *(t++) = (char) ((a << 6) | (b << 3) | c);
1657 /* premature end of string.*/
1662 /* Invalid escape code, let's take it literal then */
1674 char *cunescape_length(const char *s, size_t length) {
1675 return cunescape_length_with_prefix(s, length, NULL);
1678 char *cunescape(const char *s) {
1681 return cunescape_length(s, strlen(s));
1684 char *xescape(const char *s, const char *bad) {
1688 /* Escapes all chars in bad, in addition to \ and all special
1689 * chars, in \xFF style escaping. May be reversed with
1692 r = new(char, strlen(s) * 4 + 1);
1696 for (f = s, t = r; *f; f++) {
1698 if ((*f < ' ') || (*f >= 127) ||
1699 (*f == '\\') || strchr(bad, *f)) {
1702 *(t++) = hexchar(*f >> 4);
1703 *(t++) = hexchar(*f);
1713 char *bus_path_escape(const char *s) {
1719 /* Escapes all chars that D-Bus' object path cannot deal
1720 * with. Can be reverse with bus_path_unescape() */
1722 if (!(r = new(char, strlen(s)*3+1)))
1725 for (f = s, t = r; *f; f++) {
1727 if (!(*f >= 'A' && *f <= 'Z') &&
1728 !(*f >= 'a' && *f <= 'z') &&
1729 !(*f >= '0' && *f <= '9')) {
1731 *(t++) = hexchar(*f >> 4);
1732 *(t++) = hexchar(*f);
1742 char *bus_path_unescape(const char *f) {
1747 if (!(r = strdup(f)))
1750 for (t = r; *f; f++) {
1755 if ((a = unhexchar(f[1])) < 0 ||
1756 (b = unhexchar(f[2])) < 0) {
1757 /* Invalid escape code, let's take it literal then */
1760 *(t++) = (char) ((a << 4) | b);
1772 char *ascii_strlower(char *t) {
1777 for (p = t; *p; p++)
1778 if (*p >= 'A' && *p <= 'Z')
1779 *p = *p - 'A' + 'a';
1784 static bool ignore_file_allow_backup(const char *filename) {
1788 filename[0] == '.' ||
1789 streq(filename, "lost+found") ||
1790 streq(filename, "aquota.user") ||
1791 streq(filename, "aquota.group") ||
1792 endswith(filename, ".rpmnew") ||
1793 endswith(filename, ".rpmsave") ||
1794 endswith(filename, ".rpmorig") ||
1795 endswith(filename, ".dpkg-old") ||
1796 endswith(filename, ".dpkg-new") ||
1797 endswith(filename, ".swp");
1800 bool ignore_file(const char *filename) {
1803 if (endswith(filename, "~"))
1806 return ignore_file_allow_backup(filename);
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 table[] =
2070 return nulstr_contains(table, fstype);
2074 _cleanup_close_ int fd;
2076 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2082 TIOCL_GETKMSGREDIRECT,
2086 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2089 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2092 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2098 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2099 struct termios old_termios, new_termios;
2101 char line[LINE_MAX];
2106 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2107 new_termios = old_termios;
2109 new_termios.c_lflag &= ~ICANON;
2110 new_termios.c_cc[VMIN] = 1;
2111 new_termios.c_cc[VTIME] = 0;
2113 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2116 if (t != (usec_t) -1) {
2117 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2118 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2123 k = fread(&c, 1, 1, f);
2125 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2131 *need_nl = c != '\n';
2138 if (t != (usec_t) -1)
2139 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2142 if (!fgets(line, sizeof(line), f))
2147 if (strlen(line) != 1)
2157 int ask(char *ret, const char *replies, const char *text, ...) {
2164 on_tty = isatty(STDOUT_FILENO);
2170 bool need_nl = true;
2173 fputs(ANSI_HIGHLIGHT_ON, stdout);
2180 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2184 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2187 if (r == -EBADMSG) {
2188 puts("Bad input, please try again.");
2199 if (strchr(replies, c)) {
2204 puts("Read unexpected character, please try again.");
2208 int reset_terminal_fd(int fd, bool switch_to_text) {
2209 struct termios termios;
2212 /* Set terminal to some sane defaults */
2216 /* We leave locked terminal attributes untouched, so that
2217 * Plymouth may set whatever it wants to set, and we don't
2218 * interfere with that. */
2220 /* Disable exclusive mode, just in case */
2221 ioctl(fd, TIOCNXCL);
2223 /* Switch to text mode */
2225 ioctl(fd, KDSETMODE, KD_TEXT);
2227 /* Enable console unicode mode */
2228 ioctl(fd, KDSKBMODE, K_UNICODE);
2230 if (tcgetattr(fd, &termios) < 0) {
2235 /* We only reset the stuff that matters to the software. How
2236 * hardware is set up we don't touch assuming that somebody
2237 * else will do that for us */
2239 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2240 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2241 termios.c_oflag |= ONLCR;
2242 termios.c_cflag |= CREAD;
2243 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2245 termios.c_cc[VINTR] = 03; /* ^C */
2246 termios.c_cc[VQUIT] = 034; /* ^\ */
2247 termios.c_cc[VERASE] = 0177;
2248 termios.c_cc[VKILL] = 025; /* ^X */
2249 termios.c_cc[VEOF] = 04; /* ^D */
2250 termios.c_cc[VSTART] = 021; /* ^Q */
2251 termios.c_cc[VSTOP] = 023; /* ^S */
2252 termios.c_cc[VSUSP] = 032; /* ^Z */
2253 termios.c_cc[VLNEXT] = 026; /* ^V */
2254 termios.c_cc[VWERASE] = 027; /* ^W */
2255 termios.c_cc[VREPRINT] = 022; /* ^R */
2256 termios.c_cc[VEOL] = 0;
2257 termios.c_cc[VEOL2] = 0;
2259 termios.c_cc[VTIME] = 0;
2260 termios.c_cc[VMIN] = 1;
2262 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2266 /* Just in case, flush all crap out */
2267 tcflush(fd, TCIOFLUSH);
2272 int reset_terminal(const char *name) {
2275 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2279 r = reset_terminal_fd(fd, true);
2280 close_nointr_nofail(fd);
2285 int open_terminal(const char *name, int mode) {
2290 * If a TTY is in the process of being closed opening it might
2291 * cause EIO. This is horribly awful, but unlikely to be
2292 * changed in the kernel. Hence we work around this problem by
2293 * retrying a couple of times.
2295 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2299 fd = open(name, mode);
2306 /* Max 1s in total */
2310 usleep(50 * USEC_PER_MSEC);
2319 close_nointr_nofail(fd);
2324 close_nointr_nofail(fd);
2331 int flush_fd(int fd) {
2332 struct pollfd pollfd;
2336 pollfd.events = POLLIN;
2343 if ((r = poll(&pollfd, 1, 0)) < 0) {
2354 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2359 if (errno == EAGAIN)
2370 int acquire_terminal(
2374 bool ignore_tiocstty_eperm,
2377 int fd = -1, notify = -1, r = 0, wd = -1;
2379 struct sigaction sa_old, sa_new;
2383 /* We use inotify to be notified when the tty is closed. We
2384 * create the watch before checking if we can actually acquire
2385 * it, so that we don't lose any event.
2387 * Note: strictly speaking this actually watches for the
2388 * device being closed, it does *not* really watch whether a
2389 * tty loses its controlling process. However, unless some
2390 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2391 * its tty otherwise this will not become a problem. As long
2392 * as the administrator makes sure not configure any service
2393 * on the same tty as an untrusted user this should not be a
2394 * problem. (Which he probably should not do anyway.) */
2396 if (timeout != (usec_t) -1)
2397 ts = now(CLOCK_MONOTONIC);
2399 if (!fail && !force) {
2400 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2406 wd = inotify_add_watch(notify, name, IN_CLOSE);
2415 r = flush_fd(notify);
2420 /* We pass here O_NOCTTY only so that we can check the return
2421 * value TIOCSCTTY and have a reliable way to figure out if we
2422 * successfully became the controlling process of the tty */
2423 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2427 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2428 * if we already own the tty. */
2430 sa_new.sa_handler = SIG_IGN;
2431 sa_new.sa_flags = SA_RESTART;
2432 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2434 /* First, try to get the tty */
2435 if (ioctl(fd, TIOCSCTTY, force) < 0)
2438 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2440 /* Sometimes it makes sense to ignore TIOCSCTTY
2441 * returning EPERM, i.e. when very likely we already
2442 * are have this controlling terminal. */
2443 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2446 if (r < 0 && (force || fail || r != -EPERM)) {
2455 assert(notify >= 0);
2458 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2460 struct inotify_event *e;
2462 if (timeout != (usec_t) -1) {
2465 n = now(CLOCK_MONOTONIC);
2466 if (ts + timeout < n) {
2471 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2481 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2484 if (errno == EINTR || errno == EAGAIN)
2491 e = (struct inotify_event*) inotify_buffer;
2496 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2501 step = sizeof(struct inotify_event) + e->len;
2502 assert(step <= (size_t) l);
2504 e = (struct inotify_event*) ((uint8_t*) e + step);
2511 /* We close the tty fd here since if the old session
2512 * ended our handle will be dead. It's important that
2513 * we do this after sleeping, so that we don't enter
2514 * an endless loop. */
2515 close_nointr_nofail(fd);
2519 close_nointr_nofail(notify);
2521 r = reset_terminal_fd(fd, true);
2523 log_warning("Failed to reset terminal: %s", strerror(-r));
2529 close_nointr_nofail(fd);
2532 close_nointr_nofail(notify);
2537 int release_terminal(void) {
2539 struct sigaction sa_old, sa_new;
2541 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2544 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2545 * by our own TIOCNOTTY */
2548 sa_new.sa_handler = SIG_IGN;
2549 sa_new.sa_flags = SA_RESTART;
2550 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2552 if (ioctl(fd, TIOCNOTTY) < 0)
2555 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2557 close_nointr_nofail(fd);
2561 int sigaction_many(const struct sigaction *sa, ...) {
2566 while ((sig = va_arg(ap, int)) > 0)
2567 if (sigaction(sig, sa, NULL) < 0)
2574 int ignore_signals(int sig, ...) {
2575 struct sigaction sa;
2580 sa.sa_handler = SIG_IGN;
2581 sa.sa_flags = SA_RESTART;
2583 if (sigaction(sig, &sa, NULL) < 0)
2587 while ((sig = va_arg(ap, int)) > 0)
2588 if (sigaction(sig, &sa, NULL) < 0)
2595 int default_signals(int sig, ...) {
2596 struct sigaction sa;
2601 sa.sa_handler = SIG_DFL;
2602 sa.sa_flags = SA_RESTART;
2604 if (sigaction(sig, &sa, NULL) < 0)
2608 while ((sig = va_arg(ap, int)) > 0)
2609 if (sigaction(sig, &sa, NULL) < 0)
2616 int close_pipe(int p[]) {
2622 a = close_nointr(p[0]);
2627 b = close_nointr(p[1]);
2631 return a < 0 ? a : b;
2634 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2643 while (nbytes > 0) {
2646 if ((k = read(fd, p, nbytes)) <= 0) {
2648 if (k < 0 && errno == EINTR)
2651 if (k < 0 && errno == EAGAIN && do_poll) {
2652 struct pollfd pollfd;
2656 pollfd.events = POLLIN;
2658 if (poll(&pollfd, 1, -1) < 0) {
2662 return n > 0 ? n : -errno;
2665 if (pollfd.revents != POLLIN)
2666 return n > 0 ? n : -EIO;
2671 return n > 0 ? n : (k < 0 ? -errno : 0);
2682 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2691 while (nbytes > 0) {
2694 k = write(fd, p, nbytes);
2697 if (k < 0 && errno == EINTR)
2700 if (k < 0 && errno == EAGAIN && do_poll) {
2701 struct pollfd pollfd;
2705 pollfd.events = POLLOUT;
2707 if (poll(&pollfd, 1, -1) < 0) {
2711 return n > 0 ? n : -errno;
2714 if (pollfd.revents != POLLOUT)
2715 return n > 0 ? n : -EIO;
2720 return n > 0 ? n : (k < 0 ? -errno : 0);
2731 int parse_usec(const char *t, usec_t *usec) {
2732 static const struct {
2736 { "seconds", USEC_PER_SEC },
2737 { "second", USEC_PER_SEC },
2738 { "sec", USEC_PER_SEC },
2739 { "s", USEC_PER_SEC },
2740 { "minutes", USEC_PER_MINUTE },
2741 { "minute", USEC_PER_MINUTE },
2742 { "min", USEC_PER_MINUTE },
2743 { "months", USEC_PER_MONTH },
2744 { "month", USEC_PER_MONTH },
2745 { "msec", USEC_PER_MSEC },
2746 { "ms", USEC_PER_MSEC },
2747 { "m", USEC_PER_MINUTE },
2748 { "hours", USEC_PER_HOUR },
2749 { "hour", USEC_PER_HOUR },
2750 { "hr", USEC_PER_HOUR },
2751 { "h", USEC_PER_HOUR },
2752 { "days", USEC_PER_DAY },
2753 { "day", USEC_PER_DAY },
2754 { "d", USEC_PER_DAY },
2755 { "weeks", USEC_PER_WEEK },
2756 { "week", USEC_PER_WEEK },
2757 { "w", USEC_PER_WEEK },
2758 { "years", USEC_PER_YEAR },
2759 { "year", USEC_PER_YEAR },
2760 { "y", USEC_PER_YEAR },
2763 { "", USEC_PER_SEC }, /* default is sec */
2779 l = strtoll(p, &e, 10);
2790 e += strspn(e, WHITESPACE);
2792 for (i = 0; i < ELEMENTSOF(table); i++)
2793 if (startswith(e, table[i].suffix)) {
2794 r += (usec_t) l * table[i].usec;
2795 p = e + strlen(table[i].suffix);
2799 if (i >= ELEMENTSOF(table))
2809 int parse_nsec(const char *t, nsec_t *nsec) {
2810 static const struct {
2814 { "seconds", NSEC_PER_SEC },
2815 { "second", NSEC_PER_SEC },
2816 { "sec", NSEC_PER_SEC },
2817 { "s", NSEC_PER_SEC },
2818 { "minutes", NSEC_PER_MINUTE },
2819 { "minute", NSEC_PER_MINUTE },
2820 { "min", NSEC_PER_MINUTE },
2821 { "months", NSEC_PER_MONTH },
2822 { "month", NSEC_PER_MONTH },
2823 { "msec", NSEC_PER_MSEC },
2824 { "ms", NSEC_PER_MSEC },
2825 { "m", NSEC_PER_MINUTE },
2826 { "hours", NSEC_PER_HOUR },
2827 { "hour", NSEC_PER_HOUR },
2828 { "hr", NSEC_PER_HOUR },
2829 { "h", NSEC_PER_HOUR },
2830 { "days", NSEC_PER_DAY },
2831 { "day", NSEC_PER_DAY },
2832 { "d", NSEC_PER_DAY },
2833 { "weeks", NSEC_PER_WEEK },
2834 { "week", NSEC_PER_WEEK },
2835 { "w", NSEC_PER_WEEK },
2836 { "years", NSEC_PER_YEAR },
2837 { "year", NSEC_PER_YEAR },
2838 { "y", NSEC_PER_YEAR },
2839 { "usec", NSEC_PER_USEC },
2840 { "us", NSEC_PER_USEC },
2843 { "", 1ULL }, /* default is nsec */
2859 l = strtoll(p, &e, 10);
2870 e += strspn(e, WHITESPACE);
2872 for (i = 0; i < ELEMENTSOF(table); i++)
2873 if (startswith(e, table[i].suffix)) {
2874 r += (nsec_t) l * table[i].nsec;
2875 p = e + strlen(table[i].suffix);
2879 if (i >= ELEMENTSOF(table))
2889 int parse_bytes(const char *t, off_t *bytes) {
2890 static const struct {
2896 { "M", 1024ULL*1024ULL },
2897 { "G", 1024ULL*1024ULL*1024ULL },
2898 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2899 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2900 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2917 l = strtoll(p, &e, 10);
2928 e += strspn(e, WHITESPACE);
2930 for (i = 0; i < ELEMENTSOF(table); i++)
2931 if (startswith(e, table[i].suffix)) {
2932 r += (off_t) l * table[i].factor;
2933 p = e + strlen(table[i].suffix);
2937 if (i >= ELEMENTSOF(table))
2947 int make_stdio(int fd) {
2952 r = dup3(fd, STDIN_FILENO, 0);
2953 s = dup3(fd, STDOUT_FILENO, 0);
2954 t = dup3(fd, STDERR_FILENO, 0);
2957 close_nointr_nofail(fd);
2959 if (r < 0 || s < 0 || t < 0)
2962 /* We rely here that the new fd has O_CLOEXEC not set */
2967 int make_null_stdio(void) {
2970 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2974 return make_stdio(null_fd);
2977 bool is_device_path(const char *path) {
2979 /* Returns true on paths that refer to a device, either in
2980 * sysfs or in /dev */
2983 path_startswith(path, "/dev/") ||
2984 path_startswith(path, "/sys/");
2987 int dir_is_empty(const char *path) {
2988 _cleanup_closedir_ DIR *d;
2997 union dirent_storage buf;
2999 r = readdir_r(d, &buf.de, &de);
3006 if (!ignore_file(de->d_name))
3011 unsigned long long random_ull(void) {
3012 _cleanup_close_ int fd;
3016 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3020 r = loop_read(fd, &ull, sizeof(ull), true);
3021 if (r != sizeof(ull))
3027 return random() * RAND_MAX + random();
3030 void rename_process(const char name[8]) {
3033 /* This is a like a poor man's setproctitle(). It changes the
3034 * comm field, argv[0], and also the glibc's internally used
3035 * name of the process. For the first one a limit of 16 chars
3036 * applies, to the second one usually one of 10 (i.e. length
3037 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3038 * "systemd"). If you pass a longer string it will be
3041 prctl(PR_SET_NAME, name);
3043 if (program_invocation_name)
3044 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3046 if (saved_argc > 0) {
3050 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3052 for (i = 1; i < saved_argc; i++) {
3056 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3061 void sigset_add_many(sigset_t *ss, ...) {
3068 while ((sig = va_arg(ap, int)) > 0)
3069 assert_se(sigaddset(ss, sig) == 0);
3073 char* gethostname_malloc(void) {
3076 assert_se(uname(&u) >= 0);
3078 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3079 return strdup(u.nodename);
3081 return strdup(u.sysname);
3084 bool hostname_is_set(void) {
3087 assert_se(uname(&u) >= 0);
3089 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3092 static char *lookup_uid(uid_t uid) {
3095 _cleanup_free_ char *buf = NULL;
3096 struct passwd pwbuf, *pw = NULL;
3098 /* Shortcut things to avoid NSS lookups */
3100 return strdup("root");
3102 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3106 buf = malloc(bufsize);
3110 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3111 return strdup(pw->pw_name);
3113 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3119 char* getlogname_malloc(void) {
3123 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3128 return lookup_uid(uid);
3131 char *getusername_malloc(void) {
3138 return lookup_uid(getuid());
3141 int getttyname_malloc(int fd, char **r) {
3142 char path[PATH_MAX], *c;
3147 k = ttyname_r(fd, path, sizeof(path));
3153 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3161 int getttyname_harder(int fd, char **r) {
3165 k = getttyname_malloc(fd, &s);
3169 if (streq(s, "tty")) {
3171 return get_ctty(0, NULL, r);
3178 int get_ctty_devnr(pid_t pid, dev_t *d) {
3180 char line[LINE_MAX], *p, *fn;
3181 unsigned long ttynr;
3184 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3187 f = fopen(fn, "re");
3192 if (!fgets(line, sizeof(line), f)) {
3193 k = feof(f) ? -EIO : -errno;
3200 p = strrchr(line, ')');
3210 "%*d " /* session */
3219 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3221 char fn[PATH_MAX], *s, *b, *p;
3226 k = get_ctty_devnr(pid, &devnr);
3230 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3233 if ((k = readlink_malloc(fn, &s)) < 0) {
3238 /* This is an ugly hack */
3239 if (major(devnr) == 136) {
3240 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3250 /* Probably something like the ptys which have no
3251 * symlink in /dev/char. Let's return something
3252 * vaguely useful. */
3254 if (!(b = strdup(fn + 5)))
3264 if (startswith(s, "/dev/"))
3266 else if (startswith(s, "../"))
3284 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3290 /* This returns the first error we run into, but nevertheless
3291 * tries to go on. This closes the passed fd. */
3295 close_nointr_nofail(fd);
3297 return errno == ENOENT ? 0 : -errno;
3302 union dirent_storage buf;
3303 bool is_dir, keep_around;
3307 r = readdir_r(d, &buf.de, &de);
3308 if (r != 0 && ret == 0) {
3316 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3319 if (de->d_type == DT_UNKNOWN ||
3321 (de->d_type == DT_DIR && root_dev)) {
3322 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3323 if (ret == 0 && errno != ENOENT)
3328 is_dir = S_ISDIR(st.st_mode);
3331 (st.st_uid == 0 || st.st_uid == getuid()) &&
3332 (st.st_mode & S_ISVTX);
3334 is_dir = de->d_type == DT_DIR;
3335 keep_around = false;
3341 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3342 if (root_dev && st.st_dev != root_dev->st_dev)
3345 subdir_fd = openat(fd, de->d_name,
3346 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3347 if (subdir_fd < 0) {
3348 if (ret == 0 && errno != ENOENT)
3353 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3354 if (r < 0 && ret == 0)
3358 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3359 if (ret == 0 && errno != ENOENT)
3363 } else if (!only_dirs && !keep_around) {
3365 if (unlinkat(fd, de->d_name, 0) < 0) {
3366 if (ret == 0 && errno != ENOENT)
3377 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3382 if (fstatfs(fd, &s) < 0) {
3383 close_nointr_nofail(fd);
3387 /* We refuse to clean disk file systems with this call. This
3388 * is extra paranoia just to be sure we never ever remove
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.");
3394 close_nointr_nofail(fd);
3398 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3401 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3407 /* We refuse to clean the root file system with this
3408 * call. This is extra paranoia to never cause a really
3409 * seriously broken system. */
3410 if (path_equal(path, "/")) {
3411 log_error("Attempted to remove entire root file system, and we can't allow that.");
3415 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3418 if (errno != ENOTDIR)
3422 if (statfs(path, &s) < 0)
3425 if (s.f_type != TMPFS_MAGIC &&
3426 s.f_type != RAMFS_MAGIC) {
3427 log_error("Attempted to remove disk file system, and we can't allow that.");
3432 if (delete_root && !only_dirs)
3433 if (unlink(path) < 0 && errno != ENOENT)
3440 if (fstatfs(fd, &s) < 0) {
3441 close_nointr_nofail(fd);
3445 if (s.f_type != TMPFS_MAGIC &&
3446 s.f_type != RAMFS_MAGIC) {
3447 log_error("Attempted to remove disk file system, and we can't allow that.");
3448 close_nointr_nofail(fd);
3453 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3456 if (honour_sticky && file_is_priv_sticky(path) > 0)
3459 if (rmdir(path) < 0 && errno != ENOENT) {
3468 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3469 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3472 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3473 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3476 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3479 /* Under the assumption that we are running privileged we
3480 * first change the access mode and only then hand out
3481 * ownership to avoid a window where access is too open. */
3483 if (mode != (mode_t) -1)
3484 if (chmod(path, mode) < 0)
3487 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3488 if (chown(path, uid, gid) < 0)
3494 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3497 /* Under the assumption that we are running privileged we
3498 * first change the access mode and only then hand out
3499 * ownership to avoid a window where access is too open. */
3501 if (fchmod(fd, mode) < 0)
3504 if (fchown(fd, uid, gid) < 0)
3510 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3514 /* Allocates the cpuset in the right size */
3517 if (!(r = CPU_ALLOC(n)))
3520 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3521 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3531 if (errno != EINVAL)
3538 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3539 static const char status_indent[] = " "; /* "[" STATUS "] " */
3540 _cleanup_free_ char *s = NULL;
3541 _cleanup_close_ int fd = -1;
3542 struct iovec iovec[5];
3547 /* This is independent of logging, as status messages are
3548 * optional and go exclusively to the console. */
3550 if (vasprintf(&s, format, ap) < 0)
3553 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3566 sl = status ? sizeof(status_indent)-1 : 0;
3572 e = ellipsize(s, emax, 75);
3582 if (!isempty(status)) {
3583 IOVEC_SET_STRING(iovec[n++], "[");
3584 IOVEC_SET_STRING(iovec[n++], status);
3585 IOVEC_SET_STRING(iovec[n++], "] ");
3587 IOVEC_SET_STRING(iovec[n++], status_indent);
3590 IOVEC_SET_STRING(iovec[n++], s);
3591 IOVEC_SET_STRING(iovec[n++], "\n");
3593 if (writev(fd, iovec, n) < 0)
3599 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3605 va_start(ap, format);
3606 r = status_vprintf(status, ellipse, format, ap);
3612 int status_welcome(void) {
3614 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3616 r = parse_env_file("/etc/os-release", NEWLINE,
3617 "PRETTY_NAME", &pretty_name,
3618 "ANSI_COLOR", &ansi_color,
3620 if (r < 0 && r != -ENOENT)
3621 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3623 return status_printf(NULL, false,
3624 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3625 isempty(ansi_color) ? "1" : ansi_color,
3626 isempty(pretty_name) ? "Linux" : pretty_name);
3629 char *replace_env(const char *format, char **env) {
3636 const char *e, *word = format;
3641 for (e = format; *e; e ++) {
3652 if (!(k = strnappend(r, word, e-word-1)))
3661 } else if (*e == '$') {
3662 if (!(k = strnappend(r, word, e-word)))
3678 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3681 if (!(k = strappend(r, t)))
3694 if (!(k = strnappend(r, word, e-word)))
3705 char **replace_env_argv(char **argv, char **env) {
3707 unsigned k = 0, l = 0;
3709 l = strv_length(argv);
3711 if (!(r = new(char*, l+1)))
3714 STRV_FOREACH(i, argv) {
3716 /* If $FOO appears as single word, replace it by the split up variable */
3717 if ((*i)[0] == '$' && (*i)[1] != '{') {
3722 if ((e = strv_env_get(env, *i+1))) {
3724 if (!(m = strv_split_quoted(e))) {
3735 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3744 memcpy(r + k, m, q * sizeof(char*));
3752 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3753 if (!(r[k++] = replace_env(*i, env))) {
3763 int fd_columns(int fd) {
3767 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3776 static unsigned columns_cached(bool cached) {
3777 static __thread int env_columns = -1;
3780 if (_likely_(parsed_columns > 0 && cached))
3781 return parsed_columns;
3783 if (_unlikely_(env_columns == -1)) {
3784 e = getenv("COLUMNS");
3786 env_columns = atoi(e);
3791 if (env_columns > 0) {
3792 parsed_columns = env_columns;
3793 return parsed_columns;
3796 if (parsed_columns <= 0 || !cached)
3797 parsed_columns = fd_columns(STDOUT_FILENO);
3799 if (parsed_columns <= 0)
3800 parsed_columns = 80;
3802 return parsed_columns;
3805 unsigned columns(void) {
3806 return columns_cached(true);
3809 unsigned columns_uncached(void) {
3810 return columns_cached(false);
3813 /* intended to be used as a SIGWINCH sighandler */
3814 void columns_cache_reset(int signum) {
3818 int fd_lines(int fd) {
3822 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3831 unsigned lines(void) {
3832 static __thread int parsed_lines = 0;
3835 if (_likely_(parsed_lines > 0))
3836 return parsed_lines;
3838 e = getenv("LINES");
3840 parsed_lines = atoi(e);
3842 if (parsed_lines <= 0)
3843 parsed_lines = fd_lines(STDOUT_FILENO);
3845 if (parsed_lines <= 0)
3848 return parsed_lines;
3851 int running_in_chroot(void) {
3857 /* Only works as root */
3859 if (stat("/proc/1/root", &a) < 0)
3862 if (stat("/", &b) < 0)
3866 a.st_dev != b.st_dev ||
3867 a.st_ino != b.st_ino;
3870 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3875 assert(percent <= 100);
3876 assert(new_length >= 3);
3878 if (old_length <= 3 || old_length <= new_length)
3879 return strndup(s, old_length);
3881 r = new0(char, new_length+1);
3885 x = (new_length * percent) / 100;
3887 if (x > new_length - 3)
3895 s + old_length - (new_length - x - 3),
3896 new_length - x - 3);
3901 char *ellipsize(const char *s, size_t length, unsigned percent) {
3902 return ellipsize_mem(s, strlen(s), length, percent);
3905 int touch(const char *path) {
3910 /* This just opens the file for writing, ensuring it
3911 * exists. It doesn't call utimensat() the way /usr/bin/touch
3914 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3918 close_nointr_nofail(fd);
3922 char *unquote(const char *s, const char* quotes) {
3926 /* This is rather stupid, simply removes the heading and
3927 * trailing quotes if there is one. Doesn't care about
3928 * escaping or anything. We should make this smarter one
3935 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3936 return strndup(s+1, l-2);
3941 char *normalize_env_assignment(const char *s) {
3942 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3945 eq = strchr(s, '=');
3957 memmove(r, t, strlen(t) + 1);
3961 name = strndup(s, eq - s);
3969 value = unquote(strstrip(p), QUOTES);
3973 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3979 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3990 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4002 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4009 r = wait_for_terminate(pid, &status);
4011 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4015 if (status.si_code == CLD_EXITED) {
4016 if (status.si_status != 0) {
4017 log_warning("%s failed with error code %i.", name, status.si_status);
4018 return status.si_status;
4021 log_debug("%s succeeded.", name);
4024 } else if (status.si_code == CLD_KILLED ||
4025 status.si_code == CLD_DUMPED) {
4027 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4031 log_warning("%s failed due to unknown reason.", name);
4035 _noreturn_ void freeze(void) {
4037 /* Make sure nobody waits for us on a socket anymore */
4038 close_all_fds(NULL, 0);
4046 bool null_or_empty(struct stat *st) {
4049 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4052 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4058 int null_or_empty_path(const char *fn) {
4063 if (stat(fn, &st) < 0)
4066 return null_or_empty(&st);
4069 DIR *xopendirat(int fd, const char *name, int flags) {
4073 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4079 close_nointr_nofail(nfd);
4086 int signal_from_string_try_harder(const char *s) {
4090 signo = signal_from_string(s);
4092 if (startswith(s, "SIG"))
4093 return signal_from_string(s+3);
4098 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4104 if (!dual_timestamp_is_set(t))
4107 fprintf(f, "%s=%llu %llu\n",
4109 (unsigned long long) t->realtime,
4110 (unsigned long long) t->monotonic);
4113 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4114 unsigned long long a, b;
4119 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4120 log_debug("Failed to parse finish timestamp value %s", value);
4127 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4131 /* FIXME: to follow udev's logic 100% we need to leave valid
4132 * UTF8 chars unescaped */
4134 u = unquote(tagvalue, "\"\'");
4138 t = xescape(u, "/ ");
4144 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4153 char *fstab_node_to_udev_node(const char *p) {
4156 if (startswith(p, "LABEL="))
4157 return tag_to_udev_node(p+6, "label");
4159 if (startswith(p, "UUID="))
4160 return tag_to_udev_node(p+5, "uuid");
4162 if (startswith(p, "PARTUUID="))
4163 return tag_to_udev_node(p+9, "partuuid");
4165 if (startswith(p, "PARTLABEL="))
4166 return tag_to_udev_node(p+10, "partlabel");
4171 bool tty_is_vc(const char *tty) {
4174 if (startswith(tty, "/dev/"))
4177 return vtnr_from_tty(tty) >= 0;
4180 bool tty_is_console(const char *tty) {
4183 if (startswith(tty, "/dev/"))
4186 return streq(tty, "console");
4189 int vtnr_from_tty(const char *tty) {
4194 if (startswith(tty, "/dev/"))
4197 if (!startswith(tty, "tty") )
4200 if (tty[3] < '0' || tty[3] > '9')
4203 r = safe_atoi(tty+3, &i);
4207 if (i < 0 || i > 63)
4213 bool tty_is_vc_resolve(const char *tty) {
4214 char *active = NULL;
4219 if (startswith(tty, "/dev/"))
4222 /* Resolve where /dev/console is pointing to, if /sys is
4223 * actually ours (i.e. not read-only-mounted which is a sign
4224 * for container setups) */
4225 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4226 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4227 /* If multiple log outputs are configured the
4228 * last one is what /dev/console points to */
4229 tty = strrchr(active, ' ');
4242 const char *default_term_for_tty(const char *tty) {
4245 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4248 bool dirent_is_file(const struct dirent *de) {
4251 if (ignore_file(de->d_name))
4254 if (de->d_type != DT_REG &&
4255 de->d_type != DT_LNK &&
4256 de->d_type != DT_UNKNOWN)
4262 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4265 if (de->d_type != DT_REG &&
4266 de->d_type != DT_LNK &&
4267 de->d_type != DT_UNKNOWN)
4270 if (ignore_file_allow_backup(de->d_name))
4273 return endswith(de->d_name, suffix);
4276 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4279 Hashmap *pids = NULL;
4283 /* Executes all binaries in a directory in parallel and waits
4284 * until all they all finished. */
4287 if (!(_d = opendir(directory))) {
4289 if (errno == ENOENT)
4292 log_error("Failed to enumerate directory %s: %m", directory);
4299 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4300 log_error("Failed to allocate set.");
4304 while ((de = readdir(d))) {
4309 if (!dirent_is_file(de))
4312 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4317 if ((pid = fork()) < 0) {
4318 log_error("Failed to fork: %m");
4336 log_error("Failed to execute %s: %m", path);
4337 _exit(EXIT_FAILURE);
4340 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4342 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4343 log_error("Failed to add PID to set: %s", strerror(-k));
4348 while (!hashmap_isempty(pids)) {
4349 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4354 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4359 log_error("waitid() failed: %m");
4363 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4364 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4365 if (si.si_code == CLD_EXITED)
4366 log_error("%s exited with exit status %i.", path, si.si_status);
4368 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4370 log_debug("%s exited successfully.", path);
4381 hashmap_free_free(pids);
4384 int kill_and_sigcont(pid_t pid, int sig) {
4387 r = kill(pid, sig) < 0 ? -errno : 0;
4395 bool nulstr_contains(const char*nulstr, const char *needle) {
4401 NULSTR_FOREACH(i, nulstr)
4402 if (streq(i, needle))
4408 bool plymouth_running(void) {
4409 return access("/run/plymouth/pid", F_OK) >= 0;
4412 char* strshorten(char *s, size_t l) {
4421 static bool hostname_valid_char(char c) {
4423 (c >= 'a' && c <= 'z') ||
4424 (c >= 'A' && c <= 'Z') ||
4425 (c >= '0' && c <= '9') ||
4431 bool hostname_is_valid(const char *s) {
4437 for (p = s; *p; p++)
4438 if (!hostname_valid_char(*p))
4441 if (p-s > HOST_NAME_MAX)
4447 char* hostname_cleanup(char *s) {
4450 for (p = s, d = s; *p; p++)
4451 if ((*p >= 'a' && *p <= 'z') ||
4452 (*p >= 'A' && *p <= 'Z') ||
4453 (*p >= '0' && *p <= '9') ||
4461 strshorten(s, HOST_NAME_MAX);
4465 int pipe_eof(int fd) {
4466 struct pollfd pollfd;
4471 pollfd.events = POLLIN|POLLHUP;
4473 r = poll(&pollfd, 1, 0);
4480 return pollfd.revents & POLLHUP;
4483 int fd_wait_for_event(int fd, int event, usec_t t) {
4484 struct pollfd pollfd;
4489 pollfd.events = event;
4491 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4498 return pollfd.revents;
4501 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4512 t = new(char, strlen(path) + 1 + 6 + 1);
4516 fn = path_get_file_name(path);
4520 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4522 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4528 f = fdopen(fd, "we");
4541 int terminal_vhangup_fd(int fd) {
4544 if (ioctl(fd, TIOCVHANGUP) < 0)
4550 int terminal_vhangup(const char *name) {
4553 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4557 r = terminal_vhangup_fd(fd);
4558 close_nointr_nofail(fd);
4563 int vt_disallocate(const char *name) {
4567 /* Deallocate the VT if possible. If not possible
4568 * (i.e. because it is the active one), at least clear it
4569 * entirely (including the scrollback buffer) */
4571 if (!startswith(name, "/dev/"))
4574 if (!tty_is_vc(name)) {
4575 /* So this is not a VT. I guess we cannot deallocate
4576 * it then. But let's at least clear the screen */
4578 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4583 "\033[r" /* clear scrolling region */
4584 "\033[H" /* move home */
4585 "\033[2J", /* clear screen */
4587 close_nointr_nofail(fd);
4592 if (!startswith(name, "/dev/tty"))
4595 r = safe_atou(name+8, &u);
4602 /* Try to deallocate */
4603 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4607 r = ioctl(fd, VT_DISALLOCATE, u);
4608 close_nointr_nofail(fd);
4616 /* Couldn't deallocate, so let's clear it fully with
4618 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4623 "\033[r" /* clear scrolling region */
4624 "\033[H" /* move home */
4625 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4627 close_nointr_nofail(fd);
4632 int copy_file(const char *from, const char *to) {
4638 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4642 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4644 close_nointr_nofail(fdf);
4652 n = read(fdf, buf, sizeof(buf));
4656 close_nointr_nofail(fdf);
4667 k = loop_write(fdt, buf, n, false);
4669 r = k < 0 ? k : (errno ? -errno : -EIO);
4671 close_nointr_nofail(fdf);
4679 close_nointr_nofail(fdf);
4680 r = close_nointr(fdt);
4690 int symlink_atomic(const char *from, const char *to) {
4692 _cleanup_free_ char *t;
4695 unsigned long long ull;
4702 t = new(char, strlen(to) + 1 + 16 + 1);
4706 fn = path_get_file_name(to);
4710 x = stpcpy(t+k+1, fn);
4713 for (i = 0; i < 16; i++) {
4714 *(x++) = hexchar(ull & 0xF);
4720 if (symlink(from, t) < 0)
4723 if (rename(t, to) < 0) {
4732 bool display_is_local(const char *display) {
4736 display[0] == ':' &&
4737 display[1] >= '0' &&
4741 int socket_from_display(const char *display, char **path) {
4748 if (!display_is_local(display))
4751 k = strspn(display+1, "0123456789");
4753 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4757 c = stpcpy(f, "/tmp/.X11-unix/X");
4758 memcpy(c, display+1, k);
4767 const char **username,
4768 uid_t *uid, gid_t *gid,
4770 const char **shell) {
4778 /* We enforce some special rules for uid=0: in order to avoid
4779 * NSS lookups for root we hardcode its data. */
4781 if (streq(*username, "root") || streq(*username, "0")) {
4799 if (parse_uid(*username, &u) >= 0) {
4803 /* If there are multiple users with the same id, make
4804 * sure to leave $USER to the configured value instead
4805 * of the first occurrence in the database. However if
4806 * the uid was configured by a numeric uid, then let's
4807 * pick the real username from /etc/passwd. */
4809 *username = p->pw_name;
4812 p = getpwnam(*username);
4816 return errno != 0 ? -errno : -ESRCH;
4828 *shell = p->pw_shell;
4833 int get_group_creds(const char **groupname, gid_t *gid) {
4839 /* We enforce some special rules for gid=0: in order to avoid
4840 * NSS lookups for root we hardcode its data. */
4842 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4843 *groupname = "root";
4851 if (parse_gid(*groupname, &id) >= 0) {
4856 *groupname = g->gr_name;
4859 g = getgrnam(*groupname);
4863 return errno != 0 ? -errno : -ESRCH;
4871 int in_group(const char *name) {
4873 int ngroups_max, r, i;
4875 r = get_group_creds(&name, &gid);
4879 if (getgid() == gid)
4882 if (getegid() == gid)
4885 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4886 assert(ngroups_max > 0);
4888 gids = alloca(sizeof(gid_t) * ngroups_max);
4890 r = getgroups(ngroups_max, gids);
4894 for (i = 0; i < r; i++)
4901 int glob_exists(const char *path) {
4909 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4911 if (k == GLOB_NOMATCH)
4913 else if (k == GLOB_NOSPACE)
4916 r = !strv_isempty(g.gl_pathv);
4918 r = errno ? -errno : -EIO;
4925 int dirent_ensure_type(DIR *d, struct dirent *de) {
4931 if (de->d_type != DT_UNKNOWN)
4934 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4938 S_ISREG(st.st_mode) ? DT_REG :
4939 S_ISDIR(st.st_mode) ? DT_DIR :
4940 S_ISLNK(st.st_mode) ? DT_LNK :
4941 S_ISFIFO(st.st_mode) ? DT_FIFO :
4942 S_ISSOCK(st.st_mode) ? DT_SOCK :
4943 S_ISCHR(st.st_mode) ? DT_CHR :
4944 S_ISBLK(st.st_mode) ? DT_BLK :
4950 int in_search_path(const char *path, char **search) {
4954 r = path_get_parent(path, &parent);
4960 STRV_FOREACH(i, search) {
4961 if (path_equal(parent, *i)) {
4972 int get_files_in_directory(const char *path, char ***list) {
4980 /* Returns all files in a directory in *list, and the number
4981 * of files as return value. If list is NULL returns only the
4990 union dirent_storage buf;
4993 k = readdir_r(d, &buf.de, &de);
5002 dirent_ensure_type(d, de);
5004 if (!dirent_is_file(de))
5008 if ((unsigned) r >= n) {
5012 t = realloc(l, sizeof(char*) * n);
5021 assert((unsigned) r < n);
5023 l[r] = strdup(de->d_name);
5047 char *strjoin(const char *x, ...) {
5061 t = va_arg(ap, const char *);
5066 if (n > ((size_t) -1) - l) {
5090 t = va_arg(ap, const char *);
5104 bool is_main_thread(void) {
5105 static __thread int cached = 0;
5107 if (_unlikely_(cached == 0))
5108 cached = getpid() == gettid() ? 1 : -1;
5113 int block_get_whole_disk(dev_t d, dev_t *ret) {
5120 /* If it has a queue this is good enough for us */
5121 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5124 r = access(p, F_OK);
5132 /* If it is a partition find the originating device */
5133 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5136 r = access(p, F_OK);
5142 /* Get parent dev_t */
5143 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5146 r = read_one_line_file(p, &s);
5152 r = sscanf(s, "%u:%u", &m, &n);
5158 /* Only return this if it is really good enough for us. */
5159 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5162 r = access(p, F_OK);
5166 *ret = makedev(m, n);
5173 int file_is_priv_sticky(const char *p) {
5178 if (lstat(p, &st) < 0)
5182 (st.st_uid == 0 || st.st_uid == getuid()) &&
5183 (st.st_mode & S_ISVTX);
5186 static const char *const ioprio_class_table[] = {
5187 [IOPRIO_CLASS_NONE] = "none",
5188 [IOPRIO_CLASS_RT] = "realtime",
5189 [IOPRIO_CLASS_BE] = "best-effort",
5190 [IOPRIO_CLASS_IDLE] = "idle"
5193 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5195 static const char *const sigchld_code_table[] = {
5196 [CLD_EXITED] = "exited",
5197 [CLD_KILLED] = "killed",
5198 [CLD_DUMPED] = "dumped",
5199 [CLD_TRAPPED] = "trapped",
5200 [CLD_STOPPED] = "stopped",
5201 [CLD_CONTINUED] = "continued",
5204 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5206 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5207 [LOG_FAC(LOG_KERN)] = "kern",
5208 [LOG_FAC(LOG_USER)] = "user",
5209 [LOG_FAC(LOG_MAIL)] = "mail",
5210 [LOG_FAC(LOG_DAEMON)] = "daemon",
5211 [LOG_FAC(LOG_AUTH)] = "auth",
5212 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5213 [LOG_FAC(LOG_LPR)] = "lpr",
5214 [LOG_FAC(LOG_NEWS)] = "news",
5215 [LOG_FAC(LOG_UUCP)] = "uucp",
5216 [LOG_FAC(LOG_CRON)] = "cron",
5217 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5218 [LOG_FAC(LOG_FTP)] = "ftp",
5219 [LOG_FAC(LOG_LOCAL0)] = "local0",
5220 [LOG_FAC(LOG_LOCAL1)] = "local1",
5221 [LOG_FAC(LOG_LOCAL2)] = "local2",
5222 [LOG_FAC(LOG_LOCAL3)] = "local3",
5223 [LOG_FAC(LOG_LOCAL4)] = "local4",
5224 [LOG_FAC(LOG_LOCAL5)] = "local5",
5225 [LOG_FAC(LOG_LOCAL6)] = "local6",
5226 [LOG_FAC(LOG_LOCAL7)] = "local7"
5229 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5231 static const char *const log_level_table[] = {
5232 [LOG_EMERG] = "emerg",
5233 [LOG_ALERT] = "alert",
5234 [LOG_CRIT] = "crit",
5236 [LOG_WARNING] = "warning",
5237 [LOG_NOTICE] = "notice",
5238 [LOG_INFO] = "info",
5239 [LOG_DEBUG] = "debug"
5242 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5244 static const char* const sched_policy_table[] = {
5245 [SCHED_OTHER] = "other",
5246 [SCHED_BATCH] = "batch",
5247 [SCHED_IDLE] = "idle",
5248 [SCHED_FIFO] = "fifo",
5252 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5254 static const char* const rlimit_table[] = {
5255 [RLIMIT_CPU] = "LimitCPU",
5256 [RLIMIT_FSIZE] = "LimitFSIZE",
5257 [RLIMIT_DATA] = "LimitDATA",
5258 [RLIMIT_STACK] = "LimitSTACK",
5259 [RLIMIT_CORE] = "LimitCORE",
5260 [RLIMIT_RSS] = "LimitRSS",
5261 [RLIMIT_NOFILE] = "LimitNOFILE",
5262 [RLIMIT_AS] = "LimitAS",
5263 [RLIMIT_NPROC] = "LimitNPROC",
5264 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5265 [RLIMIT_LOCKS] = "LimitLOCKS",
5266 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5267 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5268 [RLIMIT_NICE] = "LimitNICE",
5269 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5270 [RLIMIT_RTTIME] = "LimitRTTIME"
5273 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5275 static const char* const ip_tos_table[] = {
5276 [IPTOS_LOWDELAY] = "low-delay",
5277 [IPTOS_THROUGHPUT] = "throughput",
5278 [IPTOS_RELIABILITY] = "reliability",
5279 [IPTOS_LOWCOST] = "low-cost",
5282 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5284 static const char *const __signal_table[] = {
5301 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5312 [SIGVTALRM] = "VTALRM",
5314 [SIGWINCH] = "WINCH",
5320 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5322 const char *signal_to_string(int signo) {
5323 static __thread char buf[12];
5326 name = __signal_to_string(signo);
5330 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5331 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5333 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5338 int signal_from_string(const char *s) {
5343 signo = __signal_from_string(s);
5347 if (startswith(s, "RTMIN+")) {
5351 if (safe_atou(s, &u) >= 0) {
5352 signo = (int) u + offset;
5353 if (signo > 0 && signo < _NSIG)
5359 bool kexec_loaded(void) {
5360 bool loaded = false;
5363 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5371 int strdup_or_null(const char *a, char **b) {
5389 int prot_from_flags(int flags) {
5391 switch (flags & O_ACCMODE) {
5400 return PROT_READ|PROT_WRITE;
5407 char *format_bytes(char *buf, size_t l, off_t t) {
5410 static const struct {
5414 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5415 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5416 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5417 { "G", 1024ULL*1024ULL*1024ULL },
5418 { "M", 1024ULL*1024ULL },
5422 for (i = 0; i < ELEMENTSOF(table); i++) {
5424 if (t >= table[i].factor) {
5427 (unsigned long long) (t / table[i].factor),
5428 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5435 snprintf(buf, l, "%lluB", (unsigned long long) t);
5443 void* memdup(const void *p, size_t l) {
5456 int fd_inc_sndbuf(int fd, size_t n) {
5458 socklen_t l = sizeof(value);
5460 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5462 l == sizeof(value) &&
5463 (size_t) value >= n*2)
5467 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5474 int fd_inc_rcvbuf(int fd, size_t n) {
5476 socklen_t l = sizeof(value);
5478 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5480 l == sizeof(value) &&
5481 (size_t) value >= n*2)
5485 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5492 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5493 pid_t parent_pid, agent_pid;
5495 bool stdout_is_tty, stderr_is_tty;
5503 parent_pid = getpid();
5505 /* Spawns a temporary TTY agent, making sure it goes away when
5512 if (agent_pid != 0) {
5519 * Make sure the agent goes away when the parent dies */
5520 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5521 _exit(EXIT_FAILURE);
5523 /* Check whether our parent died before we were able
5524 * to set the death signal */
5525 if (getppid() != parent_pid)
5526 _exit(EXIT_SUCCESS);
5528 /* Don't leak fds to the agent */
5529 close_all_fds(except, n_except);
5531 stdout_is_tty = isatty(STDOUT_FILENO);
5532 stderr_is_tty = isatty(STDERR_FILENO);
5534 if (!stdout_is_tty || !stderr_is_tty) {
5535 /* Detach from stdout/stderr. and reopen
5536 * /dev/tty for them. This is important to
5537 * ensure that when systemctl is started via
5538 * popen() or a similar call that expects to
5539 * read EOF we actually do generate EOF and
5540 * not delay this indefinitely by because we
5541 * keep an unused copy of stdin around. */
5542 fd = open("/dev/tty", O_WRONLY);
5544 log_error("Failed to open /dev/tty: %m");
5545 _exit(EXIT_FAILURE);
5549 dup2(fd, STDOUT_FILENO);
5552 dup2(fd, STDERR_FILENO);
5558 /* Count arguments */
5560 for (n = 0; va_arg(ap, char*); n++)
5565 l = alloca(sizeof(char *) * (n + 1));
5567 /* Fill in arguments */
5569 for (i = 0; i <= n; i++)
5570 l[i] = va_arg(ap, char*);
5574 _exit(EXIT_FAILURE);
5577 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5578 struct rlimit highest, fixed;
5582 if (setrlimit(resource, rlim) >= 0)
5588 /* So we failed to set the desired setrlimit, then let's try
5589 * to get as close as we can */
5590 assert_se(getrlimit(resource, &highest) == 0);
5592 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5593 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5595 if (setrlimit(resource, &fixed) < 0)
5601 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5602 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5614 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5617 f = fopen(path, "re");
5625 char line[LINE_MAX];
5628 for (i = 0; i < sizeof(line)-1; i++) {
5632 if (_unlikely_(c == EOF)) {
5642 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5643 value = strdup(line + l + 1);
5663 int can_sleep(const char *type) {
5667 _cleanup_free_ char *p = NULL;
5671 r = read_one_line_file("/sys/power/state", &p);
5673 return r == -ENOENT ? 0 : r;
5676 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5677 if (l == k && memcmp(w, type, l) == 0)
5683 bool is_valid_documentation_url(const char *url) {
5686 if (startswith(url, "http://") && url[7])
5689 if (startswith(url, "https://") && url[8])
5692 if (startswith(url, "file:") && url[5])
5695 if (startswith(url, "info:") && url[5])
5698 if (startswith(url, "man:") && url[4])
5704 bool in_initrd(void) {
5705 static __thread int saved = -1;
5711 /* We make two checks here:
5713 * 1. the flag file /etc/initrd-release must exist
5714 * 2. the root file system must be a memory file system
5716 * The second check is extra paranoia, since misdetecting an
5717 * initrd can have bad bad consequences due the initrd
5718 * emptying when transititioning to the main systemd.
5721 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5722 statfs("/", &s) >= 0 &&
5723 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5728 void warn_melody(void) {
5729 _cleanup_close_ int fd = -1;
5731 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5735 /* Yeah, this is synchronous. Kinda sucks. But well... */
5737 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5738 usleep(125*USEC_PER_MSEC);
5740 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5741 usleep(125*USEC_PER_MSEC);
5743 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5744 usleep(125*USEC_PER_MSEC);
5746 ioctl(fd, KIOCSOUND, 0);
5749 int make_console_stdio(void) {
5752 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5754 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5756 log_error("Failed to acquire terminal: %s", strerror(-fd));
5762 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5769 int get_home_dir(char **_h) {
5777 /* Take the user specified one */
5788 /* Hardcode home directory for root to avoid NSS */
5791 h = strdup("/root");
5799 /* Check the database... */
5803 return errno ? -errno : -ESRCH;
5805 if (!path_is_absolute(p->pw_dir))
5808 h = strdup(p->pw_dir);
5816 int get_shell(char **_sh) {
5824 /* Take the user specified one */
5825 e = getenv("SHELL");
5835 /* Hardcode home directory for root to avoid NSS */
5838 sh = strdup("/bin/sh");
5846 /* Check the database... */
5850 return errno ? -errno : -ESRCH;
5852 if (!path_is_absolute(p->pw_shell))
5855 sh = strdup(p->pw_shell);
5863 void freep(void *p) {
5867 void fclosep(FILE **f) {
5872 void closep(int *fd) {
5874 close_nointr_nofail(*fd);
5877 void closedirp(DIR **d) {
5882 void umaskp(mode_t *u) {
5886 bool filename_is_safe(const char *p) {
5900 if (strlen(p) > FILENAME_MAX)
5906 bool string_is_safe(const char *p) {
5911 for (t = p; *t; t++) {
5915 if (strchr("\\\"\'", *t))
5922 int parse_timestamp(const char *t, usec_t *usec) {
5926 usec_t plus = 0, minus = 0, ret;
5932 * 2012-09-22 16:34:22
5933 * 2012-09-22 16:34 (seconds will be set to 0)
5934 * 2012-09-22 (time will be set to 00:00:00)
5935 * 16:34:22 (date will be set to today)
5936 * 16:34 (date will be set to today, seconds to 0)
5938 * yesterday (time is set to 00:00:00)
5939 * today (time is set to 00:00:00)
5940 * tomorrow (time is set to 00:00:00)
5950 assert_se(localtime_r(&x, &tm));
5952 if (streq(t, "now"))
5955 else if (streq(t, "today")) {
5956 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5959 } else if (streq(t, "yesterday")) {
5961 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5964 } else if (streq(t, "tomorrow")) {
5966 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5969 } else if (t[0] == '+') {
5971 r = parse_usec(t+1, &plus);
5976 } else if (t[0] == '-') {
5978 r = parse_usec(t+1, &minus);
5986 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
5991 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
5996 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6003 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6010 k = strptime(t, "%y-%m-%d", &tm);
6012 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6017 k = strptime(t, "%Y-%m-%d", &tm);
6019 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6024 k = strptime(t, "%H:%M:%S", &tm);
6029 k = strptime(t, "%H:%M", &tm);
6039 if (x == (time_t) -1)
6042 ret = (usec_t) x * USEC_PER_SEC;