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 volatile unsigned cached_columns = 0;
76 static volatile unsigned cached_lines = 0;
78 size_t page_size(void) {
79 static __thread size_t pgsz = 0;
82 if (_likely_(pgsz > 0))
85 r = sysconf(_SC_PAGESIZE);
92 bool streq_ptr(const char *a, const char *b) {
94 /* Like streq(), but tries to make sense of NULL pointers */
105 usec_t now(clockid_t clock_id) {
108 assert_se(clock_gettime(clock_id, &ts) == 0);
110 return timespec_load(&ts);
113 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
116 ts->realtime = now(CLOCK_REALTIME);
117 ts->monotonic = now(CLOCK_MONOTONIC);
122 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
131 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
133 ts->monotonic = now(CLOCK_MONOTONIC);
135 if ((int64_t) ts->monotonic > delta)
136 ts->monotonic -= delta;
144 usec_t timespec_load(const struct timespec *ts) {
147 if (ts->tv_sec == (time_t) -1 &&
148 ts->tv_nsec == (long) -1)
152 (usec_t) ts->tv_sec * USEC_PER_SEC +
153 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
156 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
159 if (u == (usec_t) -1) {
160 ts->tv_sec = (time_t) -1;
161 ts->tv_nsec = (long) -1;
165 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
166 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
171 usec_t timeval_load(const struct timeval *tv) {
174 if (tv->tv_sec == (time_t) -1 &&
175 tv->tv_usec == (suseconds_t) -1)
179 (usec_t) tv->tv_sec * USEC_PER_SEC +
180 (usec_t) tv->tv_usec;
183 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
186 if (u == (usec_t) -1) {
187 tv->tv_sec = (time_t) -1;
188 tv->tv_usec = (suseconds_t) -1;
192 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
193 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
198 bool endswith(const char *s, const char *postfix) {
205 pl = strlen(postfix);
213 return memcmp(s + sl - pl, postfix, pl) == 0;
216 bool startswith(const char *s, const char *prefix) {
231 return memcmp(s, prefix, pl) == 0;
234 bool startswith_no_case(const char *s, const char *prefix) {
250 for(i = 0; i < pl; ++i)
251 if (tolower(s[i]) != tolower(prefix[i]))
257 bool first_word(const char *s, const char *word) {
272 if (memcmp(s, word, wl) != 0)
276 strchr(WHITESPACE, s[wl]);
279 int close_nointr(int fd) {
294 void close_nointr_nofail(int fd) {
295 int saved_errno = errno;
297 /* like close_nointr() but cannot fail, and guarantees errno
300 assert_se(close_nointr(fd) == 0);
305 void close_many(const int fds[], unsigned n_fd) {
308 for (i = 0; i < n_fd; i++)
309 close_nointr_nofail(fds[i]);
312 int parse_boolean(const char *v) {
315 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
317 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
323 int parse_pid(const char *s, pid_t* ret_pid) {
324 unsigned long ul = 0;
331 r = safe_atolu(s, &ul);
337 if ((unsigned long) pid != ul)
347 int parse_uid(const char *s, uid_t* ret_uid) {
348 unsigned long ul = 0;
355 r = safe_atolu(s, &ul);
361 if ((unsigned long) uid != ul)
368 int safe_atou(const char *s, unsigned *ret_u) {
376 l = strtoul(s, &x, 0);
378 if (!x || *x || errno)
379 return errno ? -errno : -EINVAL;
381 if ((unsigned long) (unsigned) l != l)
384 *ret_u = (unsigned) l;
388 int safe_atoi(const char *s, int *ret_i) {
396 l = strtol(s, &x, 0);
398 if (!x || *x || errno)
399 return errno ? -errno : -EINVAL;
401 if ((long) (int) l != l)
408 int safe_atollu(const char *s, long long unsigned *ret_llu) {
410 unsigned long long l;
416 l = strtoull(s, &x, 0);
418 if (!x || *x || errno)
419 return errno ? -errno : -EINVAL;
425 int safe_atolli(const char *s, long long int *ret_lli) {
433 l = strtoll(s, &x, 0);
435 if (!x || *x || errno)
436 return errno ? -errno : -EINVAL;
442 /* Split a string into words. */
443 char *split(const char *c, size_t *l, const char *separator, char **state) {
446 current = *state ? *state : (char*) c;
448 if (!*current || *c == 0)
451 current += strspn(current, separator);
452 *l = strcspn(current, separator);
455 return (char*) current;
458 /* Split a string into words, but consider strings enclosed in '' and
459 * "" as words even if they include spaces. */
460 char *split_quoted(const char *c, size_t *l, char **state) {
462 bool escaped = false;
464 current = *state ? *state : (char*) c;
466 if (!*current || *c == 0)
469 current += strspn(current, WHITESPACE);
471 if (*current == '\'') {
474 for (e = current; *e; e++) {
484 *state = *e == 0 ? e : e+1;
485 } else if (*current == '\"') {
488 for (e = current; *e; e++) {
498 *state = *e == 0 ? e : e+1;
500 for (e = current; *e; e++) {
505 else if (strchr(WHITESPACE, *e))
512 return (char*) current;
515 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
517 _cleanup_fclose_ FILE *f = NULL;
518 char fn[PATH_MAX], line[LINE_MAX], *p;
524 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
531 if (!fgets(line, sizeof(line), f)) {
532 r = feof(f) ? -EIO : -errno;
537 /* Let's skip the pid and comm fields. The latter is enclosed
538 * in () but does not escape any () in its value, so let's
539 * skip over it manually */
541 p = strrchr(line, ')');
553 if ((long unsigned) (pid_t) ppid != ppid)
556 *_ppid = (pid_t) ppid;
561 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
562 _cleanup_fclose_ FILE *f = NULL;
563 char fn[PATH_MAX], line[LINE_MAX], *p;
568 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
575 if (!fgets(line, sizeof(line), f)) {
582 /* Let's skip the pid and comm fields. The latter is enclosed
583 * in () but does not escape any () in its value, so let's
584 * skip over it manually */
586 p = strrchr(line, ')');
608 "%*d " /* priority */
610 "%*d " /* num_threads */
611 "%*d " /* itrealvalue */
612 "%llu " /* starttime */,
619 int write_one_line_file(const char *fn, const char *line) {
620 _cleanup_fclose_ FILE *f = NULL;
630 if (fputs(line, f) < 0)
631 return errno ? -errno : -EIO;
633 if (!endswith(line, "\n"))
639 return errno ? -errno : -EIO;
644 int fchmod_umask(int fd, mode_t m) {
649 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
655 int write_one_line_file_atomic(const char *fn, const char *line) {
663 r = fopen_temporary(fn, &f, &p);
667 fchmod_umask(fileno(f), 0644);
670 if (fputs(line, f) < 0) {
675 if (!endswith(line, "\n"))
686 if (rename(p, fn) < 0)
702 int read_one_line_file(const char *fn, char **line) {
703 _cleanup_fclose_ FILE *f = NULL;
704 char t[LINE_MAX], *c;
713 if (!fgets(t, sizeof(t), f)) {
716 return errno ? -errno : -EIO;
730 int read_full_file(const char *fn, char **contents, size_t *size) {
731 _cleanup_fclose_ FILE *f = NULL;
733 _cleanup_free_ char *buf = NULL;
740 if (fstat(fileno(f), &st) < 0)
744 if (st.st_size > 4*1024*1024)
747 n = st.st_size > 0 ? st.st_size : LINE_MAX;
754 t = realloc(buf, n+1);
759 k = fread(buf + l, 1, n - l, f);
788 const char *separator, ...) {
791 char *contents = NULL, *p;
796 if ((r = read_full_file(fname, &contents, NULL)) < 0)
801 const char *key = NULL;
803 p += strspn(p, separator);
804 p += strspn(p, WHITESPACE);
809 if (!strchr(COMMENTS, *p)) {
813 va_start(ap, separator);
814 while ((key = va_arg(ap, char *))) {
818 value = va_arg(ap, char **);
821 if (strncmp(p, key, n) != 0 ||
826 n = strcspn(p, separator);
829 strchr(QUOTES, p[0]) &&
831 v = strndup(p+1, n-2);
842 /* return empty value strings as NULL */
859 p += strcspn(p, separator);
878 if (!(f = fopen(fname, "re")))
882 char l[LINE_MAX], *p, *u;
885 if (!fgets(l, sizeof(l), f)) {
898 if (strchr(COMMENTS, *p))
901 if (!(u = normalize_env_assignment(p))) {
906 t = strv_append(m, u);
932 int write_env_file(const char *fname, char **l) {
937 r = fopen_temporary(fname, &f, &p);
941 fchmod_umask(fileno(f), 0644);
957 if (rename(p, fname) < 0)
972 char *truncate_nl(char *s) {
975 s[strcspn(s, NEWLINE)] = 0;
979 int get_process_comm(pid_t pid, char **name) {
985 r = read_one_line_file("/proc/self/comm", name);
988 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
991 r = read_one_line_file(p, name);
998 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1005 assert(max_length > 0);
1009 f = fopen("/proc/self/cmdline", "re");
1012 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1022 r = new(char, max_length);
1030 while ((c = getc(f)) != EOF) {
1052 size_t n = MIN(left-1, 3U);
1053 memcpy(k, "...", n);
1060 /* Kernel threads have no argv[] */
1070 h = get_process_comm(pid, &t);
1074 r = strjoin("[", t, "]", NULL);
1085 int is_kernel_thread(pid_t pid) {
1095 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1104 count = fread(&c, 1, 1, f);
1108 /* Kernel threads have an empty cmdline */
1111 return eof ? 1 : -errno;
1116 int get_process_exe(pid_t pid, char **name) {
1122 r = readlink_malloc("/proc/self/exe", name);
1125 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1128 r = readlink_malloc(p, name);
1135 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1145 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1155 char line[LINE_MAX], *l;
1157 if (!fgets(line, sizeof(line), f)) {
1167 if (startswith(l, field)) {
1169 l += strspn(l, WHITESPACE);
1171 l[strcspn(l, WHITESPACE)] = 0;
1173 r = parse_uid(l, uid);
1186 int get_process_uid(pid_t pid, uid_t *uid) {
1187 return get_process_id(pid, "Uid:", uid);
1190 int get_process_gid(pid_t pid, gid_t *gid) {
1191 return get_process_id(pid, "Gid:", gid);
1194 char *strnappend(const char *s, const char *suffix, size_t b) {
1202 return strndup(suffix, b);
1211 if (b > ((size_t) -1) - a)
1214 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_with_prefix(const char *s, size_t length, const char *prefix) {
1573 /* Undoes C style string escaping, and optionally prefixes it. */
1575 pl = prefix ? strlen(prefix) : 0;
1577 r = new(char, pl+length+1);
1582 memcpy(r, prefix, pl);
1584 for (f = s, t = r + pl; f < s + length; f++) {
1627 /* This is an extension of the XDG syntax files */
1632 /* hexadecimal encoding */
1635 a = unhexchar(f[1]);
1636 b = unhexchar(f[2]);
1638 if (a < 0 || b < 0) {
1639 /* Invalid escape code, let's take it literal then */
1643 *(t++) = (char) ((a << 4) | b);
1658 /* octal encoding */
1661 a = unoctchar(f[0]);
1662 b = unoctchar(f[1]);
1663 c = unoctchar(f[2]);
1665 if (a < 0 || b < 0 || c < 0) {
1666 /* Invalid escape code, let's take it literal then */
1670 *(t++) = (char) ((a << 6) | (b << 3) | c);
1678 /* premature end of string.*/
1683 /* Invalid escape code, let's take it literal then */
1695 char *cunescape_length(const char *s, size_t length) {
1696 return cunescape_length_with_prefix(s, length, NULL);
1699 char *cunescape(const char *s) {
1702 return cunescape_length(s, strlen(s));
1705 char *xescape(const char *s, const char *bad) {
1709 /* Escapes all chars in bad, in addition to \ and all special
1710 * chars, in \xFF style escaping. May be reversed with
1713 r = new(char, strlen(s) * 4 + 1);
1717 for (f = s, t = r; *f; f++) {
1719 if ((*f < ' ') || (*f >= 127) ||
1720 (*f == '\\') || strchr(bad, *f)) {
1723 *(t++) = hexchar(*f >> 4);
1724 *(t++) = hexchar(*f);
1734 char *bus_path_escape(const char *s) {
1740 /* Escapes all chars that D-Bus' object path cannot deal
1741 * with. Can be reverse with bus_path_unescape() */
1743 if (!(r = new(char, strlen(s)*3+1)))
1746 for (f = s, t = r; *f; f++) {
1748 if (!(*f >= 'A' && *f <= 'Z') &&
1749 !(*f >= 'a' && *f <= 'z') &&
1750 !(*f >= '0' && *f <= '9')) {
1752 *(t++) = hexchar(*f >> 4);
1753 *(t++) = hexchar(*f);
1763 char *bus_path_unescape(const char *f) {
1768 if (!(r = strdup(f)))
1771 for (t = r; *f; f++) {
1776 if ((a = unhexchar(f[1])) < 0 ||
1777 (b = unhexchar(f[2])) < 0) {
1778 /* Invalid escape code, let's take it literal then */
1781 *(t++) = (char) ((a << 4) | b);
1793 char *ascii_strlower(char *t) {
1798 for (p = t; *p; p++)
1799 if (*p >= 'A' && *p <= 'Z')
1800 *p = *p - 'A' + 'a';
1805 static bool ignore_file_allow_backup(const char *filename) {
1809 filename[0] == '.' ||
1810 streq(filename, "lost+found") ||
1811 streq(filename, "aquota.user") ||
1812 streq(filename, "aquota.group") ||
1813 endswith(filename, ".rpmnew") ||
1814 endswith(filename, ".rpmsave") ||
1815 endswith(filename, ".rpmorig") ||
1816 endswith(filename, ".dpkg-old") ||
1817 endswith(filename, ".dpkg-new") ||
1818 endswith(filename, ".swp");
1821 bool ignore_file(const char *filename) {
1824 if (endswith(filename, "~"))
1827 return ignore_file_allow_backup(filename);
1830 int fd_nonblock(int fd, bool nonblock) {
1835 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1839 flags |= O_NONBLOCK;
1841 flags &= ~O_NONBLOCK;
1843 if (fcntl(fd, F_SETFL, flags) < 0)
1849 int fd_cloexec(int fd, bool cloexec) {
1854 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1858 flags |= FD_CLOEXEC;
1860 flags &= ~FD_CLOEXEC;
1862 if (fcntl(fd, F_SETFD, flags) < 0)
1868 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1871 assert(n_fdset == 0 || fdset);
1873 for (i = 0; i < n_fdset; i++)
1880 int close_all_fds(const int except[], unsigned n_except) {
1885 assert(n_except == 0 || except);
1887 d = opendir("/proc/self/fd");
1892 /* When /proc isn't available (for example in chroots)
1893 * the fallback is brute forcing through the fd
1896 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1897 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1899 if (fd_in_set(fd, except, n_except))
1902 if (close_nointr(fd) < 0)
1903 if (errno != EBADF && r == 0)
1910 while ((de = readdir(d))) {
1913 if (ignore_file(de->d_name))
1916 if (safe_atoi(de->d_name, &fd) < 0)
1917 /* Let's better ignore this, just in case */
1926 if (fd_in_set(fd, except, n_except))
1929 if (close_nointr(fd) < 0) {
1930 /* Valgrind has its own FD and doesn't want to have it closed */
1931 if (errno != EBADF && r == 0)
1940 bool chars_intersect(const char *a, const char *b) {
1943 /* Returns true if any of the chars in a are in b. */
1944 for (p = a; *p; p++)
1951 char *format_timestamp(char *buf, size_t l, usec_t t) {
1961 sec = (time_t) (t / USEC_PER_SEC);
1963 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1969 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1972 n = now(CLOCK_REALTIME);
1974 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1979 if (d >= USEC_PER_YEAR)
1980 snprintf(buf, l, "%llu years and %llu months ago",
1981 (unsigned long long) (d / USEC_PER_YEAR),
1982 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1983 else if (d >= USEC_PER_MONTH)
1984 snprintf(buf, l, "%llu months and %llu days ago",
1985 (unsigned long long) (d / USEC_PER_MONTH),
1986 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1987 else if (d >= USEC_PER_WEEK)
1988 snprintf(buf, l, "%llu weeks and %llu days ago",
1989 (unsigned long long) (d / USEC_PER_WEEK),
1990 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1991 else if (d >= 2*USEC_PER_DAY)
1992 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1993 else if (d >= 25*USEC_PER_HOUR)
1994 snprintf(buf, l, "1 day and %lluh ago",
1995 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1996 else if (d >= 6*USEC_PER_HOUR)
1997 snprintf(buf, l, "%lluh ago",
1998 (unsigned long long) (d / USEC_PER_HOUR));
1999 else if (d >= USEC_PER_HOUR)
2000 snprintf(buf, l, "%lluh %llumin ago",
2001 (unsigned long long) (d / USEC_PER_HOUR),
2002 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2003 else if (d >= 5*USEC_PER_MINUTE)
2004 snprintf(buf, l, "%llumin ago",
2005 (unsigned long long) (d / USEC_PER_MINUTE));
2006 else if (d >= USEC_PER_MINUTE)
2007 snprintf(buf, l, "%llumin %llus ago",
2008 (unsigned long long) (d / USEC_PER_MINUTE),
2009 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2010 else if (d >= USEC_PER_SEC)
2011 snprintf(buf, l, "%llus ago",
2012 (unsigned long long) (d / USEC_PER_SEC));
2013 else if (d >= USEC_PER_MSEC)
2014 snprintf(buf, l, "%llums ago",
2015 (unsigned long long) (d / USEC_PER_MSEC));
2017 snprintf(buf, l, "%lluus ago",
2018 (unsigned long long) d);
2020 snprintf(buf, l, "now");
2026 char *format_timespan(char *buf, size_t l, usec_t t) {
2027 static const struct {
2031 { "w", USEC_PER_WEEK },
2032 { "d", USEC_PER_DAY },
2033 { "h", USEC_PER_HOUR },
2034 { "min", USEC_PER_MINUTE },
2035 { "s", USEC_PER_SEC },
2036 { "ms", USEC_PER_MSEC },
2046 if (t == (usec_t) -1)
2050 snprintf(p, l, "0");
2055 /* The result of this function can be parsed with parse_usec */
2057 for (i = 0; i < ELEMENTSOF(table); i++) {
2061 if (t < table[i].usec)
2067 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2068 n = MIN((size_t) k, l);
2081 bool fstype_is_network(const char *fstype) {
2082 static const char table[] =
2091 return nulstr_contains(table, fstype);
2095 _cleanup_close_ int fd;
2097 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2103 TIOCL_GETKMSGREDIRECT,
2107 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2110 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2113 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2119 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2120 struct termios old_termios, new_termios;
2122 char line[LINE_MAX];
2127 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2128 new_termios = old_termios;
2130 new_termios.c_lflag &= ~ICANON;
2131 new_termios.c_cc[VMIN] = 1;
2132 new_termios.c_cc[VTIME] = 0;
2134 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2137 if (t != (usec_t) -1) {
2138 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2139 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2144 k = fread(&c, 1, 1, f);
2146 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2152 *need_nl = c != '\n';
2159 if (t != (usec_t) -1)
2160 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2163 if (!fgets(line, sizeof(line), f))
2168 if (strlen(line) != 1)
2178 int ask(char *ret, const char *replies, const char *text, ...) {
2188 bool need_nl = true;
2191 fputs(ANSI_HIGHLIGHT_ON, stdout);
2198 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2202 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2205 if (r == -EBADMSG) {
2206 puts("Bad input, please try again.");
2217 if (strchr(replies, c)) {
2222 puts("Read unexpected character, please try again.");
2226 int reset_terminal_fd(int fd, bool switch_to_text) {
2227 struct termios termios;
2230 /* Set terminal to some sane defaults */
2234 /* We leave locked terminal attributes untouched, so that
2235 * Plymouth may set whatever it wants to set, and we don't
2236 * interfere with that. */
2238 /* Disable exclusive mode, just in case */
2239 ioctl(fd, TIOCNXCL);
2241 /* Switch to text mode */
2243 ioctl(fd, KDSETMODE, KD_TEXT);
2245 /* Enable console unicode mode */
2246 ioctl(fd, KDSKBMODE, K_UNICODE);
2248 if (tcgetattr(fd, &termios) < 0) {
2253 /* We only reset the stuff that matters to the software. How
2254 * hardware is set up we don't touch assuming that somebody
2255 * else will do that for us */
2257 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2258 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2259 termios.c_oflag |= ONLCR;
2260 termios.c_cflag |= CREAD;
2261 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2263 termios.c_cc[VINTR] = 03; /* ^C */
2264 termios.c_cc[VQUIT] = 034; /* ^\ */
2265 termios.c_cc[VERASE] = 0177;
2266 termios.c_cc[VKILL] = 025; /* ^X */
2267 termios.c_cc[VEOF] = 04; /* ^D */
2268 termios.c_cc[VSTART] = 021; /* ^Q */
2269 termios.c_cc[VSTOP] = 023; /* ^S */
2270 termios.c_cc[VSUSP] = 032; /* ^Z */
2271 termios.c_cc[VLNEXT] = 026; /* ^V */
2272 termios.c_cc[VWERASE] = 027; /* ^W */
2273 termios.c_cc[VREPRINT] = 022; /* ^R */
2274 termios.c_cc[VEOL] = 0;
2275 termios.c_cc[VEOL2] = 0;
2277 termios.c_cc[VTIME] = 0;
2278 termios.c_cc[VMIN] = 1;
2280 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2284 /* Just in case, flush all crap out */
2285 tcflush(fd, TCIOFLUSH);
2290 int reset_terminal(const char *name) {
2293 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2297 r = reset_terminal_fd(fd, true);
2298 close_nointr_nofail(fd);
2303 int open_terminal(const char *name, int mode) {
2308 * If a TTY is in the process of being closed opening it might
2309 * cause EIO. This is horribly awful, but unlikely to be
2310 * changed in the kernel. Hence we work around this problem by
2311 * retrying a couple of times.
2313 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2317 fd = open(name, mode);
2324 /* Max 1s in total */
2328 usleep(50 * USEC_PER_MSEC);
2337 close_nointr_nofail(fd);
2342 close_nointr_nofail(fd);
2349 int flush_fd(int fd) {
2350 struct pollfd pollfd;
2354 pollfd.events = POLLIN;
2361 if ((r = poll(&pollfd, 1, 0)) < 0) {
2372 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2377 if (errno == EAGAIN)
2388 int acquire_terminal(
2392 bool ignore_tiocstty_eperm,
2395 int fd = -1, notify = -1, r = 0, wd = -1;
2397 struct sigaction sa_old, sa_new;
2401 /* We use inotify to be notified when the tty is closed. We
2402 * create the watch before checking if we can actually acquire
2403 * it, so that we don't lose any event.
2405 * Note: strictly speaking this actually watches for the
2406 * device being closed, it does *not* really watch whether a
2407 * tty loses its controlling process. However, unless some
2408 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2409 * its tty otherwise this will not become a problem. As long
2410 * as the administrator makes sure not configure any service
2411 * on the same tty as an untrusted user this should not be a
2412 * problem. (Which he probably should not do anyway.) */
2414 if (timeout != (usec_t) -1)
2415 ts = now(CLOCK_MONOTONIC);
2417 if (!fail && !force) {
2418 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2424 wd = inotify_add_watch(notify, name, IN_CLOSE);
2433 r = flush_fd(notify);
2438 /* We pass here O_NOCTTY only so that we can check the return
2439 * value TIOCSCTTY and have a reliable way to figure out if we
2440 * successfully became the controlling process of the tty */
2441 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2445 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2446 * if we already own the tty. */
2448 sa_new.sa_handler = SIG_IGN;
2449 sa_new.sa_flags = SA_RESTART;
2450 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2452 /* First, try to get the tty */
2453 if (ioctl(fd, TIOCSCTTY, force) < 0)
2456 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2458 /* Sometimes it makes sense to ignore TIOCSCTTY
2459 * returning EPERM, i.e. when very likely we already
2460 * are have this controlling terminal. */
2461 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2464 if (r < 0 && (force || fail || r != -EPERM)) {
2473 assert(notify >= 0);
2476 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2478 struct inotify_event *e;
2480 if (timeout != (usec_t) -1) {
2483 n = now(CLOCK_MONOTONIC);
2484 if (ts + timeout < n) {
2489 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2499 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2502 if (errno == EINTR || errno == EAGAIN)
2509 e = (struct inotify_event*) inotify_buffer;
2514 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2519 step = sizeof(struct inotify_event) + e->len;
2520 assert(step <= (size_t) l);
2522 e = (struct inotify_event*) ((uint8_t*) e + step);
2529 /* We close the tty fd here since if the old session
2530 * ended our handle will be dead. It's important that
2531 * we do this after sleeping, so that we don't enter
2532 * an endless loop. */
2533 close_nointr_nofail(fd);
2537 close_nointr_nofail(notify);
2539 r = reset_terminal_fd(fd, true);
2541 log_warning("Failed to reset terminal: %s", strerror(-r));
2547 close_nointr_nofail(fd);
2550 close_nointr_nofail(notify);
2555 int release_terminal(void) {
2557 struct sigaction sa_old, sa_new;
2559 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2562 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2563 * by our own TIOCNOTTY */
2566 sa_new.sa_handler = SIG_IGN;
2567 sa_new.sa_flags = SA_RESTART;
2568 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2570 if (ioctl(fd, TIOCNOTTY) < 0)
2573 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2575 close_nointr_nofail(fd);
2579 int sigaction_many(const struct sigaction *sa, ...) {
2584 while ((sig = va_arg(ap, int)) > 0)
2585 if (sigaction(sig, sa, NULL) < 0)
2592 int ignore_signals(int sig, ...) {
2593 struct sigaction sa;
2598 sa.sa_handler = SIG_IGN;
2599 sa.sa_flags = SA_RESTART;
2601 if (sigaction(sig, &sa, NULL) < 0)
2605 while ((sig = va_arg(ap, int)) > 0)
2606 if (sigaction(sig, &sa, NULL) < 0)
2613 int default_signals(int sig, ...) {
2614 struct sigaction sa;
2619 sa.sa_handler = SIG_DFL;
2620 sa.sa_flags = SA_RESTART;
2622 if (sigaction(sig, &sa, NULL) < 0)
2626 while ((sig = va_arg(ap, int)) > 0)
2627 if (sigaction(sig, &sa, NULL) < 0)
2634 int close_pipe(int p[]) {
2640 a = close_nointr(p[0]);
2645 b = close_nointr(p[1]);
2649 return a < 0 ? a : b;
2652 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2661 while (nbytes > 0) {
2664 if ((k = read(fd, p, nbytes)) <= 0) {
2666 if (k < 0 && errno == EINTR)
2669 if (k < 0 && errno == EAGAIN && do_poll) {
2670 struct pollfd pollfd;
2674 pollfd.events = POLLIN;
2676 if (poll(&pollfd, 1, -1) < 0) {
2680 return n > 0 ? n : -errno;
2683 if (pollfd.revents != POLLIN)
2684 return n > 0 ? n : -EIO;
2689 return n > 0 ? n : (k < 0 ? -errno : 0);
2700 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2709 while (nbytes > 0) {
2712 k = write(fd, p, nbytes);
2715 if (k < 0 && errno == EINTR)
2718 if (k < 0 && errno == EAGAIN && do_poll) {
2719 struct pollfd pollfd;
2723 pollfd.events = POLLOUT;
2725 if (poll(&pollfd, 1, -1) < 0) {
2729 return n > 0 ? n : -errno;
2732 if (pollfd.revents != POLLOUT)
2733 return n > 0 ? n : -EIO;
2738 return n > 0 ? n : (k < 0 ? -errno : 0);
2749 int parse_usec(const char *t, usec_t *usec) {
2750 static const struct {
2754 { "seconds", USEC_PER_SEC },
2755 { "second", USEC_PER_SEC },
2756 { "sec", USEC_PER_SEC },
2757 { "s", USEC_PER_SEC },
2758 { "minutes", USEC_PER_MINUTE },
2759 { "minute", USEC_PER_MINUTE },
2760 { "min", USEC_PER_MINUTE },
2761 { "months", USEC_PER_MONTH },
2762 { "month", USEC_PER_MONTH },
2763 { "msec", USEC_PER_MSEC },
2764 { "ms", USEC_PER_MSEC },
2765 { "m", USEC_PER_MINUTE },
2766 { "hours", USEC_PER_HOUR },
2767 { "hour", USEC_PER_HOUR },
2768 { "hr", USEC_PER_HOUR },
2769 { "h", USEC_PER_HOUR },
2770 { "days", USEC_PER_DAY },
2771 { "day", USEC_PER_DAY },
2772 { "d", USEC_PER_DAY },
2773 { "weeks", USEC_PER_WEEK },
2774 { "week", USEC_PER_WEEK },
2775 { "w", USEC_PER_WEEK },
2776 { "years", USEC_PER_YEAR },
2777 { "year", USEC_PER_YEAR },
2778 { "y", USEC_PER_YEAR },
2781 { "", USEC_PER_SEC }, /* default is sec */
2797 l = strtoll(p, &e, 10);
2808 e += strspn(e, WHITESPACE);
2810 for (i = 0; i < ELEMENTSOF(table); i++)
2811 if (startswith(e, table[i].suffix)) {
2812 r += (usec_t) l * table[i].usec;
2813 p = e + strlen(table[i].suffix);
2817 if (i >= ELEMENTSOF(table))
2827 int parse_nsec(const char *t, nsec_t *nsec) {
2828 static const struct {
2832 { "seconds", NSEC_PER_SEC },
2833 { "second", NSEC_PER_SEC },
2834 { "sec", NSEC_PER_SEC },
2835 { "s", NSEC_PER_SEC },
2836 { "minutes", NSEC_PER_MINUTE },
2837 { "minute", NSEC_PER_MINUTE },
2838 { "min", NSEC_PER_MINUTE },
2839 { "months", NSEC_PER_MONTH },
2840 { "month", NSEC_PER_MONTH },
2841 { "msec", NSEC_PER_MSEC },
2842 { "ms", NSEC_PER_MSEC },
2843 { "m", NSEC_PER_MINUTE },
2844 { "hours", NSEC_PER_HOUR },
2845 { "hour", NSEC_PER_HOUR },
2846 { "hr", NSEC_PER_HOUR },
2847 { "h", NSEC_PER_HOUR },
2848 { "days", NSEC_PER_DAY },
2849 { "day", NSEC_PER_DAY },
2850 { "d", NSEC_PER_DAY },
2851 { "weeks", NSEC_PER_WEEK },
2852 { "week", NSEC_PER_WEEK },
2853 { "w", NSEC_PER_WEEK },
2854 { "years", NSEC_PER_YEAR },
2855 { "year", NSEC_PER_YEAR },
2856 { "y", NSEC_PER_YEAR },
2857 { "usec", NSEC_PER_USEC },
2858 { "us", NSEC_PER_USEC },
2861 { "", 1ULL }, /* default is nsec */
2877 l = strtoll(p, &e, 10);
2888 e += strspn(e, WHITESPACE);
2890 for (i = 0; i < ELEMENTSOF(table); i++)
2891 if (startswith(e, table[i].suffix)) {
2892 r += (nsec_t) l * table[i].nsec;
2893 p = e + strlen(table[i].suffix);
2897 if (i >= ELEMENTSOF(table))
2907 int parse_bytes(const char *t, off_t *bytes) {
2908 static const struct {
2914 { "M", 1024ULL*1024ULL },
2915 { "G", 1024ULL*1024ULL*1024ULL },
2916 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2917 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2918 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2935 l = strtoll(p, &e, 10);
2946 e += strspn(e, WHITESPACE);
2948 for (i = 0; i < ELEMENTSOF(table); i++)
2949 if (startswith(e, table[i].suffix)) {
2950 r += (off_t) l * table[i].factor;
2951 p = e + strlen(table[i].suffix);
2955 if (i >= ELEMENTSOF(table))
2965 int make_stdio(int fd) {
2970 r = dup3(fd, STDIN_FILENO, 0);
2971 s = dup3(fd, STDOUT_FILENO, 0);
2972 t = dup3(fd, STDERR_FILENO, 0);
2975 close_nointr_nofail(fd);
2977 if (r < 0 || s < 0 || t < 0)
2980 /* We rely here that the new fd has O_CLOEXEC not set */
2985 int make_null_stdio(void) {
2988 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2992 return make_stdio(null_fd);
2995 bool is_device_path(const char *path) {
2997 /* Returns true on paths that refer to a device, either in
2998 * sysfs or in /dev */
3001 path_startswith(path, "/dev/") ||
3002 path_startswith(path, "/sys/");
3005 int dir_is_empty(const char *path) {
3006 _cleanup_closedir_ DIR *d;
3015 union dirent_storage buf;
3017 r = readdir_r(d, &buf.de, &de);
3024 if (!ignore_file(de->d_name))
3029 unsigned long long random_ull(void) {
3030 _cleanup_close_ int fd;
3034 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3038 r = loop_read(fd, &ull, sizeof(ull), true);
3039 if (r != sizeof(ull))
3045 return random() * RAND_MAX + random();
3048 void rename_process(const char name[8]) {
3051 /* This is a like a poor man's setproctitle(). It changes the
3052 * comm field, argv[0], and also the glibc's internally used
3053 * name of the process. For the first one a limit of 16 chars
3054 * applies, to the second one usually one of 10 (i.e. length
3055 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3056 * "systemd"). If you pass a longer string it will be
3059 prctl(PR_SET_NAME, name);
3061 if (program_invocation_name)
3062 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3064 if (saved_argc > 0) {
3068 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3070 for (i = 1; i < saved_argc; i++) {
3074 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3079 void sigset_add_many(sigset_t *ss, ...) {
3086 while ((sig = va_arg(ap, int)) > 0)
3087 assert_se(sigaddset(ss, sig) == 0);
3091 char* gethostname_malloc(void) {
3094 assert_se(uname(&u) >= 0);
3096 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3097 return strdup(u.nodename);
3099 return strdup(u.sysname);
3102 bool hostname_is_set(void) {
3105 assert_se(uname(&u) >= 0);
3107 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3110 static char *lookup_uid(uid_t uid) {
3113 _cleanup_free_ char *buf = NULL;
3114 struct passwd pwbuf, *pw = NULL;
3116 /* Shortcut things to avoid NSS lookups */
3118 return strdup("root");
3120 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3124 buf = malloc(bufsize);
3128 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3129 return strdup(pw->pw_name);
3131 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3137 char* getlogname_malloc(void) {
3141 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3146 return lookup_uid(uid);
3149 char *getusername_malloc(void) {
3156 return lookup_uid(getuid());
3159 int getttyname_malloc(int fd, char **r) {
3160 char path[PATH_MAX], *c;
3165 k = ttyname_r(fd, path, sizeof(path));
3171 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3179 int getttyname_harder(int fd, char **r) {
3183 k = getttyname_malloc(fd, &s);
3187 if (streq(s, "tty")) {
3189 return get_ctty(0, NULL, r);
3196 int get_ctty_devnr(pid_t pid, dev_t *d) {
3198 char line[LINE_MAX], *p, *fn;
3199 unsigned long ttynr;
3202 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3205 f = fopen(fn, "re");
3210 if (!fgets(line, sizeof(line), f)) {
3211 k = feof(f) ? -EIO : -errno;
3218 p = strrchr(line, ')');
3228 "%*d " /* session */
3237 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3239 char fn[PATH_MAX], *s, *b, *p;
3244 k = get_ctty_devnr(pid, &devnr);
3248 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3251 if ((k = readlink_malloc(fn, &s)) < 0) {
3256 /* This is an ugly hack */
3257 if (major(devnr) == 136) {
3258 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3268 /* Probably something like the ptys which have no
3269 * symlink in /dev/char. Let's return something
3270 * vaguely useful. */
3272 if (!(b = strdup(fn + 5)))
3282 if (startswith(s, "/dev/"))
3284 else if (startswith(s, "../"))
3302 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3308 /* This returns the first error we run into, but nevertheless
3309 * tries to go on. This closes the passed fd. */
3313 close_nointr_nofail(fd);
3315 return errno == ENOENT ? 0 : -errno;
3320 union dirent_storage buf;
3321 bool is_dir, keep_around;
3325 r = readdir_r(d, &buf.de, &de);
3326 if (r != 0 && ret == 0) {
3334 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3337 if (de->d_type == DT_UNKNOWN ||
3339 (de->d_type == DT_DIR && root_dev)) {
3340 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3341 if (ret == 0 && errno != ENOENT)
3346 is_dir = S_ISDIR(st.st_mode);
3349 (st.st_uid == 0 || st.st_uid == getuid()) &&
3350 (st.st_mode & S_ISVTX);
3352 is_dir = de->d_type == DT_DIR;
3353 keep_around = false;
3359 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3360 if (root_dev && st.st_dev != root_dev->st_dev)
3363 subdir_fd = openat(fd, de->d_name,
3364 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3365 if (subdir_fd < 0) {
3366 if (ret == 0 && errno != ENOENT)
3371 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3372 if (r < 0 && ret == 0)
3376 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3377 if (ret == 0 && errno != ENOENT)
3381 } else if (!only_dirs && !keep_around) {
3383 if (unlinkat(fd, de->d_name, 0) < 0) {
3384 if (ret == 0 && errno != ENOENT)
3395 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3400 if (fstatfs(fd, &s) < 0) {
3401 close_nointr_nofail(fd);
3405 /* We refuse to clean disk file systems with this call. This
3406 * is extra paranoia just to be sure we never ever remove
3409 if (s.f_type != TMPFS_MAGIC &&
3410 s.f_type != RAMFS_MAGIC) {
3411 log_error("Attempted to remove disk file system, and we can't allow that.");
3412 close_nointr_nofail(fd);
3416 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3419 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3425 /* We refuse to clean the root file system with this
3426 * call. This is extra paranoia to never cause a really
3427 * seriously broken system. */
3428 if (path_equal(path, "/")) {
3429 log_error("Attempted to remove entire root file system, and we can't allow that.");
3433 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3436 if (errno != ENOTDIR)
3440 if (statfs(path, &s) < 0)
3443 if (s.f_type != TMPFS_MAGIC &&
3444 s.f_type != RAMFS_MAGIC) {
3445 log_error("Attempted to remove disk file system, and we can't allow that.");
3450 if (delete_root && !only_dirs)
3451 if (unlink(path) < 0 && errno != ENOENT)
3458 if (fstatfs(fd, &s) < 0) {
3459 close_nointr_nofail(fd);
3463 if (s.f_type != TMPFS_MAGIC &&
3464 s.f_type != RAMFS_MAGIC) {
3465 log_error("Attempted to remove disk file system, and we can't allow that.");
3466 close_nointr_nofail(fd);
3471 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3474 if (honour_sticky && file_is_priv_sticky(path) > 0)
3477 if (rmdir(path) < 0 && errno != ENOENT) {
3486 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3487 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3490 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3491 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3494 int chmod_and_chown(const char *path, 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 (mode != (mode_t) -1)
3502 if (chmod(path, mode) < 0)
3505 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3506 if (chown(path, uid, gid) < 0)
3512 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3515 /* Under the assumption that we are running privileged we
3516 * first change the access mode and only then hand out
3517 * ownership to avoid a window where access is too open. */
3519 if (fchmod(fd, mode) < 0)
3522 if (fchown(fd, uid, gid) < 0)
3528 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3532 /* Allocates the cpuset in the right size */
3535 if (!(r = CPU_ALLOC(n)))
3538 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3539 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3549 if (errno != EINVAL)
3556 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3557 static const char status_indent[] = " "; /* "[" STATUS "] " */
3558 _cleanup_free_ char *s = NULL;
3559 _cleanup_close_ int fd = -1;
3560 struct iovec iovec[5];
3565 /* This is independent of logging, as status messages are
3566 * optional and go exclusively to the console. */
3568 if (vasprintf(&s, format, ap) < 0)
3571 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3584 sl = status ? sizeof(status_indent)-1 : 0;
3590 e = ellipsize(s, emax, 75);
3600 if (!isempty(status)) {
3601 IOVEC_SET_STRING(iovec[n++], "[");
3602 IOVEC_SET_STRING(iovec[n++], status);
3603 IOVEC_SET_STRING(iovec[n++], "] ");
3605 IOVEC_SET_STRING(iovec[n++], status_indent);
3608 IOVEC_SET_STRING(iovec[n++], s);
3609 IOVEC_SET_STRING(iovec[n++], "\n");
3611 if (writev(fd, iovec, n) < 0)
3617 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3623 va_start(ap, format);
3624 r = status_vprintf(status, ellipse, format, ap);
3630 int status_welcome(void) {
3632 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3634 r = parse_env_file("/etc/os-release", NEWLINE,
3635 "PRETTY_NAME", &pretty_name,
3636 "ANSI_COLOR", &ansi_color,
3638 if (r < 0 && r != -ENOENT)
3639 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3641 return status_printf(NULL, false,
3642 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3643 isempty(ansi_color) ? "1" : ansi_color,
3644 isempty(pretty_name) ? "Linux" : pretty_name);
3647 char *replace_env(const char *format, char **env) {
3654 const char *e, *word = format;
3659 for (e = format; *e; e ++) {
3670 if (!(k = strnappend(r, word, e-word-1)))
3679 } else if (*e == '$') {
3680 if (!(k = strnappend(r, word, e-word)))
3696 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3699 if (!(k = strappend(r, t)))
3712 if (!(k = strnappend(r, word, e-word)))
3723 char **replace_env_argv(char **argv, char **env) {
3725 unsigned k = 0, l = 0;
3727 l = strv_length(argv);
3729 if (!(r = new(char*, l+1)))
3732 STRV_FOREACH(i, argv) {
3734 /* If $FOO appears as single word, replace it by the split up variable */
3735 if ((*i)[0] == '$' && (*i)[1] != '{') {
3740 if ((e = strv_env_get(env, *i+1))) {
3742 if (!(m = strv_split_quoted(e))) {
3753 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3762 memcpy(r + k, m, q * sizeof(char*));
3770 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3771 if (!(r[k++] = replace_env(*i, env))) {
3781 int fd_columns(int fd) {
3785 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3794 unsigned columns(void) {
3798 if (_likely_(cached_columns > 0))
3799 return cached_columns;
3802 e = getenv("COLUMNS");
3807 c = fd_columns(STDOUT_FILENO);
3816 int fd_lines(int fd) {
3820 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3829 unsigned lines(void) {
3833 if (_likely_(cached_lines > 0))
3834 return cached_lines;
3837 e = getenv("LINES");
3842 l = fd_lines(STDOUT_FILENO);
3848 return cached_lines;
3851 /* intended to be used as a SIGWINCH sighandler */
3852 void columns_lines_cache_reset(int signum) {
3858 static int cached_on_tty = -1;
3860 if (_unlikely_(cached_on_tty < 0))
3861 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3863 return cached_on_tty;
3866 int running_in_chroot(void) {
3872 /* Only works as root */
3874 if (stat("/proc/1/root", &a) < 0)
3877 if (stat("/", &b) < 0)
3881 a.st_dev != b.st_dev ||
3882 a.st_ino != b.st_ino;
3885 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3890 assert(percent <= 100);
3891 assert(new_length >= 3);
3893 if (old_length <= 3 || old_length <= new_length)
3894 return strndup(s, old_length);
3896 r = new0(char, new_length+1);
3900 x = (new_length * percent) / 100;
3902 if (x > new_length - 3)
3910 s + old_length - (new_length - x - 3),
3911 new_length - x - 3);
3916 char *ellipsize(const char *s, size_t length, unsigned percent) {
3917 return ellipsize_mem(s, strlen(s), length, percent);
3920 int touch(const char *path) {
3925 /* This just opens the file for writing, ensuring it
3926 * exists. It doesn't call utimensat() the way /usr/bin/touch
3929 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3933 close_nointr_nofail(fd);
3937 char *unquote(const char *s, const char* quotes) {
3941 /* This is rather stupid, simply removes the heading and
3942 * trailing quotes if there is one. Doesn't care about
3943 * escaping or anything. We should make this smarter one
3950 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3951 return strndup(s+1, l-2);
3956 char *normalize_env_assignment(const char *s) {
3957 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3960 eq = strchr(s, '=');
3972 memmove(r, t, strlen(t) + 1);
3976 name = strndup(s, eq - s);
3984 value = unquote(strstrip(p), QUOTES);
3988 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3994 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4005 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4017 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4024 r = wait_for_terminate(pid, &status);
4026 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4030 if (status.si_code == CLD_EXITED) {
4031 if (status.si_status != 0) {
4032 log_warning("%s failed with error code %i.", name, status.si_status);
4033 return status.si_status;
4036 log_debug("%s succeeded.", name);
4039 } else if (status.si_code == CLD_KILLED ||
4040 status.si_code == CLD_DUMPED) {
4042 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4046 log_warning("%s failed due to unknown reason.", name);
4050 _noreturn_ void freeze(void) {
4052 /* Make sure nobody waits for us on a socket anymore */
4053 close_all_fds(NULL, 0);
4061 bool null_or_empty(struct stat *st) {
4064 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4067 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4073 int null_or_empty_path(const char *fn) {
4078 if (stat(fn, &st) < 0)
4081 return null_or_empty(&st);
4084 DIR *xopendirat(int fd, const char *name, int flags) {
4088 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4094 close_nointr_nofail(nfd);
4101 int signal_from_string_try_harder(const char *s) {
4105 signo = signal_from_string(s);
4107 if (startswith(s, "SIG"))
4108 return signal_from_string(s+3);
4113 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4119 if (!dual_timestamp_is_set(t))
4122 fprintf(f, "%s=%llu %llu\n",
4124 (unsigned long long) t->realtime,
4125 (unsigned long long) t->monotonic);
4128 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4129 unsigned long long a, b;
4134 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4135 log_debug("Failed to parse finish timestamp value %s", value);
4142 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4146 /* FIXME: to follow udev's logic 100% we need to leave valid
4147 * UTF8 chars unescaped */
4149 u = unquote(tagvalue, "\"\'");
4153 t = xescape(u, "/ ");
4159 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4168 char *fstab_node_to_udev_node(const char *p) {
4171 if (startswith(p, "LABEL="))
4172 return tag_to_udev_node(p+6, "label");
4174 if (startswith(p, "UUID="))
4175 return tag_to_udev_node(p+5, "uuid");
4177 if (startswith(p, "PARTUUID="))
4178 return tag_to_udev_node(p+9, "partuuid");
4180 if (startswith(p, "PARTLABEL="))
4181 return tag_to_udev_node(p+10, "partlabel");
4186 bool tty_is_vc(const char *tty) {
4189 if (startswith(tty, "/dev/"))
4192 return vtnr_from_tty(tty) >= 0;
4195 bool tty_is_console(const char *tty) {
4198 if (startswith(tty, "/dev/"))
4201 return streq(tty, "console");
4204 int vtnr_from_tty(const char *tty) {
4209 if (startswith(tty, "/dev/"))
4212 if (!startswith(tty, "tty") )
4215 if (tty[3] < '0' || tty[3] > '9')
4218 r = safe_atoi(tty+3, &i);
4222 if (i < 0 || i > 63)
4228 bool tty_is_vc_resolve(const char *tty) {
4229 char *active = NULL;
4234 if (startswith(tty, "/dev/"))
4237 /* Resolve where /dev/console is pointing to, if /sys is
4238 * actually ours (i.e. not read-only-mounted which is a sign
4239 * for container setups) */
4240 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4241 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4242 /* If multiple log outputs are configured the
4243 * last one is what /dev/console points to */
4244 tty = strrchr(active, ' ');
4257 const char *default_term_for_tty(const char *tty) {
4260 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4263 bool dirent_is_file(const struct dirent *de) {
4266 if (ignore_file(de->d_name))
4269 if (de->d_type != DT_REG &&
4270 de->d_type != DT_LNK &&
4271 de->d_type != DT_UNKNOWN)
4277 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4280 if (de->d_type != DT_REG &&
4281 de->d_type != DT_LNK &&
4282 de->d_type != DT_UNKNOWN)
4285 if (ignore_file_allow_backup(de->d_name))
4288 return endswith(de->d_name, suffix);
4291 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4294 Hashmap *pids = NULL;
4298 /* Executes all binaries in a directory in parallel and waits
4299 * until all they all finished. */
4302 if (!(_d = opendir(directory))) {
4304 if (errno == ENOENT)
4307 log_error("Failed to enumerate directory %s: %m", directory);
4314 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4315 log_error("Failed to allocate set.");
4319 while ((de = readdir(d))) {
4324 if (!dirent_is_file(de))
4327 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4332 if ((pid = fork()) < 0) {
4333 log_error("Failed to fork: %m");
4351 log_error("Failed to execute %s: %m", path);
4352 _exit(EXIT_FAILURE);
4355 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4357 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4358 log_error("Failed to add PID to set: %s", strerror(-k));
4363 while (!hashmap_isempty(pids)) {
4364 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4369 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4374 log_error("waitid() failed: %m");
4378 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4379 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4380 if (si.si_code == CLD_EXITED)
4381 log_error("%s exited with exit status %i.", path, si.si_status);
4383 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4385 log_debug("%s exited successfully.", path);
4396 hashmap_free_free(pids);
4399 int kill_and_sigcont(pid_t pid, int sig) {
4402 r = kill(pid, sig) < 0 ? -errno : 0;
4410 bool nulstr_contains(const char*nulstr, const char *needle) {
4416 NULSTR_FOREACH(i, nulstr)
4417 if (streq(i, needle))
4423 bool plymouth_running(void) {
4424 return access("/run/plymouth/pid", F_OK) >= 0;
4427 char* strshorten(char *s, size_t l) {
4436 static bool hostname_valid_char(char c) {
4438 (c >= 'a' && c <= 'z') ||
4439 (c >= 'A' && c <= 'Z') ||
4440 (c >= '0' && c <= '9') ||
4446 bool hostname_is_valid(const char *s) {
4452 for (p = s; *p; p++)
4453 if (!hostname_valid_char(*p))
4456 if (p-s > HOST_NAME_MAX)
4462 char* hostname_cleanup(char *s) {
4465 for (p = s, d = s; *p; p++)
4466 if ((*p >= 'a' && *p <= 'z') ||
4467 (*p >= 'A' && *p <= 'Z') ||
4468 (*p >= '0' && *p <= '9') ||
4476 strshorten(s, HOST_NAME_MAX);
4480 int pipe_eof(int fd) {
4481 struct pollfd pollfd;
4486 pollfd.events = POLLIN|POLLHUP;
4488 r = poll(&pollfd, 1, 0);
4495 return pollfd.revents & POLLHUP;
4498 int fd_wait_for_event(int fd, int event, usec_t t) {
4499 struct pollfd pollfd;
4504 pollfd.events = event;
4506 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4513 return pollfd.revents;
4516 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4527 t = new(char, strlen(path) + 1 + 6 + 1);
4531 fn = path_get_file_name(path);
4535 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4537 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4543 f = fdopen(fd, "we");
4556 int terminal_vhangup_fd(int fd) {
4559 if (ioctl(fd, TIOCVHANGUP) < 0)
4565 int terminal_vhangup(const char *name) {
4568 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4572 r = terminal_vhangup_fd(fd);
4573 close_nointr_nofail(fd);
4578 int vt_disallocate(const char *name) {
4582 /* Deallocate the VT if possible. If not possible
4583 * (i.e. because it is the active one), at least clear it
4584 * entirely (including the scrollback buffer) */
4586 if (!startswith(name, "/dev/"))
4589 if (!tty_is_vc(name)) {
4590 /* So this is not a VT. I guess we cannot deallocate
4591 * it then. But let's at least clear the screen */
4593 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4598 "\033[r" /* clear scrolling region */
4599 "\033[H" /* move home */
4600 "\033[2J", /* clear screen */
4602 close_nointr_nofail(fd);
4607 if (!startswith(name, "/dev/tty"))
4610 r = safe_atou(name+8, &u);
4617 /* Try to deallocate */
4618 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4622 r = ioctl(fd, VT_DISALLOCATE, u);
4623 close_nointr_nofail(fd);
4631 /* Couldn't deallocate, so let's clear it fully with
4633 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4638 "\033[r" /* clear scrolling region */
4639 "\033[H" /* move home */
4640 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4642 close_nointr_nofail(fd);
4647 int copy_file(const char *from, const char *to) {
4653 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4657 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4659 close_nointr_nofail(fdf);
4667 n = read(fdf, buf, sizeof(buf));
4671 close_nointr_nofail(fdf);
4682 k = loop_write(fdt, buf, n, false);
4684 r = k < 0 ? k : (errno ? -errno : -EIO);
4686 close_nointr_nofail(fdf);
4694 close_nointr_nofail(fdf);
4695 r = close_nointr(fdt);
4705 int symlink_atomic(const char *from, const char *to) {
4707 _cleanup_free_ char *t;
4710 unsigned long long ull;
4717 t = new(char, strlen(to) + 1 + 16 + 1);
4721 fn = path_get_file_name(to);
4725 x = stpcpy(t+k+1, fn);
4728 for (i = 0; i < 16; i++) {
4729 *(x++) = hexchar(ull & 0xF);
4735 if (symlink(from, t) < 0)
4738 if (rename(t, to) < 0) {
4747 bool display_is_local(const char *display) {
4751 display[0] == ':' &&
4752 display[1] >= '0' &&
4756 int socket_from_display(const char *display, char **path) {
4763 if (!display_is_local(display))
4766 k = strspn(display+1, "0123456789");
4768 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4772 c = stpcpy(f, "/tmp/.X11-unix/X");
4773 memcpy(c, display+1, k);
4782 const char **username,
4783 uid_t *uid, gid_t *gid,
4785 const char **shell) {
4793 /* We enforce some special rules for uid=0: in order to avoid
4794 * NSS lookups for root we hardcode its data. */
4796 if (streq(*username, "root") || streq(*username, "0")) {
4814 if (parse_uid(*username, &u) >= 0) {
4818 /* If there are multiple users with the same id, make
4819 * sure to leave $USER to the configured value instead
4820 * of the first occurrence in the database. However if
4821 * the uid was configured by a numeric uid, then let's
4822 * pick the real username from /etc/passwd. */
4824 *username = p->pw_name;
4827 p = getpwnam(*username);
4831 return errno != 0 ? -errno : -ESRCH;
4843 *shell = p->pw_shell;
4848 int get_group_creds(const char **groupname, gid_t *gid) {
4854 /* We enforce some special rules for gid=0: in order to avoid
4855 * NSS lookups for root we hardcode its data. */
4857 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4858 *groupname = "root";
4866 if (parse_gid(*groupname, &id) >= 0) {
4871 *groupname = g->gr_name;
4874 g = getgrnam(*groupname);
4878 return errno != 0 ? -errno : -ESRCH;
4886 int in_group(const char *name) {
4888 int ngroups_max, r, i;
4890 r = get_group_creds(&name, &gid);
4894 if (getgid() == gid)
4897 if (getegid() == gid)
4900 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4901 assert(ngroups_max > 0);
4903 gids = alloca(sizeof(gid_t) * ngroups_max);
4905 r = getgroups(ngroups_max, gids);
4909 for (i = 0; i < r; i++)
4916 int glob_exists(const char *path) {
4924 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4926 if (k == GLOB_NOMATCH)
4928 else if (k == GLOB_NOSPACE)
4931 r = !strv_isempty(g.gl_pathv);
4933 r = errno ? -errno : -EIO;
4940 int dirent_ensure_type(DIR *d, struct dirent *de) {
4946 if (de->d_type != DT_UNKNOWN)
4949 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4953 S_ISREG(st.st_mode) ? DT_REG :
4954 S_ISDIR(st.st_mode) ? DT_DIR :
4955 S_ISLNK(st.st_mode) ? DT_LNK :
4956 S_ISFIFO(st.st_mode) ? DT_FIFO :
4957 S_ISSOCK(st.st_mode) ? DT_SOCK :
4958 S_ISCHR(st.st_mode) ? DT_CHR :
4959 S_ISBLK(st.st_mode) ? DT_BLK :
4965 int in_search_path(const char *path, char **search) {
4969 r = path_get_parent(path, &parent);
4975 STRV_FOREACH(i, search) {
4976 if (path_equal(parent, *i)) {
4987 int get_files_in_directory(const char *path, char ***list) {
4995 /* Returns all files in a directory in *list, and the number
4996 * of files as return value. If list is NULL returns only the
5005 union dirent_storage buf;
5008 k = readdir_r(d, &buf.de, &de);
5017 dirent_ensure_type(d, de);
5019 if (!dirent_is_file(de))
5023 if ((unsigned) r >= n) {
5027 t = realloc(l, sizeof(char*) * n);
5036 assert((unsigned) r < n);
5038 l[r] = strdup(de->d_name);
5062 char *strjoin(const char *x, ...) {
5076 t = va_arg(ap, const char *);
5081 if (n > ((size_t) -1) - l) {
5105 t = va_arg(ap, const char *);
5119 bool is_main_thread(void) {
5120 static __thread int cached = 0;
5122 if (_unlikely_(cached == 0))
5123 cached = getpid() == gettid() ? 1 : -1;
5128 int block_get_whole_disk(dev_t d, dev_t *ret) {
5135 /* If it has a queue this is good enough for us */
5136 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5139 r = access(p, F_OK);
5147 /* If it is a partition find the originating device */
5148 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5151 r = access(p, F_OK);
5157 /* Get parent dev_t */
5158 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5161 r = read_one_line_file(p, &s);
5167 r = sscanf(s, "%u:%u", &m, &n);
5173 /* Only return this if it is really good enough for us. */
5174 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5177 r = access(p, F_OK);
5181 *ret = makedev(m, n);
5188 int file_is_priv_sticky(const char *p) {
5193 if (lstat(p, &st) < 0)
5197 (st.st_uid == 0 || st.st_uid == getuid()) &&
5198 (st.st_mode & S_ISVTX);
5201 static const char *const ioprio_class_table[] = {
5202 [IOPRIO_CLASS_NONE] = "none",
5203 [IOPRIO_CLASS_RT] = "realtime",
5204 [IOPRIO_CLASS_BE] = "best-effort",
5205 [IOPRIO_CLASS_IDLE] = "idle"
5208 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5210 static const char *const sigchld_code_table[] = {
5211 [CLD_EXITED] = "exited",
5212 [CLD_KILLED] = "killed",
5213 [CLD_DUMPED] = "dumped",
5214 [CLD_TRAPPED] = "trapped",
5215 [CLD_STOPPED] = "stopped",
5216 [CLD_CONTINUED] = "continued",
5219 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5221 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5222 [LOG_FAC(LOG_KERN)] = "kern",
5223 [LOG_FAC(LOG_USER)] = "user",
5224 [LOG_FAC(LOG_MAIL)] = "mail",
5225 [LOG_FAC(LOG_DAEMON)] = "daemon",
5226 [LOG_FAC(LOG_AUTH)] = "auth",
5227 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5228 [LOG_FAC(LOG_LPR)] = "lpr",
5229 [LOG_FAC(LOG_NEWS)] = "news",
5230 [LOG_FAC(LOG_UUCP)] = "uucp",
5231 [LOG_FAC(LOG_CRON)] = "cron",
5232 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5233 [LOG_FAC(LOG_FTP)] = "ftp",
5234 [LOG_FAC(LOG_LOCAL0)] = "local0",
5235 [LOG_FAC(LOG_LOCAL1)] = "local1",
5236 [LOG_FAC(LOG_LOCAL2)] = "local2",
5237 [LOG_FAC(LOG_LOCAL3)] = "local3",
5238 [LOG_FAC(LOG_LOCAL4)] = "local4",
5239 [LOG_FAC(LOG_LOCAL5)] = "local5",
5240 [LOG_FAC(LOG_LOCAL6)] = "local6",
5241 [LOG_FAC(LOG_LOCAL7)] = "local7"
5244 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5246 static const char *const log_level_table[] = {
5247 [LOG_EMERG] = "emerg",
5248 [LOG_ALERT] = "alert",
5249 [LOG_CRIT] = "crit",
5251 [LOG_WARNING] = "warning",
5252 [LOG_NOTICE] = "notice",
5253 [LOG_INFO] = "info",
5254 [LOG_DEBUG] = "debug"
5257 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5259 static const char* const sched_policy_table[] = {
5260 [SCHED_OTHER] = "other",
5261 [SCHED_BATCH] = "batch",
5262 [SCHED_IDLE] = "idle",
5263 [SCHED_FIFO] = "fifo",
5267 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5269 static const char* const rlimit_table[] = {
5270 [RLIMIT_CPU] = "LimitCPU",
5271 [RLIMIT_FSIZE] = "LimitFSIZE",
5272 [RLIMIT_DATA] = "LimitDATA",
5273 [RLIMIT_STACK] = "LimitSTACK",
5274 [RLIMIT_CORE] = "LimitCORE",
5275 [RLIMIT_RSS] = "LimitRSS",
5276 [RLIMIT_NOFILE] = "LimitNOFILE",
5277 [RLIMIT_AS] = "LimitAS",
5278 [RLIMIT_NPROC] = "LimitNPROC",
5279 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5280 [RLIMIT_LOCKS] = "LimitLOCKS",
5281 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5282 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5283 [RLIMIT_NICE] = "LimitNICE",
5284 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5285 [RLIMIT_RTTIME] = "LimitRTTIME"
5288 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5290 static const char* const ip_tos_table[] = {
5291 [IPTOS_LOWDELAY] = "low-delay",
5292 [IPTOS_THROUGHPUT] = "throughput",
5293 [IPTOS_RELIABILITY] = "reliability",
5294 [IPTOS_LOWCOST] = "low-cost",
5297 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5299 static const char *const __signal_table[] = {
5316 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5327 [SIGVTALRM] = "VTALRM",
5329 [SIGWINCH] = "WINCH",
5335 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5337 const char *signal_to_string(int signo) {
5338 static __thread char buf[12];
5341 name = __signal_to_string(signo);
5345 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5346 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5348 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5353 int signal_from_string(const char *s) {
5358 signo = __signal_from_string(s);
5362 if (startswith(s, "RTMIN+")) {
5366 if (safe_atou(s, &u) >= 0) {
5367 signo = (int) u + offset;
5368 if (signo > 0 && signo < _NSIG)
5374 bool kexec_loaded(void) {
5375 bool loaded = false;
5378 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5386 int strdup_or_null(const char *a, char **b) {
5404 int prot_from_flags(int flags) {
5406 switch (flags & O_ACCMODE) {
5415 return PROT_READ|PROT_WRITE;
5422 char *format_bytes(char *buf, size_t l, off_t t) {
5425 static const struct {
5429 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5430 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5431 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5432 { "G", 1024ULL*1024ULL*1024ULL },
5433 { "M", 1024ULL*1024ULL },
5437 for (i = 0; i < ELEMENTSOF(table); i++) {
5439 if (t >= table[i].factor) {
5442 (unsigned long long) (t / table[i].factor),
5443 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5450 snprintf(buf, l, "%lluB", (unsigned long long) t);
5458 void* memdup(const void *p, size_t l) {
5471 int fd_inc_sndbuf(int fd, size_t n) {
5473 socklen_t l = sizeof(value);
5475 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5477 l == sizeof(value) &&
5478 (size_t) value >= n*2)
5482 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5489 int fd_inc_rcvbuf(int fd, size_t n) {
5491 socklen_t l = sizeof(value);
5493 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5495 l == sizeof(value) &&
5496 (size_t) value >= n*2)
5500 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5507 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5508 pid_t parent_pid, agent_pid;
5510 bool stdout_is_tty, stderr_is_tty;
5518 parent_pid = getpid();
5520 /* Spawns a temporary TTY agent, making sure it goes away when
5527 if (agent_pid != 0) {
5534 * Make sure the agent goes away when the parent dies */
5535 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5536 _exit(EXIT_FAILURE);
5538 /* Check whether our parent died before we were able
5539 * to set the death signal */
5540 if (getppid() != parent_pid)
5541 _exit(EXIT_SUCCESS);
5543 /* Don't leak fds to the agent */
5544 close_all_fds(except, n_except);
5546 stdout_is_tty = isatty(STDOUT_FILENO);
5547 stderr_is_tty = isatty(STDERR_FILENO);
5549 if (!stdout_is_tty || !stderr_is_tty) {
5550 /* Detach from stdout/stderr. and reopen
5551 * /dev/tty for them. This is important to
5552 * ensure that when systemctl is started via
5553 * popen() or a similar call that expects to
5554 * read EOF we actually do generate EOF and
5555 * not delay this indefinitely by because we
5556 * keep an unused copy of stdin around. */
5557 fd = open("/dev/tty", O_WRONLY);
5559 log_error("Failed to open /dev/tty: %m");
5560 _exit(EXIT_FAILURE);
5564 dup2(fd, STDOUT_FILENO);
5567 dup2(fd, STDERR_FILENO);
5573 /* Count arguments */
5575 for (n = 0; va_arg(ap, char*); n++)
5580 l = alloca(sizeof(char *) * (n + 1));
5582 /* Fill in arguments */
5584 for (i = 0; i <= n; i++)
5585 l[i] = va_arg(ap, char*);
5589 _exit(EXIT_FAILURE);
5592 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5593 struct rlimit highest, fixed;
5597 if (setrlimit(resource, rlim) >= 0)
5603 /* So we failed to set the desired setrlimit, then let's try
5604 * to get as close as we can */
5605 assert_se(getrlimit(resource, &highest) == 0);
5607 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5608 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5610 if (setrlimit(resource, &fixed) < 0)
5616 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5617 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5629 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5632 f = fopen(path, "re");
5640 char line[LINE_MAX];
5643 for (i = 0; i < sizeof(line)-1; i++) {
5647 if (_unlikely_(c == EOF)) {
5657 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5658 value = strdup(line + l + 1);
5678 int can_sleep(const char *type) {
5682 _cleanup_free_ char *p = NULL;
5686 r = read_one_line_file("/sys/power/state", &p);
5688 return r == -ENOENT ? 0 : r;
5691 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5692 if (l == k && memcmp(w, type, l) == 0)
5698 bool is_valid_documentation_url(const char *url) {
5701 if (startswith(url, "http://") && url[7])
5704 if (startswith(url, "https://") && url[8])
5707 if (startswith(url, "file:") && url[5])
5710 if (startswith(url, "info:") && url[5])
5713 if (startswith(url, "man:") && url[4])
5719 bool in_initrd(void) {
5720 static __thread int saved = -1;
5726 /* We make two checks here:
5728 * 1. the flag file /etc/initrd-release must exist
5729 * 2. the root file system must be a memory file system
5731 * The second check is extra paranoia, since misdetecting an
5732 * initrd can have bad bad consequences due the initrd
5733 * emptying when transititioning to the main systemd.
5736 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5737 statfs("/", &s) >= 0 &&
5738 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5743 void warn_melody(void) {
5744 _cleanup_close_ int fd = -1;
5746 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5750 /* Yeah, this is synchronous. Kinda sucks. But well... */
5752 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5753 usleep(125*USEC_PER_MSEC);
5755 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5756 usleep(125*USEC_PER_MSEC);
5758 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5759 usleep(125*USEC_PER_MSEC);
5761 ioctl(fd, KIOCSOUND, 0);
5764 int make_console_stdio(void) {
5767 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5769 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5771 log_error("Failed to acquire terminal: %s", strerror(-fd));
5777 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5784 int get_home_dir(char **_h) {
5792 /* Take the user specified one */
5803 /* Hardcode home directory for root to avoid NSS */
5806 h = strdup("/root");
5814 /* Check the database... */
5818 return errno ? -errno : -ESRCH;
5820 if (!path_is_absolute(p->pw_dir))
5823 h = strdup(p->pw_dir);
5831 int get_shell(char **_sh) {
5839 /* Take the user specified one */
5840 e = getenv("SHELL");
5850 /* Hardcode home directory for root to avoid NSS */
5853 sh = strdup("/bin/sh");
5861 /* Check the database... */
5865 return errno ? -errno : -ESRCH;
5867 if (!path_is_absolute(p->pw_shell))
5870 sh = strdup(p->pw_shell);
5878 void freep(void *p) {
5882 void fclosep(FILE **f) {
5887 void closep(int *fd) {
5889 close_nointr_nofail(*fd);
5892 void closedirp(DIR **d) {
5897 void umaskp(mode_t *u) {
5901 bool filename_is_safe(const char *p) {
5915 if (strlen(p) > FILENAME_MAX)
5921 bool string_is_safe(const char *p) {
5926 for (t = p; *t; t++) {
5927 if (*t > 0 && *t < ' ')
5930 if (strchr("\\\"\'", *t))
5937 int parse_timestamp(const char *t, usec_t *usec) {
5941 usec_t plus = 0, minus = 0, ret;
5947 * 2012-09-22 16:34:22
5948 * 2012-09-22 16:34 (seconds will be set to 0)
5949 * 2012-09-22 (time will be set to 00:00:00)
5950 * 16:34:22 (date will be set to today)
5951 * 16:34 (date will be set to today, seconds to 0)
5953 * yesterday (time is set to 00:00:00)
5954 * today (time is set to 00:00:00)
5955 * tomorrow (time is set to 00:00:00)
5965 assert_se(localtime_r(&x, &tm));
5967 if (streq(t, "now"))
5970 else if (streq(t, "today")) {
5971 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5974 } else if (streq(t, "yesterday")) {
5976 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5979 } else if (streq(t, "tomorrow")) {
5981 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5984 } else if (t[0] == '+') {
5986 r = parse_usec(t+1, &plus);
5991 } else if (t[0] == '-') {
5993 r = parse_usec(t+1, &minus);
6001 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6006 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6011 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6018 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6025 k = strptime(t, "%y-%m-%d", &tm);
6027 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6032 k = strptime(t, "%Y-%m-%d", &tm);
6034 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6039 k = strptime(t, "%H:%M:%S", &tm);
6044 k = strptime(t, "%H:%M", &tm);
6054 if (x == (time_t) -1)
6057 ret = (usec_t) x * USEC_PER_SEC;