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 static int get_process_id(pid_t pid, const char *field, 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, field)) {
1145 l += strspn(l, WHITESPACE);
1147 l[strcspn(l, WHITESPACE)] = 0;
1149 r = parse_uid(l, uid);
1162 int get_process_uid(pid_t pid, uid_t *uid) {
1163 return get_process_id(pid, "Uid:", uid);
1166 int get_process_gid(pid_t pid, gid_t *gid) {
1167 return get_process_id(pid, "Gid:", gid);
1170 char *strnappend(const char *s, const char *suffix, size_t b) {
1178 return strndup(suffix, b);
1188 if (!(r = new(char, a+b+1)))
1192 memcpy(r+a, suffix, b);
1198 char *strappend(const char *s, const char *suffix) {
1199 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1202 int readlink_malloc(const char *p, char **r) {
1212 if (!(c = new(char, l)))
1215 if ((n = readlink(p, c, l-1)) < 0) {
1221 if ((size_t) n < l-1) {
1232 int readlink_and_make_absolute(const char *p, char **r) {
1239 if ((j = readlink_malloc(p, &target)) < 0)
1242 k = file_in_same_dir(p, target);
1252 int readlink_and_canonicalize(const char *p, char **r) {
1259 j = readlink_and_make_absolute(p, &t);
1263 s = canonicalize_file_name(t);
1270 path_kill_slashes(*r);
1275 int reset_all_signal_handlers(void) {
1278 for (sig = 1; sig < _NSIG; sig++) {
1279 struct sigaction sa;
1281 if (sig == SIGKILL || sig == SIGSTOP)
1285 sa.sa_handler = SIG_DFL;
1286 sa.sa_flags = SA_RESTART;
1288 /* On Linux the first two RT signals are reserved by
1289 * glibc, and sigaction() will return EINVAL for them. */
1290 if ((sigaction(sig, &sa, NULL) < 0))
1291 if (errno != EINVAL)
1298 char *strstrip(char *s) {
1301 /* Drops trailing whitespace. Modifies the string in
1302 * place. Returns pointer to first non-space character */
1304 s += strspn(s, WHITESPACE);
1306 for (e = strchr(s, 0); e > s; e --)
1307 if (!strchr(WHITESPACE, e[-1]))
1315 char *delete_chars(char *s, const char *bad) {
1318 /* Drops all whitespace, regardless where in the string */
1320 for (f = s, t = s; *f; f++) {
1321 if (strchr(bad, *f))
1332 bool in_charset(const char *s, const char* charset) {
1338 for (i = s; *i; i++)
1339 if (!strchr(charset, *i))
1345 char *file_in_same_dir(const char *path, const char *filename) {
1352 /* This removes the last component of path and appends
1353 * filename, unless the latter is absolute anyway or the
1356 if (path_is_absolute(filename))
1357 return strdup(filename);
1359 if (!(e = strrchr(path, '/')))
1360 return strdup(filename);
1362 k = strlen(filename);
1363 if (!(r = new(char, e-path+1+k+1)))
1366 memcpy(r, path, e-path+1);
1367 memcpy(r+(e-path)+1, filename, k+1);
1372 int rmdir_parents(const char *path, const char *stop) {
1381 /* Skip trailing slashes */
1382 while (l > 0 && path[l-1] == '/')
1388 /* Skip last component */
1389 while (l > 0 && path[l-1] != '/')
1392 /* Skip trailing slashes */
1393 while (l > 0 && path[l-1] == '/')
1399 if (!(t = strndup(path, l)))
1402 if (path_startswith(stop, t)) {
1411 if (errno != ENOENT)
1419 char hexchar(int x) {
1420 static const char table[16] = "0123456789abcdef";
1422 return table[x & 15];
1425 int unhexchar(char c) {
1427 if (c >= '0' && c <= '9')
1430 if (c >= 'a' && c <= 'f')
1431 return c - 'a' + 10;
1433 if (c >= 'A' && c <= 'F')
1434 return c - 'A' + 10;
1439 char octchar(int x) {
1440 return '0' + (x & 7);
1443 int unoctchar(char c) {
1445 if (c >= '0' && c <= '7')
1451 char decchar(int x) {
1452 return '0' + (x % 10);
1455 int undecchar(char c) {
1457 if (c >= '0' && c <= '9')
1463 char *cescape(const char *s) {
1469 /* Does C style string escaping. */
1471 r = new(char, strlen(s)*4 + 1);
1475 for (f = s, t = r; *f; f++)
1521 /* For special chars we prefer octal over
1522 * hexadecimal encoding, simply because glib's
1523 * g_strescape() does the same */
1524 if ((*f < ' ') || (*f >= 127)) {
1526 *(t++) = octchar((unsigned char) *f >> 6);
1527 *(t++) = octchar((unsigned char) *f >> 3);
1528 *(t++) = octchar((unsigned char) *f);
1539 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1546 /* Undoes C style string escaping, and optionally prefixes it. */
1548 pl = prefix ? strlen(prefix) : 0;
1550 r = new(char, pl+length+1);
1555 memcpy(r, prefix, pl);
1557 for (f = s, t = r + pl; f < s + length; f++) {
1600 /* This is an extension of the XDG syntax files */
1605 /* hexadecimal encoding */
1608 a = unhexchar(f[1]);
1609 b = unhexchar(f[2]);
1611 if (a < 0 || b < 0) {
1612 /* Invalid escape code, let's take it literal then */
1616 *(t++) = (char) ((a << 4) | b);
1631 /* octal encoding */
1634 a = unoctchar(f[0]);
1635 b = unoctchar(f[1]);
1636 c = unoctchar(f[2]);
1638 if (a < 0 || b < 0 || c < 0) {
1639 /* Invalid escape code, let's take it literal then */
1643 *(t++) = (char) ((a << 6) | (b << 3) | c);
1651 /* premature end of string.*/
1656 /* Invalid escape code, let's take it literal then */
1668 char *cunescape_length(const char *s, size_t length) {
1669 return cunescape_length_with_prefix(s, length, NULL);
1672 char *cunescape(const char *s) {
1675 return cunescape_length(s, strlen(s));
1678 char *xescape(const char *s, const char *bad) {
1682 /* Escapes all chars in bad, in addition to \ and all special
1683 * chars, in \xFF style escaping. May be reversed with
1686 if (!(r = new(char, strlen(s)*4+1)))
1689 for (f = s, t = r; *f; f++) {
1691 if ((*f < ' ') || (*f >= 127) ||
1692 (*f == '\\') || strchr(bad, *f)) {
1695 *(t++) = hexchar(*f >> 4);
1696 *(t++) = hexchar(*f);
1706 char *bus_path_escape(const char *s) {
1712 /* Escapes all chars that D-Bus' object path cannot deal
1713 * with. Can be reverse with bus_path_unescape() */
1715 if (!(r = new(char, strlen(s)*3+1)))
1718 for (f = s, t = r; *f; f++) {
1720 if (!(*f >= 'A' && *f <= 'Z') &&
1721 !(*f >= 'a' && *f <= 'z') &&
1722 !(*f >= '0' && *f <= '9')) {
1724 *(t++) = hexchar(*f >> 4);
1725 *(t++) = hexchar(*f);
1735 char *bus_path_unescape(const char *f) {
1740 if (!(r = strdup(f)))
1743 for (t = r; *f; f++) {
1748 if ((a = unhexchar(f[1])) < 0 ||
1749 (b = unhexchar(f[2])) < 0) {
1750 /* Invalid escape code, let's take it literal then */
1753 *(t++) = (char) ((a << 4) | b);
1765 char *ascii_strlower(char *t) {
1770 for (p = t; *p; p++)
1771 if (*p >= 'A' && *p <= 'Z')
1772 *p = *p - 'A' + 'a';
1777 static bool ignore_file_allow_backup(const char *filename) {
1781 filename[0] == '.' ||
1782 streq(filename, "lost+found") ||
1783 streq(filename, "aquota.user") ||
1784 streq(filename, "aquota.group") ||
1785 endswith(filename, ".rpmnew") ||
1786 endswith(filename, ".rpmsave") ||
1787 endswith(filename, ".rpmorig") ||
1788 endswith(filename, ".dpkg-old") ||
1789 endswith(filename, ".dpkg-new") ||
1790 endswith(filename, ".swp");
1793 bool ignore_file(const char *filename) {
1796 if (endswith(filename, "~"))
1799 return ignore_file_allow_backup(filename);
1802 int fd_nonblock(int fd, bool nonblock) {
1807 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1811 flags |= O_NONBLOCK;
1813 flags &= ~O_NONBLOCK;
1815 if (fcntl(fd, F_SETFL, flags) < 0)
1821 int fd_cloexec(int fd, bool cloexec) {
1826 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1830 flags |= FD_CLOEXEC;
1832 flags &= ~FD_CLOEXEC;
1834 if (fcntl(fd, F_SETFD, flags) < 0)
1840 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1843 assert(n_fdset == 0 || fdset);
1845 for (i = 0; i < n_fdset; i++)
1852 int close_all_fds(const int except[], unsigned n_except) {
1857 assert(n_except == 0 || except);
1859 d = opendir("/proc/self/fd");
1864 /* When /proc isn't available (for example in chroots)
1865 * the fallback is brute forcing through the fd
1868 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1869 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1871 if (fd_in_set(fd, except, n_except))
1874 if (close_nointr(fd) < 0)
1875 if (errno != EBADF && r == 0)
1882 while ((de = readdir(d))) {
1885 if (ignore_file(de->d_name))
1888 if (safe_atoi(de->d_name, &fd) < 0)
1889 /* Let's better ignore this, just in case */
1898 if (fd_in_set(fd, except, n_except))
1901 if (close_nointr(fd) < 0) {
1902 /* Valgrind has its own FD and doesn't want to have it closed */
1903 if (errno != EBADF && r == 0)
1912 bool chars_intersect(const char *a, const char *b) {
1915 /* Returns true if any of the chars in a are in b. */
1916 for (p = a; *p; p++)
1923 char *format_timestamp(char *buf, size_t l, usec_t t) {
1933 sec = (time_t) (t / USEC_PER_SEC);
1935 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1941 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1944 n = now(CLOCK_REALTIME);
1946 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1951 if (d >= USEC_PER_YEAR)
1952 snprintf(buf, l, "%llu years and %llu months ago",
1953 (unsigned long long) (d / USEC_PER_YEAR),
1954 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1955 else if (d >= USEC_PER_MONTH)
1956 snprintf(buf, l, "%llu months and %llu days ago",
1957 (unsigned long long) (d / USEC_PER_MONTH),
1958 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1959 else if (d >= USEC_PER_WEEK)
1960 snprintf(buf, l, "%llu weeks and %llu days ago",
1961 (unsigned long long) (d / USEC_PER_WEEK),
1962 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1963 else if (d >= 2*USEC_PER_DAY)
1964 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1965 else if (d >= 25*USEC_PER_HOUR)
1966 snprintf(buf, l, "1 day and %lluh ago",
1967 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1968 else if (d >= 6*USEC_PER_HOUR)
1969 snprintf(buf, l, "%lluh ago",
1970 (unsigned long long) (d / USEC_PER_HOUR));
1971 else if (d >= USEC_PER_HOUR)
1972 snprintf(buf, l, "%lluh %llumin ago",
1973 (unsigned long long) (d / USEC_PER_HOUR),
1974 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1975 else if (d >= 5*USEC_PER_MINUTE)
1976 snprintf(buf, l, "%llumin ago",
1977 (unsigned long long) (d / USEC_PER_MINUTE));
1978 else if (d >= USEC_PER_MINUTE)
1979 snprintf(buf, l, "%llumin %llus ago",
1980 (unsigned long long) (d / USEC_PER_MINUTE),
1981 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1982 else if (d >= USEC_PER_SEC)
1983 snprintf(buf, l, "%llus ago",
1984 (unsigned long long) (d / USEC_PER_SEC));
1985 else if (d >= USEC_PER_MSEC)
1986 snprintf(buf, l, "%llums ago",
1987 (unsigned long long) (d / USEC_PER_MSEC));
1989 snprintf(buf, l, "%lluus ago",
1990 (unsigned long long) d);
1992 snprintf(buf, l, "now");
1998 char *format_timespan(char *buf, size_t l, usec_t t) {
1999 static const struct {
2003 { "w", USEC_PER_WEEK },
2004 { "d", USEC_PER_DAY },
2005 { "h", USEC_PER_HOUR },
2006 { "min", USEC_PER_MINUTE },
2007 { "s", USEC_PER_SEC },
2008 { "ms", USEC_PER_MSEC },
2018 if (t == (usec_t) -1)
2022 snprintf(p, l, "0");
2027 /* The result of this function can be parsed with parse_usec */
2029 for (i = 0; i < ELEMENTSOF(table); i++) {
2033 if (t < table[i].usec)
2039 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2040 n = MIN((size_t) k, l);
2053 bool fstype_is_network(const char *fstype) {
2054 static const char table[] =
2063 return nulstr_contains(table, fstype);
2067 _cleanup_close_ int fd;
2069 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2075 TIOCL_GETKMSGREDIRECT,
2079 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2082 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2085 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2091 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2092 struct termios old_termios, new_termios;
2094 char line[LINE_MAX];
2099 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2100 new_termios = old_termios;
2102 new_termios.c_lflag &= ~ICANON;
2103 new_termios.c_cc[VMIN] = 1;
2104 new_termios.c_cc[VTIME] = 0;
2106 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2109 if (t != (usec_t) -1) {
2110 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2111 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2116 k = fread(&c, 1, 1, f);
2118 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2124 *need_nl = c != '\n';
2131 if (t != (usec_t) -1)
2132 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2135 if (!fgets(line, sizeof(line), f))
2140 if (strlen(line) != 1)
2150 int ask(char *ret, const char *replies, const char *text, ...) {
2157 on_tty = isatty(STDOUT_FILENO);
2163 bool need_nl = true;
2166 fputs(ANSI_HIGHLIGHT_ON, stdout);
2173 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2177 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2180 if (r == -EBADMSG) {
2181 puts("Bad input, please try again.");
2192 if (strchr(replies, c)) {
2197 puts("Read unexpected character, please try again.");
2201 int reset_terminal_fd(int fd, bool switch_to_text) {
2202 struct termios termios;
2205 /* Set terminal to some sane defaults */
2209 /* We leave locked terminal attributes untouched, so that
2210 * Plymouth may set whatever it wants to set, and we don't
2211 * interfere with that. */
2213 /* Disable exclusive mode, just in case */
2214 ioctl(fd, TIOCNXCL);
2216 /* Switch to text mode */
2218 ioctl(fd, KDSETMODE, KD_TEXT);
2220 /* Enable console unicode mode */
2221 ioctl(fd, KDSKBMODE, K_UNICODE);
2223 if (tcgetattr(fd, &termios) < 0) {
2228 /* We only reset the stuff that matters to the software. How
2229 * hardware is set up we don't touch assuming that somebody
2230 * else will do that for us */
2232 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2233 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2234 termios.c_oflag |= ONLCR;
2235 termios.c_cflag |= CREAD;
2236 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2238 termios.c_cc[VINTR] = 03; /* ^C */
2239 termios.c_cc[VQUIT] = 034; /* ^\ */
2240 termios.c_cc[VERASE] = 0177;
2241 termios.c_cc[VKILL] = 025; /* ^X */
2242 termios.c_cc[VEOF] = 04; /* ^D */
2243 termios.c_cc[VSTART] = 021; /* ^Q */
2244 termios.c_cc[VSTOP] = 023; /* ^S */
2245 termios.c_cc[VSUSP] = 032; /* ^Z */
2246 termios.c_cc[VLNEXT] = 026; /* ^V */
2247 termios.c_cc[VWERASE] = 027; /* ^W */
2248 termios.c_cc[VREPRINT] = 022; /* ^R */
2249 termios.c_cc[VEOL] = 0;
2250 termios.c_cc[VEOL2] = 0;
2252 termios.c_cc[VTIME] = 0;
2253 termios.c_cc[VMIN] = 1;
2255 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2259 /* Just in case, flush all crap out */
2260 tcflush(fd, TCIOFLUSH);
2265 int reset_terminal(const char *name) {
2268 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2272 r = reset_terminal_fd(fd, true);
2273 close_nointr_nofail(fd);
2278 int open_terminal(const char *name, int mode) {
2283 * If a TTY is in the process of being closed opening it might
2284 * cause EIO. This is horribly awful, but unlikely to be
2285 * changed in the kernel. Hence we work around this problem by
2286 * retrying a couple of times.
2288 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2292 fd = open(name, mode);
2299 /* Max 1s in total */
2303 usleep(50 * USEC_PER_MSEC);
2312 close_nointr_nofail(fd);
2317 close_nointr_nofail(fd);
2324 int flush_fd(int fd) {
2325 struct pollfd pollfd;
2329 pollfd.events = POLLIN;
2336 if ((r = poll(&pollfd, 1, 0)) < 0) {
2347 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2352 if (errno == EAGAIN)
2363 int acquire_terminal(
2367 bool ignore_tiocstty_eperm,
2370 int fd = -1, notify = -1, r = 0, wd = -1;
2372 struct sigaction sa_old, sa_new;
2376 /* We use inotify to be notified when the tty is closed. We
2377 * create the watch before checking if we can actually acquire
2378 * it, so that we don't lose any event.
2380 * Note: strictly speaking this actually watches for the
2381 * device being closed, it does *not* really watch whether a
2382 * tty loses its controlling process. However, unless some
2383 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2384 * its tty otherwise this will not become a problem. As long
2385 * as the administrator makes sure not configure any service
2386 * on the same tty as an untrusted user this should not be a
2387 * problem. (Which he probably should not do anyway.) */
2389 if (timeout != (usec_t) -1)
2390 ts = now(CLOCK_MONOTONIC);
2392 if (!fail && !force) {
2393 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2399 wd = inotify_add_watch(notify, name, IN_CLOSE);
2408 r = flush_fd(notify);
2413 /* We pass here O_NOCTTY only so that we can check the return
2414 * value TIOCSCTTY and have a reliable way to figure out if we
2415 * successfully became the controlling process of the tty */
2416 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2420 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2421 * if we already own the tty. */
2423 sa_new.sa_handler = SIG_IGN;
2424 sa_new.sa_flags = SA_RESTART;
2425 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2427 /* First, try to get the tty */
2428 if (ioctl(fd, TIOCSCTTY, force) < 0)
2431 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2433 /* Sometimes it makes sense to ignore TIOCSCTTY
2434 * returning EPERM, i.e. when very likely we already
2435 * are have this controlling terminal. */
2436 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2439 if (r < 0 && (force || fail || r != -EPERM)) {
2448 assert(notify >= 0);
2451 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2453 struct inotify_event *e;
2455 if (timeout != (usec_t) -1) {
2458 n = now(CLOCK_MONOTONIC);
2459 if (ts + timeout < n) {
2464 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2474 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2477 if (errno == EINTR || errno == EAGAIN)
2484 e = (struct inotify_event*) inotify_buffer;
2489 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2494 step = sizeof(struct inotify_event) + e->len;
2495 assert(step <= (size_t) l);
2497 e = (struct inotify_event*) ((uint8_t*) e + step);
2504 /* We close the tty fd here since if the old session
2505 * ended our handle will be dead. It's important that
2506 * we do this after sleeping, so that we don't enter
2507 * an endless loop. */
2508 close_nointr_nofail(fd);
2512 close_nointr_nofail(notify);
2514 r = reset_terminal_fd(fd, true);
2516 log_warning("Failed to reset terminal: %s", strerror(-r));
2522 close_nointr_nofail(fd);
2525 close_nointr_nofail(notify);
2530 int release_terminal(void) {
2532 struct sigaction sa_old, sa_new;
2534 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2537 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2538 * by our own TIOCNOTTY */
2541 sa_new.sa_handler = SIG_IGN;
2542 sa_new.sa_flags = SA_RESTART;
2543 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2545 if (ioctl(fd, TIOCNOTTY) < 0)
2548 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2550 close_nointr_nofail(fd);
2554 int sigaction_many(const struct sigaction *sa, ...) {
2559 while ((sig = va_arg(ap, int)) > 0)
2560 if (sigaction(sig, sa, NULL) < 0)
2567 int ignore_signals(int sig, ...) {
2568 struct sigaction sa;
2573 sa.sa_handler = SIG_IGN;
2574 sa.sa_flags = SA_RESTART;
2576 if (sigaction(sig, &sa, NULL) < 0)
2580 while ((sig = va_arg(ap, int)) > 0)
2581 if (sigaction(sig, &sa, NULL) < 0)
2588 int default_signals(int sig, ...) {
2589 struct sigaction sa;
2594 sa.sa_handler = SIG_DFL;
2595 sa.sa_flags = SA_RESTART;
2597 if (sigaction(sig, &sa, NULL) < 0)
2601 while ((sig = va_arg(ap, int)) > 0)
2602 if (sigaction(sig, &sa, NULL) < 0)
2609 int close_pipe(int p[]) {
2615 a = close_nointr(p[0]);
2620 b = close_nointr(p[1]);
2624 return a < 0 ? a : b;
2627 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2636 while (nbytes > 0) {
2639 if ((k = read(fd, p, nbytes)) <= 0) {
2641 if (k < 0 && errno == EINTR)
2644 if (k < 0 && errno == EAGAIN && do_poll) {
2645 struct pollfd pollfd;
2649 pollfd.events = POLLIN;
2651 if (poll(&pollfd, 1, -1) < 0) {
2655 return n > 0 ? n : -errno;
2658 if (pollfd.revents != POLLIN)
2659 return n > 0 ? n : -EIO;
2664 return n > 0 ? n : (k < 0 ? -errno : 0);
2675 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2684 while (nbytes > 0) {
2687 k = write(fd, p, nbytes);
2690 if (k < 0 && errno == EINTR)
2693 if (k < 0 && errno == EAGAIN && do_poll) {
2694 struct pollfd pollfd;
2698 pollfd.events = POLLOUT;
2700 if (poll(&pollfd, 1, -1) < 0) {
2704 return n > 0 ? n : -errno;
2707 if (pollfd.revents != POLLOUT)
2708 return n > 0 ? n : -EIO;
2713 return n > 0 ? n : (k < 0 ? -errno : 0);
2724 int parse_usec(const char *t, usec_t *usec) {
2725 static const struct {
2729 { "sec", USEC_PER_SEC },
2730 { "s", USEC_PER_SEC },
2731 { "min", USEC_PER_MINUTE },
2732 { "hr", USEC_PER_HOUR },
2733 { "h", USEC_PER_HOUR },
2734 { "d", USEC_PER_DAY },
2735 { "w", USEC_PER_WEEK },
2736 { "msec", USEC_PER_MSEC },
2737 { "ms", USEC_PER_MSEC },
2738 { "m", USEC_PER_MINUTE },
2741 { "", USEC_PER_SEC }, /* default is sec */
2757 l = strtoll(p, &e, 10);
2768 e += strspn(e, WHITESPACE);
2770 for (i = 0; i < ELEMENTSOF(table); i++)
2771 if (startswith(e, table[i].suffix)) {
2772 r += (usec_t) l * table[i].usec;
2773 p = e + strlen(table[i].suffix);
2777 if (i >= ELEMENTSOF(table))
2787 int parse_nsec(const char *t, nsec_t *nsec) {
2788 static const struct {
2792 { "sec", NSEC_PER_SEC },
2793 { "s", NSEC_PER_SEC },
2794 { "min", NSEC_PER_MINUTE },
2795 { "hr", NSEC_PER_HOUR },
2796 { "h", NSEC_PER_HOUR },
2797 { "d", NSEC_PER_DAY },
2798 { "w", NSEC_PER_WEEK },
2799 { "msec", NSEC_PER_MSEC },
2800 { "ms", NSEC_PER_MSEC },
2801 { "m", NSEC_PER_MINUTE },
2802 { "usec", NSEC_PER_USEC },
2803 { "us", NSEC_PER_USEC },
2806 { "", 1ULL }, /* default is nsec */
2822 l = strtoll(p, &e, 10);
2833 e += strspn(e, WHITESPACE);
2835 for (i = 0; i < ELEMENTSOF(table); i++)
2836 if (startswith(e, table[i].suffix)) {
2837 r += (nsec_t) l * table[i].nsec;
2838 p = e + strlen(table[i].suffix);
2842 if (i >= ELEMENTSOF(table))
2852 int parse_bytes(const char *t, off_t *bytes) {
2853 static const struct {
2859 { "M", 1024ULL*1024ULL },
2860 { "G", 1024ULL*1024ULL*1024ULL },
2861 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2862 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2863 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2880 l = strtoll(p, &e, 10);
2891 e += strspn(e, WHITESPACE);
2893 for (i = 0; i < ELEMENTSOF(table); i++)
2894 if (startswith(e, table[i].suffix)) {
2895 r += (off_t) l * table[i].factor;
2896 p = e + strlen(table[i].suffix);
2900 if (i >= ELEMENTSOF(table))
2910 int make_stdio(int fd) {
2915 r = dup3(fd, STDIN_FILENO, 0);
2916 s = dup3(fd, STDOUT_FILENO, 0);
2917 t = dup3(fd, STDERR_FILENO, 0);
2920 close_nointr_nofail(fd);
2922 if (r < 0 || s < 0 || t < 0)
2925 /* We rely here that the new fd has O_CLOEXEC not set */
2930 int make_null_stdio(void) {
2933 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2937 return make_stdio(null_fd);
2940 bool is_device_path(const char *path) {
2942 /* Returns true on paths that refer to a device, either in
2943 * sysfs or in /dev */
2946 path_startswith(path, "/dev/") ||
2947 path_startswith(path, "/sys/");
2950 int dir_is_empty(const char *path) {
2951 _cleanup_closedir_ DIR *d;
2959 struct dirent buf, *de;
2961 r = readdir_r(d, &buf, &de);
2968 if (!ignore_file(de->d_name))
2973 unsigned long long random_ull(void) {
2974 _cleanup_close_ int fd;
2978 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2982 r = loop_read(fd, &ull, sizeof(ull), true);
2983 if (r != sizeof(ull))
2989 return random() * RAND_MAX + random();
2992 void rename_process(const char name[8]) {
2995 /* This is a like a poor man's setproctitle(). It changes the
2996 * comm field, argv[0], and also the glibc's internally used
2997 * name of the process. For the first one a limit of 16 chars
2998 * applies, to the second one usually one of 10 (i.e. length
2999 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3000 * "systemd"). If you pass a longer string it will be
3003 prctl(PR_SET_NAME, name);
3005 if (program_invocation_name)
3006 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3008 if (saved_argc > 0) {
3012 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3014 for (i = 1; i < saved_argc; i++) {
3018 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3023 void sigset_add_many(sigset_t *ss, ...) {
3030 while ((sig = va_arg(ap, int)) > 0)
3031 assert_se(sigaddset(ss, sig) == 0);
3035 char* gethostname_malloc(void) {
3038 assert_se(uname(&u) >= 0);
3040 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3041 return strdup(u.nodename);
3043 return strdup(u.sysname);
3046 bool hostname_is_set(void) {
3049 assert_se(uname(&u) >= 0);
3051 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3054 static char *lookup_uid(uid_t uid) {
3057 _cleanup_free_ char *buf = NULL;
3058 struct passwd pwbuf, *pw = NULL;
3060 /* Shortcut things to avoid NSS lookups */
3062 return strdup("root");
3064 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3068 buf = malloc(bufsize);
3072 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3073 return strdup(pw->pw_name);
3075 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3081 char* getlogname_malloc(void) {
3085 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3090 return lookup_uid(uid);
3093 char *getusername_malloc(void) {
3100 return lookup_uid(getuid());
3103 int getttyname_malloc(int fd, char **r) {
3104 char path[PATH_MAX], *c;
3109 k = ttyname_r(fd, path, sizeof(path));
3115 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3123 int getttyname_harder(int fd, char **r) {
3127 k = getttyname_malloc(fd, &s);
3131 if (streq(s, "tty")) {
3133 return get_ctty(0, NULL, r);
3140 int get_ctty_devnr(pid_t pid, dev_t *d) {
3142 char line[LINE_MAX], *p, *fn;
3143 unsigned long ttynr;
3146 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3149 f = fopen(fn, "re");
3154 if (!fgets(line, sizeof(line), f)) {
3155 k = feof(f) ? -EIO : -errno;
3162 p = strrchr(line, ')');
3172 "%*d " /* session */
3181 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3183 char fn[PATH_MAX], *s, *b, *p;
3188 k = get_ctty_devnr(pid, &devnr);
3192 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3195 if ((k = readlink_malloc(fn, &s)) < 0) {
3200 /* This is an ugly hack */
3201 if (major(devnr) == 136) {
3202 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3212 /* Probably something like the ptys which have no
3213 * symlink in /dev/char. Let's return something
3214 * vaguely useful. */
3216 if (!(b = strdup(fn + 5)))
3226 if (startswith(s, "/dev/"))
3228 else if (startswith(s, "../"))
3246 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3252 /* This returns the first error we run into, but nevertheless
3253 * tries to go on. This closes the passed fd. */
3257 close_nointr_nofail(fd);
3259 return errno == ENOENT ? 0 : -errno;
3263 struct dirent buf, *de;
3264 bool is_dir, keep_around;
3268 r = readdir_r(d, &buf, &de);
3269 if (r != 0 && ret == 0) {
3277 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3280 if (de->d_type == DT_UNKNOWN ||
3282 (de->d_type == DT_DIR && root_dev)) {
3283 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3284 if (ret == 0 && errno != ENOENT)
3289 is_dir = S_ISDIR(st.st_mode);
3292 (st.st_uid == 0 || st.st_uid == getuid()) &&
3293 (st.st_mode & S_ISVTX);
3295 is_dir = de->d_type == DT_DIR;
3296 keep_around = false;
3302 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3303 if (root_dev && st.st_dev != root_dev->st_dev)
3306 subdir_fd = openat(fd, de->d_name,
3307 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3308 if (subdir_fd < 0) {
3309 if (ret == 0 && errno != ENOENT)
3314 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3315 if (r < 0 && ret == 0)
3319 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3320 if (ret == 0 && errno != ENOENT)
3324 } else if (!only_dirs && !keep_around) {
3326 if (unlinkat(fd, de->d_name, 0) < 0) {
3327 if (ret == 0 && errno != ENOENT)
3338 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3343 if (fstatfs(fd, &s) < 0) {
3344 close_nointr_nofail(fd);
3348 /* We refuse to clean disk file systems with this call. This
3349 * is extra paranoia just to be sure we never ever remove
3352 if (s.f_type != TMPFS_MAGIC &&
3353 s.f_type != RAMFS_MAGIC) {
3354 log_error("Attempted to remove disk file system, and we can't allow that.");
3355 close_nointr_nofail(fd);
3359 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3362 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3368 /* We refuse to clean the root file system with this
3369 * call. This is extra paranoia to never cause a really
3370 * seriously broken system. */
3371 if (path_equal(path, "/")) {
3372 log_error("Attempted to remove entire root file system, and we can't allow that.");
3376 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3379 if (errno != ENOTDIR)
3383 if (statfs(path, &s) < 0)
3386 if (s.f_type != TMPFS_MAGIC &&
3387 s.f_type != RAMFS_MAGIC) {
3388 log_error("Attempted to remove disk file system, and we can't allow that.");
3393 if (delete_root && !only_dirs)
3394 if (unlink(path) < 0 && errno != ENOENT)
3401 if (fstatfs(fd, &s) < 0) {
3402 close_nointr_nofail(fd);
3406 if (s.f_type != TMPFS_MAGIC &&
3407 s.f_type != RAMFS_MAGIC) {
3408 log_error("Attempted to remove disk file system, and we can't allow that.");
3409 close_nointr_nofail(fd);
3414 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3417 if (honour_sticky && file_is_priv_sticky(path) > 0)
3420 if (rmdir(path) < 0 && errno != ENOENT) {
3429 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3430 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3433 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3434 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3437 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3440 /* Under the assumption that we are running privileged we
3441 * first change the access mode and only then hand out
3442 * ownership to avoid a window where access is too open. */
3444 if (mode != (mode_t) -1)
3445 if (chmod(path, mode) < 0)
3448 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3449 if (chown(path, uid, gid) < 0)
3455 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3458 /* Under the assumption that we are running privileged we
3459 * first change the access mode and only then hand out
3460 * ownership to avoid a window where access is too open. */
3462 if (fchmod(fd, mode) < 0)
3465 if (fchown(fd, uid, gid) < 0)
3471 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3475 /* Allocates the cpuset in the right size */
3478 if (!(r = CPU_ALLOC(n)))
3481 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3482 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3492 if (errno != EINVAL)
3499 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3500 static const char status_indent[] = " "; /* "[" STATUS "] " */
3501 _cleanup_free_ char *s = NULL;
3502 _cleanup_close_ int fd = -1;
3503 struct iovec iovec[5];
3508 /* This is independent of logging, as status messages are
3509 * optional and go exclusively to the console. */
3511 if (vasprintf(&s, format, ap) < 0)
3514 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3527 sl = status ? sizeof(status_indent)-1 : 0;
3533 e = ellipsize(s, emax, 75);
3543 if (!isempty(status)) {
3544 IOVEC_SET_STRING(iovec[n++], "[");
3545 IOVEC_SET_STRING(iovec[n++], status);
3546 IOVEC_SET_STRING(iovec[n++], "] ");
3548 IOVEC_SET_STRING(iovec[n++], status_indent);
3551 IOVEC_SET_STRING(iovec[n++], s);
3552 IOVEC_SET_STRING(iovec[n++], "\n");
3554 if (writev(fd, iovec, n) < 0)
3560 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3566 va_start(ap, format);
3567 r = status_vprintf(status, ellipse, format, ap);
3573 int status_welcome(void) {
3575 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3577 r = parse_env_file("/etc/os-release", NEWLINE,
3578 "PRETTY_NAME", &pretty_name,
3579 "ANSI_COLOR", &ansi_color,
3581 if (r < 0 && r != -ENOENT)
3582 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3584 return status_printf(NULL, false,
3585 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3586 isempty(ansi_color) ? "1" : ansi_color,
3587 isempty(pretty_name) ? "Linux" : pretty_name);
3590 char *replace_env(const char *format, char **env) {
3597 const char *e, *word = format;
3602 for (e = format; *e; e ++) {
3613 if (!(k = strnappend(r, word, e-word-1)))
3622 } else if (*e == '$') {
3623 if (!(k = strnappend(r, word, e-word)))
3639 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3642 if (!(k = strappend(r, t)))
3655 if (!(k = strnappend(r, word, e-word)))
3666 char **replace_env_argv(char **argv, char **env) {
3668 unsigned k = 0, l = 0;
3670 l = strv_length(argv);
3672 if (!(r = new(char*, l+1)))
3675 STRV_FOREACH(i, argv) {
3677 /* If $FOO appears as single word, replace it by the split up variable */
3678 if ((*i)[0] == '$' && (*i)[1] != '{') {
3683 if ((e = strv_env_get(env, *i+1))) {
3685 if (!(m = strv_split_quoted(e))) {
3696 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3705 memcpy(r + k, m, q * sizeof(char*));
3713 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3714 if (!(r[k++] = replace_env(*i, env))) {
3724 int fd_columns(int fd) {
3728 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3737 static unsigned columns_cached(bool cached) {
3738 static __thread int parsed_columns = 0, env_columns = -1;
3741 if (_likely_(parsed_columns > 0 && cached))
3742 return parsed_columns;
3744 if (_unlikely_(env_columns == -1)) {
3745 e = getenv("COLUMNS");
3747 env_columns = atoi(e);
3752 if (env_columns > 0) {
3753 parsed_columns = env_columns;
3754 return parsed_columns;
3757 if (parsed_columns <= 0 || !cached)
3758 parsed_columns = fd_columns(STDOUT_FILENO);
3760 if (parsed_columns <= 0)
3761 parsed_columns = 80;
3763 return parsed_columns;
3766 unsigned columns(void) {
3767 return columns_cached(true);
3770 unsigned columns_uncached(void) {
3771 return columns_cached(false);
3774 int fd_lines(int fd) {
3778 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3787 unsigned lines(void) {
3788 static __thread int parsed_lines = 0;
3791 if (_likely_(parsed_lines > 0))
3792 return parsed_lines;
3794 e = getenv("LINES");
3796 parsed_lines = atoi(e);
3798 if (parsed_lines <= 0)
3799 parsed_lines = fd_lines(STDOUT_FILENO);
3801 if (parsed_lines <= 0)
3804 return parsed_lines;
3807 int running_in_chroot(void) {
3813 /* Only works as root */
3815 if (stat("/proc/1/root", &a) < 0)
3818 if (stat("/", &b) < 0)
3822 a.st_dev != b.st_dev ||
3823 a.st_ino != b.st_ino;
3826 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3831 assert(percent <= 100);
3832 assert(new_length >= 3);
3834 if (old_length <= 3 || old_length <= new_length)
3835 return strndup(s, old_length);
3837 r = new0(char, new_length+1);
3841 x = (new_length * percent) / 100;
3843 if (x > new_length - 3)
3851 s + old_length - (new_length - x - 3),
3852 new_length - x - 3);
3857 char *ellipsize(const char *s, size_t length, unsigned percent) {
3858 return ellipsize_mem(s, strlen(s), length, percent);
3861 int touch(const char *path) {
3866 /* This just opens the file for writing, ensuring it
3867 * exists. It doesn't call utimensat() the way /usr/bin/touch
3870 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3874 close_nointr_nofail(fd);
3878 char *unquote(const char *s, const char* quotes) {
3882 /* This is rather stupid, simply removes the heading and
3883 * trailing quotes if there is one. Doesn't care about
3884 * escaping or anything. We should make this smarter one
3891 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3892 return strndup(s+1, l-2);
3897 char *normalize_env_assignment(const char *s) {
3898 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3901 eq = strchr(s, '=');
3913 memmove(r, t, strlen(t) + 1);
3917 name = strndup(s, eq - s);
3925 value = unquote(strstrip(p), QUOTES);
3929 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3935 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3946 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3958 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3965 r = wait_for_terminate(pid, &status);
3967 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3971 if (status.si_code == CLD_EXITED) {
3972 if (status.si_status != 0) {
3973 log_warning("%s failed with error code %i.", name, status.si_status);
3974 return status.si_status;
3977 log_debug("%s succeeded.", name);
3980 } else if (status.si_code == CLD_KILLED ||
3981 status.si_code == CLD_DUMPED) {
3983 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3987 log_warning("%s failed due to unknown reason.", name);
3991 _noreturn_ void freeze(void) {
3993 /* Make sure nobody waits for us on a socket anymore */
3994 close_all_fds(NULL, 0);
4002 bool null_or_empty(struct stat *st) {
4005 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4008 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4014 int null_or_empty_path(const char *fn) {
4019 if (stat(fn, &st) < 0)
4022 return null_or_empty(&st);
4025 DIR *xopendirat(int fd, const char *name, int flags) {
4029 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4035 close_nointr_nofail(nfd);
4042 int signal_from_string_try_harder(const char *s) {
4046 signo = signal_from_string(s);
4048 if (startswith(s, "SIG"))
4049 return signal_from_string(s+3);
4054 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4060 if (!dual_timestamp_is_set(t))
4063 fprintf(f, "%s=%llu %llu\n",
4065 (unsigned long long) t->realtime,
4066 (unsigned long long) t->monotonic);
4069 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4070 unsigned long long a, b;
4075 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4076 log_debug("Failed to parse finish timestamp value %s", value);
4083 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4087 /* FIXME: to follow udev's logic 100% we need to leave valid
4088 * UTF8 chars unescaped */
4090 u = unquote(tagvalue, "\"\'");
4094 t = xescape(u, "/ ");
4100 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4109 char *fstab_node_to_udev_node(const char *p) {
4112 if (startswith(p, "LABEL="))
4113 return tag_to_udev_node(p+6, "label");
4115 if (startswith(p, "UUID="))
4116 return tag_to_udev_node(p+5, "uuid");
4118 if (startswith(p, "PARTUUID="))
4119 return tag_to_udev_node(p+9, "partuuid");
4121 if (startswith(p, "PARTLABEL="))
4122 return tag_to_udev_node(p+10, "partlabel");
4127 bool tty_is_vc(const char *tty) {
4130 if (startswith(tty, "/dev/"))
4133 return vtnr_from_tty(tty) >= 0;
4136 bool tty_is_console(const char *tty) {
4139 if (startswith(tty, "/dev/"))
4142 return streq(tty, "console");
4145 int vtnr_from_tty(const char *tty) {
4150 if (startswith(tty, "/dev/"))
4153 if (!startswith(tty, "tty") )
4156 if (tty[3] < '0' || tty[3] > '9')
4159 r = safe_atoi(tty+3, &i);
4163 if (i < 0 || i > 63)
4169 bool tty_is_vc_resolve(const char *tty) {
4170 char *active = NULL;
4175 if (startswith(tty, "/dev/"))
4178 /* Resolve where /dev/console is pointing to, if /sys is
4179 * actually ours (i.e. not read-only-mounted which is a sign
4180 * for container setups) */
4181 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4182 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4183 /* If multiple log outputs are configured the
4184 * last one is what /dev/console points to */
4185 tty = strrchr(active, ' ');
4198 const char *default_term_for_tty(const char *tty) {
4201 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4204 bool dirent_is_file(const struct dirent *de) {
4207 if (ignore_file(de->d_name))
4210 if (de->d_type != DT_REG &&
4211 de->d_type != DT_LNK &&
4212 de->d_type != DT_UNKNOWN)
4218 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4221 if (de->d_type != DT_REG &&
4222 de->d_type != DT_LNK &&
4223 de->d_type != DT_UNKNOWN)
4226 if (ignore_file_allow_backup(de->d_name))
4229 return endswith(de->d_name, suffix);
4232 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4235 Hashmap *pids = NULL;
4239 /* Executes all binaries in a directory in parallel and waits
4240 * until all they all finished. */
4243 if (!(_d = opendir(directory))) {
4245 if (errno == ENOENT)
4248 log_error("Failed to enumerate directory %s: %m", directory);
4255 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4256 log_error("Failed to allocate set.");
4260 while ((de = readdir(d))) {
4265 if (!dirent_is_file(de))
4268 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4273 if ((pid = fork()) < 0) {
4274 log_error("Failed to fork: %m");
4292 log_error("Failed to execute %s: %m", path);
4293 _exit(EXIT_FAILURE);
4296 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4298 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4299 log_error("Failed to add PID to set: %s", strerror(-k));
4304 while (!hashmap_isempty(pids)) {
4305 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4310 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4315 log_error("waitid() failed: %m");
4319 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4320 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4321 if (si.si_code == CLD_EXITED)
4322 log_error("%s exited with exit status %i.", path, si.si_status);
4324 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4326 log_debug("%s exited successfully.", path);
4337 hashmap_free_free(pids);
4340 int kill_and_sigcont(pid_t pid, int sig) {
4343 r = kill(pid, sig) < 0 ? -errno : 0;
4351 bool nulstr_contains(const char*nulstr, const char *needle) {
4357 NULSTR_FOREACH(i, nulstr)
4358 if (streq(i, needle))
4364 bool plymouth_running(void) {
4365 return access("/run/plymouth/pid", F_OK) >= 0;
4368 char* strshorten(char *s, size_t l) {
4377 static bool hostname_valid_char(char c) {
4379 (c >= 'a' && c <= 'z') ||
4380 (c >= 'A' && c <= 'Z') ||
4381 (c >= '0' && c <= '9') ||
4387 bool hostname_is_valid(const char *s) {
4393 for (p = s; *p; p++)
4394 if (!hostname_valid_char(*p))
4397 if (p-s > HOST_NAME_MAX)
4403 char* hostname_cleanup(char *s) {
4406 for (p = s, d = s; *p; p++)
4407 if ((*p >= 'a' && *p <= 'z') ||
4408 (*p >= 'A' && *p <= 'Z') ||
4409 (*p >= '0' && *p <= '9') ||
4417 strshorten(s, HOST_NAME_MAX);
4421 int pipe_eof(int fd) {
4422 struct pollfd pollfd;
4427 pollfd.events = POLLIN|POLLHUP;
4429 r = poll(&pollfd, 1, 0);
4436 return pollfd.revents & POLLHUP;
4439 int fd_wait_for_event(int fd, int event, usec_t t) {
4440 struct pollfd pollfd;
4445 pollfd.events = event;
4447 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4454 return pollfd.revents;
4457 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4468 t = new(char, strlen(path) + 1 + 6 + 1);
4472 fn = path_get_file_name(path);
4476 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4478 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4484 f = fdopen(fd, "we");
4497 int terminal_vhangup_fd(int fd) {
4500 if (ioctl(fd, TIOCVHANGUP) < 0)
4506 int terminal_vhangup(const char *name) {
4509 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4513 r = terminal_vhangup_fd(fd);
4514 close_nointr_nofail(fd);
4519 int vt_disallocate(const char *name) {
4523 /* Deallocate the VT if possible. If not possible
4524 * (i.e. because it is the active one), at least clear it
4525 * entirely (including the scrollback buffer) */
4527 if (!startswith(name, "/dev/"))
4530 if (!tty_is_vc(name)) {
4531 /* So this is not a VT. I guess we cannot deallocate
4532 * it then. But let's at least clear the screen */
4534 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4539 "\033[r" /* clear scrolling region */
4540 "\033[H" /* move home */
4541 "\033[2J", /* clear screen */
4543 close_nointr_nofail(fd);
4548 if (!startswith(name, "/dev/tty"))
4551 r = safe_atou(name+8, &u);
4558 /* Try to deallocate */
4559 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4563 r = ioctl(fd, VT_DISALLOCATE, u);
4564 close_nointr_nofail(fd);
4572 /* Couldn't deallocate, so let's clear it fully with
4574 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4579 "\033[r" /* clear scrolling region */
4580 "\033[H" /* move home */
4581 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4583 close_nointr_nofail(fd);
4588 int copy_file(const char *from, const char *to) {
4594 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4598 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4600 close_nointr_nofail(fdf);
4608 n = read(fdf, buf, sizeof(buf));
4612 close_nointr_nofail(fdf);
4623 k = loop_write(fdt, buf, n, false);
4625 r = k < 0 ? k : (errno ? -errno : -EIO);
4627 close_nointr_nofail(fdf);
4635 close_nointr_nofail(fdf);
4636 r = close_nointr(fdt);
4646 int symlink_atomic(const char *from, const char *to) {
4648 _cleanup_free_ char *t;
4651 unsigned long long ull;
4658 t = new(char, strlen(to) + 1 + 16 + 1);
4662 fn = path_get_file_name(to);
4666 x = stpcpy(t+k+1, fn);
4669 for (i = 0; i < 16; i++) {
4670 *(x++) = hexchar(ull & 0xF);
4676 if (symlink(from, t) < 0)
4679 if (rename(t, to) < 0) {
4688 bool display_is_local(const char *display) {
4692 display[0] == ':' &&
4693 display[1] >= '0' &&
4697 int socket_from_display(const char *display, char **path) {
4704 if (!display_is_local(display))
4707 k = strspn(display+1, "0123456789");
4709 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4713 c = stpcpy(f, "/tmp/.X11-unix/X");
4714 memcpy(c, display+1, k);
4723 const char **username,
4724 uid_t *uid, gid_t *gid,
4726 const char **shell) {
4734 /* We enforce some special rules for uid=0: in order to avoid
4735 * NSS lookups for root we hardcode its data. */
4737 if (streq(*username, "root") || streq(*username, "0")) {
4755 if (parse_uid(*username, &u) >= 0) {
4759 /* If there are multiple users with the same id, make
4760 * sure to leave $USER to the configured value instead
4761 * of the first occurrence in the database. However if
4762 * the uid was configured by a numeric uid, then let's
4763 * pick the real username from /etc/passwd. */
4765 *username = p->pw_name;
4768 p = getpwnam(*username);
4772 return errno != 0 ? -errno : -ESRCH;
4784 *shell = p->pw_shell;
4789 int get_group_creds(const char **groupname, gid_t *gid) {
4795 /* We enforce some special rules for gid=0: in order to avoid
4796 * NSS lookups for root we hardcode its data. */
4798 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4799 *groupname = "root";
4807 if (parse_gid(*groupname, &id) >= 0) {
4812 *groupname = g->gr_name;
4815 g = getgrnam(*groupname);
4819 return errno != 0 ? -errno : -ESRCH;
4827 int in_group(const char *name) {
4829 int ngroups_max, r, i;
4831 r = get_group_creds(&name, &gid);
4835 if (getgid() == gid)
4838 if (getegid() == gid)
4841 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4842 assert(ngroups_max > 0);
4844 gids = alloca(sizeof(gid_t) * ngroups_max);
4846 r = getgroups(ngroups_max, gids);
4850 for (i = 0; i < r; i++)
4857 int glob_exists(const char *path) {
4865 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4867 if (k == GLOB_NOMATCH)
4869 else if (k == GLOB_NOSPACE)
4872 r = !strv_isempty(g.gl_pathv);
4874 r = errno ? -errno : -EIO;
4881 int dirent_ensure_type(DIR *d, struct dirent *de) {
4887 if (de->d_type != DT_UNKNOWN)
4890 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4894 S_ISREG(st.st_mode) ? DT_REG :
4895 S_ISDIR(st.st_mode) ? DT_DIR :
4896 S_ISLNK(st.st_mode) ? DT_LNK :
4897 S_ISFIFO(st.st_mode) ? DT_FIFO :
4898 S_ISSOCK(st.st_mode) ? DT_SOCK :
4899 S_ISCHR(st.st_mode) ? DT_CHR :
4900 S_ISBLK(st.st_mode) ? DT_BLK :
4906 int in_search_path(const char *path, char **search) {
4910 r = path_get_parent(path, &parent);
4916 STRV_FOREACH(i, search) {
4917 if (path_equal(parent, *i)) {
4928 int get_files_in_directory(const char *path, char ***list) {
4936 /* Returns all files in a directory in *list, and the number
4937 * of files as return value. If list is NULL returns only the
4945 struct dirent buffer, *de;
4948 k = readdir_r(d, &buffer, &de);
4957 dirent_ensure_type(d, de);
4959 if (!dirent_is_file(de))
4963 if ((unsigned) r >= n) {
4967 t = realloc(l, sizeof(char*) * n);
4976 assert((unsigned) r < n);
4978 l[r] = strdup(de->d_name);
5002 char *strjoin(const char *x, ...) {
5015 t = va_arg(ap, const char *);
5038 t = va_arg(ap, const char *);
5052 bool is_main_thread(void) {
5053 static __thread int cached = 0;
5055 if (_unlikely_(cached == 0))
5056 cached = getpid() == gettid() ? 1 : -1;
5061 int block_get_whole_disk(dev_t d, dev_t *ret) {
5068 /* If it has a queue this is good enough for us */
5069 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5072 r = access(p, F_OK);
5080 /* If it is a partition find the originating device */
5081 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5084 r = access(p, F_OK);
5090 /* Get parent dev_t */
5091 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5094 r = read_one_line_file(p, &s);
5100 r = sscanf(s, "%u:%u", &m, &n);
5106 /* Only return this if it is really good enough for us. */
5107 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5110 r = access(p, F_OK);
5114 *ret = makedev(m, n);
5121 int file_is_priv_sticky(const char *p) {
5126 if (lstat(p, &st) < 0)
5130 (st.st_uid == 0 || st.st_uid == getuid()) &&
5131 (st.st_mode & S_ISVTX);
5134 static const char *const ioprio_class_table[] = {
5135 [IOPRIO_CLASS_NONE] = "none",
5136 [IOPRIO_CLASS_RT] = "realtime",
5137 [IOPRIO_CLASS_BE] = "best-effort",
5138 [IOPRIO_CLASS_IDLE] = "idle"
5141 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5143 static const char *const sigchld_code_table[] = {
5144 [CLD_EXITED] = "exited",
5145 [CLD_KILLED] = "killed",
5146 [CLD_DUMPED] = "dumped",
5147 [CLD_TRAPPED] = "trapped",
5148 [CLD_STOPPED] = "stopped",
5149 [CLD_CONTINUED] = "continued",
5152 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5154 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5155 [LOG_FAC(LOG_KERN)] = "kern",
5156 [LOG_FAC(LOG_USER)] = "user",
5157 [LOG_FAC(LOG_MAIL)] = "mail",
5158 [LOG_FAC(LOG_DAEMON)] = "daemon",
5159 [LOG_FAC(LOG_AUTH)] = "auth",
5160 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5161 [LOG_FAC(LOG_LPR)] = "lpr",
5162 [LOG_FAC(LOG_NEWS)] = "news",
5163 [LOG_FAC(LOG_UUCP)] = "uucp",
5164 [LOG_FAC(LOG_CRON)] = "cron",
5165 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5166 [LOG_FAC(LOG_FTP)] = "ftp",
5167 [LOG_FAC(LOG_LOCAL0)] = "local0",
5168 [LOG_FAC(LOG_LOCAL1)] = "local1",
5169 [LOG_FAC(LOG_LOCAL2)] = "local2",
5170 [LOG_FAC(LOG_LOCAL3)] = "local3",
5171 [LOG_FAC(LOG_LOCAL4)] = "local4",
5172 [LOG_FAC(LOG_LOCAL5)] = "local5",
5173 [LOG_FAC(LOG_LOCAL6)] = "local6",
5174 [LOG_FAC(LOG_LOCAL7)] = "local7"
5177 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5179 static const char *const log_level_table[] = {
5180 [LOG_EMERG] = "emerg",
5181 [LOG_ALERT] = "alert",
5182 [LOG_CRIT] = "crit",
5184 [LOG_WARNING] = "warning",
5185 [LOG_NOTICE] = "notice",
5186 [LOG_INFO] = "info",
5187 [LOG_DEBUG] = "debug"
5190 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5192 static const char* const sched_policy_table[] = {
5193 [SCHED_OTHER] = "other",
5194 [SCHED_BATCH] = "batch",
5195 [SCHED_IDLE] = "idle",
5196 [SCHED_FIFO] = "fifo",
5200 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5202 static const char* const rlimit_table[] = {
5203 [RLIMIT_CPU] = "LimitCPU",
5204 [RLIMIT_FSIZE] = "LimitFSIZE",
5205 [RLIMIT_DATA] = "LimitDATA",
5206 [RLIMIT_STACK] = "LimitSTACK",
5207 [RLIMIT_CORE] = "LimitCORE",
5208 [RLIMIT_RSS] = "LimitRSS",
5209 [RLIMIT_NOFILE] = "LimitNOFILE",
5210 [RLIMIT_AS] = "LimitAS",
5211 [RLIMIT_NPROC] = "LimitNPROC",
5212 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5213 [RLIMIT_LOCKS] = "LimitLOCKS",
5214 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5215 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5216 [RLIMIT_NICE] = "LimitNICE",
5217 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5218 [RLIMIT_RTTIME] = "LimitRTTIME"
5221 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5223 static const char* const ip_tos_table[] = {
5224 [IPTOS_LOWDELAY] = "low-delay",
5225 [IPTOS_THROUGHPUT] = "throughput",
5226 [IPTOS_RELIABILITY] = "reliability",
5227 [IPTOS_LOWCOST] = "low-cost",
5230 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5232 static const char *const __signal_table[] = {
5249 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5260 [SIGVTALRM] = "VTALRM",
5262 [SIGWINCH] = "WINCH",
5268 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5270 const char *signal_to_string(int signo) {
5271 static __thread char buf[12];
5274 name = __signal_to_string(signo);
5278 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5279 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5281 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5286 int signal_from_string(const char *s) {
5291 signo =__signal_from_string(s);
5295 if (startswith(s, "RTMIN+")) {
5299 if (safe_atou(s, &u) >= 0) {
5300 signo = (int) u + offset;
5301 if (signo > 0 && signo < _NSIG)
5307 bool kexec_loaded(void) {
5308 bool loaded = false;
5311 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5319 int strdup_or_null(const char *a, char **b) {
5337 int prot_from_flags(int flags) {
5339 switch (flags & O_ACCMODE) {
5348 return PROT_READ|PROT_WRITE;
5355 char *format_bytes(char *buf, size_t l, off_t t) {
5358 static const struct {
5362 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5363 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5364 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5365 { "G", 1024ULL*1024ULL*1024ULL },
5366 { "M", 1024ULL*1024ULL },
5370 for (i = 0; i < ELEMENTSOF(table); i++) {
5372 if (t >= table[i].factor) {
5375 (unsigned long long) (t / table[i].factor),
5376 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5383 snprintf(buf, l, "%lluB", (unsigned long long) t);
5391 void* memdup(const void *p, size_t l) {
5404 int fd_inc_sndbuf(int fd, size_t n) {
5406 socklen_t l = sizeof(value);
5408 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5410 l == sizeof(value) &&
5411 (size_t) value >= n*2)
5415 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5422 int fd_inc_rcvbuf(int fd, size_t n) {
5424 socklen_t l = sizeof(value);
5426 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5428 l == sizeof(value) &&
5429 (size_t) value >= n*2)
5433 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5440 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5441 pid_t parent_pid, agent_pid;
5443 bool stdout_is_tty, stderr_is_tty;
5451 parent_pid = getpid();
5453 /* Spawns a temporary TTY agent, making sure it goes away when
5460 if (agent_pid != 0) {
5467 * Make sure the agent goes away when the parent dies */
5468 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5469 _exit(EXIT_FAILURE);
5471 /* Check whether our parent died before we were able
5472 * to set the death signal */
5473 if (getppid() != parent_pid)
5474 _exit(EXIT_SUCCESS);
5476 /* Don't leak fds to the agent */
5477 close_all_fds(except, n_except);
5479 stdout_is_tty = isatty(STDOUT_FILENO);
5480 stderr_is_tty = isatty(STDERR_FILENO);
5482 if (!stdout_is_tty || !stderr_is_tty) {
5483 /* Detach from stdout/stderr. and reopen
5484 * /dev/tty for them. This is important to
5485 * ensure that when systemctl is started via
5486 * popen() or a similar call that expects to
5487 * read EOF we actually do generate EOF and
5488 * not delay this indefinitely by because we
5489 * keep an unused copy of stdin around. */
5490 fd = open("/dev/tty", O_WRONLY);
5492 log_error("Failed to open /dev/tty: %m");
5493 _exit(EXIT_FAILURE);
5497 dup2(fd, STDOUT_FILENO);
5500 dup2(fd, STDERR_FILENO);
5506 /* Count arguments */
5508 for (n = 0; va_arg(ap, char*); n++)
5513 l = alloca(sizeof(char *) * (n + 1));
5515 /* Fill in arguments */
5517 for (i = 0; i <= n; i++)
5518 l[i] = va_arg(ap, char*);
5522 _exit(EXIT_FAILURE);
5525 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5526 struct rlimit highest, fixed;
5530 if (setrlimit(resource, rlim) >= 0)
5536 /* So we failed to set the desired setrlimit, then let's try
5537 * to get as close as we can */
5538 assert_se(getrlimit(resource, &highest) == 0);
5540 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5541 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5543 if (setrlimit(resource, &fixed) < 0)
5549 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5550 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5562 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5565 f = fopen(path, "re");
5573 char line[LINE_MAX];
5576 for (i = 0; i < sizeof(line)-1; i++) {
5580 if (_unlikely_(c == EOF)) {
5590 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5591 value = strdup(line + l + 1);
5611 int can_sleep(const char *type) {
5615 _cleanup_free_ char *p = NULL;
5619 r = read_one_line_file("/sys/power/state", &p);
5621 return r == -ENOENT ? 0 : r;
5624 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5625 if (l == k && memcmp(w, type, l) == 0)
5631 bool is_valid_documentation_url(const char *url) {
5634 if (startswith(url, "http://") && url[7])
5637 if (startswith(url, "https://") && url[8])
5640 if (startswith(url, "file:") && url[5])
5643 if (startswith(url, "info:") && url[5])
5646 if (startswith(url, "man:") && url[4])
5652 bool in_initrd(void) {
5653 static __thread int saved = -1;
5659 /* We make two checks here:
5661 * 1. the flag file /etc/initrd-release must exist
5662 * 2. the root file system must be a memory file system
5664 * The second check is extra paranoia, since misdetecting an
5665 * initrd can have bad bad consequences due the initrd
5666 * emptying when transititioning to the main systemd.
5669 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5670 statfs("/", &s) >= 0 &&
5671 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5676 void warn_melody(void) {
5677 _cleanup_close_ int fd = -1;
5679 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5683 /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5685 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5686 usleep(125*USEC_PER_MSEC);
5688 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5689 usleep(125*USEC_PER_MSEC);
5691 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5692 usleep(125*USEC_PER_MSEC);
5694 ioctl(fd, KIOCSOUND, 0);
5697 int make_console_stdio(void) {
5700 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5702 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5704 log_error("Failed to acquire terminal: %s", strerror(-fd));
5710 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5717 int get_home_dir(char **_h) {
5725 /* Take the user specified one */
5736 /* Hardcode home directory for root to avoid NSS */
5739 h = strdup("/root");
5747 /* Check the database... */
5751 return errno ? -errno : -ESRCH;
5753 if (!path_is_absolute(p->pw_dir))
5756 h = strdup(p->pw_dir);
5764 int get_shell(char **_sh) {
5772 /* Take the user specified one */
5773 e = getenv("SHELL");
5783 /* Hardcode home directory for root to avoid NSS */
5786 sh = strdup("/bin/sh");
5794 /* Check the database... */
5798 return errno ? -errno : -ESRCH;
5800 if (!path_is_absolute(p->pw_shell))
5803 sh = strdup(p->pw_shell);
5811 void freep(void *p) {
5815 void fclosep(FILE **f) {
5820 void closep(int *fd) {
5822 close_nointr_nofail(*fd);
5825 void closedirp(DIR **d) {
5830 void umaskp(mode_t *u) {