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>
67 #include "path-util.h"
68 #include "exit-status.h"
72 char **saved_argv = NULL;
74 size_t page_size(void) {
75 static __thread size_t pgsz = 0;
78 if (_likely_(pgsz > 0))
81 r = sysconf(_SC_PAGESIZE);
88 bool streq_ptr(const char *a, const char *b) {
90 /* Like streq(), but tries to make sense of NULL pointers */
101 usec_t now(clockid_t clock_id) {
104 assert_se(clock_gettime(clock_id, &ts) == 0);
106 return timespec_load(&ts);
109 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
112 ts->realtime = now(CLOCK_REALTIME);
113 ts->monotonic = now(CLOCK_MONOTONIC);
118 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
127 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
129 ts->monotonic = now(CLOCK_MONOTONIC);
131 if ((int64_t) ts->monotonic > delta)
132 ts->monotonic -= delta;
140 usec_t timespec_load(const struct timespec *ts) {
144 (usec_t) ts->tv_sec * USEC_PER_SEC +
145 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
148 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
151 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
152 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
157 usec_t timeval_load(const struct timeval *tv) {
161 (usec_t) tv->tv_sec * USEC_PER_SEC +
162 (usec_t) tv->tv_usec;
165 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
168 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
169 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
174 bool endswith(const char *s, const char *postfix) {
181 pl = strlen(postfix);
189 return memcmp(s + sl - pl, postfix, pl) == 0;
192 bool startswith(const char *s, const char *prefix) {
207 return memcmp(s, prefix, pl) == 0;
210 bool startswith_no_case(const char *s, const char *prefix) {
226 for(i = 0; i < pl; ++i)
227 if (tolower(s[i]) != tolower(prefix[i]))
233 bool first_word(const char *s, const char *word) {
248 if (memcmp(s, word, wl) != 0)
252 strchr(WHITESPACE, s[wl]);
255 int close_nointr(int fd) {
270 void close_nointr_nofail(int fd) {
271 int saved_errno = errno;
273 /* like close_nointr() but cannot fail, and guarantees errno
276 assert_se(close_nointr(fd) == 0);
281 void close_many(const int fds[], unsigned n_fd) {
284 for (i = 0; i < n_fd; i++)
285 close_nointr_nofail(fds[i]);
288 int parse_boolean(const char *v) {
291 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
293 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
299 int parse_pid(const char *s, pid_t* ret_pid) {
300 unsigned long ul = 0;
307 r = safe_atolu(s, &ul);
313 if ((unsigned long) pid != ul)
323 int parse_uid(const char *s, uid_t* ret_uid) {
324 unsigned long ul = 0;
331 r = safe_atolu(s, &ul);
337 if ((unsigned long) uid != ul)
344 int safe_atou(const char *s, unsigned *ret_u) {
352 l = strtoul(s, &x, 0);
354 if (!x || *x || errno)
355 return errno ? -errno : -EINVAL;
357 if ((unsigned long) (unsigned) l != l)
360 *ret_u = (unsigned) l;
364 int safe_atoi(const char *s, int *ret_i) {
372 l = strtol(s, &x, 0);
374 if (!x || *x || errno)
375 return errno ? -errno : -EINVAL;
377 if ((long) (int) l != l)
384 int safe_atollu(const char *s, long long unsigned *ret_llu) {
386 unsigned long long l;
392 l = strtoull(s, &x, 0);
394 if (!x || *x || errno)
395 return errno ? -errno : -EINVAL;
401 int safe_atolli(const char *s, long long int *ret_lli) {
409 l = strtoll(s, &x, 0);
411 if (!x || *x || errno)
412 return errno ? -errno : -EINVAL;
418 /* Split a string into words. */
419 char *split(const char *c, size_t *l, const char *separator, char **state) {
422 current = *state ? *state : (char*) c;
424 if (!*current || *c == 0)
427 current += strspn(current, separator);
428 *l = strcspn(current, separator);
431 return (char*) current;
434 /* Split a string into words, but consider strings enclosed in '' and
435 * "" as words even if they include spaces. */
436 char *split_quoted(const char *c, size_t *l, char **state) {
438 bool escaped = false;
440 current = *state ? *state : (char*) c;
442 if (!*current || *c == 0)
445 current += strspn(current, WHITESPACE);
447 if (*current == '\'') {
450 for (e = current; *e; e++) {
460 *state = *e == 0 ? e : e+1;
461 } else if (*current == '\"') {
464 for (e = current; *e; e++) {
474 *state = *e == 0 ? e : e+1;
476 for (e = current; *e; e++) {
481 else if (strchr(WHITESPACE, *e))
488 return (char*) current;
491 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
493 _cleanup_fclose_ FILE *f = NULL;
494 char fn[PATH_MAX], line[LINE_MAX], *p;
500 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
507 if (!fgets(line, sizeof(line), f)) {
508 r = feof(f) ? -EIO : -errno;
513 /* Let's skip the pid and comm fields. The latter is enclosed
514 * in () but does not escape any () in its value, so let's
515 * skip over it manually */
517 p = strrchr(line, ')');
529 if ((long unsigned) (pid_t) ppid != ppid)
532 *_ppid = (pid_t) ppid;
537 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
538 _cleanup_fclose_ FILE *f = NULL;
539 char fn[PATH_MAX], line[LINE_MAX], *p;
544 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
551 if (!fgets(line, sizeof(line), f)) {
558 /* Let's skip the pid and comm fields. The latter is enclosed
559 * in () but does not escape any () in its value, so let's
560 * skip over it manually */
562 p = strrchr(line, ')');
584 "%*d " /* priority */
586 "%*d " /* num_threads */
587 "%*d " /* itrealvalue */
588 "%llu " /* starttime */,
595 int write_one_line_file(const char *fn, const char *line) {
596 _cleanup_fclose_ FILE *f = NULL;
606 if (fputs(line, f) < 0)
607 return errno ? -errno : -EIO;
609 if (!endswith(line, "\n"))
615 return errno ? -errno : -EIO;
620 int fchmod_umask(int fd, mode_t m) {
625 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
631 int write_one_line_file_atomic(const char *fn, const char *line) {
639 r = fopen_temporary(fn, &f, &p);
643 fchmod_umask(fileno(f), 0644);
646 if (fputs(line, f) < 0) {
651 if (!endswith(line, "\n"))
662 if (rename(p, fn) < 0)
678 int read_one_line_file(const char *fn, char **line) {
679 _cleanup_fclose_ FILE *f = NULL;
680 char t[LINE_MAX], *c;
689 if (!fgets(t, sizeof(t), f)) {
692 return errno ? -errno : -EIO;
706 int read_full_file(const char *fn, char **contents, size_t *size) {
707 _cleanup_fclose_ FILE *f = NULL;
709 _cleanup_free_ char *buf = NULL;
716 if (fstat(fileno(f), &st) < 0)
720 if (st.st_size > 4*1024*1024)
723 n = st.st_size > 0 ? st.st_size : LINE_MAX;
730 t = realloc(buf, n+1);
735 k = fread(buf + l, 1, n - l, f);
764 const char *separator, ...) {
767 char *contents = NULL, *p;
772 if ((r = read_full_file(fname, &contents, NULL)) < 0)
777 const char *key = NULL;
779 p += strspn(p, separator);
780 p += strspn(p, WHITESPACE);
785 if (!strchr(COMMENTS, *p)) {
789 va_start(ap, separator);
790 while ((key = va_arg(ap, char *))) {
794 value = va_arg(ap, char **);
797 if (strncmp(p, key, n) != 0 ||
802 n = strcspn(p, separator);
805 strchr(QUOTES, p[0]) &&
807 v = strndup(p+1, n-2);
818 /* return empty value strings as NULL */
835 p += strcspn(p, separator);
854 if (!(f = fopen(fname, "re")))
858 char l[LINE_MAX], *p, *u;
861 if (!fgets(l, sizeof(l), f)) {
874 if (strchr(COMMENTS, *p))
877 if (!(u = normalize_env_assignment(p))) {
882 t = strv_append(m, u);
908 int write_env_file(const char *fname, char **l) {
913 r = fopen_temporary(fname, &f, &p);
917 fchmod_umask(fileno(f), 0644);
933 if (rename(p, fname) < 0)
948 char *truncate_nl(char *s) {
951 s[strcspn(s, NEWLINE)] = 0;
955 int get_process_comm(pid_t pid, char **name) {
961 r = read_one_line_file("/proc/self/comm", name);
964 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
967 r = read_one_line_file(p, name);
974 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
981 assert(max_length > 0);
985 f = fopen("/proc/self/cmdline", "re");
988 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
998 r = new(char, max_length);
1006 while ((c = getc(f)) != EOF) {
1028 size_t n = MIN(left-1, 3U);
1029 memcpy(k, "...", n);
1036 /* Kernel threads have no argv[] */
1046 h = get_process_comm(pid, &t);
1050 r = strjoin("[", t, "]", NULL);
1061 int is_kernel_thread(pid_t pid) {
1071 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1080 count = fread(&c, 1, 1, f);
1084 /* Kernel threads have an empty cmdline */
1087 return eof ? 1 : -errno;
1092 int get_process_exe(pid_t pid, char **name) {
1098 r = readlink_malloc("/proc/self/exe", name);
1101 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1104 r = readlink_malloc(p, name);
1111 int get_process_uid(pid_t pid, uid_t *uid) {
1121 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1131 char line[LINE_MAX], *l;
1133 if (!fgets(line, sizeof(line), f)) {
1143 if (startswith(l, "Uid:")) {
1145 l += strspn(l, WHITESPACE);
1147 l[strcspn(l, WHITESPACE)] = 0;
1149 r = parse_uid(l, uid);
1162 char *strnappend(const char *s, const char *suffix, size_t b) {
1170 return strndup(suffix, b);
1180 if (!(r = new(char, a+b+1)))
1184 memcpy(r+a, suffix, b);
1190 char *strappend(const char *s, const char *suffix) {
1191 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1194 int readlink_malloc(const char *p, char **r) {
1204 if (!(c = new(char, l)))
1207 if ((n = readlink(p, c, l-1)) < 0) {
1213 if ((size_t) n < l-1) {
1224 int readlink_and_make_absolute(const char *p, char **r) {
1231 if ((j = readlink_malloc(p, &target)) < 0)
1234 k = file_in_same_dir(p, target);
1244 int readlink_and_canonicalize(const char *p, char **r) {
1251 j = readlink_and_make_absolute(p, &t);
1255 s = canonicalize_file_name(t);
1262 path_kill_slashes(*r);
1267 int reset_all_signal_handlers(void) {
1270 for (sig = 1; sig < _NSIG; sig++) {
1271 struct sigaction sa;
1273 if (sig == SIGKILL || sig == SIGSTOP)
1277 sa.sa_handler = SIG_DFL;
1278 sa.sa_flags = SA_RESTART;
1280 /* On Linux the first two RT signals are reserved by
1281 * glibc, and sigaction() will return EINVAL for them. */
1282 if ((sigaction(sig, &sa, NULL) < 0))
1283 if (errno != EINVAL)
1290 char *strstrip(char *s) {
1293 /* Drops trailing whitespace. Modifies the string in
1294 * place. Returns pointer to first non-space character */
1296 s += strspn(s, WHITESPACE);
1298 for (e = strchr(s, 0); e > s; e --)
1299 if (!strchr(WHITESPACE, e[-1]))
1307 char *delete_chars(char *s, const char *bad) {
1310 /* Drops all whitespace, regardless where in the string */
1312 for (f = s, t = s; *f; f++) {
1313 if (strchr(bad, *f))
1324 bool in_charset(const char *s, const char* charset) {
1330 for (i = s; *i; i++)
1331 if (!strchr(charset, *i))
1337 char *file_in_same_dir(const char *path, const char *filename) {
1344 /* This removes the last component of path and appends
1345 * filename, unless the latter is absolute anyway or the
1348 if (path_is_absolute(filename))
1349 return strdup(filename);
1351 if (!(e = strrchr(path, '/')))
1352 return strdup(filename);
1354 k = strlen(filename);
1355 if (!(r = new(char, e-path+1+k+1)))
1358 memcpy(r, path, e-path+1);
1359 memcpy(r+(e-path)+1, filename, k+1);
1364 int rmdir_parents(const char *path, const char *stop) {
1373 /* Skip trailing slashes */
1374 while (l > 0 && path[l-1] == '/')
1380 /* Skip last component */
1381 while (l > 0 && path[l-1] != '/')
1384 /* Skip trailing slashes */
1385 while (l > 0 && path[l-1] == '/')
1391 if (!(t = strndup(path, l)))
1394 if (path_startswith(stop, t)) {
1403 if (errno != ENOENT)
1411 char hexchar(int x) {
1412 static const char table[16] = "0123456789abcdef";
1414 return table[x & 15];
1417 int unhexchar(char c) {
1419 if (c >= '0' && c <= '9')
1422 if (c >= 'a' && c <= 'f')
1423 return c - 'a' + 10;
1425 if (c >= 'A' && c <= 'F')
1426 return c - 'A' + 10;
1431 char octchar(int x) {
1432 return '0' + (x & 7);
1435 int unoctchar(char c) {
1437 if (c >= '0' && c <= '7')
1443 char decchar(int x) {
1444 return '0' + (x % 10);
1447 int undecchar(char c) {
1449 if (c >= '0' && c <= '9')
1455 char *cescape(const char *s) {
1461 /* Does C style string escaping. */
1463 r = new(char, strlen(s)*4 + 1);
1467 for (f = s, t = r; *f; f++)
1513 /* For special chars we prefer octal over
1514 * hexadecimal encoding, simply because glib's
1515 * g_strescape() does the same */
1516 if ((*f < ' ') || (*f >= 127)) {
1518 *(t++) = octchar((unsigned char) *f >> 6);
1519 *(t++) = octchar((unsigned char) *f >> 3);
1520 *(t++) = octchar((unsigned char) *f);
1531 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1538 /* Undoes C style string escaping, and optionally prefixes it. */
1540 pl = prefix ? strlen(prefix) : 0;
1542 r = new(char, pl+length+1);
1547 memcpy(r, prefix, pl);
1549 for (f = s, t = r + pl; f < s + length; f++) {
1592 /* This is an extension of the XDG syntax files */
1597 /* hexadecimal encoding */
1600 a = unhexchar(f[1]);
1601 b = unhexchar(f[2]);
1603 if (a < 0 || b < 0) {
1604 /* Invalid escape code, let's take it literal then */
1608 *(t++) = (char) ((a << 4) | b);
1623 /* octal encoding */
1626 a = unoctchar(f[0]);
1627 b = unoctchar(f[1]);
1628 c = unoctchar(f[2]);
1630 if (a < 0 || b < 0 || c < 0) {
1631 /* Invalid escape code, let's take it literal then */
1635 *(t++) = (char) ((a << 6) | (b << 3) | c);
1643 /* premature end of string.*/
1648 /* Invalid escape code, let's take it literal then */
1660 char *cunescape_length(const char *s, size_t length) {
1661 return cunescape_length_with_prefix(s, length, NULL);
1664 char *cunescape(const char *s) {
1667 return cunescape_length(s, strlen(s));
1670 char *xescape(const char *s, const char *bad) {
1674 /* Escapes all chars in bad, in addition to \ and all special
1675 * chars, in \xFF style escaping. May be reversed with
1678 if (!(r = new(char, strlen(s)*4+1)))
1681 for (f = s, t = r; *f; f++) {
1683 if ((*f < ' ') || (*f >= 127) ||
1684 (*f == '\\') || strchr(bad, *f)) {
1687 *(t++) = hexchar(*f >> 4);
1688 *(t++) = hexchar(*f);
1698 char *bus_path_escape(const char *s) {
1704 /* Escapes all chars that D-Bus' object path cannot deal
1705 * with. Can be reverse with bus_path_unescape() */
1707 if (!(r = new(char, strlen(s)*3+1)))
1710 for (f = s, t = r; *f; f++) {
1712 if (!(*f >= 'A' && *f <= 'Z') &&
1713 !(*f >= 'a' && *f <= 'z') &&
1714 !(*f >= '0' && *f <= '9')) {
1716 *(t++) = hexchar(*f >> 4);
1717 *(t++) = hexchar(*f);
1727 char *bus_path_unescape(const char *f) {
1732 if (!(r = strdup(f)))
1735 for (t = r; *f; f++) {
1740 if ((a = unhexchar(f[1])) < 0 ||
1741 (b = unhexchar(f[2])) < 0) {
1742 /* Invalid escape code, let's take it literal then */
1745 *(t++) = (char) ((a << 4) | b);
1757 char *ascii_strlower(char *t) {
1762 for (p = t; *p; p++)
1763 if (*p >= 'A' && *p <= 'Z')
1764 *p = *p - 'A' + 'a';
1769 static bool ignore_file_allow_backup(const char *filename) {
1773 filename[0] == '.' ||
1774 streq(filename, "lost+found") ||
1775 streq(filename, "aquota.user") ||
1776 streq(filename, "aquota.group") ||
1777 endswith(filename, ".rpmnew") ||
1778 endswith(filename, ".rpmsave") ||
1779 endswith(filename, ".rpmorig") ||
1780 endswith(filename, ".dpkg-old") ||
1781 endswith(filename, ".dpkg-new") ||
1782 endswith(filename, ".swp");
1785 bool ignore_file(const char *filename) {
1788 if (endswith(filename, "~"))
1791 return ignore_file_allow_backup(filename);
1794 int fd_nonblock(int fd, bool nonblock) {
1799 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1803 flags |= O_NONBLOCK;
1805 flags &= ~O_NONBLOCK;
1807 if (fcntl(fd, F_SETFL, flags) < 0)
1813 int fd_cloexec(int fd, bool cloexec) {
1818 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1822 flags |= FD_CLOEXEC;
1824 flags &= ~FD_CLOEXEC;
1826 if (fcntl(fd, F_SETFD, flags) < 0)
1832 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1835 assert(n_fdset == 0 || fdset);
1837 for (i = 0; i < n_fdset; i++)
1844 int close_all_fds(const int except[], unsigned n_except) {
1849 assert(n_except == 0 || except);
1851 d = opendir("/proc/self/fd");
1856 /* When /proc isn't available (for example in chroots)
1857 * the fallback is brute forcing through the fd
1860 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1861 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1863 if (fd_in_set(fd, except, n_except))
1866 if (close_nointr(fd) < 0)
1867 if (errno != EBADF && r == 0)
1874 while ((de = readdir(d))) {
1877 if (ignore_file(de->d_name))
1880 if (safe_atoi(de->d_name, &fd) < 0)
1881 /* Let's better ignore this, just in case */
1890 if (fd_in_set(fd, except, n_except))
1893 if (close_nointr(fd) < 0) {
1894 /* Valgrind has its own FD and doesn't want to have it closed */
1895 if (errno != EBADF && r == 0)
1904 bool chars_intersect(const char *a, const char *b) {
1907 /* Returns true if any of the chars in a are in b. */
1908 for (p = a; *p; p++)
1915 char *format_timestamp(char *buf, size_t l, usec_t t) {
1925 sec = (time_t) (t / USEC_PER_SEC);
1927 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1933 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1936 n = now(CLOCK_REALTIME);
1938 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1943 if (d >= USEC_PER_YEAR)
1944 snprintf(buf, l, "%llu years and %llu months ago",
1945 (unsigned long long) (d / USEC_PER_YEAR),
1946 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1947 else if (d >= USEC_PER_MONTH)
1948 snprintf(buf, l, "%llu months and %llu days ago",
1949 (unsigned long long) (d / USEC_PER_MONTH),
1950 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1951 else if (d >= USEC_PER_WEEK)
1952 snprintf(buf, l, "%llu weeks and %llu days ago",
1953 (unsigned long long) (d / USEC_PER_WEEK),
1954 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1955 else if (d >= 2*USEC_PER_DAY)
1956 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1957 else if (d >= 25*USEC_PER_HOUR)
1958 snprintf(buf, l, "1 day and %lluh ago",
1959 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1960 else if (d >= 6*USEC_PER_HOUR)
1961 snprintf(buf, l, "%lluh ago",
1962 (unsigned long long) (d / USEC_PER_HOUR));
1963 else if (d >= USEC_PER_HOUR)
1964 snprintf(buf, l, "%lluh %llumin ago",
1965 (unsigned long long) (d / USEC_PER_HOUR),
1966 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1967 else if (d >= 5*USEC_PER_MINUTE)
1968 snprintf(buf, l, "%llumin ago",
1969 (unsigned long long) (d / USEC_PER_MINUTE));
1970 else if (d >= USEC_PER_MINUTE)
1971 snprintf(buf, l, "%llumin %llus ago",
1972 (unsigned long long) (d / USEC_PER_MINUTE),
1973 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1974 else if (d >= USEC_PER_SEC)
1975 snprintf(buf, l, "%llus ago",
1976 (unsigned long long) (d / USEC_PER_SEC));
1977 else if (d >= USEC_PER_MSEC)
1978 snprintf(buf, l, "%llums ago",
1979 (unsigned long long) (d / USEC_PER_MSEC));
1981 snprintf(buf, l, "%lluus ago",
1982 (unsigned long long) d);
1984 snprintf(buf, l, "now");
1990 char *format_timespan(char *buf, size_t l, usec_t t) {
1991 static const struct {
1995 { "w", USEC_PER_WEEK },
1996 { "d", USEC_PER_DAY },
1997 { "h", USEC_PER_HOUR },
1998 { "min", USEC_PER_MINUTE },
1999 { "s", USEC_PER_SEC },
2000 { "ms", USEC_PER_MSEC },
2010 if (t == (usec_t) -1)
2014 snprintf(p, l, "0");
2019 /* The result of this function can be parsed with parse_usec */
2021 for (i = 0; i < ELEMENTSOF(table); i++) {
2025 if (t < table[i].usec)
2031 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2032 n = MIN((size_t) k, l);
2045 bool fstype_is_network(const char *fstype) {
2046 static const char table[] =
2055 return nulstr_contains(table, fstype);
2059 _cleanup_close_ int fd;
2061 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2067 TIOCL_GETKMSGREDIRECT,
2071 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2074 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2077 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2083 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2084 struct termios old_termios, new_termios;
2086 char line[LINE_MAX];
2091 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2092 new_termios = old_termios;
2094 new_termios.c_lflag &= ~ICANON;
2095 new_termios.c_cc[VMIN] = 1;
2096 new_termios.c_cc[VTIME] = 0;
2098 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2101 if (t != (usec_t) -1) {
2102 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2103 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2108 k = fread(&c, 1, 1, f);
2110 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2116 *need_nl = c != '\n';
2123 if (t != (usec_t) -1)
2124 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2127 if (!fgets(line, sizeof(line), f))
2132 if (strlen(line) != 1)
2142 int ask(char *ret, const char *replies, const char *text, ...) {
2149 on_tty = isatty(STDOUT_FILENO);
2155 bool need_nl = true;
2158 fputs(ANSI_HIGHLIGHT_ON, stdout);
2165 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2169 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2172 if (r == -EBADMSG) {
2173 puts("Bad input, please try again.");
2184 if (strchr(replies, c)) {
2189 puts("Read unexpected character, please try again.");
2193 int reset_terminal_fd(int fd, bool switch_to_text) {
2194 struct termios termios;
2197 /* Set terminal to some sane defaults */
2201 /* We leave locked terminal attributes untouched, so that
2202 * Plymouth may set whatever it wants to set, and we don't
2203 * interfere with that. */
2205 /* Disable exclusive mode, just in case */
2206 ioctl(fd, TIOCNXCL);
2208 /* Switch to text mode */
2210 ioctl(fd, KDSETMODE, KD_TEXT);
2212 /* Enable console unicode mode */
2213 ioctl(fd, KDSKBMODE, K_UNICODE);
2215 if (tcgetattr(fd, &termios) < 0) {
2220 /* We only reset the stuff that matters to the software. How
2221 * hardware is set up we don't touch assuming that somebody
2222 * else will do that for us */
2224 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2225 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2226 termios.c_oflag |= ONLCR;
2227 termios.c_cflag |= CREAD;
2228 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2230 termios.c_cc[VINTR] = 03; /* ^C */
2231 termios.c_cc[VQUIT] = 034; /* ^\ */
2232 termios.c_cc[VERASE] = 0177;
2233 termios.c_cc[VKILL] = 025; /* ^X */
2234 termios.c_cc[VEOF] = 04; /* ^D */
2235 termios.c_cc[VSTART] = 021; /* ^Q */
2236 termios.c_cc[VSTOP] = 023; /* ^S */
2237 termios.c_cc[VSUSP] = 032; /* ^Z */
2238 termios.c_cc[VLNEXT] = 026; /* ^V */
2239 termios.c_cc[VWERASE] = 027; /* ^W */
2240 termios.c_cc[VREPRINT] = 022; /* ^R */
2241 termios.c_cc[VEOL] = 0;
2242 termios.c_cc[VEOL2] = 0;
2244 termios.c_cc[VTIME] = 0;
2245 termios.c_cc[VMIN] = 1;
2247 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2251 /* Just in case, flush all crap out */
2252 tcflush(fd, TCIOFLUSH);
2257 int reset_terminal(const char *name) {
2260 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2264 r = reset_terminal_fd(fd, true);
2265 close_nointr_nofail(fd);
2270 int open_terminal(const char *name, int mode) {
2275 * If a TTY is in the process of being closed opening it might
2276 * cause EIO. This is horribly awful, but unlikely to be
2277 * changed in the kernel. Hence we work around this problem by
2278 * retrying a couple of times.
2280 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2284 fd = open(name, mode);
2291 /* Max 1s in total */
2295 usleep(50 * USEC_PER_MSEC);
2304 close_nointr_nofail(fd);
2309 close_nointr_nofail(fd);
2316 int flush_fd(int fd) {
2317 struct pollfd pollfd;
2321 pollfd.events = POLLIN;
2328 if ((r = poll(&pollfd, 1, 0)) < 0) {
2339 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2344 if (errno == EAGAIN)
2355 int acquire_terminal(
2359 bool ignore_tiocstty_eperm,
2362 int fd = -1, notify = -1, r = 0, wd = -1;
2364 struct sigaction sa_old, sa_new;
2368 /* We use inotify to be notified when the tty is closed. We
2369 * create the watch before checking if we can actually acquire
2370 * it, so that we don't lose any event.
2372 * Note: strictly speaking this actually watches for the
2373 * device being closed, it does *not* really watch whether a
2374 * tty loses its controlling process. However, unless some
2375 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2376 * its tty otherwise this will not become a problem. As long
2377 * as the administrator makes sure not configure any service
2378 * on the same tty as an untrusted user this should not be a
2379 * problem. (Which he probably should not do anyway.) */
2381 if (timeout != (usec_t) -1)
2382 ts = now(CLOCK_MONOTONIC);
2384 if (!fail && !force) {
2385 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2391 wd = inotify_add_watch(notify, name, IN_CLOSE);
2400 r = flush_fd(notify);
2405 /* We pass here O_NOCTTY only so that we can check the return
2406 * value TIOCSCTTY and have a reliable way to figure out if we
2407 * successfully became the controlling process of the tty */
2408 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2412 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2413 * if we already own the tty. */
2415 sa_new.sa_handler = SIG_IGN;
2416 sa_new.sa_flags = SA_RESTART;
2417 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2419 /* First, try to get the tty */
2420 if (ioctl(fd, TIOCSCTTY, force) < 0)
2423 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2425 /* Sometimes it makes sense to ignore TIOCSCTTY
2426 * returning EPERM, i.e. when very likely we already
2427 * are have this controlling terminal. */
2428 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2431 if (r < 0 && (force || fail || r != -EPERM)) {
2440 assert(notify >= 0);
2443 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2445 struct inotify_event *e;
2447 if (timeout != (usec_t) -1) {
2450 n = now(CLOCK_MONOTONIC);
2451 if (ts + timeout < n) {
2456 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2466 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2469 if (errno == EINTR || errno == EAGAIN)
2476 e = (struct inotify_event*) inotify_buffer;
2481 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2486 step = sizeof(struct inotify_event) + e->len;
2487 assert(step <= (size_t) l);
2489 e = (struct inotify_event*) ((uint8_t*) e + step);
2496 /* We close the tty fd here since if the old session
2497 * ended our handle will be dead. It's important that
2498 * we do this after sleeping, so that we don't enter
2499 * an endless loop. */
2500 close_nointr_nofail(fd);
2504 close_nointr_nofail(notify);
2506 r = reset_terminal_fd(fd, true);
2508 log_warning("Failed to reset terminal: %s", strerror(-r));
2514 close_nointr_nofail(fd);
2517 close_nointr_nofail(notify);
2522 int release_terminal(void) {
2524 struct sigaction sa_old, sa_new;
2526 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2529 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2530 * by our own TIOCNOTTY */
2533 sa_new.sa_handler = SIG_IGN;
2534 sa_new.sa_flags = SA_RESTART;
2535 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2537 if (ioctl(fd, TIOCNOTTY) < 0)
2540 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2542 close_nointr_nofail(fd);
2546 int sigaction_many(const struct sigaction *sa, ...) {
2551 while ((sig = va_arg(ap, int)) > 0)
2552 if (sigaction(sig, sa, NULL) < 0)
2559 int ignore_signals(int sig, ...) {
2560 struct sigaction sa;
2565 sa.sa_handler = SIG_IGN;
2566 sa.sa_flags = SA_RESTART;
2568 if (sigaction(sig, &sa, NULL) < 0)
2572 while ((sig = va_arg(ap, int)) > 0)
2573 if (sigaction(sig, &sa, NULL) < 0)
2580 int default_signals(int sig, ...) {
2581 struct sigaction sa;
2586 sa.sa_handler = SIG_DFL;
2587 sa.sa_flags = SA_RESTART;
2589 if (sigaction(sig, &sa, NULL) < 0)
2593 while ((sig = va_arg(ap, int)) > 0)
2594 if (sigaction(sig, &sa, NULL) < 0)
2601 int close_pipe(int p[]) {
2607 a = close_nointr(p[0]);
2612 b = close_nointr(p[1]);
2616 return a < 0 ? a : b;
2619 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2628 while (nbytes > 0) {
2631 if ((k = read(fd, p, nbytes)) <= 0) {
2633 if (k < 0 && errno == EINTR)
2636 if (k < 0 && errno == EAGAIN && do_poll) {
2637 struct pollfd pollfd;
2641 pollfd.events = POLLIN;
2643 if (poll(&pollfd, 1, -1) < 0) {
2647 return n > 0 ? n : -errno;
2650 if (pollfd.revents != POLLIN)
2651 return n > 0 ? n : -EIO;
2656 return n > 0 ? n : (k < 0 ? -errno : 0);
2667 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2676 while (nbytes > 0) {
2679 k = write(fd, p, nbytes);
2682 if (k < 0 && errno == EINTR)
2685 if (k < 0 && errno == EAGAIN && do_poll) {
2686 struct pollfd pollfd;
2690 pollfd.events = POLLOUT;
2692 if (poll(&pollfd, 1, -1) < 0) {
2696 return n > 0 ? n : -errno;
2699 if (pollfd.revents != POLLOUT)
2700 return n > 0 ? n : -EIO;
2705 return n > 0 ? n : (k < 0 ? -errno : 0);
2716 int parse_usec(const char *t, usec_t *usec) {
2717 static const struct {
2721 { "sec", USEC_PER_SEC },
2722 { "s", USEC_PER_SEC },
2723 { "min", USEC_PER_MINUTE },
2724 { "hr", USEC_PER_HOUR },
2725 { "h", USEC_PER_HOUR },
2726 { "d", USEC_PER_DAY },
2727 { "w", USEC_PER_WEEK },
2728 { "msec", USEC_PER_MSEC },
2729 { "ms", USEC_PER_MSEC },
2730 { "m", USEC_PER_MINUTE },
2733 { "", USEC_PER_SEC }, /* default is sec */
2749 l = strtoll(p, &e, 10);
2760 e += strspn(e, WHITESPACE);
2762 for (i = 0; i < ELEMENTSOF(table); i++)
2763 if (startswith(e, table[i].suffix)) {
2764 r += (usec_t) l * table[i].usec;
2765 p = e + strlen(table[i].suffix);
2769 if (i >= ELEMENTSOF(table))
2779 int parse_nsec(const char *t, nsec_t *nsec) {
2780 static const struct {
2784 { "sec", NSEC_PER_SEC },
2785 { "s", NSEC_PER_SEC },
2786 { "min", NSEC_PER_MINUTE },
2787 { "hr", NSEC_PER_HOUR },
2788 { "h", NSEC_PER_HOUR },
2789 { "d", NSEC_PER_DAY },
2790 { "w", NSEC_PER_WEEK },
2791 { "msec", NSEC_PER_MSEC },
2792 { "ms", NSEC_PER_MSEC },
2793 { "m", NSEC_PER_MINUTE },
2794 { "usec", NSEC_PER_USEC },
2795 { "us", NSEC_PER_USEC },
2798 { "", 1ULL }, /* default is nsec */
2814 l = strtoll(p, &e, 10);
2825 e += strspn(e, WHITESPACE);
2827 for (i = 0; i < ELEMENTSOF(table); i++)
2828 if (startswith(e, table[i].suffix)) {
2829 r += (nsec_t) l * table[i].nsec;
2830 p = e + strlen(table[i].suffix);
2834 if (i >= ELEMENTSOF(table))
2844 int parse_bytes(const char *t, off_t *bytes) {
2845 static const struct {
2851 { "M", 1024ULL*1024ULL },
2852 { "G", 1024ULL*1024ULL*1024ULL },
2853 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2854 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2855 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2872 l = strtoll(p, &e, 10);
2883 e += strspn(e, WHITESPACE);
2885 for (i = 0; i < ELEMENTSOF(table); i++)
2886 if (startswith(e, table[i].suffix)) {
2887 r += (off_t) l * table[i].factor;
2888 p = e + strlen(table[i].suffix);
2892 if (i >= ELEMENTSOF(table))
2902 int make_stdio(int fd) {
2907 r = dup2(fd, STDIN_FILENO);
2908 s = dup2(fd, STDOUT_FILENO);
2909 t = dup2(fd, STDERR_FILENO);
2912 close_nointr_nofail(fd);
2914 if (r < 0 || s < 0 || t < 0)
2917 fd_cloexec(STDIN_FILENO, false);
2918 fd_cloexec(STDOUT_FILENO, false);
2919 fd_cloexec(STDERR_FILENO, false);
2924 int make_null_stdio(void) {
2927 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2931 return make_stdio(null_fd);
2934 bool is_device_path(const char *path) {
2936 /* Returns true on paths that refer to a device, either in
2937 * sysfs or in /dev */
2940 path_startswith(path, "/dev/") ||
2941 path_startswith(path, "/sys/");
2944 int dir_is_empty(const char *path) {
2945 _cleanup_closedir_ DIR *d;
2953 struct dirent buf, *de;
2955 r = readdir_r(d, &buf, &de);
2962 if (!ignore_file(de->d_name))
2967 unsigned long long random_ull(void) {
2968 _cleanup_close_ int fd;
2972 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2976 r = loop_read(fd, &ull, sizeof(ull), true);
2977 if (r != sizeof(ull))
2983 return random() * RAND_MAX + random();
2986 void rename_process(const char name[8]) {
2989 /* This is a like a poor man's setproctitle(). It changes the
2990 * comm field, argv[0], and also the glibc's internally used
2991 * name of the process. For the first one a limit of 16 chars
2992 * applies, to the second one usually one of 10 (i.e. length
2993 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2994 * "systemd"). If you pass a longer string it will be
2997 prctl(PR_SET_NAME, name);
2999 if (program_invocation_name)
3000 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3002 if (saved_argc > 0) {
3006 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3008 for (i = 1; i < saved_argc; i++) {
3012 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3017 void sigset_add_many(sigset_t *ss, ...) {
3024 while ((sig = va_arg(ap, int)) > 0)
3025 assert_se(sigaddset(ss, sig) == 0);
3029 char* gethostname_malloc(void) {
3032 assert_se(uname(&u) >= 0);
3034 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3035 return strdup(u.nodename);
3037 return strdup(u.sysname);
3040 bool hostname_is_set(void) {
3043 assert_se(uname(&u) >= 0);
3045 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3048 static char *lookup_uid(uid_t uid) {
3051 _cleanup_free_ char *buf = NULL;
3052 struct passwd pwbuf, *pw = NULL;
3054 /* Shortcut things to avoid NSS lookups */
3056 return strdup("root");
3058 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3062 buf = malloc(bufsize);
3066 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3067 return strdup(pw->pw_name);
3069 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3075 char* getlogname_malloc(void) {
3079 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3084 return lookup_uid(uid);
3087 char *getusername_malloc(void) {
3094 return lookup_uid(getuid());
3097 int getttyname_malloc(int fd, char **r) {
3098 char path[PATH_MAX], *c;
3103 k = ttyname_r(fd, path, sizeof(path));
3109 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3117 int getttyname_harder(int fd, char **r) {
3121 k = getttyname_malloc(fd, &s);
3125 if (streq(s, "tty")) {
3127 return get_ctty(0, NULL, r);
3134 int get_ctty_devnr(pid_t pid, dev_t *d) {
3136 char line[LINE_MAX], *p, *fn;
3137 unsigned long ttynr;
3140 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3143 f = fopen(fn, "re");
3148 if (!fgets(line, sizeof(line), f)) {
3149 k = feof(f) ? -EIO : -errno;
3156 p = strrchr(line, ')');
3166 "%*d " /* session */
3175 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3177 char fn[PATH_MAX], *s, *b, *p;
3182 k = get_ctty_devnr(pid, &devnr);
3186 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3189 if ((k = readlink_malloc(fn, &s)) < 0) {
3194 /* This is an ugly hack */
3195 if (major(devnr) == 136) {
3196 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3206 /* Probably something like the ptys which have no
3207 * symlink in /dev/char. Let's return something
3208 * vaguely useful. */
3210 if (!(b = strdup(fn + 5)))
3220 if (startswith(s, "/dev/"))
3222 else if (startswith(s, "../"))
3240 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3246 /* This returns the first error we run into, but nevertheless
3247 * tries to go on. This closes the passed fd. */
3251 close_nointr_nofail(fd);
3253 return errno == ENOENT ? 0 : -errno;
3257 struct dirent buf, *de;
3258 bool is_dir, keep_around;
3262 r = readdir_r(d, &buf, &de);
3263 if (r != 0 && ret == 0) {
3271 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3274 if (de->d_type == DT_UNKNOWN ||
3276 (de->d_type == DT_DIR && root_dev)) {
3277 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3278 if (ret == 0 && errno != ENOENT)
3283 is_dir = S_ISDIR(st.st_mode);
3286 (st.st_uid == 0 || st.st_uid == getuid()) &&
3287 (st.st_mode & S_ISVTX);
3289 is_dir = de->d_type == DT_DIR;
3290 keep_around = false;
3296 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3297 if (root_dev && st.st_dev != root_dev->st_dev)
3300 subdir_fd = openat(fd, de->d_name,
3301 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3302 if (subdir_fd < 0) {
3303 if (ret == 0 && errno != ENOENT)
3308 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3309 if (r < 0 && ret == 0)
3313 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3314 if (ret == 0 && errno != ENOENT)
3318 } else if (!only_dirs && !keep_around) {
3320 if (unlinkat(fd, de->d_name, 0) < 0) {
3321 if (ret == 0 && errno != ENOENT)
3332 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3337 if (fstatfs(fd, &s) < 0) {
3338 close_nointr_nofail(fd);
3342 /* We refuse to clean disk file systems with this call. This
3343 * is extra paranoia just to be sure we never ever remove
3346 if (s.f_type != TMPFS_MAGIC &&
3347 s.f_type != RAMFS_MAGIC) {
3348 log_error("Attempted to remove disk file system, and we can't allow that.");
3349 close_nointr_nofail(fd);
3353 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3356 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3362 /* We refuse to clean the root file system with this
3363 * call. This is extra paranoia to never cause a really
3364 * seriously broken system. */
3365 if (path_equal(path, "/")) {
3366 log_error("Attempted to remove entire root file system, and we can't allow that.");
3370 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3373 if (errno != ENOTDIR)
3377 if (statfs(path, &s) < 0)
3380 if (s.f_type != TMPFS_MAGIC &&
3381 s.f_type != RAMFS_MAGIC) {
3382 log_error("Attempted to remove disk file system, and we can't allow that.");
3387 if (delete_root && !only_dirs)
3388 if (unlink(path) < 0 && errno != ENOENT)
3395 if (fstatfs(fd, &s) < 0) {
3396 close_nointr_nofail(fd);
3400 if (s.f_type != TMPFS_MAGIC &&
3401 s.f_type != RAMFS_MAGIC) {
3402 log_error("Attempted to remove disk file system, and we can't allow that.");
3403 close_nointr_nofail(fd);
3408 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3411 if (honour_sticky && file_is_priv_sticky(path) > 0)
3414 if (rmdir(path) < 0 && errno != ENOENT) {
3423 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3424 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3427 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3428 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3431 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3434 /* Under the assumption that we are running privileged we
3435 * first change the access mode and only then hand out
3436 * ownership to avoid a window where access is too open. */
3438 if (mode != (mode_t) -1)
3439 if (chmod(path, mode) < 0)
3442 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3443 if (chown(path, uid, gid) < 0)
3449 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3452 /* Under the assumption that we are running privileged we
3453 * first change the access mode and only then hand out
3454 * ownership to avoid a window where access is too open. */
3456 if (fchmod(fd, mode) < 0)
3459 if (fchown(fd, uid, gid) < 0)
3465 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3469 /* Allocates the cpuset in the right size */
3472 if (!(r = CPU_ALLOC(n)))
3475 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3476 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3486 if (errno != EINVAL)
3493 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3495 static const char status_indent[] = " "; /* "[" STATUS "] " */
3497 struct iovec iovec[5];
3502 /* This is independent of logging, as status messages are
3503 * optional and go exclusively to the console. */
3505 if (vasprintf(&s, format, ap) < 0)
3508 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3521 sl = status ? strlen(status_indent) : 0;
3527 e = ellipsize(s, emax, 75);
3537 if (!isempty(status)) {
3538 IOVEC_SET_STRING(iovec[n++], "[");
3539 IOVEC_SET_STRING(iovec[n++], status);
3540 IOVEC_SET_STRING(iovec[n++], "] ");
3542 IOVEC_SET_STRING(iovec[n++], status_indent);
3545 IOVEC_SET_STRING(iovec[n++], s);
3546 IOVEC_SET_STRING(iovec[n++], "\n");
3548 writev(fd, iovec, n);
3554 close_nointr_nofail(fd);
3557 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3562 va_start(ap, format);
3563 status_vprintf(status, ellipse, format, ap);
3567 void status_welcome(void) {
3568 char *pretty_name = NULL, *ansi_color = NULL;
3569 const char *const_pretty = NULL, *const_color = NULL;
3572 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3573 "PRETTY_NAME", &pretty_name,
3574 "ANSI_COLOR", &ansi_color,
3578 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3581 if (!pretty_name && !const_pretty)
3582 const_pretty = "Linux";
3584 if (!ansi_color && !const_color)
3589 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3590 const_color ? const_color : ansi_color,
3591 const_pretty ? const_pretty : pretty_name);
3597 char *replace_env(const char *format, char **env) {
3604 const char *e, *word = format;
3609 for (e = format; *e; e ++) {
3620 if (!(k = strnappend(r, word, e-word-1)))
3629 } else if (*e == '$') {
3630 if (!(k = strnappend(r, word, e-word)))
3646 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3649 if (!(k = strappend(r, t)))
3662 if (!(k = strnappend(r, word, e-word)))
3673 char **replace_env_argv(char **argv, char **env) {
3675 unsigned k = 0, l = 0;
3677 l = strv_length(argv);
3679 if (!(r = new(char*, l+1)))
3682 STRV_FOREACH(i, argv) {
3684 /* If $FOO appears as single word, replace it by the split up variable */
3685 if ((*i)[0] == '$' && (*i)[1] != '{') {
3690 if ((e = strv_env_get(env, *i+1))) {
3692 if (!(m = strv_split_quoted(e))) {
3703 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3712 memcpy(r + k, m, q * sizeof(char*));
3720 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3721 if (!(r[k++] = replace_env(*i, env))) {
3731 int fd_columns(int fd) {
3735 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3744 static unsigned columns_cached(bool cached) {
3745 static __thread int parsed_columns = 0, env_columns = -1;
3748 if (_likely_(parsed_columns > 0 && cached))
3749 return parsed_columns;
3751 if (_unlikely_(env_columns == -1)) {
3752 e = getenv("COLUMNS");
3754 env_columns = atoi(e);
3759 if (env_columns > 0) {
3760 parsed_columns = env_columns;
3761 return parsed_columns;
3764 if (parsed_columns <= 0 || !cached)
3765 parsed_columns = fd_columns(STDOUT_FILENO);
3767 if (parsed_columns <= 0)
3768 parsed_columns = 80;
3770 return parsed_columns;
3773 unsigned columns(void) {
3774 return columns_cached(true);
3777 unsigned columns_uncached(void) {
3778 return columns_cached(false);
3781 int fd_lines(int fd) {
3785 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3794 unsigned lines(void) {
3795 static __thread int parsed_lines = 0;
3798 if (_likely_(parsed_lines > 0))
3799 return parsed_lines;
3801 e = getenv("LINES");
3803 parsed_lines = atoi(e);
3805 if (parsed_lines <= 0)
3806 parsed_lines = fd_lines(STDOUT_FILENO);
3808 if (parsed_lines <= 0)
3811 return parsed_lines;
3814 int running_in_chroot(void) {
3820 /* Only works as root */
3822 if (stat("/proc/1/root", &a) < 0)
3825 if (stat("/", &b) < 0)
3829 a.st_dev != b.st_dev ||
3830 a.st_ino != b.st_ino;
3833 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3838 assert(percent <= 100);
3839 assert(new_length >= 3);
3841 if (old_length <= 3 || old_length <= new_length)
3842 return strndup(s, old_length);
3844 r = new0(char, new_length+1);
3848 x = (new_length * percent) / 100;
3850 if (x > new_length - 3)
3858 s + old_length - (new_length - x - 3),
3859 new_length - x - 3);
3864 char *ellipsize(const char *s, size_t length, unsigned percent) {
3865 return ellipsize_mem(s, strlen(s), length, percent);
3868 int touch(const char *path) {
3873 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3876 close_nointr_nofail(fd);
3880 char *unquote(const char *s, const char* quotes) {
3888 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3889 return strndup(s+1, l-2);
3894 char *normalize_env_assignment(const char *s) {
3895 char *name, *value, *p, *r;
3900 if (!(r = strdup(s)))
3906 if (!(name = strndup(s, p - s)))
3909 if (!(p = strdup(p+1))) {
3914 value = unquote(strstrip(p), QUOTES);
3922 if (asprintf(&r, "%s=%s", name, value) < 0)
3931 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3942 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3954 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3961 r = wait_for_terminate(pid, &status);
3963 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3967 if (status.si_code == CLD_EXITED) {
3968 if (status.si_status != 0) {
3969 log_warning("%s failed with error code %i.", name, status.si_status);
3970 return status.si_status;
3973 log_debug("%s succeeded.", name);
3976 } else if (status.si_code == CLD_KILLED ||
3977 status.si_code == CLD_DUMPED) {
3979 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3983 log_warning("%s failed due to unknown reason.", name);
3987 _noreturn_ void freeze(void) {
3989 /* Make sure nobody waits for us on a socket anymore */
3990 close_all_fds(NULL, 0);
3998 bool null_or_empty(struct stat *st) {
4001 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4004 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4010 int null_or_empty_path(const char *fn) {
4015 if (stat(fn, &st) < 0)
4018 return null_or_empty(&st);
4021 DIR *xopendirat(int fd, const char *name, int flags) {
4025 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4028 if (!(d = fdopendir(nfd))) {
4029 close_nointr_nofail(nfd);
4036 int signal_from_string_try_harder(const char *s) {
4040 if ((signo = signal_from_string(s)) <= 0)
4041 if (startswith(s, "SIG"))
4042 return signal_from_string(s+3);
4047 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4053 if (!dual_timestamp_is_set(t))
4056 fprintf(f, "%s=%llu %llu\n",
4058 (unsigned long long) t->realtime,
4059 (unsigned long long) t->monotonic);
4062 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4063 unsigned long long a, b;
4068 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4069 log_debug("Failed to parse finish timestamp value %s", value);
4076 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4080 /* FIXME: to follow udev's logic 100% we need to leave valid
4081 * UTF8 chars unescaped */
4083 u = unquote(tagvalue, "\"\'");
4087 t = xescape(u, "/ ");
4093 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4102 char *fstab_node_to_udev_node(const char *p) {
4103 if (startswith(p, "LABEL="))
4104 return tag_to_udev_node(p+6, "label");
4106 if (startswith(p, "UUID="))
4107 return tag_to_udev_node(p+5, "uuid");
4109 if (startswith(p, "PARTUUID="))
4110 return tag_to_udev_node(p+9, "partuuid");
4112 if (startswith(p, "PARTLABEL="))
4113 return tag_to_udev_node(p+10, "partlabel");
4118 bool tty_is_vc(const char *tty) {
4121 if (startswith(tty, "/dev/"))
4124 return vtnr_from_tty(tty) >= 0;
4127 bool tty_is_console(const char *tty) {
4130 if (startswith(tty, "/dev/"))
4133 return streq(tty, "console");
4136 int vtnr_from_tty(const char *tty) {
4141 if (startswith(tty, "/dev/"))
4144 if (!startswith(tty, "tty") )
4147 if (tty[3] < '0' || tty[3] > '9')
4150 r = safe_atoi(tty+3, &i);
4154 if (i < 0 || i > 63)
4160 bool tty_is_vc_resolve(const char *tty) {
4161 char *active = NULL;
4166 if (startswith(tty, "/dev/"))
4169 /* Resolve where /dev/console is pointing to, if /sys is
4170 * actually ours (i.e. not read-only-mounted which is a sign
4171 * for container setups) */
4172 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4173 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4174 /* If multiple log outputs are configured the
4175 * last one is what /dev/console points to */
4176 tty = strrchr(active, ' ');
4189 const char *default_term_for_tty(const char *tty) {
4192 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4195 bool dirent_is_file(const struct dirent *de) {
4198 if (ignore_file(de->d_name))
4201 if (de->d_type != DT_REG &&
4202 de->d_type != DT_LNK &&
4203 de->d_type != DT_UNKNOWN)
4209 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4212 if (de->d_type != DT_REG &&
4213 de->d_type != DT_LNK &&
4214 de->d_type != DT_UNKNOWN)
4217 if (ignore_file_allow_backup(de->d_name))
4220 return endswith(de->d_name, suffix);
4223 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4226 Hashmap *pids = NULL;
4230 /* Executes all binaries in a directory in parallel and waits
4231 * until all they all finished. */
4234 if (!(_d = opendir(directory))) {
4236 if (errno == ENOENT)
4239 log_error("Failed to enumerate directory %s: %m", directory);
4246 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4247 log_error("Failed to allocate set.");
4251 while ((de = readdir(d))) {
4256 if (!dirent_is_file(de))
4259 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4264 if ((pid = fork()) < 0) {
4265 log_error("Failed to fork: %m");
4283 log_error("Failed to execute %s: %m", path);
4284 _exit(EXIT_FAILURE);
4287 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4289 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4290 log_error("Failed to add PID to set: %s", strerror(-k));
4295 while (!hashmap_isempty(pids)) {
4296 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4301 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4306 log_error("waitid() failed: %m");
4310 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4311 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4312 if (si.si_code == CLD_EXITED)
4313 log_error("%s exited with exit status %i.", path, si.si_status);
4315 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4317 log_debug("%s exited successfully.", path);
4328 hashmap_free_free(pids);
4331 int kill_and_sigcont(pid_t pid, int sig) {
4334 r = kill(pid, sig) < 0 ? -errno : 0;
4342 bool nulstr_contains(const char*nulstr, const char *needle) {
4348 NULSTR_FOREACH(i, nulstr)
4349 if (streq(i, needle))
4355 bool plymouth_running(void) {
4356 return access("/run/plymouth/pid", F_OK) >= 0;
4359 char* strshorten(char *s, size_t l) {
4368 static bool hostname_valid_char(char c) {
4370 (c >= 'a' && c <= 'z') ||
4371 (c >= 'A' && c <= 'Z') ||
4372 (c >= '0' && c <= '9') ||
4378 bool hostname_is_valid(const char *s) {
4384 for (p = s; *p; p++)
4385 if (!hostname_valid_char(*p))
4388 if (p-s > HOST_NAME_MAX)
4394 char* hostname_cleanup(char *s) {
4397 for (p = s, d = s; *p; p++)
4398 if ((*p >= 'a' && *p <= 'z') ||
4399 (*p >= 'A' && *p <= 'Z') ||
4400 (*p >= '0' && *p <= '9') ||
4408 strshorten(s, HOST_NAME_MAX);
4412 int pipe_eof(int fd) {
4413 struct pollfd pollfd;
4418 pollfd.events = POLLIN|POLLHUP;
4420 r = poll(&pollfd, 1, 0);
4427 return pollfd.revents & POLLHUP;
4430 int fd_wait_for_event(int fd, int event, usec_t t) {
4431 struct pollfd pollfd;
4436 pollfd.events = event;
4438 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4445 return pollfd.revents;
4448 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4459 t = new(char, strlen(path) + 1 + 6 + 1);
4463 fn = path_get_file_name(path);
4467 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4469 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4475 f = fdopen(fd, "we");
4488 int terminal_vhangup_fd(int fd) {
4491 if (ioctl(fd, TIOCVHANGUP) < 0)
4497 int terminal_vhangup(const char *name) {
4500 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4504 r = terminal_vhangup_fd(fd);
4505 close_nointr_nofail(fd);
4510 int vt_disallocate(const char *name) {
4514 /* Deallocate the VT if possible. If not possible
4515 * (i.e. because it is the active one), at least clear it
4516 * entirely (including the scrollback buffer) */
4518 if (!startswith(name, "/dev/"))
4521 if (!tty_is_vc(name)) {
4522 /* So this is not a VT. I guess we cannot deallocate
4523 * it then. But let's at least clear the screen */
4525 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4530 "\033[r" /* clear scrolling region */
4531 "\033[H" /* move home */
4532 "\033[2J", /* clear screen */
4534 close_nointr_nofail(fd);
4539 if (!startswith(name, "/dev/tty"))
4542 r = safe_atou(name+8, &u);
4549 /* Try to deallocate */
4550 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4554 r = ioctl(fd, VT_DISALLOCATE, u);
4555 close_nointr_nofail(fd);
4563 /* Couldn't deallocate, so let's clear it fully with
4565 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4570 "\033[r" /* clear scrolling region */
4571 "\033[H" /* move home */
4572 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4574 close_nointr_nofail(fd);
4579 int copy_file(const char *from, const char *to) {
4585 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4589 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4591 close_nointr_nofail(fdf);
4599 n = read(fdf, buf, sizeof(buf));
4603 close_nointr_nofail(fdf);
4614 k = loop_write(fdt, buf, n, false);
4616 r = k < 0 ? k : (errno ? -errno : -EIO);
4618 close_nointr_nofail(fdf);
4626 close_nointr_nofail(fdf);
4627 r = close_nointr(fdt);
4637 int symlink_or_copy(const char *from, const char *to) {
4638 char *pf = NULL, *pt = NULL;
4645 if (path_get_parent(from, &pf) < 0 ||
4646 path_get_parent(to, &pt) < 0) {
4651 if (stat(pf, &a) < 0 ||
4657 if (a.st_dev != b.st_dev) {
4661 return copy_file(from, to);
4664 if (symlink(from, to) < 0) {
4678 int symlink_or_copy_atomic(const char *from, const char *to) {
4682 unsigned long long ull;
4689 t = new(char, strlen(to) + 1 + 16 + 1);
4693 fn = path_get_file_name(to);
4697 x = stpcpy(t+k+1, fn);
4700 for (i = 0; i < 16; i++) {
4701 *(x++) = hexchar(ull & 0xF);
4707 r = symlink_or_copy(from, t);
4714 if (rename(t, to) < 0) {
4725 bool display_is_local(const char *display) {
4729 display[0] == ':' &&
4730 display[1] >= '0' &&
4734 int socket_from_display(const char *display, char **path) {
4741 if (!display_is_local(display))
4744 k = strspn(display+1, "0123456789");
4746 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4750 c = stpcpy(f, "/tmp/.X11-unix/X");
4751 memcpy(c, display+1, k);
4760 const char **username,
4761 uid_t *uid, gid_t *gid,
4763 const char **shell) {
4771 /* We enforce some special rules for uid=0: in order to avoid
4772 * NSS lookups for root we hardcode its data. */
4774 if (streq(*username, "root") || streq(*username, "0")) {
4792 if (parse_uid(*username, &u) >= 0) {
4796 /* If there are multiple users with the same id, make
4797 * sure to leave $USER to the configured value instead
4798 * of the first occurrence in the database. However if
4799 * the uid was configured by a numeric uid, then let's
4800 * pick the real username from /etc/passwd. */
4802 *username = p->pw_name;
4805 p = getpwnam(*username);
4809 return errno != 0 ? -errno : -ESRCH;
4821 *shell = p->pw_shell;
4826 int get_group_creds(const char **groupname, gid_t *gid) {
4832 /* We enforce some special rules for gid=0: in order to avoid
4833 * NSS lookups for root we hardcode its data. */
4835 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4836 *groupname = "root";
4844 if (parse_gid(*groupname, &id) >= 0) {
4849 *groupname = g->gr_name;
4852 g = getgrnam(*groupname);
4856 return errno != 0 ? -errno : -ESRCH;
4864 int in_group(const char *name) {
4866 int ngroups_max, r, i;
4868 r = get_group_creds(&name, &gid);
4872 if (getgid() == gid)
4875 if (getegid() == gid)
4878 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4879 assert(ngroups_max > 0);
4881 gids = alloca(sizeof(gid_t) * ngroups_max);
4883 r = getgroups(ngroups_max, gids);
4887 for (i = 0; i < r; i++)
4894 int glob_exists(const char *path) {
4902 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4904 if (k == GLOB_NOMATCH)
4906 else if (k == GLOB_NOSPACE)
4909 r = !strv_isempty(g.gl_pathv);
4911 r = errno ? -errno : -EIO;
4918 int dirent_ensure_type(DIR *d, struct dirent *de) {
4924 if (de->d_type != DT_UNKNOWN)
4927 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4931 S_ISREG(st.st_mode) ? DT_REG :
4932 S_ISDIR(st.st_mode) ? DT_DIR :
4933 S_ISLNK(st.st_mode) ? DT_LNK :
4934 S_ISFIFO(st.st_mode) ? DT_FIFO :
4935 S_ISSOCK(st.st_mode) ? DT_SOCK :
4936 S_ISCHR(st.st_mode) ? DT_CHR :
4937 S_ISBLK(st.st_mode) ? DT_BLK :
4943 int in_search_path(const char *path, char **search) {
4947 r = path_get_parent(path, &parent);
4953 STRV_FOREACH(i, search) {
4954 if (path_equal(parent, *i)) {
4965 int get_files_in_directory(const char *path, char ***list) {
4973 /* Returns all files in a directory in *list, and the number
4974 * of files as return value. If list is NULL returns only the
4982 struct dirent buffer, *de;
4985 k = readdir_r(d, &buffer, &de);
4994 dirent_ensure_type(d, de);
4996 if (!dirent_is_file(de))
5000 if ((unsigned) r >= n) {
5004 t = realloc(l, sizeof(char*) * n);
5013 assert((unsigned) r < n);
5015 l[r] = strdup(de->d_name);
5039 char *strjoin(const char *x, ...) {
5052 t = va_arg(ap, const char *);
5075 t = va_arg(ap, const char *);
5089 bool is_main_thread(void) {
5090 static __thread int cached = 0;
5092 if (_unlikely_(cached == 0))
5093 cached = getpid() == gettid() ? 1 : -1;
5098 int block_get_whole_disk(dev_t d, dev_t *ret) {
5105 /* If it has a queue this is good enough for us */
5106 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5109 r = access(p, F_OK);
5117 /* If it is a partition find the originating device */
5118 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5121 r = access(p, F_OK);
5127 /* Get parent dev_t */
5128 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5131 r = read_one_line_file(p, &s);
5137 r = sscanf(s, "%u:%u", &m, &n);
5143 /* Only return this if it is really good enough for us. */
5144 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5147 r = access(p, F_OK);
5151 *ret = makedev(m, n);
5158 int file_is_priv_sticky(const char *p) {
5163 if (lstat(p, &st) < 0)
5167 (st.st_uid == 0 || st.st_uid == getuid()) &&
5168 (st.st_mode & S_ISVTX);
5171 static const char *const ioprio_class_table[] = {
5172 [IOPRIO_CLASS_NONE] = "none",
5173 [IOPRIO_CLASS_RT] = "realtime",
5174 [IOPRIO_CLASS_BE] = "best-effort",
5175 [IOPRIO_CLASS_IDLE] = "idle"
5178 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5180 static const char *const sigchld_code_table[] = {
5181 [CLD_EXITED] = "exited",
5182 [CLD_KILLED] = "killed",
5183 [CLD_DUMPED] = "dumped",
5184 [CLD_TRAPPED] = "trapped",
5185 [CLD_STOPPED] = "stopped",
5186 [CLD_CONTINUED] = "continued",
5189 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5191 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5192 [LOG_FAC(LOG_KERN)] = "kern",
5193 [LOG_FAC(LOG_USER)] = "user",
5194 [LOG_FAC(LOG_MAIL)] = "mail",
5195 [LOG_FAC(LOG_DAEMON)] = "daemon",
5196 [LOG_FAC(LOG_AUTH)] = "auth",
5197 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5198 [LOG_FAC(LOG_LPR)] = "lpr",
5199 [LOG_FAC(LOG_NEWS)] = "news",
5200 [LOG_FAC(LOG_UUCP)] = "uucp",
5201 [LOG_FAC(LOG_CRON)] = "cron",
5202 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5203 [LOG_FAC(LOG_FTP)] = "ftp",
5204 [LOG_FAC(LOG_LOCAL0)] = "local0",
5205 [LOG_FAC(LOG_LOCAL1)] = "local1",
5206 [LOG_FAC(LOG_LOCAL2)] = "local2",
5207 [LOG_FAC(LOG_LOCAL3)] = "local3",
5208 [LOG_FAC(LOG_LOCAL4)] = "local4",
5209 [LOG_FAC(LOG_LOCAL5)] = "local5",
5210 [LOG_FAC(LOG_LOCAL6)] = "local6",
5211 [LOG_FAC(LOG_LOCAL7)] = "local7"
5214 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5216 static const char *const log_level_table[] = {
5217 [LOG_EMERG] = "emerg",
5218 [LOG_ALERT] = "alert",
5219 [LOG_CRIT] = "crit",
5221 [LOG_WARNING] = "warning",
5222 [LOG_NOTICE] = "notice",
5223 [LOG_INFO] = "info",
5224 [LOG_DEBUG] = "debug"
5227 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5229 static const char* const sched_policy_table[] = {
5230 [SCHED_OTHER] = "other",
5231 [SCHED_BATCH] = "batch",
5232 [SCHED_IDLE] = "idle",
5233 [SCHED_FIFO] = "fifo",
5237 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5239 static const char* const rlimit_table[] = {
5240 [RLIMIT_CPU] = "LimitCPU",
5241 [RLIMIT_FSIZE] = "LimitFSIZE",
5242 [RLIMIT_DATA] = "LimitDATA",
5243 [RLIMIT_STACK] = "LimitSTACK",
5244 [RLIMIT_CORE] = "LimitCORE",
5245 [RLIMIT_RSS] = "LimitRSS",
5246 [RLIMIT_NOFILE] = "LimitNOFILE",
5247 [RLIMIT_AS] = "LimitAS",
5248 [RLIMIT_NPROC] = "LimitNPROC",
5249 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5250 [RLIMIT_LOCKS] = "LimitLOCKS",
5251 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5252 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5253 [RLIMIT_NICE] = "LimitNICE",
5254 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5255 [RLIMIT_RTTIME] = "LimitRTTIME"
5258 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5260 static const char* const ip_tos_table[] = {
5261 [IPTOS_LOWDELAY] = "low-delay",
5262 [IPTOS_THROUGHPUT] = "throughput",
5263 [IPTOS_RELIABILITY] = "reliability",
5264 [IPTOS_LOWCOST] = "low-cost",
5267 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5269 static const char *const __signal_table[] = {
5286 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5297 [SIGVTALRM] = "VTALRM",
5299 [SIGWINCH] = "WINCH",
5305 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5307 const char *signal_to_string(int signo) {
5308 static __thread char buf[12];
5311 name = __signal_to_string(signo);
5315 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5316 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5318 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5323 int signal_from_string(const char *s) {
5328 signo =__signal_from_string(s);
5332 if (startswith(s, "RTMIN+")) {
5336 if (safe_atou(s, &u) >= 0) {
5337 signo = (int) u + offset;
5338 if (signo > 0 && signo < _NSIG)
5344 bool kexec_loaded(void) {
5345 bool loaded = false;
5348 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5356 int strdup_or_null(const char *a, char **b) {
5374 int prot_from_flags(int flags) {
5376 switch (flags & O_ACCMODE) {
5385 return PROT_READ|PROT_WRITE;
5392 char *format_bytes(char *buf, size_t l, off_t t) {
5395 static const struct {
5399 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5400 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5401 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5402 { "G", 1024ULL*1024ULL*1024ULL },
5403 { "M", 1024ULL*1024ULL },
5407 for (i = 0; i < ELEMENTSOF(table); i++) {
5409 if (t >= table[i].factor) {
5412 (unsigned long long) (t / table[i].factor),
5413 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5420 snprintf(buf, l, "%lluB", (unsigned long long) t);
5428 void* memdup(const void *p, size_t l) {
5441 int fd_inc_sndbuf(int fd, size_t n) {
5443 socklen_t l = sizeof(value);
5445 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5447 l == sizeof(value) &&
5448 (size_t) value >= n*2)
5452 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5459 int fd_inc_rcvbuf(int fd, size_t n) {
5461 socklen_t l = sizeof(value);
5463 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5465 l == sizeof(value) &&
5466 (size_t) value >= n*2)
5470 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5477 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5478 pid_t parent_pid, agent_pid;
5480 bool stdout_is_tty, stderr_is_tty;
5488 parent_pid = getpid();
5490 /* Spawns a temporary TTY agent, making sure it goes away when
5497 if (agent_pid != 0) {
5504 * Make sure the agent goes away when the parent dies */
5505 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5506 _exit(EXIT_FAILURE);
5508 /* Check whether our parent died before we were able
5509 * to set the death signal */
5510 if (getppid() != parent_pid)
5511 _exit(EXIT_SUCCESS);
5513 /* Don't leak fds to the agent */
5514 close_all_fds(except, n_except);
5516 stdout_is_tty = isatty(STDOUT_FILENO);
5517 stderr_is_tty = isatty(STDERR_FILENO);
5519 if (!stdout_is_tty || !stderr_is_tty) {
5520 /* Detach from stdout/stderr. and reopen
5521 * /dev/tty for them. This is important to
5522 * ensure that when systemctl is started via
5523 * popen() or a similar call that expects to
5524 * read EOF we actually do generate EOF and
5525 * not delay this indefinitely by because we
5526 * keep an unused copy of stdin around. */
5527 fd = open("/dev/tty", O_WRONLY);
5529 log_error("Failed to open /dev/tty: %m");
5530 _exit(EXIT_FAILURE);
5534 dup2(fd, STDOUT_FILENO);
5537 dup2(fd, STDERR_FILENO);
5543 /* Count arguments */
5545 for (n = 0; va_arg(ap, char*); n++)
5550 l = alloca(sizeof(char *) * (n + 1));
5552 /* Fill in arguments */
5554 for (i = 0; i <= n; i++)
5555 l[i] = va_arg(ap, char*);
5559 _exit(EXIT_FAILURE);
5562 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5563 struct rlimit highest, fixed;
5567 if (setrlimit(resource, rlim) >= 0)
5573 /* So we failed to set the desired setrlimit, then let's try
5574 * to get as close as we can */
5575 assert_se(getrlimit(resource, &highest) == 0);
5577 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5578 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5580 if (setrlimit(resource, &fixed) < 0)
5586 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5587 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5599 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5602 f = fopen(path, "re");
5610 char line[LINE_MAX];
5613 for (i = 0; i < sizeof(line)-1; i++) {
5617 if (_unlikely_(c == EOF)) {
5627 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5628 value = strdup(line + l + 1);
5648 int can_sleep(const char *type) {
5652 _cleanup_free_ char *p = NULL;
5656 r = read_one_line_file("/sys/power/state", &p);
5658 return r == -ENOENT ? 0 : r;
5661 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5662 if (l == k && memcmp(w, type, l) == 0)
5668 bool is_valid_documentation_url(const char *url) {
5671 if (startswith(url, "http://") && url[7])
5674 if (startswith(url, "https://") && url[8])
5677 if (startswith(url, "file:") && url[5])
5680 if (startswith(url, "info:") && url[5])
5683 if (startswith(url, "man:") && url[4])
5689 bool in_initrd(void) {
5690 static __thread int saved = -1;
5696 /* We make two checks here:
5698 * 1. the flag file /etc/initrd-release must exist
5699 * 2. the root file system must be a memory file system
5701 * The second check is extra paranoia, since misdetecting an
5702 * initrd can have bad bad consequences due the initrd
5703 * emptying when transititioning to the main systemd.
5706 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5707 statfs("/", &s) >= 0 &&
5708 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5713 void warn_melody(void) {
5714 _cleanup_close_ int fd = -1;
5716 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5720 /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5722 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5723 usleep(125*USEC_PER_MSEC);
5725 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5726 usleep(125*USEC_PER_MSEC);
5728 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5729 usleep(125*USEC_PER_MSEC);
5731 ioctl(fd, KIOCSOUND, 0);
5734 int make_console_stdio(void) {
5737 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5739 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5741 log_error("Failed to acquire terminal: %s", strerror(-fd));
5747 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5754 int get_home_dir(char **_h) {
5762 /* Take the user specified one */
5773 /* Hardcode home directory for root to avoid NSS */
5776 h = strdup("/root");
5784 /* Check the database... */
5788 return errno ? -errno : -ESRCH;
5790 if (!path_is_absolute(p->pw_dir))
5793 h = strdup(p->pw_dir);
5801 int get_shell(char **_sh) {
5809 /* Take the user specified one */
5810 e = getenv("SHELL");
5820 /* Hardcode home directory for root to avoid NSS */
5823 sh = strdup("/bin/sh");
5831 /* Check the database... */
5835 return errno ? -errno : -ESRCH;
5837 if (!path_is_absolute(p->pw_shell))
5840 sh = strdup(p->pw_shell);
5848 void freep(void *p) {
5852 void fclosep(FILE **f) {
5857 void closep(int *fd) {
5859 close_nointr_nofail(*fd);
5862 void closedirp(DIR **d) {