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 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3408 if (fstatfs(fd, &s) < 0) {
3409 close_nointr_nofail(fd);
3413 /* We refuse to clean disk file systems with this call. This
3414 * is extra paranoia just to be sure we never ever remove
3417 if (s.f_type != TMPFS_MAGIC &&
3418 s.f_type != RAMFS_MAGIC) {
3419 log_error("Attempted to remove disk file system, and we can't allow that.");
3420 close_nointr_nofail(fd);
3424 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3427 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3433 /* We refuse to clean the root file system with this
3434 * call. This is extra paranoia to never cause a really
3435 * seriously broken system. */
3436 if (path_equal(path, "/")) {
3437 log_error("Attempted to remove entire root file system, and we can't allow that.");
3441 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3444 if (errno != ENOTDIR)
3448 if (statfs(path, &s) < 0)
3451 if (s.f_type != TMPFS_MAGIC &&
3452 s.f_type != RAMFS_MAGIC) {
3453 log_error("Attempted to remove disk file system, and we can't allow that.");
3458 if (delete_root && !only_dirs)
3459 if (unlink(path) < 0 && errno != ENOENT)
3466 if (fstatfs(fd, &s) < 0) {
3467 close_nointr_nofail(fd);
3471 if (s.f_type != TMPFS_MAGIC &&
3472 s.f_type != RAMFS_MAGIC) {
3473 log_error("Attempted to remove disk file system, and we can't allow that.");
3474 close_nointr_nofail(fd);
3479 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3482 if (honour_sticky && file_is_priv_sticky(path) > 0)
3485 if (rmdir(path) < 0 && errno != ENOENT) {
3494 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3495 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3498 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3499 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3502 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3505 /* Under the assumption that we are running privileged we
3506 * first change the access mode and only then hand out
3507 * ownership to avoid a window where access is too open. */
3509 if (mode != (mode_t) -1)
3510 if (chmod(path, mode) < 0)
3513 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3514 if (chown(path, uid, gid) < 0)
3520 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3523 /* Under the assumption that we are running privileged we
3524 * first change the access mode and only then hand out
3525 * ownership to avoid a window where access is too open. */
3527 if (fchmod(fd, mode) < 0)
3530 if (fchown(fd, uid, gid) < 0)
3536 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3540 /* Allocates the cpuset in the right size */
3543 if (!(r = CPU_ALLOC(n)))
3546 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3547 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3557 if (errno != EINVAL)
3564 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3565 static const char status_indent[] = " "; /* "[" STATUS "] " */
3566 _cleanup_free_ char *s = NULL;
3567 _cleanup_close_ int fd = -1;
3568 struct iovec iovec[5];
3573 /* This is independent of logging, as status messages are
3574 * optional and go exclusively to the console. */
3576 if (vasprintf(&s, format, ap) < 0)
3579 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3592 sl = status ? sizeof(status_indent)-1 : 0;
3598 e = ellipsize(s, emax, 75);
3608 if (!isempty(status)) {
3609 IOVEC_SET_STRING(iovec[n++], "[");
3610 IOVEC_SET_STRING(iovec[n++], status);
3611 IOVEC_SET_STRING(iovec[n++], "] ");
3613 IOVEC_SET_STRING(iovec[n++], status_indent);
3616 IOVEC_SET_STRING(iovec[n++], s);
3617 IOVEC_SET_STRING(iovec[n++], "\n");
3619 if (writev(fd, iovec, n) < 0)
3625 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3631 va_start(ap, format);
3632 r = status_vprintf(status, ellipse, format, ap);
3638 int status_welcome(void) {
3640 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3642 r = parse_env_file("/etc/os-release", NEWLINE,
3643 "PRETTY_NAME", &pretty_name,
3644 "ANSI_COLOR", &ansi_color,
3646 if (r < 0 && r != -ENOENT)
3647 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3649 return status_printf(NULL, false,
3650 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3651 isempty(ansi_color) ? "1" : ansi_color,
3652 isempty(pretty_name) ? "Linux" : pretty_name);
3655 char *replace_env(const char *format, char **env) {
3662 const char *e, *word = format;
3667 for (e = format; *e; e ++) {
3678 if (!(k = strnappend(r, word, e-word-1)))
3687 } else if (*e == '$') {
3688 if (!(k = strnappend(r, word, e-word)))
3704 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3707 if (!(k = strappend(r, t)))
3720 if (!(k = strnappend(r, word, e-word)))
3731 char **replace_env_argv(char **argv, char **env) {
3733 unsigned k = 0, l = 0;
3735 l = strv_length(argv);
3737 if (!(r = new(char*, l+1)))
3740 STRV_FOREACH(i, argv) {
3742 /* If $FOO appears as single word, replace it by the split up variable */
3743 if ((*i)[0] == '$' && (*i)[1] != '{') {
3748 if ((e = strv_env_get(env, *i+1))) {
3750 if (!(m = strv_split_quoted(e))) {
3761 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3770 memcpy(r + k, m, q * sizeof(char*));
3778 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3779 if (!(r[k++] = replace_env(*i, env))) {
3789 int fd_columns(int fd) {
3793 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3802 unsigned columns(void) {
3806 if (_likely_(cached_columns > 0))
3807 return cached_columns;
3810 e = getenv("COLUMNS");
3815 c = fd_columns(STDOUT_FILENO);
3824 int fd_lines(int fd) {
3828 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3837 unsigned lines(void) {
3841 if (_likely_(cached_lines > 0))
3842 return cached_lines;
3845 e = getenv("LINES");
3850 l = fd_lines(STDOUT_FILENO);
3856 return cached_lines;
3859 /* intended to be used as a SIGWINCH sighandler */
3860 void columns_lines_cache_reset(int signum) {
3866 static int cached_on_tty = -1;
3868 if (_unlikely_(cached_on_tty < 0))
3869 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3871 return cached_on_tty;
3874 int running_in_chroot(void) {
3880 /* Only works as root */
3882 if (stat("/proc/1/root", &a) < 0)
3885 if (stat("/", &b) < 0)
3889 a.st_dev != b.st_dev ||
3890 a.st_ino != b.st_ino;
3893 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3898 assert(percent <= 100);
3899 assert(new_length >= 3);
3901 if (old_length <= 3 || old_length <= new_length)
3902 return strndup(s, old_length);
3904 r = new0(char, new_length+1);
3908 x = (new_length * percent) / 100;
3910 if (x > new_length - 3)
3918 s + old_length - (new_length - x - 3),
3919 new_length - x - 3);
3924 char *ellipsize(const char *s, size_t length, unsigned percent) {
3925 return ellipsize_mem(s, strlen(s), length, percent);
3928 int touch(const char *path) {
3933 /* This just opens the file for writing, ensuring it
3934 * exists. It doesn't call utimensat() the way /usr/bin/touch
3937 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3941 close_nointr_nofail(fd);
3945 char *unquote(const char *s, const char* quotes) {
3949 /* This is rather stupid, simply removes the heading and
3950 * trailing quotes if there is one. Doesn't care about
3951 * escaping or anything. We should make this smarter one
3958 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3959 return strndup(s+1, l-2);
3964 char *normalize_env_assignment(const char *s) {
3965 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3968 eq = strchr(s, '=');
3980 memmove(r, t, strlen(t) + 1);
3984 name = strndup(s, eq - s);
3992 value = unquote(strstrip(p), QUOTES);
3996 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
4002 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4013 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4025 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4032 r = wait_for_terminate(pid, &status);
4034 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4038 if (status.si_code == CLD_EXITED) {
4039 if (status.si_status != 0) {
4040 log_warning("%s failed with error code %i.", name, status.si_status);
4041 return status.si_status;
4044 log_debug("%s succeeded.", name);
4047 } else if (status.si_code == CLD_KILLED ||
4048 status.si_code == CLD_DUMPED) {
4050 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4054 log_warning("%s failed due to unknown reason.", name);
4058 _noreturn_ void freeze(void) {
4060 /* Make sure nobody waits for us on a socket anymore */
4061 close_all_fds(NULL, 0);
4069 bool null_or_empty(struct stat *st) {
4072 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4075 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4081 int null_or_empty_path(const char *fn) {
4086 if (stat(fn, &st) < 0)
4089 return null_or_empty(&st);
4092 DIR *xopendirat(int fd, const char *name, int flags) {
4096 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4102 close_nointr_nofail(nfd);
4109 int signal_from_string_try_harder(const char *s) {
4113 signo = signal_from_string(s);
4115 if (startswith(s, "SIG"))
4116 return signal_from_string(s+3);
4121 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4127 if (!dual_timestamp_is_set(t))
4130 fprintf(f, "%s=%llu %llu\n",
4132 (unsigned long long) t->realtime,
4133 (unsigned long long) t->monotonic);
4136 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4137 unsigned long long a, b;
4142 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4143 log_debug("Failed to parse finish timestamp value %s", value);
4150 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4154 /* FIXME: to follow udev's logic 100% we need to leave valid
4155 * UTF8 chars unescaped */
4157 u = unquote(tagvalue, "\"\'");
4161 t = xescape(u, "/ ");
4167 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4176 char *fstab_node_to_udev_node(const char *p) {
4179 if (startswith(p, "LABEL="))
4180 return tag_to_udev_node(p+6, "label");
4182 if (startswith(p, "UUID="))
4183 return tag_to_udev_node(p+5, "uuid");
4185 if (startswith(p, "PARTUUID="))
4186 return tag_to_udev_node(p+9, "partuuid");
4188 if (startswith(p, "PARTLABEL="))
4189 return tag_to_udev_node(p+10, "partlabel");
4194 bool tty_is_vc(const char *tty) {
4197 if (startswith(tty, "/dev/"))
4200 return vtnr_from_tty(tty) >= 0;
4203 bool tty_is_console(const char *tty) {
4206 if (startswith(tty, "/dev/"))
4209 return streq(tty, "console");
4212 int vtnr_from_tty(const char *tty) {
4217 if (startswith(tty, "/dev/"))
4220 if (!startswith(tty, "tty") )
4223 if (tty[3] < '0' || tty[3] > '9')
4226 r = safe_atoi(tty+3, &i);
4230 if (i < 0 || i > 63)
4236 bool tty_is_vc_resolve(const char *tty) {
4237 char *active = NULL;
4242 if (startswith(tty, "/dev/"))
4245 /* Resolve where /dev/console is pointing to, if /sys is
4246 * actually ours (i.e. not read-only-mounted which is a sign
4247 * for container setups) */
4248 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4249 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4250 /* If multiple log outputs are configured the
4251 * last one is what /dev/console points to */
4252 tty = strrchr(active, ' ');
4265 const char *default_term_for_tty(const char *tty) {
4268 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4271 bool dirent_is_file(const struct dirent *de) {
4274 if (ignore_file(de->d_name))
4277 if (de->d_type != DT_REG &&
4278 de->d_type != DT_LNK &&
4279 de->d_type != DT_UNKNOWN)
4285 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4288 if (de->d_type != DT_REG &&
4289 de->d_type != DT_LNK &&
4290 de->d_type != DT_UNKNOWN)
4293 if (ignore_file_allow_backup(de->d_name))
4296 return endswith(de->d_name, suffix);
4299 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4302 Hashmap *pids = NULL;
4306 /* Executes all binaries in a directory in parallel and waits
4307 * until all they all finished. */
4310 if (!(_d = opendir(directory))) {
4312 if (errno == ENOENT)
4315 log_error("Failed to enumerate directory %s: %m", directory);
4322 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4323 log_error("Failed to allocate set.");
4327 while ((de = readdir(d))) {
4332 if (!dirent_is_file(de))
4335 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4340 if ((pid = fork()) < 0) {
4341 log_error("Failed to fork: %m");
4359 log_error("Failed to execute %s: %m", path);
4360 _exit(EXIT_FAILURE);
4363 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4365 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4366 log_error("Failed to add PID to set: %s", strerror(-k));
4371 while (!hashmap_isempty(pids)) {
4372 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4377 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4382 log_error("waitid() failed: %m");
4386 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4387 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4388 if (si.si_code == CLD_EXITED)
4389 log_error("%s exited with exit status %i.", path, si.si_status);
4391 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4393 log_debug("%s exited successfully.", path);
4404 hashmap_free_free(pids);
4407 int kill_and_sigcont(pid_t pid, int sig) {
4410 r = kill(pid, sig) < 0 ? -errno : 0;
4418 bool nulstr_contains(const char*nulstr, const char *needle) {
4424 NULSTR_FOREACH(i, nulstr)
4425 if (streq(i, needle))
4431 bool plymouth_running(void) {
4432 return access("/run/plymouth/pid", F_OK) >= 0;
4435 char* strshorten(char *s, size_t l) {
4444 static bool hostname_valid_char(char c) {
4446 (c >= 'a' && c <= 'z') ||
4447 (c >= 'A' && c <= 'Z') ||
4448 (c >= '0' && c <= '9') ||
4454 bool hostname_is_valid(const char *s) {
4460 for (p = s; *p; p++)
4461 if (!hostname_valid_char(*p))
4464 if (p-s > HOST_NAME_MAX)
4470 char* hostname_cleanup(char *s) {
4473 for (p = s, d = s; *p; p++)
4474 if ((*p >= 'a' && *p <= 'z') ||
4475 (*p >= 'A' && *p <= 'Z') ||
4476 (*p >= '0' && *p <= '9') ||
4484 strshorten(s, HOST_NAME_MAX);
4488 int pipe_eof(int fd) {
4489 struct pollfd pollfd;
4494 pollfd.events = POLLIN|POLLHUP;
4496 r = poll(&pollfd, 1, 0);
4503 return pollfd.revents & POLLHUP;
4506 int fd_wait_for_event(int fd, int event, usec_t t) {
4507 struct pollfd pollfd;
4512 pollfd.events = event;
4514 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4521 return pollfd.revents;
4524 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4535 t = new(char, strlen(path) + 1 + 6 + 1);
4539 fn = path_get_file_name(path);
4543 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4545 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4551 f = fdopen(fd, "we");
4564 int terminal_vhangup_fd(int fd) {
4567 if (ioctl(fd, TIOCVHANGUP) < 0)
4573 int terminal_vhangup(const char *name) {
4576 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4580 r = terminal_vhangup_fd(fd);
4581 close_nointr_nofail(fd);
4586 int vt_disallocate(const char *name) {
4590 /* Deallocate the VT if possible. If not possible
4591 * (i.e. because it is the active one), at least clear it
4592 * entirely (including the scrollback buffer) */
4594 if (!startswith(name, "/dev/"))
4597 if (!tty_is_vc(name)) {
4598 /* So this is not a VT. I guess we cannot deallocate
4599 * it then. But let's at least clear the screen */
4601 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4606 "\033[r" /* clear scrolling region */
4607 "\033[H" /* move home */
4608 "\033[2J", /* clear screen */
4610 close_nointr_nofail(fd);
4615 if (!startswith(name, "/dev/tty"))
4618 r = safe_atou(name+8, &u);
4625 /* Try to deallocate */
4626 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4630 r = ioctl(fd, VT_DISALLOCATE, u);
4631 close_nointr_nofail(fd);
4639 /* Couldn't deallocate, so let's clear it fully with
4641 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4646 "\033[r" /* clear scrolling region */
4647 "\033[H" /* move home */
4648 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4650 close_nointr_nofail(fd);
4655 int copy_file(const char *from, const char *to) {
4661 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4665 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4667 close_nointr_nofail(fdf);
4675 n = read(fdf, buf, sizeof(buf));
4679 close_nointr_nofail(fdf);
4690 k = loop_write(fdt, buf, n, false);
4692 r = k < 0 ? k : (errno ? -errno : -EIO);
4694 close_nointr_nofail(fdf);
4702 close_nointr_nofail(fdf);
4703 r = close_nointr(fdt);
4713 int symlink_atomic(const char *from, const char *to) {
4715 _cleanup_free_ char *t;
4718 unsigned long long ull;
4725 t = new(char, strlen(to) + 1 + 16 + 1);
4729 fn = path_get_file_name(to);
4733 x = stpcpy(t+k+1, fn);
4736 for (i = 0; i < 16; i++) {
4737 *(x++) = hexchar(ull & 0xF);
4743 if (symlink(from, t) < 0)
4746 if (rename(t, to) < 0) {
4755 bool display_is_local(const char *display) {
4759 display[0] == ':' &&
4760 display[1] >= '0' &&
4764 int socket_from_display(const char *display, char **path) {
4771 if (!display_is_local(display))
4774 k = strspn(display+1, "0123456789");
4776 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4780 c = stpcpy(f, "/tmp/.X11-unix/X");
4781 memcpy(c, display+1, k);
4790 const char **username,
4791 uid_t *uid, gid_t *gid,
4793 const char **shell) {
4801 /* We enforce some special rules for uid=0: in order to avoid
4802 * NSS lookups for root we hardcode its data. */
4804 if (streq(*username, "root") || streq(*username, "0")) {
4822 if (parse_uid(*username, &u) >= 0) {
4826 /* If there are multiple users with the same id, make
4827 * sure to leave $USER to the configured value instead
4828 * of the first occurrence in the database. However if
4829 * the uid was configured by a numeric uid, then let's
4830 * pick the real username from /etc/passwd. */
4832 *username = p->pw_name;
4835 p = getpwnam(*username);
4839 return errno != 0 ? -errno : -ESRCH;
4851 *shell = p->pw_shell;
4856 int get_group_creds(const char **groupname, gid_t *gid) {
4862 /* We enforce some special rules for gid=0: in order to avoid
4863 * NSS lookups for root we hardcode its data. */
4865 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4866 *groupname = "root";
4874 if (parse_gid(*groupname, &id) >= 0) {
4879 *groupname = g->gr_name;
4882 g = getgrnam(*groupname);
4886 return errno != 0 ? -errno : -ESRCH;
4894 int in_group(const char *name) {
4896 int ngroups_max, r, i;
4898 r = get_group_creds(&name, &gid);
4902 if (getgid() == gid)
4905 if (getegid() == gid)
4908 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4909 assert(ngroups_max > 0);
4911 gids = alloca(sizeof(gid_t) * ngroups_max);
4913 r = getgroups(ngroups_max, gids);
4917 for (i = 0; i < r; i++)
4924 int glob_exists(const char *path) {
4932 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4934 if (k == GLOB_NOMATCH)
4936 else if (k == GLOB_NOSPACE)
4939 r = !strv_isempty(g.gl_pathv);
4941 r = errno ? -errno : -EIO;
4948 int dirent_ensure_type(DIR *d, struct dirent *de) {
4954 if (de->d_type != DT_UNKNOWN)
4957 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4961 S_ISREG(st.st_mode) ? DT_REG :
4962 S_ISDIR(st.st_mode) ? DT_DIR :
4963 S_ISLNK(st.st_mode) ? DT_LNK :
4964 S_ISFIFO(st.st_mode) ? DT_FIFO :
4965 S_ISSOCK(st.st_mode) ? DT_SOCK :
4966 S_ISCHR(st.st_mode) ? DT_CHR :
4967 S_ISBLK(st.st_mode) ? DT_BLK :
4973 int in_search_path(const char *path, char **search) {
4977 r = path_get_parent(path, &parent);
4983 STRV_FOREACH(i, search) {
4984 if (path_equal(parent, *i)) {
4995 int get_files_in_directory(const char *path, char ***list) {
5003 /* Returns all files in a directory in *list, and the number
5004 * of files as return value. If list is NULL returns only the
5013 union dirent_storage buf;
5016 k = readdir_r(d, &buf.de, &de);
5025 dirent_ensure_type(d, de);
5027 if (!dirent_is_file(de))
5031 if ((unsigned) r >= n) {
5035 t = realloc(l, sizeof(char*) * n);
5044 assert((unsigned) r < n);
5046 l[r] = strdup(de->d_name);
5070 char *strjoin(const char *x, ...) {
5084 t = va_arg(ap, const char *);
5089 if (n > ((size_t) -1) - l) {
5113 t = va_arg(ap, const char *);
5127 bool is_main_thread(void) {
5128 static __thread int cached = 0;
5130 if (_unlikely_(cached == 0))
5131 cached = getpid() == gettid() ? 1 : -1;
5136 int block_get_whole_disk(dev_t d, dev_t *ret) {
5143 /* If it has a queue this is good enough for us */
5144 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5147 r = access(p, F_OK);
5155 /* If it is a partition find the originating device */
5156 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5159 r = access(p, F_OK);
5165 /* Get parent dev_t */
5166 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5169 r = read_one_line_file(p, &s);
5175 r = sscanf(s, "%u:%u", &m, &n);
5181 /* Only return this if it is really good enough for us. */
5182 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5185 r = access(p, F_OK);
5189 *ret = makedev(m, n);
5196 int file_is_priv_sticky(const char *p) {
5201 if (lstat(p, &st) < 0)
5205 (st.st_uid == 0 || st.st_uid == getuid()) &&
5206 (st.st_mode & S_ISVTX);
5209 static const char *const ioprio_class_table[] = {
5210 [IOPRIO_CLASS_NONE] = "none",
5211 [IOPRIO_CLASS_RT] = "realtime",
5212 [IOPRIO_CLASS_BE] = "best-effort",
5213 [IOPRIO_CLASS_IDLE] = "idle"
5216 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
5218 static const char *const sigchld_code_table[] = {
5219 [CLD_EXITED] = "exited",
5220 [CLD_KILLED] = "killed",
5221 [CLD_DUMPED] = "dumped",
5222 [CLD_TRAPPED] = "trapped",
5223 [CLD_STOPPED] = "stopped",
5224 [CLD_CONTINUED] = "continued",
5227 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5229 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5230 [LOG_FAC(LOG_KERN)] = "kern",
5231 [LOG_FAC(LOG_USER)] = "user",
5232 [LOG_FAC(LOG_MAIL)] = "mail",
5233 [LOG_FAC(LOG_DAEMON)] = "daemon",
5234 [LOG_FAC(LOG_AUTH)] = "auth",
5235 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5236 [LOG_FAC(LOG_LPR)] = "lpr",
5237 [LOG_FAC(LOG_NEWS)] = "news",
5238 [LOG_FAC(LOG_UUCP)] = "uucp",
5239 [LOG_FAC(LOG_CRON)] = "cron",
5240 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5241 [LOG_FAC(LOG_FTP)] = "ftp",
5242 [LOG_FAC(LOG_LOCAL0)] = "local0",
5243 [LOG_FAC(LOG_LOCAL1)] = "local1",
5244 [LOG_FAC(LOG_LOCAL2)] = "local2",
5245 [LOG_FAC(LOG_LOCAL3)] = "local3",
5246 [LOG_FAC(LOG_LOCAL4)] = "local4",
5247 [LOG_FAC(LOG_LOCAL5)] = "local5",
5248 [LOG_FAC(LOG_LOCAL6)] = "local6",
5249 [LOG_FAC(LOG_LOCAL7)] = "local7"
5252 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5254 static const char *const log_level_table[] = {
5255 [LOG_EMERG] = "emerg",
5256 [LOG_ALERT] = "alert",
5257 [LOG_CRIT] = "crit",
5259 [LOG_WARNING] = "warning",
5260 [LOG_NOTICE] = "notice",
5261 [LOG_INFO] = "info",
5262 [LOG_DEBUG] = "debug"
5265 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5267 static const char* const sched_policy_table[] = {
5268 [SCHED_OTHER] = "other",
5269 [SCHED_BATCH] = "batch",
5270 [SCHED_IDLE] = "idle",
5271 [SCHED_FIFO] = "fifo",
5275 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5277 static const char* const rlimit_table[] = {
5278 [RLIMIT_CPU] = "LimitCPU",
5279 [RLIMIT_FSIZE] = "LimitFSIZE",
5280 [RLIMIT_DATA] = "LimitDATA",
5281 [RLIMIT_STACK] = "LimitSTACK",
5282 [RLIMIT_CORE] = "LimitCORE",
5283 [RLIMIT_RSS] = "LimitRSS",
5284 [RLIMIT_NOFILE] = "LimitNOFILE",
5285 [RLIMIT_AS] = "LimitAS",
5286 [RLIMIT_NPROC] = "LimitNPROC",
5287 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5288 [RLIMIT_LOCKS] = "LimitLOCKS",
5289 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5290 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5291 [RLIMIT_NICE] = "LimitNICE",
5292 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5293 [RLIMIT_RTTIME] = "LimitRTTIME"
5296 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5298 static const char* const ip_tos_table[] = {
5299 [IPTOS_LOWDELAY] = "low-delay",
5300 [IPTOS_THROUGHPUT] = "throughput",
5301 [IPTOS_RELIABILITY] = "reliability",
5302 [IPTOS_LOWCOST] = "low-cost",
5305 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5307 static const char *const __signal_table[] = {
5324 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5335 [SIGVTALRM] = "VTALRM",
5337 [SIGWINCH] = "WINCH",
5343 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5345 const char *signal_to_string(int signo) {
5346 static __thread char buf[12];
5349 name = __signal_to_string(signo);
5353 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5354 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5356 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5361 int signal_from_string(const char *s) {
5366 signo = __signal_from_string(s);
5370 if (startswith(s, "RTMIN+")) {
5374 if (safe_atou(s, &u) >= 0) {
5375 signo = (int) u + offset;
5376 if (signo > 0 && signo < _NSIG)
5382 bool kexec_loaded(void) {
5383 bool loaded = false;
5386 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5394 int strdup_or_null(const char *a, char **b) {
5412 int prot_from_flags(int flags) {
5414 switch (flags & O_ACCMODE) {
5423 return PROT_READ|PROT_WRITE;
5430 char *format_bytes(char *buf, size_t l, off_t t) {
5433 static const struct {
5437 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5438 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5439 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5440 { "G", 1024ULL*1024ULL*1024ULL },
5441 { "M", 1024ULL*1024ULL },
5445 for (i = 0; i < ELEMENTSOF(table); i++) {
5447 if (t >= table[i].factor) {
5450 (unsigned long long) (t / table[i].factor),
5451 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5458 snprintf(buf, l, "%lluB", (unsigned long long) t);
5466 void* memdup(const void *p, size_t l) {
5479 int fd_inc_sndbuf(int fd, size_t n) {
5481 socklen_t l = sizeof(value);
5483 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5485 l == sizeof(value) &&
5486 (size_t) value >= n*2)
5490 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5497 int fd_inc_rcvbuf(int fd, size_t n) {
5499 socklen_t l = sizeof(value);
5501 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5503 l == sizeof(value) &&
5504 (size_t) value >= n*2)
5508 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5515 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5516 pid_t parent_pid, agent_pid;
5518 bool stdout_is_tty, stderr_is_tty;
5526 parent_pid = getpid();
5528 /* Spawns a temporary TTY agent, making sure it goes away when
5535 if (agent_pid != 0) {
5542 * Make sure the agent goes away when the parent dies */
5543 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5544 _exit(EXIT_FAILURE);
5546 /* Check whether our parent died before we were able
5547 * to set the death signal */
5548 if (getppid() != parent_pid)
5549 _exit(EXIT_SUCCESS);
5551 /* Don't leak fds to the agent */
5552 close_all_fds(except, n_except);
5554 stdout_is_tty = isatty(STDOUT_FILENO);
5555 stderr_is_tty = isatty(STDERR_FILENO);
5557 if (!stdout_is_tty || !stderr_is_tty) {
5558 /* Detach from stdout/stderr. and reopen
5559 * /dev/tty for them. This is important to
5560 * ensure that when systemctl is started via
5561 * popen() or a similar call that expects to
5562 * read EOF we actually do generate EOF and
5563 * not delay this indefinitely by because we
5564 * keep an unused copy of stdin around. */
5565 fd = open("/dev/tty", O_WRONLY);
5567 log_error("Failed to open /dev/tty: %m");
5568 _exit(EXIT_FAILURE);
5572 dup2(fd, STDOUT_FILENO);
5575 dup2(fd, STDERR_FILENO);
5581 /* Count arguments */
5583 for (n = 0; va_arg(ap, char*); n++)
5588 l = alloca(sizeof(char *) * (n + 1));
5590 /* Fill in arguments */
5592 for (i = 0; i <= n; i++)
5593 l[i] = va_arg(ap, char*);
5597 _exit(EXIT_FAILURE);
5600 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5601 struct rlimit highest, fixed;
5605 if (setrlimit(resource, rlim) >= 0)
5611 /* So we failed to set the desired setrlimit, then let's try
5612 * to get as close as we can */
5613 assert_se(getrlimit(resource, &highest) == 0);
5615 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5616 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5618 if (setrlimit(resource, &fixed) < 0)
5624 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5625 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5637 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5640 f = fopen(path, "re");
5648 char line[LINE_MAX];
5651 for (i = 0; i < sizeof(line)-1; i++) {
5655 if (_unlikely_(c == EOF)) {
5665 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5666 value = strdup(line + l + 1);
5686 int can_sleep(const char *type) {
5690 _cleanup_free_ char *p = NULL;
5694 r = read_one_line_file("/sys/power/state", &p);
5696 return r == -ENOENT ? 0 : r;
5699 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5700 if (l == k && memcmp(w, type, l) == 0)
5706 int can_sleep_disk(const char *type) {
5710 _cleanup_free_ char *p = NULL;
5714 r = read_one_line_file("/sys/power/disk", &p);
5716 return r == -ENOENT ? 0 : r;
5719 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5720 if (l == k && memcmp(w, type, l) == 0)
5723 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5730 bool is_valid_documentation_url(const char *url) {
5733 if (startswith(url, "http://") && url[7])
5736 if (startswith(url, "https://") && url[8])
5739 if (startswith(url, "file:") && url[5])
5742 if (startswith(url, "info:") && url[5])
5745 if (startswith(url, "man:") && url[4])
5751 bool in_initrd(void) {
5752 static __thread int saved = -1;
5758 /* We make two checks here:
5760 * 1. the flag file /etc/initrd-release must exist
5761 * 2. the root file system must be a memory file system
5763 * The second check is extra paranoia, since misdetecting an
5764 * initrd can have bad bad consequences due the initrd
5765 * emptying when transititioning to the main systemd.
5768 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5769 statfs("/", &s) >= 0 &&
5770 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5775 void warn_melody(void) {
5776 _cleanup_close_ int fd = -1;
5778 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5782 /* Yeah, this is synchronous. Kinda sucks. But well... */
5784 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5785 usleep(125*USEC_PER_MSEC);
5787 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5788 usleep(125*USEC_PER_MSEC);
5790 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5791 usleep(125*USEC_PER_MSEC);
5793 ioctl(fd, KIOCSOUND, 0);
5796 int make_console_stdio(void) {
5799 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5801 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5803 log_error("Failed to acquire terminal: %s", strerror(-fd));
5809 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5816 int get_home_dir(char **_h) {
5824 /* Take the user specified one */
5835 /* Hardcode home directory for root to avoid NSS */
5838 h = strdup("/root");
5846 /* Check the database... */
5850 return errno ? -errno : -ESRCH;
5852 if (!path_is_absolute(p->pw_dir))
5855 h = strdup(p->pw_dir);
5863 int get_shell(char **_sh) {
5871 /* Take the user specified one */
5872 e = getenv("SHELL");
5882 /* Hardcode home directory for root to avoid NSS */
5885 sh = strdup("/bin/sh");
5893 /* Check the database... */
5897 return errno ? -errno : -ESRCH;
5899 if (!path_is_absolute(p->pw_shell))
5902 sh = strdup(p->pw_shell);
5910 void freep(void *p) {
5914 void fclosep(FILE **f) {
5919 void closep(int *fd) {
5921 close_nointr_nofail(*fd);
5924 void closedirp(DIR **d) {
5929 void umaskp(mode_t *u) {
5933 bool filename_is_safe(const char *p) {
5947 if (strlen(p) > FILENAME_MAX)
5953 bool string_is_safe(const char *p) {
5958 for (t = p; *t; t++) {
5959 if (*t > 0 && *t < ' ')
5962 if (strchr("\\\"\'", *t))
5969 int parse_timestamp(const char *t, usec_t *usec) {
5973 usec_t plus = 0, minus = 0, ret;
5979 * 2012-09-22 16:34:22
5980 * 2012-09-22 16:34 (seconds will be set to 0)
5981 * 2012-09-22 (time will be set to 00:00:00)
5982 * 16:34:22 (date will be set to today)
5983 * 16:34 (date will be set to today, seconds to 0)
5985 * yesterday (time is set to 00:00:00)
5986 * today (time is set to 00:00:00)
5987 * tomorrow (time is set to 00:00:00)
5997 assert_se(localtime_r(&x, &tm));
5999 if (streq(t, "now"))
6002 else if (streq(t, "today")) {
6003 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6006 } else if (streq(t, "yesterday")) {
6008 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6011 } else if (streq(t, "tomorrow")) {
6013 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6016 } else if (t[0] == '+') {
6018 r = parse_usec(t+1, &plus);
6023 } else if (t[0] == '-') {
6025 r = parse_usec(t+1, &minus);
6033 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6038 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6043 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6050 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6057 k = strptime(t, "%y-%m-%d", &tm);
6059 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6064 k = strptime(t, "%Y-%m-%d", &tm);
6066 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6071 k = strptime(t, "%H:%M:%S", &tm);
6076 k = strptime(t, "%H:%M", &tm);
6086 if (x == (time_t) -1)
6089 ret = (usec_t) x * USEC_PER_SEC;
6102 /* hey glibc, APIs with callbacks without a user pointer are so useless */
6103 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
6104 int (*compar) (const void *, const void *, void *), void *arg) {
6113 p = (void *)(((const char *) base) + (idx * size));
6114 comparison = compar(key, p, arg);
6117 else if (comparison > 0)
6125 bool is_locale_utf8(void) {
6127 static int cached_answer = -1;
6129 if (cached_answer >= 0)
6132 if (!setlocale(LC_ALL, "")) {
6133 cached_answer = true;
6137 set = nl_langinfo(CODESET);
6139 cached_answer = true;
6143 cached_answer = streq(set, "UTF-8");
6145 return (bool)cached_answer;
6148 const char *draw_special_char(DrawSpecialChar ch) {
6149 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
6151 [DRAW_BOX_VERT] = "\342\224\202", /* │ */
6152 [DRAW_BOX_VERT_AND_RIGHT] = "\342\224\234", /* ├ */
6153 [DRAW_BOX_UP_AND_RIGHT] = "\342\224\224", /* └ */
6154 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
6156 /* ASCII fallback */ {
6157 [DRAW_BOX_VERT] = "|",
6158 [DRAW_BOX_VERT_AND_RIGHT] = "+",
6159 [DRAW_BOX_UP_AND_RIGHT] = "\\",
6160 [DRAW_TRIANGULAR_BULLET] = ">",
6164 return draw_table[!is_locale_utf8()][ch];