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>
70 #include "path-util.h"
71 #include "exit-status.h"
75 char **saved_argv = NULL;
77 static volatile unsigned cached_columns = 0;
78 static volatile unsigned cached_lines = 0;
80 bool is_efiboot(void) {
81 return access("/sys/firmware/efi", F_OK) >= 0;
84 size_t page_size(void) {
85 static __thread size_t pgsz = 0;
88 if (_likely_(pgsz > 0))
91 r = sysconf(_SC_PAGESIZE);
98 bool streq_ptr(const char *a, const char *b) {
100 /* Like streq(), but tries to make sense of NULL pointers */
111 usec_t now(clockid_t clock_id) {
114 assert_se(clock_gettime(clock_id, &ts) == 0);
116 return timespec_load(&ts);
119 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
122 ts->realtime = now(CLOCK_REALTIME);
123 ts->monotonic = now(CLOCK_MONOTONIC);
128 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
137 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
139 ts->monotonic = now(CLOCK_MONOTONIC);
141 if ((int64_t) ts->monotonic > delta)
142 ts->monotonic -= delta;
150 usec_t timespec_load(const struct timespec *ts) {
153 if (ts->tv_sec == (time_t) -1 &&
154 ts->tv_nsec == (long) -1)
157 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
161 (usec_t) ts->tv_sec * USEC_PER_SEC +
162 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
165 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
168 if (u == (usec_t) -1) {
169 ts->tv_sec = (time_t) -1;
170 ts->tv_nsec = (long) -1;
174 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
175 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
180 usec_t timeval_load(const struct timeval *tv) {
183 if (tv->tv_sec == (time_t) -1 &&
184 tv->tv_usec == (suseconds_t) -1)
187 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
191 (usec_t) tv->tv_sec * USEC_PER_SEC +
192 (usec_t) tv->tv_usec;
195 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
198 if (u == (usec_t) -1) {
199 tv->tv_sec = (time_t) -1;
200 tv->tv_usec = (suseconds_t) -1;
204 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
205 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
210 char* endswith(const char *s, const char *postfix) {
217 pl = strlen(postfix);
220 return (char*) s + sl;
225 if (memcmp(s + sl - pl, postfix, pl) != 0)
228 return (char*) s + sl - pl;
231 char* startswith(const char *s, const char *prefix) {
248 char* startswith_no_case(const char *s, const char *prefix) {
258 if (tolower(*a) != tolower(*b))
265 bool first_word(const char *s, const char *word) {
280 if (memcmp(s, word, wl) != 0)
284 strchr(WHITESPACE, s[wl]);
287 int close_nointr(int fd) {
302 void close_nointr_nofail(int fd) {
303 int saved_errno = errno;
305 /* like close_nointr() but cannot fail, and guarantees errno
308 assert_se(close_nointr(fd) == 0);
313 void close_many(const int fds[], unsigned n_fd) {
316 for (i = 0; i < n_fd; i++)
317 close_nointr_nofail(fds[i]);
320 int parse_boolean(const char *v) {
323 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
325 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
331 int parse_pid(const char *s, pid_t* ret_pid) {
332 unsigned long ul = 0;
339 r = safe_atolu(s, &ul);
345 if ((unsigned long) pid != ul)
355 int parse_uid(const char *s, uid_t* ret_uid) {
356 unsigned long ul = 0;
363 r = safe_atolu(s, &ul);
369 if ((unsigned long) uid != ul)
376 int safe_atou(const char *s, unsigned *ret_u) {
384 l = strtoul(s, &x, 0);
386 if (!x || x == s || *x || errno)
387 return errno ? -errno : -EINVAL;
389 if ((unsigned long) (unsigned) l != l)
392 *ret_u = (unsigned) l;
396 int safe_atoi(const char *s, int *ret_i) {
404 l = strtol(s, &x, 0);
406 if (!x || x == s || *x || errno)
407 return errno ? -errno : -EINVAL;
409 if ((long) (int) l != l)
416 int safe_atollu(const char *s, long long unsigned *ret_llu) {
418 unsigned long long l;
424 l = strtoull(s, &x, 0);
426 if (!x || x == s || *x || errno)
427 return errno ? -errno : -EINVAL;
433 int safe_atolli(const char *s, long long int *ret_lli) {
441 l = strtoll(s, &x, 0);
443 if (!x || x == s || *x || errno)
444 return errno ? -errno : -EINVAL;
450 /* Split a string into words. */
451 char *split(const char *c, size_t *l, const char *separator, char **state) {
454 current = *state ? *state : (char*) c;
456 if (!*current || *c == 0)
459 current += strspn(current, separator);
460 *l = strcspn(current, separator);
463 return (char*) current;
466 /* Split a string into words, but consider strings enclosed in '' and
467 * "" as words even if they include spaces. */
468 char *split_quoted(const char *c, size_t *l, char **state) {
470 bool escaped = false;
472 current = *state ? *state : (char*) c;
474 if (!*current || *c == 0)
477 current += strspn(current, WHITESPACE);
479 if (*current == '\'') {
482 for (e = current; *e; e++) {
492 *state = *e == 0 ? e : e+1;
493 } else if (*current == '\"') {
496 for (e = current; *e; e++) {
506 *state = *e == 0 ? e : e+1;
508 for (e = current; *e; e++) {
513 else if (strchr(WHITESPACE, *e))
520 return (char*) current;
523 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
525 _cleanup_fclose_ FILE *f = NULL;
526 char fn[PATH_MAX], line[LINE_MAX], *p;
532 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
539 if (!fgets(line, sizeof(line), f)) {
540 r = feof(f) ? -EIO : -errno;
545 /* Let's skip the pid and comm fields. The latter is enclosed
546 * in () but does not escape any () in its value, so let's
547 * skip over it manually */
549 p = strrchr(line, ')');
561 if ((long unsigned) (pid_t) ppid != ppid)
564 *_ppid = (pid_t) ppid;
569 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
570 _cleanup_fclose_ FILE *f = NULL;
571 char fn[PATH_MAX], line[LINE_MAX], *p;
576 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
583 if (!fgets(line, sizeof(line), f)) {
590 /* Let's skip the pid and comm fields. The latter is enclosed
591 * in () but does not escape any () in its value, so let's
592 * skip over it manually */
594 p = strrchr(line, ')');
616 "%*d " /* priority */
618 "%*d " /* num_threads */
619 "%*d " /* itrealvalue */
620 "%llu " /* starttime */,
627 int write_one_line_file(const char *fn, const char *line) {
628 _cleanup_fclose_ FILE *f = NULL;
638 if (fputs(line, f) < 0)
639 return errno ? -errno : -EIO;
641 if (!endswith(line, "\n"))
647 return errno ? -errno : -EIO;
652 int fchmod_umask(int fd, mode_t m) {
657 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
663 int write_one_line_file_atomic(const char *fn, const char *line) {
671 r = fopen_temporary(fn, &f, &p);
675 fchmod_umask(fileno(f), 0644);
678 if (fputs(line, f) < 0) {
683 if (!endswith(line, "\n"))
694 if (rename(p, fn) < 0)
710 int read_one_line_file(const char *fn, char **line) {
711 _cleanup_fclose_ FILE *f = NULL;
712 char t[LINE_MAX], *c;
721 if (!fgets(t, sizeof(t), f)) {
724 return errno ? -errno : -EIO;
738 int read_full_file(const char *fn, char **contents, size_t *size) {
739 _cleanup_fclose_ FILE *f = NULL;
741 _cleanup_free_ char *buf = NULL;
748 if (fstat(fileno(f), &st) < 0)
752 if (st.st_size > 4*1024*1024)
755 n = st.st_size > 0 ? st.st_size : LINE_MAX;
762 t = realloc(buf, n+1);
767 k = fread(buf + l, 1, n - l, f);
796 const char *separator, ...) {
799 char *contents = NULL, *p;
804 if ((r = read_full_file(fname, &contents, NULL)) < 0)
809 const char *key = NULL;
811 p += strspn(p, separator);
812 p += strspn(p, WHITESPACE);
817 if (!strchr(COMMENTS, *p)) {
821 va_start(ap, separator);
822 while ((key = va_arg(ap, char *))) {
826 value = va_arg(ap, char **);
829 if (strncmp(p, key, n) != 0 ||
834 n = strcspn(p, separator);
837 strchr(QUOTES, p[0]) &&
839 v = strndup(p+1, n-2);
850 /* return empty value strings as NULL */
867 p += strcspn(p, separator);
886 if (!(f = fopen(fname, "re")))
890 char l[LINE_MAX], *p, *u;
893 if (!fgets(l, sizeof(l), f)) {
906 if (strchr(COMMENTS, *p))
909 if (!(u = normalize_env_assignment(p))) {
914 t = strv_append(m, u);
940 int write_env_file(const char *fname, char **l) {
945 r = fopen_temporary(fname, &f, &p);
949 fchmod_umask(fileno(f), 0644);
965 if (rename(p, fname) < 0)
980 char *truncate_nl(char *s) {
983 s[strcspn(s, NEWLINE)] = 0;
987 int get_process_comm(pid_t pid, char **name) {
993 r = read_one_line_file("/proc/self/comm", name);
996 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
999 r = read_one_line_file(p, name);
1006 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1013 assert(max_length > 0);
1017 f = fopen("/proc/self/cmdline", "re");
1020 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1030 r = new(char, max_length);
1038 while ((c = getc(f)) != EOF) {
1060 size_t n = MIN(left-1, 3U);
1061 memcpy(k, "...", n);
1068 /* Kernel threads have no argv[] */
1078 h = get_process_comm(pid, &t);
1082 r = strjoin("[", t, "]", NULL);
1093 int is_kernel_thread(pid_t pid) {
1103 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1112 count = fread(&c, 1, 1, f);
1116 /* Kernel threads have an empty cmdline */
1119 return eof ? 1 : -errno;
1124 int get_process_exe(pid_t pid, char **name) {
1130 r = readlink_malloc("/proc/self/exe", name);
1133 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1136 r = readlink_malloc(p, name);
1143 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1153 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1163 char line[LINE_MAX], *l;
1165 if (!fgets(line, sizeof(line), f)) {
1175 if (startswith(l, field)) {
1177 l += strspn(l, WHITESPACE);
1179 l[strcspn(l, WHITESPACE)] = 0;
1181 r = parse_uid(l, uid);
1194 int get_process_uid(pid_t pid, uid_t *uid) {
1195 return get_process_id(pid, "Uid:", uid);
1198 int get_process_gid(pid_t pid, gid_t *gid) {
1199 return get_process_id(pid, "Gid:", gid);
1202 char *strnappend(const char *s, const char *suffix, size_t b) {
1210 return strndup(suffix, b);
1219 if (b > ((size_t) -1) - a)
1222 r = new(char, a+b+1);
1227 memcpy(r+a, suffix, b);
1233 char *strappend(const char *s, const char *suffix) {
1234 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1237 int readlink_malloc(const char *p, char **r) {
1247 if (!(c = new(char, l)))
1250 if ((n = readlink(p, c, l-1)) < 0) {
1256 if ((size_t) n < l-1) {
1267 int readlink_and_make_absolute(const char *p, char **r) {
1274 if ((j = readlink_malloc(p, &target)) < 0)
1277 k = file_in_same_dir(p, target);
1287 int readlink_and_canonicalize(const char *p, char **r) {
1294 j = readlink_and_make_absolute(p, &t);
1298 s = canonicalize_file_name(t);
1305 path_kill_slashes(*r);
1310 int reset_all_signal_handlers(void) {
1313 for (sig = 1; sig < _NSIG; sig++) {
1314 struct sigaction sa;
1316 if (sig == SIGKILL || sig == SIGSTOP)
1320 sa.sa_handler = SIG_DFL;
1321 sa.sa_flags = SA_RESTART;
1323 /* On Linux the first two RT signals are reserved by
1324 * glibc, and sigaction() will return EINVAL for them. */
1325 if ((sigaction(sig, &sa, NULL) < 0))
1326 if (errno != EINVAL)
1333 char *strstrip(char *s) {
1336 /* Drops trailing whitespace. Modifies the string in
1337 * place. Returns pointer to first non-space character */
1339 s += strspn(s, WHITESPACE);
1341 for (e = strchr(s, 0); e > s; e --)
1342 if (!strchr(WHITESPACE, e[-1]))
1350 char *delete_chars(char *s, const char *bad) {
1353 /* Drops all whitespace, regardless where in the string */
1355 for (f = s, t = s; *f; f++) {
1356 if (strchr(bad, *f))
1367 bool in_charset(const char *s, const char* charset) {
1373 for (i = s; *i; i++)
1374 if (!strchr(charset, *i))
1380 char *file_in_same_dir(const char *path, const char *filename) {
1387 /* This removes the last component of path and appends
1388 * filename, unless the latter is absolute anyway or the
1391 if (path_is_absolute(filename))
1392 return strdup(filename);
1394 if (!(e = strrchr(path, '/')))
1395 return strdup(filename);
1397 k = strlen(filename);
1398 if (!(r = new(char, e-path+1+k+1)))
1401 memcpy(r, path, e-path+1);
1402 memcpy(r+(e-path)+1, filename, k+1);
1407 int rmdir_parents(const char *path, const char *stop) {
1416 /* Skip trailing slashes */
1417 while (l > 0 && path[l-1] == '/')
1423 /* Skip last component */
1424 while (l > 0 && path[l-1] != '/')
1427 /* Skip trailing slashes */
1428 while (l > 0 && path[l-1] == '/')
1434 if (!(t = strndup(path, l)))
1437 if (path_startswith(stop, t)) {
1446 if (errno != ENOENT)
1454 char hexchar(int x) {
1455 static const char table[16] = "0123456789abcdef";
1457 return table[x & 15];
1460 int unhexchar(char c) {
1462 if (c >= '0' && c <= '9')
1465 if (c >= 'a' && c <= 'f')
1466 return c - 'a' + 10;
1468 if (c >= 'A' && c <= 'F')
1469 return c - 'A' + 10;
1474 char octchar(int x) {
1475 return '0' + (x & 7);
1478 int unoctchar(char c) {
1480 if (c >= '0' && c <= '7')
1486 char decchar(int x) {
1487 return '0' + (x % 10);
1490 int undecchar(char c) {
1492 if (c >= '0' && c <= '9')
1498 char *cescape(const char *s) {
1504 /* Does C style string escaping. */
1506 r = new(char, strlen(s)*4 + 1);
1510 for (f = s, t = r; *f; f++)
1556 /* For special chars we prefer octal over
1557 * hexadecimal encoding, simply because glib's
1558 * g_strescape() does the same */
1559 if ((*f < ' ') || (*f >= 127)) {
1561 *(t++) = octchar((unsigned char) *f >> 6);
1562 *(t++) = octchar((unsigned char) *f >> 3);
1563 *(t++) = octchar((unsigned char) *f);
1574 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1581 /* Undoes C style string escaping, and optionally prefixes it. */
1583 pl = prefix ? strlen(prefix) : 0;
1585 r = new(char, pl+length+1);
1590 memcpy(r, prefix, pl);
1592 for (f = s, t = r + pl; f < s + length; f++) {
1635 /* This is an extension of the XDG syntax files */
1640 /* hexadecimal encoding */
1643 a = unhexchar(f[1]);
1644 b = unhexchar(f[2]);
1646 if (a < 0 || b < 0) {
1647 /* Invalid escape code, let's take it literal then */
1651 *(t++) = (char) ((a << 4) | b);
1666 /* octal encoding */
1669 a = unoctchar(f[0]);
1670 b = unoctchar(f[1]);
1671 c = unoctchar(f[2]);
1673 if (a < 0 || b < 0 || c < 0) {
1674 /* Invalid escape code, let's take it literal then */
1678 *(t++) = (char) ((a << 6) | (b << 3) | c);
1686 /* premature end of string.*/
1691 /* Invalid escape code, let's take it literal then */
1703 char *cunescape_length(const char *s, size_t length) {
1704 return cunescape_length_with_prefix(s, length, NULL);
1707 char *cunescape(const char *s) {
1710 return cunescape_length(s, strlen(s));
1713 char *xescape(const char *s, const char *bad) {
1717 /* Escapes all chars in bad, in addition to \ and all special
1718 * chars, in \xFF style escaping. May be reversed with
1721 r = new(char, strlen(s) * 4 + 1);
1725 for (f = s, t = r; *f; f++) {
1727 if ((*f < ' ') || (*f >= 127) ||
1728 (*f == '\\') || strchr(bad, *f)) {
1731 *(t++) = hexchar(*f >> 4);
1732 *(t++) = hexchar(*f);
1742 char *bus_path_escape(const char *s) {
1748 /* Escapes all chars that D-Bus' object path cannot deal
1749 * with. Can be reverse with bus_path_unescape() */
1751 if (!(r = new(char, strlen(s)*3+1)))
1754 for (f = s, t = r; *f; f++) {
1756 if (!(*f >= 'A' && *f <= 'Z') &&
1757 !(*f >= 'a' && *f <= 'z') &&
1758 !(*f >= '0' && *f <= '9')) {
1760 *(t++) = hexchar(*f >> 4);
1761 *(t++) = hexchar(*f);
1771 char *bus_path_unescape(const char *f) {
1776 if (!(r = strdup(f)))
1779 for (t = r; *f; f++) {
1784 if ((a = unhexchar(f[1])) < 0 ||
1785 (b = unhexchar(f[2])) < 0) {
1786 /* Invalid escape code, let's take it literal then */
1789 *(t++) = (char) ((a << 4) | b);
1801 char *ascii_strlower(char *t) {
1806 for (p = t; *p; p++)
1807 if (*p >= 'A' && *p <= 'Z')
1808 *p = *p - 'A' + 'a';
1813 static bool ignore_file_allow_backup(const char *filename) {
1817 filename[0] == '.' ||
1818 streq(filename, "lost+found") ||
1819 streq(filename, "aquota.user") ||
1820 streq(filename, "aquota.group") ||
1821 endswith(filename, ".rpmnew") ||
1822 endswith(filename, ".rpmsave") ||
1823 endswith(filename, ".rpmorig") ||
1824 endswith(filename, ".dpkg-old") ||
1825 endswith(filename, ".dpkg-new") ||
1826 endswith(filename, ".swp");
1829 bool ignore_file(const char *filename) {
1832 if (endswith(filename, "~"))
1835 return ignore_file_allow_backup(filename);
1838 int fd_nonblock(int fd, bool nonblock) {
1843 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1847 flags |= O_NONBLOCK;
1849 flags &= ~O_NONBLOCK;
1851 if (fcntl(fd, F_SETFL, flags) < 0)
1857 int fd_cloexec(int fd, bool cloexec) {
1862 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1866 flags |= FD_CLOEXEC;
1868 flags &= ~FD_CLOEXEC;
1870 if (fcntl(fd, F_SETFD, flags) < 0)
1876 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1879 assert(n_fdset == 0 || fdset);
1881 for (i = 0; i < n_fdset; i++)
1888 int close_all_fds(const int except[], unsigned n_except) {
1893 assert(n_except == 0 || except);
1895 d = opendir("/proc/self/fd");
1900 /* When /proc isn't available (for example in chroots)
1901 * the fallback is brute forcing through the fd
1904 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1905 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1907 if (fd_in_set(fd, except, n_except))
1910 if (close_nointr(fd) < 0)
1911 if (errno != EBADF && r == 0)
1918 while ((de = readdir(d))) {
1921 if (ignore_file(de->d_name))
1924 if (safe_atoi(de->d_name, &fd) < 0)
1925 /* Let's better ignore this, just in case */
1934 if (fd_in_set(fd, except, n_except))
1937 if (close_nointr(fd) < 0) {
1938 /* Valgrind has its own FD and doesn't want to have it closed */
1939 if (errno != EBADF && r == 0)
1948 bool chars_intersect(const char *a, const char *b) {
1951 /* Returns true if any of the chars in a are in b. */
1952 for (p = a; *p; p++)
1959 char *format_timestamp(char *buf, size_t l, usec_t t) {
1969 sec = (time_t) (t / USEC_PER_SEC);
1971 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1977 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1980 n = now(CLOCK_REALTIME);
1982 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1987 if (d >= USEC_PER_YEAR)
1988 snprintf(buf, l, "%llu years and %llu months ago",
1989 (unsigned long long) (d / USEC_PER_YEAR),
1990 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1991 else if (d >= USEC_PER_MONTH)
1992 snprintf(buf, l, "%llu months and %llu days ago",
1993 (unsigned long long) (d / USEC_PER_MONTH),
1994 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1995 else if (d >= USEC_PER_WEEK)
1996 snprintf(buf, l, "%llu weeks and %llu days ago",
1997 (unsigned long long) (d / USEC_PER_WEEK),
1998 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1999 else if (d >= 2*USEC_PER_DAY)
2000 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2001 else if (d >= 25*USEC_PER_HOUR)
2002 snprintf(buf, l, "1 day and %lluh ago",
2003 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2004 else if (d >= 6*USEC_PER_HOUR)
2005 snprintf(buf, l, "%lluh ago",
2006 (unsigned long long) (d / USEC_PER_HOUR));
2007 else if (d >= USEC_PER_HOUR)
2008 snprintf(buf, l, "%lluh %llumin ago",
2009 (unsigned long long) (d / USEC_PER_HOUR),
2010 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2011 else if (d >= 5*USEC_PER_MINUTE)
2012 snprintf(buf, l, "%llumin ago",
2013 (unsigned long long) (d / USEC_PER_MINUTE));
2014 else if (d >= USEC_PER_MINUTE)
2015 snprintf(buf, l, "%llumin %llus ago",
2016 (unsigned long long) (d / USEC_PER_MINUTE),
2017 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2018 else if (d >= USEC_PER_SEC)
2019 snprintf(buf, l, "%llus ago",
2020 (unsigned long long) (d / USEC_PER_SEC));
2021 else if (d >= USEC_PER_MSEC)
2022 snprintf(buf, l, "%llums ago",
2023 (unsigned long long) (d / USEC_PER_MSEC));
2025 snprintf(buf, l, "%lluus ago",
2026 (unsigned long long) d);
2028 snprintf(buf, l, "now");
2034 char *format_timespan(char *buf, size_t l, usec_t t) {
2035 static const struct {
2039 { "w", USEC_PER_WEEK },
2040 { "d", USEC_PER_DAY },
2041 { "h", USEC_PER_HOUR },
2042 { "min", USEC_PER_MINUTE },
2043 { "s", USEC_PER_SEC },
2044 { "ms", USEC_PER_MSEC },
2054 if (t == (usec_t) -1)
2058 snprintf(p, l, "0");
2063 /* The result of this function can be parsed with parse_usec */
2065 for (i = 0; i < ELEMENTSOF(table); i++) {
2069 if (t < table[i].usec)
2075 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2076 n = MIN((size_t) k, l);
2089 bool fstype_is_network(const char *fstype) {
2090 static const char table[] =
2099 return nulstr_contains(table, fstype);
2103 _cleanup_close_ int fd;
2105 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2111 TIOCL_GETKMSGREDIRECT,
2115 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2118 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2121 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2127 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2128 struct termios old_termios, new_termios;
2130 char line[LINE_MAX];
2135 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2136 new_termios = old_termios;
2138 new_termios.c_lflag &= ~ICANON;
2139 new_termios.c_cc[VMIN] = 1;
2140 new_termios.c_cc[VTIME] = 0;
2142 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2145 if (t != (usec_t) -1) {
2146 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2147 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2152 k = fread(&c, 1, 1, f);
2154 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2160 *need_nl = c != '\n';
2167 if (t != (usec_t) -1)
2168 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2171 if (!fgets(line, sizeof(line), f))
2176 if (strlen(line) != 1)
2186 int ask(char *ret, const char *replies, const char *text, ...) {
2196 bool need_nl = true;
2199 fputs(ANSI_HIGHLIGHT_ON, stdout);
2206 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2210 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2213 if (r == -EBADMSG) {
2214 puts("Bad input, please try again.");
2225 if (strchr(replies, c)) {
2230 puts("Read unexpected character, please try again.");
2234 int reset_terminal_fd(int fd, bool switch_to_text) {
2235 struct termios termios;
2238 /* Set terminal to some sane defaults */
2242 /* We leave locked terminal attributes untouched, so that
2243 * Plymouth may set whatever it wants to set, and we don't
2244 * interfere with that. */
2246 /* Disable exclusive mode, just in case */
2247 ioctl(fd, TIOCNXCL);
2249 /* Switch to text mode */
2251 ioctl(fd, KDSETMODE, KD_TEXT);
2253 /* Enable console unicode mode */
2254 ioctl(fd, KDSKBMODE, K_UNICODE);
2256 if (tcgetattr(fd, &termios) < 0) {
2261 /* We only reset the stuff that matters to the software. How
2262 * hardware is set up we don't touch assuming that somebody
2263 * else will do that for us */
2265 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2266 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2267 termios.c_oflag |= ONLCR;
2268 termios.c_cflag |= CREAD;
2269 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2271 termios.c_cc[VINTR] = 03; /* ^C */
2272 termios.c_cc[VQUIT] = 034; /* ^\ */
2273 termios.c_cc[VERASE] = 0177;
2274 termios.c_cc[VKILL] = 025; /* ^X */
2275 termios.c_cc[VEOF] = 04; /* ^D */
2276 termios.c_cc[VSTART] = 021; /* ^Q */
2277 termios.c_cc[VSTOP] = 023; /* ^S */
2278 termios.c_cc[VSUSP] = 032; /* ^Z */
2279 termios.c_cc[VLNEXT] = 026; /* ^V */
2280 termios.c_cc[VWERASE] = 027; /* ^W */
2281 termios.c_cc[VREPRINT] = 022; /* ^R */
2282 termios.c_cc[VEOL] = 0;
2283 termios.c_cc[VEOL2] = 0;
2285 termios.c_cc[VTIME] = 0;
2286 termios.c_cc[VMIN] = 1;
2288 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2292 /* Just in case, flush all crap out */
2293 tcflush(fd, TCIOFLUSH);
2298 int reset_terminal(const char *name) {
2301 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2305 r = reset_terminal_fd(fd, true);
2306 close_nointr_nofail(fd);
2311 int open_terminal(const char *name, int mode) {
2316 * If a TTY is in the process of being closed opening it might
2317 * cause EIO. This is horribly awful, but unlikely to be
2318 * changed in the kernel. Hence we work around this problem by
2319 * retrying a couple of times.
2321 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2325 fd = open(name, mode);
2332 /* Max 1s in total */
2336 usleep(50 * USEC_PER_MSEC);
2345 close_nointr_nofail(fd);
2350 close_nointr_nofail(fd);
2357 int flush_fd(int fd) {
2358 struct pollfd pollfd;
2362 pollfd.events = POLLIN;
2369 if ((r = poll(&pollfd, 1, 0)) < 0) {
2380 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2385 if (errno == EAGAIN)
2396 int acquire_terminal(
2400 bool ignore_tiocstty_eperm,
2403 int fd = -1, notify = -1, r = 0, wd = -1;
2405 struct sigaction sa_old, sa_new;
2409 /* We use inotify to be notified when the tty is closed. We
2410 * create the watch before checking if we can actually acquire
2411 * it, so that we don't lose any event.
2413 * Note: strictly speaking this actually watches for the
2414 * device being closed, it does *not* really watch whether a
2415 * tty loses its controlling process. However, unless some
2416 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2417 * its tty otherwise this will not become a problem. As long
2418 * as the administrator makes sure not configure any service
2419 * on the same tty as an untrusted user this should not be a
2420 * problem. (Which he probably should not do anyway.) */
2422 if (timeout != (usec_t) -1)
2423 ts = now(CLOCK_MONOTONIC);
2425 if (!fail && !force) {
2426 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2432 wd = inotify_add_watch(notify, name, IN_CLOSE);
2441 r = flush_fd(notify);
2446 /* We pass here O_NOCTTY only so that we can check the return
2447 * value TIOCSCTTY and have a reliable way to figure out if we
2448 * successfully became the controlling process of the tty */
2449 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2453 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2454 * if we already own the tty. */
2456 sa_new.sa_handler = SIG_IGN;
2457 sa_new.sa_flags = SA_RESTART;
2458 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2460 /* First, try to get the tty */
2461 if (ioctl(fd, TIOCSCTTY, force) < 0)
2464 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2466 /* Sometimes it makes sense to ignore TIOCSCTTY
2467 * returning EPERM, i.e. when very likely we already
2468 * are have this controlling terminal. */
2469 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2472 if (r < 0 && (force || fail || r != -EPERM)) {
2481 assert(notify >= 0);
2484 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2486 struct inotify_event *e;
2488 if (timeout != (usec_t) -1) {
2491 n = now(CLOCK_MONOTONIC);
2492 if (ts + timeout < n) {
2497 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2507 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2510 if (errno == EINTR || errno == EAGAIN)
2517 e = (struct inotify_event*) inotify_buffer;
2522 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2527 step = sizeof(struct inotify_event) + e->len;
2528 assert(step <= (size_t) l);
2530 e = (struct inotify_event*) ((uint8_t*) e + step);
2537 /* We close the tty fd here since if the old session
2538 * ended our handle will be dead. It's important that
2539 * we do this after sleeping, so that we don't enter
2540 * an endless loop. */
2541 close_nointr_nofail(fd);
2545 close_nointr_nofail(notify);
2547 r = reset_terminal_fd(fd, true);
2549 log_warning("Failed to reset terminal: %s", strerror(-r));
2555 close_nointr_nofail(fd);
2558 close_nointr_nofail(notify);
2563 int release_terminal(void) {
2565 struct sigaction sa_old, sa_new;
2567 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2570 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2571 * by our own TIOCNOTTY */
2574 sa_new.sa_handler = SIG_IGN;
2575 sa_new.sa_flags = SA_RESTART;
2576 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2578 if (ioctl(fd, TIOCNOTTY) < 0)
2581 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2583 close_nointr_nofail(fd);
2587 int sigaction_many(const struct sigaction *sa, ...) {
2592 while ((sig = va_arg(ap, int)) > 0)
2593 if (sigaction(sig, sa, NULL) < 0)
2600 int ignore_signals(int sig, ...) {
2601 struct sigaction sa;
2606 sa.sa_handler = SIG_IGN;
2607 sa.sa_flags = SA_RESTART;
2609 if (sigaction(sig, &sa, NULL) < 0)
2613 while ((sig = va_arg(ap, int)) > 0)
2614 if (sigaction(sig, &sa, NULL) < 0)
2621 int default_signals(int sig, ...) {
2622 struct sigaction sa;
2627 sa.sa_handler = SIG_DFL;
2628 sa.sa_flags = SA_RESTART;
2630 if (sigaction(sig, &sa, NULL) < 0)
2634 while ((sig = va_arg(ap, int)) > 0)
2635 if (sigaction(sig, &sa, NULL) < 0)
2642 int close_pipe(int p[]) {
2648 a = close_nointr(p[0]);
2653 b = close_nointr(p[1]);
2657 return a < 0 ? a : b;
2660 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2669 while (nbytes > 0) {
2672 if ((k = read(fd, p, nbytes)) <= 0) {
2674 if (k < 0 && errno == EINTR)
2677 if (k < 0 && errno == EAGAIN && do_poll) {
2678 struct pollfd pollfd;
2682 pollfd.events = POLLIN;
2684 if (poll(&pollfd, 1, -1) < 0) {
2688 return n > 0 ? n : -errno;
2691 if (pollfd.revents != POLLIN)
2692 return n > 0 ? n : -EIO;
2697 return n > 0 ? n : (k < 0 ? -errno : 0);
2708 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2717 while (nbytes > 0) {
2720 k = write(fd, p, nbytes);
2723 if (k < 0 && errno == EINTR)
2726 if (k < 0 && errno == EAGAIN && do_poll) {
2727 struct pollfd pollfd;
2731 pollfd.events = POLLOUT;
2733 if (poll(&pollfd, 1, -1) < 0) {
2737 return n > 0 ? n : -errno;
2740 if (pollfd.revents != POLLOUT)
2741 return n > 0 ? n : -EIO;
2746 return n > 0 ? n : (k < 0 ? -errno : 0);
2757 int parse_usec(const char *t, usec_t *usec) {
2758 static const struct {
2762 { "seconds", USEC_PER_SEC },
2763 { "second", USEC_PER_SEC },
2764 { "sec", USEC_PER_SEC },
2765 { "s", USEC_PER_SEC },
2766 { "minutes", USEC_PER_MINUTE },
2767 { "minute", USEC_PER_MINUTE },
2768 { "min", USEC_PER_MINUTE },
2769 { "months", USEC_PER_MONTH },
2770 { "month", USEC_PER_MONTH },
2771 { "msec", USEC_PER_MSEC },
2772 { "ms", USEC_PER_MSEC },
2773 { "m", USEC_PER_MINUTE },
2774 { "hours", USEC_PER_HOUR },
2775 { "hour", USEC_PER_HOUR },
2776 { "hr", USEC_PER_HOUR },
2777 { "h", USEC_PER_HOUR },
2778 { "days", USEC_PER_DAY },
2779 { "day", USEC_PER_DAY },
2780 { "d", USEC_PER_DAY },
2781 { "weeks", USEC_PER_WEEK },
2782 { "week", USEC_PER_WEEK },
2783 { "w", USEC_PER_WEEK },
2784 { "years", USEC_PER_YEAR },
2785 { "year", USEC_PER_YEAR },
2786 { "y", USEC_PER_YEAR },
2789 { "", USEC_PER_SEC }, /* default is sec */
2805 l = strtoll(p, &e, 10);
2816 e += strspn(e, WHITESPACE);
2818 for (i = 0; i < ELEMENTSOF(table); i++)
2819 if (startswith(e, table[i].suffix)) {
2820 r += (usec_t) l * table[i].usec;
2821 p = e + strlen(table[i].suffix);
2825 if (i >= ELEMENTSOF(table))
2835 int parse_nsec(const char *t, nsec_t *nsec) {
2836 static const struct {
2840 { "seconds", NSEC_PER_SEC },
2841 { "second", NSEC_PER_SEC },
2842 { "sec", NSEC_PER_SEC },
2843 { "s", NSEC_PER_SEC },
2844 { "minutes", NSEC_PER_MINUTE },
2845 { "minute", NSEC_PER_MINUTE },
2846 { "min", NSEC_PER_MINUTE },
2847 { "months", NSEC_PER_MONTH },
2848 { "month", NSEC_PER_MONTH },
2849 { "msec", NSEC_PER_MSEC },
2850 { "ms", NSEC_PER_MSEC },
2851 { "m", NSEC_PER_MINUTE },
2852 { "hours", NSEC_PER_HOUR },
2853 { "hour", NSEC_PER_HOUR },
2854 { "hr", NSEC_PER_HOUR },
2855 { "h", NSEC_PER_HOUR },
2856 { "days", NSEC_PER_DAY },
2857 { "day", NSEC_PER_DAY },
2858 { "d", NSEC_PER_DAY },
2859 { "weeks", NSEC_PER_WEEK },
2860 { "week", NSEC_PER_WEEK },
2861 { "w", NSEC_PER_WEEK },
2862 { "years", NSEC_PER_YEAR },
2863 { "year", NSEC_PER_YEAR },
2864 { "y", NSEC_PER_YEAR },
2865 { "usec", NSEC_PER_USEC },
2866 { "us", NSEC_PER_USEC },
2869 { "", 1ULL }, /* default is nsec */
2885 l = strtoll(p, &e, 10);
2896 e += strspn(e, WHITESPACE);
2898 for (i = 0; i < ELEMENTSOF(table); i++)
2899 if (startswith(e, table[i].suffix)) {
2900 r += (nsec_t) l * table[i].nsec;
2901 p = e + strlen(table[i].suffix);
2905 if (i >= ELEMENTSOF(table))
2915 int parse_bytes(const char *t, off_t *bytes) {
2916 static const struct {
2922 { "M", 1024ULL*1024ULL },
2923 { "G", 1024ULL*1024ULL*1024ULL },
2924 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2925 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2926 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2943 l = strtoll(p, &e, 10);
2954 e += strspn(e, WHITESPACE);
2956 for (i = 0; i < ELEMENTSOF(table); i++)
2957 if (startswith(e, table[i].suffix)) {
2958 r += (off_t) l * table[i].factor;
2959 p = e + strlen(table[i].suffix);
2963 if (i >= ELEMENTSOF(table))
2973 int make_stdio(int fd) {
2978 r = dup3(fd, STDIN_FILENO, 0);
2979 s = dup3(fd, STDOUT_FILENO, 0);
2980 t = dup3(fd, STDERR_FILENO, 0);
2983 close_nointr_nofail(fd);
2985 if (r < 0 || s < 0 || t < 0)
2988 /* We rely here that the new fd has O_CLOEXEC not set */
2993 int make_null_stdio(void) {
2996 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
3000 return make_stdio(null_fd);
3003 bool is_device_path(const char *path) {
3005 /* Returns true on paths that refer to a device, either in
3006 * sysfs or in /dev */
3009 path_startswith(path, "/dev/") ||
3010 path_startswith(path, "/sys/");
3013 int dir_is_empty(const char *path) {
3014 _cleanup_closedir_ DIR *d;
3023 union dirent_storage buf;
3025 r = readdir_r(d, &buf.de, &de);
3032 if (!ignore_file(de->d_name))
3037 unsigned long long random_ull(void) {
3038 _cleanup_close_ int fd;
3042 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3046 r = loop_read(fd, &ull, sizeof(ull), true);
3047 if (r != sizeof(ull))
3053 return random() * RAND_MAX + random();
3056 void rename_process(const char name[8]) {
3059 /* This is a like a poor man's setproctitle(). It changes the
3060 * comm field, argv[0], and also the glibc's internally used
3061 * name of the process. For the first one a limit of 16 chars
3062 * applies, to the second one usually one of 10 (i.e. length
3063 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3064 * "systemd"). If you pass a longer string it will be
3067 prctl(PR_SET_NAME, name);
3069 if (program_invocation_name)
3070 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3072 if (saved_argc > 0) {
3076 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3078 for (i = 1; i < saved_argc; i++) {
3082 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3087 void sigset_add_many(sigset_t *ss, ...) {
3094 while ((sig = va_arg(ap, int)) > 0)
3095 assert_se(sigaddset(ss, sig) == 0);
3099 char* gethostname_malloc(void) {
3102 assert_se(uname(&u) >= 0);
3104 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3105 return strdup(u.nodename);
3107 return strdup(u.sysname);
3110 bool hostname_is_set(void) {
3113 assert_se(uname(&u) >= 0);
3115 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3118 static char *lookup_uid(uid_t uid) {
3121 _cleanup_free_ char *buf = NULL;
3122 struct passwd pwbuf, *pw = NULL;
3124 /* Shortcut things to avoid NSS lookups */
3126 return strdup("root");
3128 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3132 buf = malloc(bufsize);
3136 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3137 return strdup(pw->pw_name);
3139 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3145 char* getlogname_malloc(void) {
3149 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3154 return lookup_uid(uid);
3157 char *getusername_malloc(void) {
3164 return lookup_uid(getuid());
3167 int getttyname_malloc(int fd, char **r) {
3168 char path[PATH_MAX], *c;
3173 k = ttyname_r(fd, path, sizeof(path));
3179 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3187 int getttyname_harder(int fd, char **r) {
3191 k = getttyname_malloc(fd, &s);
3195 if (streq(s, "tty")) {
3197 return get_ctty(0, NULL, r);
3204 int get_ctty_devnr(pid_t pid, dev_t *d) {
3206 char line[LINE_MAX], *p, *fn;
3207 unsigned long ttynr;
3210 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3213 f = fopen(fn, "re");
3218 if (!fgets(line, sizeof(line), f)) {
3219 k = feof(f) ? -EIO : -errno;
3226 p = strrchr(line, ')');
3236 "%*d " /* session */
3245 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3247 char fn[PATH_MAX], *s, *b, *p;
3252 k = get_ctty_devnr(pid, &devnr);
3256 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3259 if ((k = readlink_malloc(fn, &s)) < 0) {
3264 /* This is an ugly hack */
3265 if (major(devnr) == 136) {
3266 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3276 /* Probably something like the ptys which have no
3277 * symlink in /dev/char. Let's return something
3278 * vaguely useful. */
3280 if (!(b = strdup(fn + 5)))
3290 if (startswith(s, "/dev/"))
3292 else if (startswith(s, "../"))
3310 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3316 /* This returns the first error we run into, but nevertheless
3317 * tries to go on. This closes the passed fd. */
3321 close_nointr_nofail(fd);
3323 return errno == ENOENT ? 0 : -errno;
3328 union dirent_storage buf;
3329 bool is_dir, keep_around;
3333 r = readdir_r(d, &buf.de, &de);
3334 if (r != 0 && ret == 0) {
3342 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3345 if (de->d_type == DT_UNKNOWN ||
3347 (de->d_type == DT_DIR && root_dev)) {
3348 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3349 if (ret == 0 && errno != ENOENT)
3354 is_dir = S_ISDIR(st.st_mode);
3357 (st.st_uid == 0 || st.st_uid == getuid()) &&
3358 (st.st_mode & S_ISVTX);
3360 is_dir = de->d_type == DT_DIR;
3361 keep_around = false;
3367 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3368 if (root_dev && st.st_dev != root_dev->st_dev)
3371 subdir_fd = openat(fd, de->d_name,
3372 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3373 if (subdir_fd < 0) {
3374 if (ret == 0 && errno != ENOENT)
3379 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3380 if (r < 0 && ret == 0)
3384 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3385 if (ret == 0 && errno != ENOENT)
3389 } else if (!only_dirs && !keep_around) {
3391 if (unlinkat(fd, de->d_name, 0) < 0) {
3392 if (ret == 0 && errno != ENOENT)
3403 static int is_temporary_fs(struct statfs *s) {
3405 return s->f_type == TMPFS_MAGIC ||
3406 (long)s->f_type == (long)RAMFS_MAGIC;
3409 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3414 if (fstatfs(fd, &s) < 0) {
3415 close_nointr_nofail(fd);
3419 /* We refuse to clean disk file systems with this call. This
3420 * is extra paranoia just to be sure we never ever remove
3422 if (!is_temporary_fs(&s)) {
3423 log_error("Attempted to remove disk file system, and we can't allow that.");
3424 close_nointr_nofail(fd);
3428 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3431 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3437 /* We refuse to clean the root file system with this
3438 * call. This is extra paranoia to never cause a really
3439 * seriously broken system. */
3440 if (path_equal(path, "/")) {
3441 log_error("Attempted to remove entire root file system, and we can't allow that.");
3445 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3448 if (errno != ENOTDIR)
3452 if (statfs(path, &s) < 0)
3455 if (!is_temporary_fs(&s)) {
3456 log_error("Attempted to remove disk file system, and we can't allow that.");
3461 if (delete_root && !only_dirs)
3462 if (unlink(path) < 0 && errno != ENOENT)
3469 if (fstatfs(fd, &s) < 0) {
3470 close_nointr_nofail(fd);
3474 if (!is_temporary_fs(&s)) {
3475 log_error("Attempted to remove disk file system, and we can't allow that.");
3476 close_nointr_nofail(fd);
3481 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3484 if (honour_sticky && file_is_priv_sticky(path) > 0)
3487 if (rmdir(path) < 0 && errno != ENOENT) {
3496 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3497 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3500 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3501 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3504 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3507 /* Under the assumption that we are running privileged we
3508 * first change the access mode and only then hand out
3509 * ownership to avoid a window where access is too open. */
3511 if (mode != (mode_t) -1)
3512 if (chmod(path, mode) < 0)
3515 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3516 if (chown(path, uid, gid) < 0)
3522 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3525 /* Under the assumption that we are running privileged we
3526 * first change the access mode and only then hand out
3527 * ownership to avoid a window where access is too open. */
3529 if (fchmod(fd, mode) < 0)
3532 if (fchown(fd, uid, gid) < 0)
3538 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3542 /* Allocates the cpuset in the right size */
3545 if (!(r = CPU_ALLOC(n)))
3548 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3549 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3559 if (errno != EINVAL)
3566 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3567 static const char status_indent[] = " "; /* "[" STATUS "] " */
3568 _cleanup_free_ char *s = NULL;
3569 _cleanup_close_ int fd = -1;
3570 struct iovec iovec[5];
3575 /* This is independent of logging, as status messages are
3576 * optional and go exclusively to the console. */
3578 if (vasprintf(&s, format, ap) < 0)
3581 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3594 sl = status ? sizeof(status_indent)-1 : 0;
3600 e = ellipsize(s, emax, 75);
3610 if (!isempty(status)) {
3611 IOVEC_SET_STRING(iovec[n++], "[");
3612 IOVEC_SET_STRING(iovec[n++], status);
3613 IOVEC_SET_STRING(iovec[n++], "] ");
3615 IOVEC_SET_STRING(iovec[n++], status_indent);
3618 IOVEC_SET_STRING(iovec[n++], s);
3619 IOVEC_SET_STRING(iovec[n++], "\n");
3621 if (writev(fd, iovec, n) < 0)
3627 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3633 va_start(ap, format);
3634 r = status_vprintf(status, ellipse, format, ap);
3640 int status_welcome(void) {
3642 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3644 r = parse_env_file("/etc/os-release", NEWLINE,
3645 "PRETTY_NAME", &pretty_name,
3646 "ANSI_COLOR", &ansi_color,
3648 if (r < 0 && r != -ENOENT)
3649 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3651 return status_printf(NULL, false,
3652 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3653 isempty(ansi_color) ? "1" : ansi_color,
3654 isempty(pretty_name) ? "Linux" : pretty_name);
3657 char *replace_env(const char *format, char **env) {
3664 const char *e, *word = format;
3669 for (e = format; *e; e ++) {
3680 if (!(k = strnappend(r, word, e-word-1)))
3689 } else if (*e == '$') {
3690 if (!(k = strnappend(r, word, e-word)))
3706 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3709 if (!(k = strappend(r, t)))
3722 if (!(k = strnappend(r, word, e-word)))
3733 char **replace_env_argv(char **argv, char **env) {
3735 unsigned k = 0, l = 0;
3737 l = strv_length(argv);
3739 if (!(r = new(char*, l+1)))
3742 STRV_FOREACH(i, argv) {
3744 /* If $FOO appears as single word, replace it by the split up variable */
3745 if ((*i)[0] == '$' && (*i)[1] != '{') {
3750 if ((e = strv_env_get(env, *i+1))) {
3752 if (!(m = strv_split_quoted(e))) {
3763 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3772 memcpy(r + k, m, q * sizeof(char*));
3780 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3781 if (!(r[k++] = replace_env(*i, env))) {
3791 int fd_columns(int fd) {
3795 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3804 unsigned columns(void) {
3808 if (_likely_(cached_columns > 0))
3809 return cached_columns;
3812 e = getenv("COLUMNS");
3817 c = fd_columns(STDOUT_FILENO);
3826 int fd_lines(int fd) {
3830 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3839 unsigned lines(void) {
3843 if (_likely_(cached_lines > 0))
3844 return cached_lines;
3847 e = getenv("LINES");
3852 l = fd_lines(STDOUT_FILENO);
3858 return cached_lines;
3861 /* intended to be used as a SIGWINCH sighandler */
3862 void columns_lines_cache_reset(int signum) {
3868 static int cached_on_tty = -1;
3870 if (_unlikely_(cached_on_tty < 0))
3871 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3873 return cached_on_tty;
3876 int running_in_chroot(void) {
3882 /* Only works as root */
3884 if (stat("/proc/1/root", &a) < 0)
3887 if (stat("/", &b) < 0)
3891 a.st_dev != b.st_dev ||
3892 a.st_ino != b.st_ino;
3895 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3900 assert(percent <= 100);
3901 assert(new_length >= 3);
3903 if (old_length <= 3 || old_length <= new_length)
3904 return strndup(s, old_length);
3906 r = new0(char, new_length+1);
3910 x = (new_length * percent) / 100;
3912 if (x > new_length - 3)
3920 s + old_length - (new_length - x - 3),
3921 new_length - x - 3);
3926 char *ellipsize(const char *s, size_t length, unsigned percent) {
3927 return ellipsize_mem(s, strlen(s), length, percent);
3930 int touch(const char *path) {
3935 /* This just opens the file for writing, ensuring it
3936 * exists. It doesn't call utimensat() the way /usr/bin/touch
3939 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3943 close_nointr_nofail(fd);
3947 char *unquote(const char *s, const char* quotes) {
3951 /* This is rather stupid, simply removes the heading and
3952 * trailing quotes if there is one. Doesn't care about
3953 * escaping or anything. We should make this smarter one
3960 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3961 return strndup(s+1, l-2);
3966 char *normalize_env_assignment(const char *s) {
3967 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3970 eq = strchr(s, '=');
3982 memmove(r, t, strlen(t) + 1);
3986 name = strndup(s, eq - s);
3994 value = unquote(strstrip(p), QUOTES);
3998 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
4004 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4015 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4027 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4034 r = wait_for_terminate(pid, &status);
4036 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4040 if (status.si_code == CLD_EXITED) {
4041 if (status.si_status != 0) {
4042 log_warning("%s failed with error code %i.", name, status.si_status);
4043 return status.si_status;
4046 log_debug("%s succeeded.", name);
4049 } else if (status.si_code == CLD_KILLED ||
4050 status.si_code == CLD_DUMPED) {
4052 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4056 log_warning("%s failed due to unknown reason.", name);
4060 _noreturn_ void freeze(void) {
4062 /* Make sure nobody waits for us on a socket anymore */
4063 close_all_fds(NULL, 0);
4071 bool null_or_empty(struct stat *st) {
4074 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4077 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4083 int null_or_empty_path(const char *fn) {
4088 if (stat(fn, &st) < 0)
4091 return null_or_empty(&st);
4094 DIR *xopendirat(int fd, const char *name, int flags) {
4098 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4104 close_nointr_nofail(nfd);
4111 int signal_from_string_try_harder(const char *s) {
4115 signo = signal_from_string(s);
4117 if (startswith(s, "SIG"))
4118 return signal_from_string(s+3);
4123 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4129 if (!dual_timestamp_is_set(t))
4132 fprintf(f, "%s=%llu %llu\n",
4134 (unsigned long long) t->realtime,
4135 (unsigned long long) t->monotonic);
4138 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4139 unsigned long long a, b;
4144 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4145 log_debug("Failed to parse finish timestamp value %s", value);
4152 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4156 /* FIXME: to follow udev's logic 100% we need to leave valid
4157 * UTF8 chars unescaped */
4159 u = unquote(tagvalue, "\"\'");
4163 t = xescape(u, "/ ");
4169 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4178 char *fstab_node_to_udev_node(const char *p) {
4181 if (startswith(p, "LABEL="))
4182 return tag_to_udev_node(p+6, "label");
4184 if (startswith(p, "UUID="))
4185 return tag_to_udev_node(p+5, "uuid");
4187 if (startswith(p, "PARTUUID="))
4188 return tag_to_udev_node(p+9, "partuuid");
4190 if (startswith(p, "PARTLABEL="))
4191 return tag_to_udev_node(p+10, "partlabel");
4196 bool tty_is_vc(const char *tty) {
4199 if (startswith(tty, "/dev/"))
4202 return vtnr_from_tty(tty) >= 0;
4205 bool tty_is_console(const char *tty) {
4208 if (startswith(tty, "/dev/"))
4211 return streq(tty, "console");
4214 int vtnr_from_tty(const char *tty) {
4219 if (startswith(tty, "/dev/"))
4222 if (!startswith(tty, "tty") )
4225 if (tty[3] < '0' || tty[3] > '9')
4228 r = safe_atoi(tty+3, &i);
4232 if (i < 0 || i > 63)
4238 bool tty_is_vc_resolve(const char *tty) {
4239 char *active = NULL;
4244 if (startswith(tty, "/dev/"))
4247 /* Resolve where /dev/console is pointing to, if /sys is
4248 * actually ours (i.e. not read-only-mounted which is a sign
4249 * for container setups) */
4250 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4251 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4252 /* If multiple log outputs are configured the
4253 * last one is what /dev/console points to */
4254 tty = strrchr(active, ' ');
4267 const char *default_term_for_tty(const char *tty) {
4270 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4273 bool dirent_is_file(const struct dirent *de) {
4276 if (ignore_file(de->d_name))
4279 if (de->d_type != DT_REG &&
4280 de->d_type != DT_LNK &&
4281 de->d_type != DT_UNKNOWN)
4287 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4290 if (de->d_type != DT_REG &&
4291 de->d_type != DT_LNK &&
4292 de->d_type != DT_UNKNOWN)
4295 if (ignore_file_allow_backup(de->d_name))
4298 return endswith(de->d_name, suffix);
4301 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4304 Hashmap *pids = NULL;
4308 /* Executes all binaries in a directory in parallel and waits
4309 * until all they all finished. */
4312 if (!(_d = opendir(directory))) {
4314 if (errno == ENOENT)
4317 log_error("Failed to enumerate directory %s: %m", directory);
4324 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4325 log_error("Failed to allocate set.");
4329 while ((de = readdir(d))) {
4334 if (!dirent_is_file(de))
4337 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4342 if ((pid = fork()) < 0) {
4343 log_error("Failed to fork: %m");
4361 log_error("Failed to execute %s: %m", path);
4362 _exit(EXIT_FAILURE);
4365 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4367 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4368 log_error("Failed to add PID to set: %s", strerror(-k));
4373 while (!hashmap_isempty(pids)) {
4374 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4379 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4384 log_error("waitid() failed: %m");
4388 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4389 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4390 if (si.si_code == CLD_EXITED)
4391 log_error("%s exited with exit status %i.", path, si.si_status);
4393 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4395 log_debug("%s exited successfully.", path);
4406 hashmap_free_free(pids);
4409 int kill_and_sigcont(pid_t pid, int sig) {
4412 r = kill(pid, sig) < 0 ? -errno : 0;
4420 bool nulstr_contains(const char*nulstr, const char *needle) {
4426 NULSTR_FOREACH(i, nulstr)
4427 if (streq(i, needle))
4433 bool plymouth_running(void) {
4434 return access("/run/plymouth/pid", F_OK) >= 0;
4437 char* strshorten(char *s, size_t l) {
4446 static bool hostname_valid_char(char c) {
4448 (c >= 'a' && c <= 'z') ||
4449 (c >= 'A' && c <= 'Z') ||
4450 (c >= '0' && c <= '9') ||
4456 bool hostname_is_valid(const char *s) {
4462 for (p = s; *p; p++)
4463 if (!hostname_valid_char(*p))
4466 if (p-s > HOST_NAME_MAX)
4472 char* hostname_cleanup(char *s) {
4475 for (p = s, d = s; *p; p++)
4476 if ((*p >= 'a' && *p <= 'z') ||
4477 (*p >= 'A' && *p <= 'Z') ||
4478 (*p >= '0' && *p <= '9') ||
4486 strshorten(s, HOST_NAME_MAX);
4490 int pipe_eof(int fd) {
4491 struct pollfd pollfd;
4496 pollfd.events = POLLIN|POLLHUP;
4498 r = poll(&pollfd, 1, 0);
4505 return pollfd.revents & POLLHUP;
4508 int fd_wait_for_event(int fd, int event, usec_t t) {
4509 struct pollfd pollfd;
4514 pollfd.events = event;
4516 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4523 return pollfd.revents;
4526 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4537 t = new(char, strlen(path) + 1 + 6 + 1);
4541 fn = path_get_file_name(path);
4545 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4547 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4553 f = fdopen(fd, "we");
4566 int terminal_vhangup_fd(int fd) {
4569 if (ioctl(fd, TIOCVHANGUP) < 0)
4575 int terminal_vhangup(const char *name) {
4578 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4582 r = terminal_vhangup_fd(fd);
4583 close_nointr_nofail(fd);
4588 int vt_disallocate(const char *name) {
4592 /* Deallocate the VT if possible. If not possible
4593 * (i.e. because it is the active one), at least clear it
4594 * entirely (including the scrollback buffer) */
4596 if (!startswith(name, "/dev/"))
4599 if (!tty_is_vc(name)) {
4600 /* So this is not a VT. I guess we cannot deallocate
4601 * it then. But let's at least clear the screen */
4603 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4608 "\033[r" /* clear scrolling region */
4609 "\033[H" /* move home */
4610 "\033[2J", /* clear screen */
4612 close_nointr_nofail(fd);
4617 if (!startswith(name, "/dev/tty"))
4620 r = safe_atou(name+8, &u);
4627 /* Try to deallocate */
4628 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4632 r = ioctl(fd, VT_DISALLOCATE, u);
4633 close_nointr_nofail(fd);
4641 /* Couldn't deallocate, so let's clear it fully with
4643 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4648 "\033[r" /* clear scrolling region */
4649 "\033[H" /* move home */
4650 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4652 close_nointr_nofail(fd);
4657 int copy_file(const char *from, const char *to) {
4663 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4667 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4669 close_nointr_nofail(fdf);
4677 n = read(fdf, buf, sizeof(buf));
4681 close_nointr_nofail(fdf);
4692 k = loop_write(fdt, buf, n, false);
4694 r = k < 0 ? k : (errno ? -errno : -EIO);
4696 close_nointr_nofail(fdf);
4704 close_nointr_nofail(fdf);
4705 r = close_nointr(fdt);
4715 int symlink_atomic(const char *from, const char *to) {
4717 _cleanup_free_ char *t;
4720 unsigned long long ull;
4727 t = new(char, strlen(to) + 1 + 16 + 1);
4731 fn = path_get_file_name(to);
4735 x = stpcpy(t+k+1, fn);
4738 for (i = 0; i < 16; i++) {
4739 *(x++) = hexchar(ull & 0xF);
4745 if (symlink(from, t) < 0)
4748 if (rename(t, to) < 0) {
4757 bool display_is_local(const char *display) {
4761 display[0] == ':' &&
4762 display[1] >= '0' &&
4766 int socket_from_display(const char *display, char **path) {
4773 if (!display_is_local(display))
4776 k = strspn(display+1, "0123456789");
4778 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4782 c = stpcpy(f, "/tmp/.X11-unix/X");
4783 memcpy(c, display+1, k);
4792 const char **username,
4793 uid_t *uid, gid_t *gid,
4795 const char **shell) {
4803 /* We enforce some special rules for uid=0: in order to avoid
4804 * NSS lookups for root we hardcode its data. */
4806 if (streq(*username, "root") || streq(*username, "0")) {
4824 if (parse_uid(*username, &u) >= 0) {
4828 /* If there are multiple users with the same id, make
4829 * sure to leave $USER to the configured value instead
4830 * of the first occurrence in the database. However if
4831 * the uid was configured by a numeric uid, then let's
4832 * pick the real username from /etc/passwd. */
4834 *username = p->pw_name;
4837 p = getpwnam(*username);
4841 return errno != 0 ? -errno : -ESRCH;
4853 *shell = p->pw_shell;
4858 int get_group_creds(const char **groupname, gid_t *gid) {
4864 /* We enforce some special rules for gid=0: in order to avoid
4865 * NSS lookups for root we hardcode its data. */
4867 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4868 *groupname = "root";
4876 if (parse_gid(*groupname, &id) >= 0) {
4881 *groupname = g->gr_name;
4884 g = getgrnam(*groupname);
4888 return errno != 0 ? -errno : -ESRCH;
4896 int in_group(const char *name) {
4898 int ngroups_max, r, i;
4900 r = get_group_creds(&name, &gid);
4904 if (getgid() == gid)
4907 if (getegid() == gid)
4910 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4911 assert(ngroups_max > 0);
4913 gids = alloca(sizeof(gid_t) * ngroups_max);
4915 r = getgroups(ngroups_max, gids);
4919 for (i = 0; i < r; i++)
4926 int glob_exists(const char *path) {
4934 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4936 if (k == GLOB_NOMATCH)
4938 else if (k == GLOB_NOSPACE)
4941 r = !strv_isempty(g.gl_pathv);
4943 r = errno ? -errno : -EIO;
4950 int dirent_ensure_type(DIR *d, struct dirent *de) {
4956 if (de->d_type != DT_UNKNOWN)
4959 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4963 S_ISREG(st.st_mode) ? DT_REG :
4964 S_ISDIR(st.st_mode) ? DT_DIR :
4965 S_ISLNK(st.st_mode) ? DT_LNK :
4966 S_ISFIFO(st.st_mode) ? DT_FIFO :
4967 S_ISSOCK(st.st_mode) ? DT_SOCK :
4968 S_ISCHR(st.st_mode) ? DT_CHR :
4969 S_ISBLK(st.st_mode) ? DT_BLK :
4975 int in_search_path(const char *path, char **search) {
4979 r = path_get_parent(path, &parent);
4985 STRV_FOREACH(i, search) {
4986 if (path_equal(parent, *i)) {
4997 int get_files_in_directory(const char *path, char ***list) {
5005 /* Returns all files in a directory in *list, and the number
5006 * of files as return value. If list is NULL returns only the
5015 union dirent_storage buf;
5018 k = readdir_r(d, &buf.de, &de);
5027 dirent_ensure_type(d, de);
5029 if (!dirent_is_file(de))
5033 if ((unsigned) r >= n) {
5037 t = realloc(l, sizeof(char*) * n);
5046 assert((unsigned) r < n);
5048 l[r] = strdup(de->d_name);
5072 char *strjoin(const char *x, ...) {
5086 t = va_arg(ap, const char *);
5091 if (n > ((size_t) -1) - l) {
5115 t = va_arg(ap, const char *);
5129 bool is_main_thread(void) {
5130 static __thread int cached = 0;
5132 if (_unlikely_(cached == 0))
5133 cached = getpid() == gettid() ? 1 : -1;
5138 int block_get_whole_disk(dev_t d, dev_t *ret) {
5145 /* If it has a queue this is good enough for us */
5146 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5149 r = access(p, F_OK);
5157 /* If it is a partition find the originating device */
5158 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5161 r = access(p, F_OK);
5167 /* Get parent dev_t */
5168 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5171 r = read_one_line_file(p, &s);
5177 r = sscanf(s, "%u:%u", &m, &n);
5183 /* Only return this if it is really good enough for us. */
5184 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5187 r = access(p, F_OK);
5191 *ret = makedev(m, n);
5198 int file_is_priv_sticky(const char *p) {
5203 if (lstat(p, &st) < 0)
5207 (st.st_uid == 0 || st.st_uid == getuid()) &&
5208 (st.st_mode & S_ISVTX);
5211 static const char *const ioprio_class_table[] = {
5212 [IOPRIO_CLASS_NONE] = "none",
5213 [IOPRIO_CLASS_RT] = "realtime",
5214 [IOPRIO_CLASS_BE] = "best-effort",
5215 [IOPRIO_CLASS_IDLE] = "idle"
5218 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
5220 static const char *const sigchld_code_table[] = {
5221 [CLD_EXITED] = "exited",
5222 [CLD_KILLED] = "killed",
5223 [CLD_DUMPED] = "dumped",
5224 [CLD_TRAPPED] = "trapped",
5225 [CLD_STOPPED] = "stopped",
5226 [CLD_CONTINUED] = "continued",
5229 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5231 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5232 [LOG_FAC(LOG_KERN)] = "kern",
5233 [LOG_FAC(LOG_USER)] = "user",
5234 [LOG_FAC(LOG_MAIL)] = "mail",
5235 [LOG_FAC(LOG_DAEMON)] = "daemon",
5236 [LOG_FAC(LOG_AUTH)] = "auth",
5237 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5238 [LOG_FAC(LOG_LPR)] = "lpr",
5239 [LOG_FAC(LOG_NEWS)] = "news",
5240 [LOG_FAC(LOG_UUCP)] = "uucp",
5241 [LOG_FAC(LOG_CRON)] = "cron",
5242 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5243 [LOG_FAC(LOG_FTP)] = "ftp",
5244 [LOG_FAC(LOG_LOCAL0)] = "local0",
5245 [LOG_FAC(LOG_LOCAL1)] = "local1",
5246 [LOG_FAC(LOG_LOCAL2)] = "local2",
5247 [LOG_FAC(LOG_LOCAL3)] = "local3",
5248 [LOG_FAC(LOG_LOCAL4)] = "local4",
5249 [LOG_FAC(LOG_LOCAL5)] = "local5",
5250 [LOG_FAC(LOG_LOCAL6)] = "local6",
5251 [LOG_FAC(LOG_LOCAL7)] = "local7"
5254 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5256 static const char *const log_level_table[] = {
5257 [LOG_EMERG] = "emerg",
5258 [LOG_ALERT] = "alert",
5259 [LOG_CRIT] = "crit",
5261 [LOG_WARNING] = "warning",
5262 [LOG_NOTICE] = "notice",
5263 [LOG_INFO] = "info",
5264 [LOG_DEBUG] = "debug"
5267 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5269 static const char* const sched_policy_table[] = {
5270 [SCHED_OTHER] = "other",
5271 [SCHED_BATCH] = "batch",
5272 [SCHED_IDLE] = "idle",
5273 [SCHED_FIFO] = "fifo",
5277 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5279 static const char* const rlimit_table[] = {
5280 [RLIMIT_CPU] = "LimitCPU",
5281 [RLIMIT_FSIZE] = "LimitFSIZE",
5282 [RLIMIT_DATA] = "LimitDATA",
5283 [RLIMIT_STACK] = "LimitSTACK",
5284 [RLIMIT_CORE] = "LimitCORE",
5285 [RLIMIT_RSS] = "LimitRSS",
5286 [RLIMIT_NOFILE] = "LimitNOFILE",
5287 [RLIMIT_AS] = "LimitAS",
5288 [RLIMIT_NPROC] = "LimitNPROC",
5289 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5290 [RLIMIT_LOCKS] = "LimitLOCKS",
5291 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5292 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5293 [RLIMIT_NICE] = "LimitNICE",
5294 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5295 [RLIMIT_RTTIME] = "LimitRTTIME"
5298 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5300 static const char* const ip_tos_table[] = {
5301 [IPTOS_LOWDELAY] = "low-delay",
5302 [IPTOS_THROUGHPUT] = "throughput",
5303 [IPTOS_RELIABILITY] = "reliability",
5304 [IPTOS_LOWCOST] = "low-cost",
5307 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5309 static const char *const __signal_table[] = {
5326 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5337 [SIGVTALRM] = "VTALRM",
5339 [SIGWINCH] = "WINCH",
5345 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5347 const char *signal_to_string(int signo) {
5348 static __thread char buf[12];
5351 name = __signal_to_string(signo);
5355 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5356 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5358 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5363 int signal_from_string(const char *s) {
5368 signo = __signal_from_string(s);
5372 if (startswith(s, "RTMIN+")) {
5376 if (safe_atou(s, &u) >= 0) {
5377 signo = (int) u + offset;
5378 if (signo > 0 && signo < _NSIG)
5384 bool kexec_loaded(void) {
5385 bool loaded = false;
5388 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5396 int strdup_or_null(const char *a, char **b) {
5414 int prot_from_flags(int flags) {
5416 switch (flags & O_ACCMODE) {
5425 return PROT_READ|PROT_WRITE;
5432 char *format_bytes(char *buf, size_t l, off_t t) {
5435 static const struct {
5439 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5440 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5441 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5442 { "G", 1024ULL*1024ULL*1024ULL },
5443 { "M", 1024ULL*1024ULL },
5447 for (i = 0; i < ELEMENTSOF(table); i++) {
5449 if (t >= table[i].factor) {
5452 (unsigned long long) (t / table[i].factor),
5453 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5460 snprintf(buf, l, "%lluB", (unsigned long long) t);
5468 void* memdup(const void *p, size_t l) {
5481 int fd_inc_sndbuf(int fd, size_t n) {
5483 socklen_t l = sizeof(value);
5485 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5487 l == sizeof(value) &&
5488 (size_t) value >= n*2)
5492 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5499 int fd_inc_rcvbuf(int fd, size_t n) {
5501 socklen_t l = sizeof(value);
5503 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5505 l == sizeof(value) &&
5506 (size_t) value >= n*2)
5510 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5517 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5518 pid_t parent_pid, agent_pid;
5520 bool stdout_is_tty, stderr_is_tty;
5528 parent_pid = getpid();
5530 /* Spawns a temporary TTY agent, making sure it goes away when
5537 if (agent_pid != 0) {
5544 * Make sure the agent goes away when the parent dies */
5545 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5546 _exit(EXIT_FAILURE);
5548 /* Check whether our parent died before we were able
5549 * to set the death signal */
5550 if (getppid() != parent_pid)
5551 _exit(EXIT_SUCCESS);
5553 /* Don't leak fds to the agent */
5554 close_all_fds(except, n_except);
5556 stdout_is_tty = isatty(STDOUT_FILENO);
5557 stderr_is_tty = isatty(STDERR_FILENO);
5559 if (!stdout_is_tty || !stderr_is_tty) {
5560 /* Detach from stdout/stderr. and reopen
5561 * /dev/tty for them. This is important to
5562 * ensure that when systemctl is started via
5563 * popen() or a similar call that expects to
5564 * read EOF we actually do generate EOF and
5565 * not delay this indefinitely by because we
5566 * keep an unused copy of stdin around. */
5567 fd = open("/dev/tty", O_WRONLY);
5569 log_error("Failed to open /dev/tty: %m");
5570 _exit(EXIT_FAILURE);
5574 dup2(fd, STDOUT_FILENO);
5577 dup2(fd, STDERR_FILENO);
5583 /* Count arguments */
5585 for (n = 0; va_arg(ap, char*); n++)
5590 l = alloca(sizeof(char *) * (n + 1));
5592 /* Fill in arguments */
5594 for (i = 0; i <= n; i++)
5595 l[i] = va_arg(ap, char*);
5599 _exit(EXIT_FAILURE);
5602 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5603 struct rlimit highest, fixed;
5607 if (setrlimit(resource, rlim) >= 0)
5613 /* So we failed to set the desired setrlimit, then let's try
5614 * to get as close as we can */
5615 assert_se(getrlimit(resource, &highest) == 0);
5617 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5618 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5620 if (setrlimit(resource, &fixed) < 0)
5626 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5627 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5639 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5642 f = fopen(path, "re");
5650 char line[LINE_MAX];
5653 for (i = 0; i < sizeof(line)-1; i++) {
5657 if (_unlikely_(c == EOF)) {
5667 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5668 value = strdup(line + l + 1);
5688 int can_sleep(const char *type) {
5692 _cleanup_free_ char *p = NULL;
5696 r = read_one_line_file("/sys/power/state", &p);
5698 return r == -ENOENT ? 0 : r;
5701 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5702 if (l == k && memcmp(w, type, l) == 0)
5708 int can_sleep_disk(const char *type) {
5712 _cleanup_free_ char *p = NULL;
5716 r = read_one_line_file("/sys/power/disk", &p);
5718 return r == -ENOENT ? 0 : r;
5721 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5722 if (l == k && memcmp(w, type, l) == 0)
5725 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5732 bool is_valid_documentation_url(const char *url) {
5735 if (startswith(url, "http://") && url[7])
5738 if (startswith(url, "https://") && url[8])
5741 if (startswith(url, "file:") && url[5])
5744 if (startswith(url, "info:") && url[5])
5747 if (startswith(url, "man:") && url[4])
5753 bool in_initrd(void) {
5754 static __thread int saved = -1;
5760 /* We make two checks here:
5762 * 1. the flag file /etc/initrd-release must exist
5763 * 2. the root file system must be a memory file system
5765 * The second check is extra paranoia, since misdetecting an
5766 * initrd can have bad bad consequences due the initrd
5767 * emptying when transititioning to the main systemd.
5770 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5771 statfs("/", &s) >= 0 &&
5772 is_temporary_fs(&s);
5777 void warn_melody(void) {
5778 _cleanup_close_ int fd = -1;
5780 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5784 /* Yeah, this is synchronous. Kinda sucks. But well... */
5786 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5787 usleep(125*USEC_PER_MSEC);
5789 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5790 usleep(125*USEC_PER_MSEC);
5792 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5793 usleep(125*USEC_PER_MSEC);
5795 ioctl(fd, KIOCSOUND, 0);
5798 int make_console_stdio(void) {
5801 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5803 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5805 log_error("Failed to acquire terminal: %s", strerror(-fd));
5811 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5818 int get_home_dir(char **_h) {
5826 /* Take the user specified one */
5837 /* Hardcode home directory for root to avoid NSS */
5840 h = strdup("/root");
5848 /* Check the database... */
5852 return errno ? -errno : -ESRCH;
5854 if (!path_is_absolute(p->pw_dir))
5857 h = strdup(p->pw_dir);
5865 int get_shell(char **_sh) {
5873 /* Take the user specified one */
5874 e = getenv("SHELL");
5884 /* Hardcode home directory for root to avoid NSS */
5887 sh = strdup("/bin/sh");
5895 /* Check the database... */
5899 return errno ? -errno : -ESRCH;
5901 if (!path_is_absolute(p->pw_shell))
5904 sh = strdup(p->pw_shell);
5912 void freep(void *p) {
5916 void fclosep(FILE **f) {
5921 void closep(int *fd) {
5923 close_nointr_nofail(*fd);
5926 void closedirp(DIR **d) {
5931 void umaskp(mode_t *u) {
5935 bool filename_is_safe(const char *p) {
5949 if (strlen(p) > FILENAME_MAX)
5955 bool string_is_safe(const char *p) {
5960 for (t = p; *t; t++) {
5961 if (*t > 0 && *t < ' ')
5964 if (strchr("\\\"\'", *t))
5971 int parse_timestamp(const char *t, usec_t *usec) {
5975 usec_t plus = 0, minus = 0, ret;
5981 * 2012-09-22 16:34:22
5982 * 2012-09-22 16:34 (seconds will be set to 0)
5983 * 2012-09-22 (time will be set to 00:00:00)
5984 * 16:34:22 (date will be set to today)
5985 * 16:34 (date will be set to today, seconds to 0)
5987 * yesterday (time is set to 00:00:00)
5988 * today (time is set to 00:00:00)
5989 * tomorrow (time is set to 00:00:00)
5999 assert_se(localtime_r(&x, &tm));
6001 if (streq(t, "now"))
6004 else if (streq(t, "today")) {
6005 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6008 } else if (streq(t, "yesterday")) {
6010 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6013 } else if (streq(t, "tomorrow")) {
6015 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6018 } else if (t[0] == '+') {
6020 r = parse_usec(t+1, &plus);
6025 } else if (t[0] == '-') {
6027 r = parse_usec(t+1, &minus);
6035 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6040 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6045 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6052 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6059 k = strptime(t, "%y-%m-%d", &tm);
6061 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6066 k = strptime(t, "%Y-%m-%d", &tm);
6068 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6073 k = strptime(t, "%H:%M:%S", &tm);
6078 k = strptime(t, "%H:%M", &tm);
6088 if (x == (time_t) -1)
6091 ret = (usec_t) x * USEC_PER_SEC;
6104 /* hey glibc, APIs with callbacks without a user pointer are so useless */
6105 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
6106 int (*compar) (const void *, const void *, void *), void *arg) {
6115 p = (void *)(((const char *) base) + (idx * size));
6116 comparison = compar(key, p, arg);
6119 else if (comparison > 0)
6127 bool is_locale_utf8(void) {
6129 static int cached_answer = -1;
6131 if (cached_answer >= 0)
6134 if (!setlocale(LC_ALL, "")) {
6135 cached_answer = true;
6139 set = nl_langinfo(CODESET);
6141 cached_answer = true;
6145 cached_answer = streq(set, "UTF-8");
6147 return (bool)cached_answer;
6150 const char *draw_special_char(DrawSpecialChar ch) {
6151 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
6153 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
6154 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
6155 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
6156 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
6158 /* ASCII fallback */ {
6159 [DRAW_TREE_VERT] = "| ",
6160 [DRAW_TREE_BRANCH] = "|-",
6161 [DRAW_TREE_RIGHT] = "`-",
6162 [DRAW_TRIANGULAR_BULLET] = "> ",
6166 return draw_table[!is_locale_utf8()][ch];
6169 char *strreplace(const char *text, const char *old_string, const char *new_string) {
6172 size_t l, old_len, new_len;
6178 old_len = strlen(old_string);
6179 new_len = strlen(new_string);
6192 if (!startswith(f, old_string)) {
6198 nl = l - old_len + new_len;
6199 a = realloc(r, nl + 1);
6207 t = stpcpy(t, new_string);