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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU 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>
53 #include <sys/capability.h>
62 #include "exit-status.h"
65 size_t page_size(void) {
66 static __thread size_t pgsz = 0;
72 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
79 bool streq_ptr(const char *a, const char *b) {
81 /* Like streq(), but tries to make sense of NULL pointers */
92 usec_t now(clockid_t clock_id) {
95 assert_se(clock_gettime(clock_id, &ts) == 0);
97 return timespec_load(&ts);
100 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
103 ts->realtime = now(CLOCK_REALTIME);
104 ts->monotonic = now(CLOCK_MONOTONIC);
109 usec_t timespec_load(const struct timespec *ts) {
113 (usec_t) ts->tv_sec * USEC_PER_SEC +
114 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
117 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
120 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
121 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
126 usec_t timeval_load(const struct timeval *tv) {
130 (usec_t) tv->tv_sec * USEC_PER_SEC +
131 (usec_t) tv->tv_usec;
134 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
137 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
138 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
143 bool endswith(const char *s, const char *postfix) {
150 pl = strlen(postfix);
158 return memcmp(s + sl - pl, postfix, pl) == 0;
161 bool startswith(const char *s, const char *prefix) {
176 return memcmp(s, prefix, pl) == 0;
179 bool startswith_no_case(const char *s, const char *prefix) {
195 for(i = 0; i < pl; ++i) {
196 if (tolower(s[i]) != tolower(prefix[i]))
203 bool first_word(const char *s, const char *word) {
218 if (memcmp(s, word, wl) != 0)
222 strchr(WHITESPACE, s[wl]);
225 int close_nointr(int fd) {
231 if ((r = close(fd)) >= 0)
239 void close_nointr_nofail(int fd) {
240 int saved_errno = errno;
242 /* like close_nointr() but cannot fail, and guarantees errno
245 assert_se(close_nointr(fd) == 0);
250 void close_many(const int fds[], unsigned n_fd) {
253 for (i = 0; i < n_fd; i++)
254 close_nointr_nofail(fds[i]);
257 int parse_boolean(const char *v) {
260 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
262 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
268 int parse_pid(const char *s, pid_t* ret_pid) {
269 unsigned long ul = 0;
276 if ((r = safe_atolu(s, &ul)) < 0)
281 if ((unsigned long) pid != ul)
291 int safe_atou(const char *s, unsigned *ret_u) {
299 l = strtoul(s, &x, 0);
301 if (!x || *x || errno)
302 return errno ? -errno : -EINVAL;
304 if ((unsigned long) (unsigned) l != l)
307 *ret_u = (unsigned) l;
311 int safe_atoi(const char *s, int *ret_i) {
319 l = strtol(s, &x, 0);
321 if (!x || *x || errno)
322 return errno ? -errno : -EINVAL;
324 if ((long) (int) l != l)
331 int safe_atollu(const char *s, long long unsigned *ret_llu) {
333 unsigned long long l;
339 l = strtoull(s, &x, 0);
341 if (!x || *x || errno)
342 return errno ? -errno : -EINVAL;
348 int safe_atolli(const char *s, long long int *ret_lli) {
356 l = strtoll(s, &x, 0);
358 if (!x || *x || errno)
359 return errno ? -errno : -EINVAL;
365 /* Split a string into words. */
366 char *split(const char *c, size_t *l, const char *separator, char **state) {
369 current = *state ? *state : (char*) c;
371 if (!*current || *c == 0)
374 current += strspn(current, separator);
375 *l = strcspn(current, separator);
378 return (char*) current;
381 /* Split a string into words, but consider strings enclosed in '' and
382 * "" as words even if they include spaces. */
383 char *split_quoted(const char *c, size_t *l, char **state) {
385 bool escaped = false;
387 current = *state ? *state : (char*) c;
389 if (!*current || *c == 0)
392 current += strspn(current, WHITESPACE);
394 if (*current == '\'') {
397 for (e = current; *e; e++) {
407 *state = *e == 0 ? e : e+1;
408 } else if (*current == '\"') {
411 for (e = current; *e; e++) {
421 *state = *e == 0 ? e : e+1;
423 for (e = current; *e; e++) {
428 else if (strchr(WHITESPACE, *e))
435 return (char*) current;
438 char **split_path_and_make_absolute(const char *p) {
442 if (!(l = strv_split(p, ":")))
445 if (!strv_path_make_absolute_cwd(l)) {
453 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
456 char fn[PATH_MAX], line[LINE_MAX], *p;
462 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
465 if (!(f = fopen(fn, "r")))
468 if (!(fgets(line, sizeof(line), f))) {
476 /* Let's skip the pid and comm fields. The latter is enclosed
477 * in () but does not escape any () in its value, so let's
478 * skip over it manually */
480 if (!(p = strrchr(line, ')')))
491 if ((long unsigned) (pid_t) ppid != ppid)
494 *_ppid = (pid_t) ppid;
499 int write_one_line_file(const char *fn, const char *line) {
506 if (!(f = fopen(fn, "we")))
509 if (fputs(line, f) < 0) {
514 if (!endswith(line, "\n"))
532 int read_one_line_file(const char *fn, char **line) {
535 char t[LINE_MAX], *c;
540 if (!(f = fopen(fn, "re")))
543 if (!(fgets(t, sizeof(t), f))) {
548 if (!(c = strdup(t))) {
563 int read_full_file(const char *fn, char **contents) {
570 if (!(f = fopen(fn, "re")))
573 if (fstat(fileno(f), &st) < 0) {
578 n = st.st_size > 0 ? st.st_size : LINE_MAX;
585 if (!(t = realloc(buf, n+1))) {
591 k = fread(buf + l, 1, n - l, f);
606 if (n > 4*1024*1024) {
614 else if (!(buf = calloc(1, 1))) {
633 const char *separator, ...) {
641 if ((r = read_full_file(fname, &contents)) < 0)
646 const char *key = NULL;
648 p += strspn(p, separator);
649 p += strspn(p, WHITESPACE);
654 if (!strchr(COMMENTS, *p)) {
658 va_start(ap, separator);
659 while ((key = va_arg(ap, char *))) {
663 value = va_arg(ap, char **);
666 if (strncmp(p, key, n) != 0 ||
671 n = strcspn(p, separator);
674 strchr(QUOTES, p[0]) &&
676 v = strndup(p+1, n-2);
687 /* return empty value strings as NULL */
704 p += strcspn(p, separator);
723 if (!(f = fopen(fname, "re")))
727 char l[LINE_MAX], *p, *u;
730 if (!fgets(l, sizeof(l), f)) {
743 if (strchr(COMMENTS, *p))
746 if (!(u = normalize_env_assignment(p))) {
747 log_error("Out of memory");
752 t = strv_append(m, u);
756 log_error("Out of memory");
779 char *truncate_nl(char *s) {
782 s[strcspn(s, NEWLINE)] = 0;
786 int get_process_name(pid_t pid, char **name) {
793 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
796 r = read_one_line_file(p, name);
805 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
813 assert(max_length > 0);
816 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
825 if (!(r = new(char, max_length))) {
832 while ((c = getc(f)) != EOF) {
854 size_t n = MIN(left-1, 3U);
862 /* Kernel threads have no argv[] */
869 if ((h = get_process_name(pid, &t)) < 0)
872 h = asprintf(&r, "[%s]", t);
883 char *strnappend(const char *s, const char *suffix, size_t b) {
891 return strndup(suffix, b);
901 if (!(r = new(char, a+b+1)))
905 memcpy(r+a, suffix, b);
911 char *strappend(const char *s, const char *suffix) {
912 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
915 int readlink_malloc(const char *p, char **r) {
925 if (!(c = new(char, l)))
928 if ((n = readlink(p, c, l-1)) < 0) {
934 if ((size_t) n < l-1) {
945 int readlink_and_make_absolute(const char *p, char **r) {
952 if ((j = readlink_malloc(p, &target)) < 0)
955 k = file_in_same_dir(p, target);
965 int parent_of_path(const char *path, char **_r) {
966 const char *e, *a = NULL, *b = NULL, *p;
976 for (e = path; *e; e++) {
978 if (!slash && *e == '/') {
982 } else if (slash && *e != '/')
997 r = strndup(path, p-path);
1007 char *file_name_from_path(const char *p) {
1012 if ((r = strrchr(p, '/')))
1018 bool path_is_absolute(const char *p) {
1024 bool is_path(const char *p) {
1026 return !!strchr(p, '/');
1029 char *path_make_absolute(const char *p, const char *prefix) {
1034 /* Makes every item in the list an absolute path by prepending
1035 * the prefix, if specified and necessary */
1037 if (path_is_absolute(p) || !prefix)
1040 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1046 char *path_make_absolute_cwd(const char *p) {
1051 /* Similar to path_make_absolute(), but prefixes with the
1052 * current working directory. */
1054 if (path_is_absolute(p))
1057 if (!(cwd = get_current_dir_name()))
1060 r = path_make_absolute(p, cwd);
1066 char **strv_path_make_absolute_cwd(char **l) {
1069 /* Goes through every item in the string list and makes it
1070 * absolute. This works in place and won't rollback any
1071 * changes on failure. */
1073 STRV_FOREACH(s, l) {
1076 if (!(t = path_make_absolute_cwd(*s)))
1086 char **strv_path_canonicalize(char **l) {
1089 bool enomem = false;
1091 if (strv_isempty(l))
1094 /* Goes through every item in the string list and canonicalize
1095 * the path. This works in place and won't rollback any
1096 * changes on failure. */
1098 STRV_FOREACH(s, l) {
1101 t = path_make_absolute_cwd(*s);
1110 u = canonicalize_file_name(t);
1114 if (errno == ENOMEM || !errno)
1131 int reset_all_signal_handlers(void) {
1134 for (sig = 1; sig < _NSIG; sig++) {
1135 struct sigaction sa;
1137 if (sig == SIGKILL || sig == SIGSTOP)
1141 sa.sa_handler = SIG_DFL;
1142 sa.sa_flags = SA_RESTART;
1144 /* On Linux the first two RT signals are reserved by
1145 * glibc, and sigaction() will return EINVAL for them. */
1146 if ((sigaction(sig, &sa, NULL) < 0))
1147 if (errno != EINVAL)
1154 char *strstrip(char *s) {
1157 /* Drops trailing whitespace. Modifies the string in
1158 * place. Returns pointer to first non-space character */
1160 s += strspn(s, WHITESPACE);
1162 for (e = s; *e; e++)
1163 if (!strchr(WHITESPACE, *e))
1174 char *delete_chars(char *s, const char *bad) {
1177 /* Drops all whitespace, regardless where in the string */
1179 for (f = s, t = s; *f; f++) {
1180 if (strchr(bad, *f))
1191 char *file_in_same_dir(const char *path, const char *filename) {
1198 /* This removes the last component of path and appends
1199 * filename, unless the latter is absolute anyway or the
1202 if (path_is_absolute(filename))
1203 return strdup(filename);
1205 if (!(e = strrchr(path, '/')))
1206 return strdup(filename);
1208 k = strlen(filename);
1209 if (!(r = new(char, e-path+1+k+1)))
1212 memcpy(r, path, e-path+1);
1213 memcpy(r+(e-path)+1, filename, k+1);
1218 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1221 if (label_mkdir(path, mode) >= 0)
1222 if (chmod_and_chown(path, mode, uid, gid) < 0)
1225 if (lstat(path, &st) < 0)
1228 if ((st.st_mode & 0777) != mode ||
1231 !S_ISDIR(st.st_mode)) {
1240 int mkdir_parents(const char *path, mode_t mode) {
1245 /* Creates every parent directory in the path except the last
1248 p = path + strspn(path, "/");
1253 e = p + strcspn(p, "/");
1254 p = e + strspn(e, "/");
1256 /* Is this the last component? If so, then we're
1261 if (!(t = strndup(path, e - path)))
1264 r = label_mkdir(t, mode);
1267 if (r < 0 && errno != EEXIST)
1272 int mkdir_p(const char *path, mode_t mode) {
1277 if ((r = mkdir_parents(path, mode)) < 0)
1280 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1286 int rmdir_parents(const char *path, const char *stop) {
1295 /* Skip trailing slashes */
1296 while (l > 0 && path[l-1] == '/')
1302 /* Skip last component */
1303 while (l > 0 && path[l-1] != '/')
1306 /* Skip trailing slashes */
1307 while (l > 0 && path[l-1] == '/')
1313 if (!(t = strndup(path, l)))
1316 if (path_startswith(stop, t)) {
1325 if (errno != ENOENT)
1333 char hexchar(int x) {
1334 static const char table[16] = "0123456789abcdef";
1336 return table[x & 15];
1339 int unhexchar(char c) {
1341 if (c >= '0' && c <= '9')
1344 if (c >= 'a' && c <= 'f')
1345 return c - 'a' + 10;
1347 if (c >= 'A' && c <= 'F')
1348 return c - 'A' + 10;
1353 char octchar(int x) {
1354 return '0' + (x & 7);
1357 int unoctchar(char c) {
1359 if (c >= '0' && c <= '7')
1365 char decchar(int x) {
1366 return '0' + (x % 10);
1369 int undecchar(char c) {
1371 if (c >= '0' && c <= '9')
1377 char *cescape(const char *s) {
1383 /* Does C style string escaping. */
1385 if (!(r = new(char, strlen(s)*4 + 1)))
1388 for (f = s, t = r; *f; f++)
1434 /* For special chars we prefer octal over
1435 * hexadecimal encoding, simply because glib's
1436 * g_strescape() does the same */
1437 if ((*f < ' ') || (*f >= 127)) {
1439 *(t++) = octchar((unsigned char) *f >> 6);
1440 *(t++) = octchar((unsigned char) *f >> 3);
1441 *(t++) = octchar((unsigned char) *f);
1452 char *cunescape_length(const char *s, size_t length) {
1458 /* Undoes C style string escaping */
1460 if (!(r = new(char, length+1)))
1463 for (f = s, t = r; f < s + length; f++) {
1506 /* This is an extension of the XDG syntax files */
1511 /* hexadecimal encoding */
1514 if ((a = unhexchar(f[1])) < 0 ||
1515 (b = unhexchar(f[2])) < 0) {
1516 /* Invalid escape code, let's take it literal then */
1520 *(t++) = (char) ((a << 4) | b);
1535 /* octal encoding */
1538 if ((a = unoctchar(f[0])) < 0 ||
1539 (b = unoctchar(f[1])) < 0 ||
1540 (c = unoctchar(f[2])) < 0) {
1541 /* Invalid escape code, let's take it literal then */
1545 *(t++) = (char) ((a << 6) | (b << 3) | c);
1553 /* premature end of string.*/
1558 /* Invalid escape code, let's take it literal then */
1570 char *cunescape(const char *s) {
1571 return cunescape_length(s, strlen(s));
1574 char *xescape(const char *s, const char *bad) {
1578 /* Escapes all chars in bad, in addition to \ and all special
1579 * chars, in \xFF style escaping. May be reversed with
1582 if (!(r = new(char, strlen(s)*4+1)))
1585 for (f = s, t = r; *f; f++) {
1587 if ((*f < ' ') || (*f >= 127) ||
1588 (*f == '\\') || strchr(bad, *f)) {
1591 *(t++) = hexchar(*f >> 4);
1592 *(t++) = hexchar(*f);
1602 char *bus_path_escape(const char *s) {
1608 /* Escapes all chars that D-Bus' object path cannot deal
1609 * with. Can be reverse with bus_path_unescape() */
1611 if (!(r = new(char, strlen(s)*3+1)))
1614 for (f = s, t = r; *f; f++) {
1616 if (!(*f >= 'A' && *f <= 'Z') &&
1617 !(*f >= 'a' && *f <= 'z') &&
1618 !(*f >= '0' && *f <= '9')) {
1620 *(t++) = hexchar(*f >> 4);
1621 *(t++) = hexchar(*f);
1631 char *bus_path_unescape(const char *f) {
1636 if (!(r = strdup(f)))
1639 for (t = r; *f; f++) {
1644 if ((a = unhexchar(f[1])) < 0 ||
1645 (b = unhexchar(f[2])) < 0) {
1646 /* Invalid escape code, let's take it literal then */
1649 *(t++) = (char) ((a << 4) | b);
1661 char *path_kill_slashes(char *path) {
1665 /* Removes redundant inner and trailing slashes. Modifies the
1666 * passed string in-place.
1668 * ///foo///bar/ becomes /foo/bar
1671 for (f = path, t = path; *f; f++) {
1686 /* Special rule, if we are talking of the root directory, a
1687 trailing slash is good */
1689 if (t == path && slash)
1696 bool path_startswith(const char *path, const char *prefix) {
1700 if ((path[0] == '/') != (prefix[0] == '/'))
1706 path += strspn(path, "/");
1707 prefix += strspn(prefix, "/");
1715 a = strcspn(path, "/");
1716 b = strcspn(prefix, "/");
1721 if (memcmp(path, prefix, a) != 0)
1729 bool path_equal(const char *a, const char *b) {
1733 if ((a[0] == '/') != (b[0] == '/'))
1739 a += strspn(a, "/");
1740 b += strspn(b, "/");
1742 if (*a == 0 && *b == 0)
1745 if (*a == 0 || *b == 0)
1748 j = strcspn(a, "/");
1749 k = strcspn(b, "/");
1754 if (memcmp(a, b, j) != 0)
1762 char *ascii_strlower(char *t) {
1767 for (p = t; *p; p++)
1768 if (*p >= 'A' && *p <= 'Z')
1769 *p = *p - 'A' + 'a';
1774 bool ignore_file(const char *filename) {
1778 filename[0] == '.' ||
1779 streq(filename, "lost+found") ||
1780 streq(filename, "aquota.user") ||
1781 streq(filename, "aquota.group") ||
1782 endswith(filename, "~") ||
1783 endswith(filename, ".rpmnew") ||
1784 endswith(filename, ".rpmsave") ||
1785 endswith(filename, ".rpmorig") ||
1786 endswith(filename, ".dpkg-old") ||
1787 endswith(filename, ".dpkg-new") ||
1788 endswith(filename, ".swp");
1791 int fd_nonblock(int fd, bool nonblock) {
1796 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1800 flags |= O_NONBLOCK;
1802 flags &= ~O_NONBLOCK;
1804 if (fcntl(fd, F_SETFL, flags) < 0)
1810 int fd_cloexec(int fd, bool cloexec) {
1815 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1819 flags |= FD_CLOEXEC;
1821 flags &= ~FD_CLOEXEC;
1823 if (fcntl(fd, F_SETFD, flags) < 0)
1829 int close_all_fds(const int except[], unsigned n_except) {
1834 if (!(d = opendir("/proc/self/fd")))
1837 while ((de = readdir(d))) {
1840 if (ignore_file(de->d_name))
1843 if (safe_atoi(de->d_name, &fd) < 0)
1844 /* Let's better ignore this, just in case */
1858 for (i = 0; i < n_except; i++)
1859 if (except[i] == fd) {
1868 if (close_nointr(fd) < 0) {
1869 /* Valgrind has its own FD and doesn't want to have it closed */
1870 if (errno != EBADF && r == 0)
1879 bool chars_intersect(const char *a, const char *b) {
1882 /* Returns true if any of the chars in a are in b. */
1883 for (p = a; *p; p++)
1890 char *format_timestamp(char *buf, size_t l, usec_t t) {
1900 sec = (time_t) (t / USEC_PER_SEC);
1902 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1908 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1911 n = now(CLOCK_REALTIME);
1913 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1918 if (d >= USEC_PER_YEAR)
1919 snprintf(buf, l, "%llu years and %llu months ago",
1920 (unsigned long long) (d / USEC_PER_YEAR),
1921 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1922 else if (d >= USEC_PER_MONTH)
1923 snprintf(buf, l, "%llu months and %llu days ago",
1924 (unsigned long long) (d / USEC_PER_MONTH),
1925 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1926 else if (d >= USEC_PER_WEEK)
1927 snprintf(buf, l, "%llu weeks and %llu days ago",
1928 (unsigned long long) (d / USEC_PER_WEEK),
1929 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1930 else if (d >= 2*USEC_PER_DAY)
1931 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1932 else if (d >= 25*USEC_PER_HOUR)
1933 snprintf(buf, l, "1 day and %lluh ago",
1934 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1935 else if (d >= 6*USEC_PER_HOUR)
1936 snprintf(buf, l, "%lluh ago",
1937 (unsigned long long) (d / USEC_PER_HOUR));
1938 else if (d >= USEC_PER_HOUR)
1939 snprintf(buf, l, "%lluh %llumin ago",
1940 (unsigned long long) (d / USEC_PER_HOUR),
1941 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1942 else if (d >= 5*USEC_PER_MINUTE)
1943 snprintf(buf, l, "%llumin ago",
1944 (unsigned long long) (d / USEC_PER_MINUTE));
1945 else if (d >= USEC_PER_MINUTE)
1946 snprintf(buf, l, "%llumin %llus ago",
1947 (unsigned long long) (d / USEC_PER_MINUTE),
1948 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1949 else if (d >= USEC_PER_SEC)
1950 snprintf(buf, l, "%llus ago",
1951 (unsigned long long) (d / USEC_PER_SEC));
1952 else if (d >= USEC_PER_MSEC)
1953 snprintf(buf, l, "%llums ago",
1954 (unsigned long long) (d / USEC_PER_MSEC));
1956 snprintf(buf, l, "%lluus ago",
1957 (unsigned long long) d);
1959 snprintf(buf, l, "now");
1965 char *format_timespan(char *buf, size_t l, usec_t t) {
1966 static const struct {
1970 { "w", USEC_PER_WEEK },
1971 { "d", USEC_PER_DAY },
1972 { "h", USEC_PER_HOUR },
1973 { "min", USEC_PER_MINUTE },
1974 { "s", USEC_PER_SEC },
1975 { "ms", USEC_PER_MSEC },
1985 if (t == (usec_t) -1)
1989 snprintf(p, l, "0");
1994 /* The result of this function can be parsed with parse_usec */
1996 for (i = 0; i < ELEMENTSOF(table); i++) {
2000 if (t < table[i].usec)
2006 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2007 n = MIN((size_t) k, l);
2020 bool fstype_is_network(const char *fstype) {
2021 static const char * const table[] = {
2033 for (i = 0; i < ELEMENTSOF(table); i++)
2034 if (streq(table[i], fstype))
2043 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2048 TIOCL_GETKMSGREDIRECT,
2052 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2055 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2058 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2061 close_nointr_nofail(r);
2065 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2066 struct termios old_termios, new_termios;
2068 char line[LINE_MAX];
2073 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2074 new_termios = old_termios;
2076 new_termios.c_lflag &= ~ICANON;
2077 new_termios.c_cc[VMIN] = 1;
2078 new_termios.c_cc[VTIME] = 0;
2080 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2083 k = fread(&c, 1, 1, f);
2085 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2091 *need_nl = c != '\n';
2098 if (!(fgets(line, sizeof(line), f)))
2103 if (strlen(line) != 1)
2113 int ask(char *ret, const char *replies, const char *text, ...) {
2120 on_tty = isatty(STDOUT_FILENO);
2126 bool need_nl = true;
2129 fputs("\x1B[1m", stdout);
2136 fputs("\x1B[0m", stdout);
2140 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2142 if (r == -EBADMSG) {
2143 puts("Bad input, please try again.");
2154 if (strchr(replies, c)) {
2159 puts("Read unexpected character, please try again.");
2163 int reset_terminal(int fd) {
2164 struct termios termios;
2168 /* Set terminal to some sane defaults */
2172 /* We leave locked terminal attributes untouched, so that
2173 * Plymouth may set whatever it wants to set, and we don't
2174 * interfere with that. */
2176 /* Disable exclusive mode, just in case */
2177 ioctl(fd, TIOCNXCL);
2179 /* Enable console unicode mode */
2181 ioctl(fd, KDSKBMODE, &arg);
2183 if (tcgetattr(fd, &termios) < 0) {
2188 /* We only reset the stuff that matters to the software. How
2189 * hardware is set up we don't touch assuming that somebody
2190 * else will do that for us */
2192 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2193 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2194 termios.c_oflag |= ONLCR;
2195 termios.c_cflag |= CREAD;
2196 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2198 termios.c_cc[VINTR] = 03; /* ^C */
2199 termios.c_cc[VQUIT] = 034; /* ^\ */
2200 termios.c_cc[VERASE] = 0177;
2201 termios.c_cc[VKILL] = 025; /* ^X */
2202 termios.c_cc[VEOF] = 04; /* ^D */
2203 termios.c_cc[VSTART] = 021; /* ^Q */
2204 termios.c_cc[VSTOP] = 023; /* ^S */
2205 termios.c_cc[VSUSP] = 032; /* ^Z */
2206 termios.c_cc[VLNEXT] = 026; /* ^V */
2207 termios.c_cc[VWERASE] = 027; /* ^W */
2208 termios.c_cc[VREPRINT] = 022; /* ^R */
2209 termios.c_cc[VEOL] = 0;
2210 termios.c_cc[VEOL2] = 0;
2212 termios.c_cc[VTIME] = 0;
2213 termios.c_cc[VMIN] = 1;
2215 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2219 /* Just in case, flush all crap out */
2220 tcflush(fd, TCIOFLUSH);
2225 int open_terminal(const char *name, int mode) {
2230 * If a TTY is in the process of being closed opening it might
2231 * cause EIO. This is horribly awful, but unlikely to be
2232 * changed in the kernel. Hence we work around this problem by
2233 * retrying a couple of times.
2235 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2239 if ((fd = open(name, mode)) >= 0)
2248 usleep(50 * USEC_PER_MSEC);
2255 if ((r = isatty(fd)) < 0) {
2256 close_nointr_nofail(fd);
2261 close_nointr_nofail(fd);
2268 int flush_fd(int fd) {
2269 struct pollfd pollfd;
2273 pollfd.events = POLLIN;
2280 if ((r = poll(&pollfd, 1, 0)) < 0) {
2291 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2296 if (errno == EAGAIN)
2307 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2308 int fd = -1, notify = -1, r, wd = -1;
2312 /* We use inotify to be notified when the tty is closed. We
2313 * create the watch before checking if we can actually acquire
2314 * it, so that we don't lose any event.
2316 * Note: strictly speaking this actually watches for the
2317 * device being closed, it does *not* really watch whether a
2318 * tty loses its controlling process. However, unless some
2319 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2320 * its tty otherwise this will not become a problem. As long
2321 * as the administrator makes sure not configure any service
2322 * on the same tty as an untrusted user this should not be a
2323 * problem. (Which he probably should not do anyway.) */
2325 if (!fail && !force) {
2326 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2331 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2339 if ((r = flush_fd(notify)) < 0)
2342 /* We pass here O_NOCTTY only so that we can check the return
2343 * value TIOCSCTTY and have a reliable way to figure out if we
2344 * successfully became the controlling process of the tty */
2345 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2348 /* First, try to get the tty */
2349 r = ioctl(fd, TIOCSCTTY, force);
2351 /* Sometimes it makes sense to ignore TIOCSCTTY
2352 * returning EPERM, i.e. when very likely we already
2353 * are have this controlling terminal. */
2354 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2357 if (r < 0 && (force || fail || errno != EPERM)) {
2367 assert(notify >= 0);
2370 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2372 struct inotify_event *e;
2374 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2383 e = (struct inotify_event*) inotify_buffer;
2388 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2393 step = sizeof(struct inotify_event) + e->len;
2394 assert(step <= (size_t) l);
2396 e = (struct inotify_event*) ((uint8_t*) e + step);
2403 /* We close the tty fd here since if the old session
2404 * ended our handle will be dead. It's important that
2405 * we do this after sleeping, so that we don't enter
2406 * an endless loop. */
2407 close_nointr_nofail(fd);
2411 close_nointr_nofail(notify);
2413 if ((r = reset_terminal(fd)) < 0)
2414 log_warning("Failed to reset terminal: %s", strerror(-r));
2420 close_nointr_nofail(fd);
2423 close_nointr_nofail(notify);
2428 int release_terminal(void) {
2430 struct sigaction sa_old, sa_new;
2432 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2435 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2436 * by our own TIOCNOTTY */
2439 sa_new.sa_handler = SIG_IGN;
2440 sa_new.sa_flags = SA_RESTART;
2441 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2443 if (ioctl(fd, TIOCNOTTY) < 0)
2446 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2448 close_nointr_nofail(fd);
2452 int sigaction_many(const struct sigaction *sa, ...) {
2457 while ((sig = va_arg(ap, int)) > 0)
2458 if (sigaction(sig, sa, NULL) < 0)
2465 int ignore_signals(int sig, ...) {
2466 struct sigaction sa;
2471 sa.sa_handler = SIG_IGN;
2472 sa.sa_flags = SA_RESTART;
2474 if (sigaction(sig, &sa, NULL) < 0)
2478 while ((sig = va_arg(ap, int)) > 0)
2479 if (sigaction(sig, &sa, NULL) < 0)
2486 int default_signals(int sig, ...) {
2487 struct sigaction sa;
2492 sa.sa_handler = SIG_DFL;
2493 sa.sa_flags = SA_RESTART;
2495 if (sigaction(sig, &sa, NULL) < 0)
2499 while ((sig = va_arg(ap, int)) > 0)
2500 if (sigaction(sig, &sa, NULL) < 0)
2507 int close_pipe(int p[]) {
2513 a = close_nointr(p[0]);
2518 b = close_nointr(p[1]);
2522 return a < 0 ? a : b;
2525 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2534 while (nbytes > 0) {
2537 if ((k = read(fd, p, nbytes)) <= 0) {
2539 if (k < 0 && errno == EINTR)
2542 if (k < 0 && errno == EAGAIN && do_poll) {
2543 struct pollfd pollfd;
2547 pollfd.events = POLLIN;
2549 if (poll(&pollfd, 1, -1) < 0) {
2553 return n > 0 ? n : -errno;
2556 if (pollfd.revents != POLLIN)
2557 return n > 0 ? n : -EIO;
2562 return n > 0 ? n : (k < 0 ? -errno : 0);
2573 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2582 while (nbytes > 0) {
2585 if ((k = write(fd, p, nbytes)) <= 0) {
2587 if (k < 0 && errno == EINTR)
2590 if (k < 0 && errno == EAGAIN && do_poll) {
2591 struct pollfd pollfd;
2595 pollfd.events = POLLOUT;
2597 if (poll(&pollfd, 1, -1) < 0) {
2601 return n > 0 ? n : -errno;
2604 if (pollfd.revents != POLLOUT)
2605 return n > 0 ? n : -EIO;
2610 return n > 0 ? n : (k < 0 ? -errno : 0);
2621 int path_is_mount_point(const char *t) {
2626 if (lstat(t, &a) < 0) {
2627 if (errno == ENOENT)
2633 if ((r = parent_of_path(t, &parent)) < 0)
2636 r = lstat(parent, &b);
2642 return a.st_dev != b.st_dev;
2645 int parse_usec(const char *t, usec_t *usec) {
2646 static const struct {
2650 { "sec", USEC_PER_SEC },
2651 { "s", USEC_PER_SEC },
2652 { "min", USEC_PER_MINUTE },
2653 { "hr", USEC_PER_HOUR },
2654 { "h", USEC_PER_HOUR },
2655 { "d", USEC_PER_DAY },
2656 { "w", USEC_PER_WEEK },
2657 { "msec", USEC_PER_MSEC },
2658 { "ms", USEC_PER_MSEC },
2659 { "m", USEC_PER_MINUTE },
2662 { "", USEC_PER_SEC },
2678 l = strtoll(p, &e, 10);
2689 e += strspn(e, WHITESPACE);
2691 for (i = 0; i < ELEMENTSOF(table); i++)
2692 if (startswith(e, table[i].suffix)) {
2693 r += (usec_t) l * table[i].usec;
2694 p = e + strlen(table[i].suffix);
2698 if (i >= ELEMENTSOF(table))
2708 int make_stdio(int fd) {
2713 r = dup2(fd, STDIN_FILENO);
2714 s = dup2(fd, STDOUT_FILENO);
2715 t = dup2(fd, STDERR_FILENO);
2718 close_nointr_nofail(fd);
2720 if (r < 0 || s < 0 || t < 0)
2726 int make_null_stdio(void) {
2729 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2732 return make_stdio(null_fd);
2735 bool is_device_path(const char *path) {
2737 /* Returns true on paths that refer to a device, either in
2738 * sysfs or in /dev */
2741 path_startswith(path, "/dev/") ||
2742 path_startswith(path, "/sys/");
2745 int dir_is_empty(const char *path) {
2748 struct dirent buf, *de;
2750 if (!(d = opendir(path)))
2754 if ((r = readdir_r(d, &buf, &de)) > 0) {
2764 if (!ignore_file(de->d_name)) {
2774 unsigned long long random_ull(void) {
2779 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2782 r = loop_read(fd, &ull, sizeof(ull), true);
2783 close_nointr_nofail(fd);
2785 if (r != sizeof(ull))
2791 return random() * RAND_MAX + random();
2794 void rename_process(const char name[8]) {
2797 prctl(PR_SET_NAME, name);
2799 /* This is a like a poor man's setproctitle(). The string
2800 * passed should fit in 7 chars (i.e. the length of
2803 if (program_invocation_name)
2804 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2807 void sigset_add_many(sigset_t *ss, ...) {
2814 while ((sig = va_arg(ap, int)) > 0)
2815 assert_se(sigaddset(ss, sig) == 0);
2819 char* gethostname_malloc(void) {
2822 assert_se(uname(&u) >= 0);
2825 return strdup(u.nodename);
2827 return strdup(u.sysname);
2830 char* getlogname_malloc(void) {
2834 struct passwd pwbuf, *pw = NULL;
2837 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2842 /* Shortcut things to avoid NSS lookups */
2844 return strdup("root");
2846 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2849 if (!(buf = malloc(bufsize)))
2852 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2853 name = strdup(pw->pw_name);
2860 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2866 int getttyname_malloc(int fd, char **r) {
2867 char path[PATH_MAX], *c;
2872 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2877 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2884 int getttyname_harder(int fd, char **r) {
2888 if ((k = getttyname_malloc(fd, &s)) < 0)
2891 if (streq(s, "tty")) {
2893 return get_ctty(r, NULL);
2900 int get_ctty_devnr(dev_t *d) {
2902 char line[LINE_MAX], *p;
2903 unsigned long ttynr;
2906 if (!(f = fopen("/proc/self/stat", "r")))
2909 if (!(fgets(line, sizeof(line), f))) {
2917 if (!(p = strrchr(line, ')')))
2926 "%*d " /* session */
2935 int get_ctty(char **r, dev_t *_devnr) {
2937 char fn[PATH_MAX], *s, *b, *p;
2942 if ((k = get_ctty_devnr(&devnr)) < 0)
2945 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2948 if ((k = readlink_malloc(fn, &s)) < 0) {
2953 /* This is an ugly hack */
2954 if (major(devnr) == 136) {
2955 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2965 /* Probably something like the ptys which have no
2966 * symlink in /dev/char. Let's return something
2967 * vaguely useful. */
2969 if (!(b = strdup(fn + 5)))
2979 if (startswith(s, "/dev/"))
2981 else if (startswith(s, "../"))
2999 static int rm_rf_children(int fd, bool only_dirs) {
3005 /* This returns the first error we run into, but nevertheless
3008 if (!(d = fdopendir(fd))) {
3009 close_nointr_nofail(fd);
3011 return errno == ENOENT ? 0 : -errno;
3015 struct dirent buf, *de;
3019 if ((r = readdir_r(d, &buf, &de)) != 0) {
3028 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3031 if (de->d_type == DT_UNKNOWN) {
3034 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3035 if (ret == 0 && errno != ENOENT)
3040 is_dir = S_ISDIR(st.st_mode);
3042 is_dir = de->d_type == DT_DIR;
3047 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3048 if (ret == 0 && errno != ENOENT)
3053 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3058 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3059 if (ret == 0 && errno != ENOENT)
3062 } else if (!only_dirs) {
3064 if (unlinkat(fd, de->d_name, 0) < 0) {
3065 if (ret == 0 && errno != ENOENT)
3076 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3082 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3084 if (errno != ENOTDIR)
3087 if (delete_root && !only_dirs)
3088 if (unlink(path) < 0)
3094 r = rm_rf_children(fd, only_dirs);
3097 if (rmdir(path) < 0) {
3105 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3108 /* Under the assumption that we are running privileged we
3109 * first change the access mode and only then hand out
3110 * ownership to avoid a window where access is too open. */
3112 if (chmod(path, mode) < 0)
3115 if (chown(path, uid, gid) < 0)
3121 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3125 /* Allocates the cpuset in the right size */
3128 if (!(r = CPU_ALLOC(n)))
3131 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3132 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3142 if (errno != EINVAL)
3149 void status_vprintf(const char *format, va_list ap) {
3155 /* This independent of logging, as status messages are
3156 * optional and go exclusively to the console. */
3158 if (vasprintf(&s, format, ap) < 0)
3161 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3164 write(fd, s, strlen(s));
3170 close_nointr_nofail(fd);
3173 void status_printf(const char *format, ...) {
3178 va_start(ap, format);
3179 status_vprintf(format, ap);
3183 void status_welcome(void) {
3184 char *pretty_name = NULL, *ansi_color = NULL;
3185 const char *const_pretty = NULL, *const_color = NULL;
3188 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3189 "PRETTY_NAME", &pretty_name,
3190 "ANSI_COLOR", &ansi_color,
3194 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3197 #if defined(TARGET_FEDORA)
3199 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3202 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3206 if (!ansi_color && pretty_name) {
3208 /* This tries to mimic the color magic the old Red Hat sysinit
3211 if (startswith(pretty_name, "Red Hat"))
3212 const_color = "0;31"; /* Red for RHEL */
3213 else if (startswith(pretty_name, "Fedora"))
3214 const_color = "0;34"; /* Blue for Fedora */
3217 #elif defined(TARGET_SUSE)
3220 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3223 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3228 const_color = "0;32"; /* Green for openSUSE */
3230 #elif defined(TARGET_GENTOO)
3233 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3236 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3241 const_color = "1;34"; /* Light Blue for Gentoo */
3243 #elif defined(TARGET_ALTLINUX)
3246 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3249 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3254 const_color = "0;36"; /* Cyan for ALTLinux */
3257 #elif defined(TARGET_DEBIAN)
3262 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3265 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3267 pretty_name = strappend("Debian ", version);
3271 log_warning("Failed to allocate Debian version string.");
3276 const_color = "1;31"; /* Light Red for Debian */
3278 #elif defined(TARGET_UBUNTU)
3280 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3281 "DISTRIB_DESCRIPTION", &pretty_name,
3285 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3289 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3291 #elif defined(TARGET_MANDRIVA)
3296 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3298 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3300 p = strstr(s, " release ");
3304 p[strcspn(p, " ")] = '\0';
3306 /* This corresponds to standard rc.sysinit */
3307 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3308 const_color = "1;36";
3310 log_warning("Failed to allocate Mandriva version string.");
3312 log_warning("Failed to parse /etc/mandriva-release");
3319 if (!pretty_name && !const_pretty)
3320 const_pretty = "Linux";
3322 if (!ansi_color && !const_color)
3325 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3326 const_color ? const_color : ansi_color,
3327 const_pretty ? const_pretty : pretty_name);
3333 char *replace_env(const char *format, char **env) {
3340 const char *e, *word = format;
3345 for (e = format; *e; e ++) {
3356 if (!(k = strnappend(r, word, e-word-1)))
3365 } else if (*e == '$') {
3366 if (!(k = strnappend(r, word, e-word)))
3382 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3385 if (!(k = strappend(r, t)))
3398 if (!(k = strnappend(r, word, e-word)))
3409 char **replace_env_argv(char **argv, char **env) {
3411 unsigned k = 0, l = 0;
3413 l = strv_length(argv);
3415 if (!(r = new(char*, l+1)))
3418 STRV_FOREACH(i, argv) {
3420 /* If $FOO appears as single word, replace it by the split up variable */
3421 if ((*i)[0] == '$' && (*i)[1] != '{') {
3426 if ((e = strv_env_get(env, *i+1))) {
3428 if (!(m = strv_split_quoted(e))) {
3439 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3448 memcpy(r + k, m, q * sizeof(char*));
3456 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3457 if (!(r[k++] = replace_env(*i, env))) {
3468 static __thread int parsed_columns = 0;
3471 if (parsed_columns > 0)
3472 return parsed_columns;
3474 if ((e = getenv("COLUMNS")))
3475 parsed_columns = atoi(e);
3477 if (parsed_columns <= 0) {
3481 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3482 parsed_columns = ws.ws_col;
3485 if (parsed_columns <= 0)
3486 parsed_columns = 80;
3488 return parsed_columns;
3491 int running_in_chroot(void) {
3497 /* Only works as root */
3499 if (stat("/proc/1/root", &a) < 0)
3502 if (stat("/", &b) < 0)
3506 a.st_dev != b.st_dev ||
3507 a.st_ino != b.st_ino;
3510 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3515 assert(percent <= 100);
3516 assert(length >= 3);
3520 if (l <= 3 || l <= length)
3523 if (!(r = new0(char, length+1)))
3526 x = (length * percent) / 100;
3536 s + l - (length - x - 3),
3542 int touch(const char *path) {
3547 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3550 close_nointr_nofail(fd);
3554 char *unquote(const char *s, const char* quotes) {
3558 if ((l = strlen(s)) < 2)
3561 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3562 return strndup(s+1, l-2);
3567 char *normalize_env_assignment(const char *s) {
3568 char *name, *value, *p, *r;
3573 if (!(r = strdup(s)))
3579 if (!(name = strndup(s, p - s)))
3582 if (!(p = strdup(p+1))) {
3587 value = unquote(strstrip(p), QUOTES);
3595 if (asprintf(&r, "%s=%s", name, value) < 0)
3604 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3611 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3623 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3630 if ((r = wait_for_terminate(pid, &status)) < 0) {
3631 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3635 if (status.si_code == CLD_EXITED) {
3636 if (status.si_status != 0) {
3637 log_warning("%s failed with error code %i.", name, status.si_status);
3638 return status.si_status;
3641 log_debug("%s succeeded.", name);
3644 } else if (status.si_code == CLD_KILLED ||
3645 status.si_code == CLD_DUMPED) {
3647 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3651 log_warning("%s failed due to unknown reason.", name);
3658 /* Make sure nobody waits for us on a socket anymore */
3659 close_all_fds(NULL, 0);
3667 bool null_or_empty(struct stat *st) {
3670 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3673 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3679 DIR *xopendirat(int fd, const char *name, int flags) {
3683 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3686 if (!(d = fdopendir(nfd))) {
3687 close_nointr_nofail(nfd);
3694 int signal_from_string_try_harder(const char *s) {
3698 if ((signo = signal_from_string(s)) <= 0)
3699 if (startswith(s, "SIG"))
3700 return signal_from_string(s+3);
3705 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3711 if (!dual_timestamp_is_set(t))
3714 fprintf(f, "%s=%llu %llu\n",
3716 (unsigned long long) t->realtime,
3717 (unsigned long long) t->monotonic);
3720 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3721 unsigned long long a, b;
3726 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3727 log_debug("Failed to parse finish timestamp value %s", value);
3734 char *fstab_node_to_udev_node(const char *p) {
3738 /* FIXME: to follow udev's logic 100% we need to leave valid
3739 * UTF8 chars unescaped */
3741 if (startswith(p, "LABEL=")) {
3743 if (!(u = unquote(p+6, "\"\'")))
3746 t = xescape(u, "/ ");
3752 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3761 if (startswith(p, "UUID=")) {
3763 if (!(u = unquote(p+5, "\"\'")))
3766 t = xescape(u, "/ ");
3772 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3784 void filter_environ(const char *prefix) {
3791 for (i = 0, j = 0; environ[i]; i++) {
3793 if (startswith(environ[i], prefix))
3796 environ[j++] = environ[i];
3802 bool tty_is_vc(const char *tty) {
3805 if (startswith(tty, "/dev/"))
3808 return startswith(tty, "tty") &&
3809 tty[3] >= '0' && tty[3] <= '9';
3812 const char *default_term_for_tty(const char *tty) {
3813 char *active = NULL;
3818 if (startswith(tty, "/dev/"))
3821 /* Resolve where /dev/console is pointing when determining
3823 if (streq(tty, "console"))
3824 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3825 /* If multiple log outputs are configured the
3826 * last one is what /dev/console points to */
3827 if ((tty = strrchr(active, ' ')))
3833 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3839 /* Returns a short identifier for the various VM implementations */
3840 int detect_vm(const char **id) {
3842 #if defined(__i386__) || defined(__x86_64__)
3844 /* Both CPUID and DMI are x86 specific interfaces... */
3846 static const char *const dmi_vendors[] = {
3847 "/sys/class/dmi/id/sys_vendor",
3848 "/sys/class/dmi/id/board_vendor",
3849 "/sys/class/dmi/id/bios_vendor"
3852 static const char dmi_vendor_table[] =
3854 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3855 "VMware\0" "vmware\0"
3857 "Microsoft Corporation\0" "microsoft\0"
3858 "innotek GmbH\0" "oracle\0"
3860 "Bochs\0" "bochs\0";
3862 static const char cpuid_vendor_table[] =
3863 "XenVMMXenVMM\0" "xen\0"
3864 "KVMKVMKVM\0" "kvm\0"
3865 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3866 "VMwareVMware\0" "vmware\0"
3867 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3868 "Microsoft Hv\0" "microsoft\0";
3879 /* http://lwn.net/Articles/301888/ */
3882 #if defined (__i386__)
3885 #elif defined (__amd64__)
3890 /* First detect whether there is a hypervisor */
3892 __asm__ __volatile__ (
3893 /* ebx/rbx is being used for PIC! */
3894 " push %%"REG_b" \n\t"
3896 " pop %%"REG_b" \n\t"
3898 : "=a" (eax), "=c" (ecx)
3902 hypervisor = !!(ecx & ecx & 0x80000000U);
3906 /* There is a hypervisor, see what it is */
3908 __asm__ __volatile__ (
3909 /* ebx/rbx is being used for PIC! */
3910 " push %%"REG_b" \n\t"
3912 " mov %%ebx, %1 \n\t"
3913 " pop %%"REG_b" \n\t"
3915 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3919 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3920 if (streq(sig.text, j)) {
3929 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3932 const char *found = NULL;
3934 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3941 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3942 if (startswith(s, j))
3965 int detect_container(const char **id) {
3968 /* Unfortunately many of these operations require root access
3969 * in one way or another */
3974 if (running_in_chroot() > 0) {
3982 /* /proc/vz exists in container and outside of the container,
3983 * /proc/bc only outside of the container. */
3984 if (access("/proc/vz", F_OK) >= 0 &&
3985 access("/proc/bc", F_OK) < 0) {
3993 if ((f = fopen("/proc/self/cgroup", "r"))) {
3996 char line[LINE_MAX], *p;
3998 if (!fgets(line, sizeof(line), f))
4001 if (!(p = strchr(strstrip(line), ':')))
4004 if (strncmp(p, ":ns:", 4))
4007 if (!streq(p, ":ns:/")) {
4023 /* Returns a short identifier for the various VM/container implementations */
4024 int detect_virtualization(const char **id) {
4025 static __thread const char *cached_id = NULL;
4031 if (cached_id == (const char*) -1)
4040 if ((r = detect_container(&_id)) != 0)
4043 r = detect_vm(&_id);
4052 cached_id = (const char*) -1;
4057 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4060 Hashmap *pids = NULL;
4064 /* Executes all binaries in a directory in parallel and waits
4065 * until all they all finished. */
4068 if (!(_d = opendir(directory))) {
4070 if (errno == ENOENT)
4073 log_error("Failed to enumerate directory %s: %m", directory);
4080 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4081 log_error("Failed to allocate set.");
4085 while ((de = readdir(d))) {
4090 if (ignore_file(de->d_name))
4093 if (de->d_type != DT_REG &&
4094 de->d_type != DT_LNK &&
4095 de->d_type != DT_UNKNOWN)
4098 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4099 log_error("Out of memory");
4103 if ((pid = fork()) < 0) {
4104 log_error("Failed to fork: %m");
4123 log_error("Failed to execute %s: %m", path);
4124 _exit(EXIT_FAILURE);
4127 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4129 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4130 log_error("Failed to add PID to set: %s", strerror(-k));
4135 while (!hashmap_isempty(pids)) {
4140 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4145 log_error("waitid() failed: %m");
4149 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4150 if (!is_clean_exit(si.si_code, si.si_status)) {
4151 if (si.si_code == CLD_EXITED)
4152 log_error("%s exited with exit status %i.", path, si.si_status);
4154 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4156 log_debug("%s exited successfully.", path);
4167 hashmap_free_free(pids);
4170 int kill_and_sigcont(pid_t pid, int sig) {
4173 r = kill(pid, sig) < 0 ? -errno : 0;
4181 bool nulstr_contains(const char*nulstr, const char *needle) {
4187 NULSTR_FOREACH(i, nulstr)
4188 if (streq(i, needle))
4194 bool plymouth_running(void) {
4195 return access("/run/plymouth/pid", F_OK) >= 0;
4198 void parse_syslog_priority(char **p, int *priority) {
4199 int a = 0, b = 0, c = 0;
4209 if (!strchr(*p, '>'))
4212 if ((*p)[2] == '>') {
4213 c = undecchar((*p)[1]);
4215 } else if ((*p)[3] == '>') {
4216 b = undecchar((*p)[1]);
4217 c = undecchar((*p)[2]);
4219 } else if ((*p)[4] == '>') {
4220 a = undecchar((*p)[1]);
4221 b = undecchar((*p)[2]);
4222 c = undecchar((*p)[3]);
4227 if (a < 0 || b < 0 || c < 0)
4230 *priority = a*100+b*10+c;
4234 int have_effective_cap(int value) {
4236 cap_flag_value_t fv;
4239 if (!(cap = cap_get_proc()))
4242 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4251 static const char *const ioprio_class_table[] = {
4252 [IOPRIO_CLASS_NONE] = "none",
4253 [IOPRIO_CLASS_RT] = "realtime",
4254 [IOPRIO_CLASS_BE] = "best-effort",
4255 [IOPRIO_CLASS_IDLE] = "idle"
4258 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4260 static const char *const sigchld_code_table[] = {
4261 [CLD_EXITED] = "exited",
4262 [CLD_KILLED] = "killed",
4263 [CLD_DUMPED] = "dumped",
4264 [CLD_TRAPPED] = "trapped",
4265 [CLD_STOPPED] = "stopped",
4266 [CLD_CONTINUED] = "continued",
4269 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4271 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4272 [LOG_FAC(LOG_KERN)] = "kern",
4273 [LOG_FAC(LOG_USER)] = "user",
4274 [LOG_FAC(LOG_MAIL)] = "mail",
4275 [LOG_FAC(LOG_DAEMON)] = "daemon",
4276 [LOG_FAC(LOG_AUTH)] = "auth",
4277 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4278 [LOG_FAC(LOG_LPR)] = "lpr",
4279 [LOG_FAC(LOG_NEWS)] = "news",
4280 [LOG_FAC(LOG_UUCP)] = "uucp",
4281 [LOG_FAC(LOG_CRON)] = "cron",
4282 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4283 [LOG_FAC(LOG_FTP)] = "ftp",
4284 [LOG_FAC(LOG_LOCAL0)] = "local0",
4285 [LOG_FAC(LOG_LOCAL1)] = "local1",
4286 [LOG_FAC(LOG_LOCAL2)] = "local2",
4287 [LOG_FAC(LOG_LOCAL3)] = "local3",
4288 [LOG_FAC(LOG_LOCAL4)] = "local4",
4289 [LOG_FAC(LOG_LOCAL5)] = "local5",
4290 [LOG_FAC(LOG_LOCAL6)] = "local6",
4291 [LOG_FAC(LOG_LOCAL7)] = "local7"
4294 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4296 static const char *const log_level_table[] = {
4297 [LOG_EMERG] = "emerg",
4298 [LOG_ALERT] = "alert",
4299 [LOG_CRIT] = "crit",
4301 [LOG_WARNING] = "warning",
4302 [LOG_NOTICE] = "notice",
4303 [LOG_INFO] = "info",
4304 [LOG_DEBUG] = "debug"
4307 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4309 static const char* const sched_policy_table[] = {
4310 [SCHED_OTHER] = "other",
4311 [SCHED_BATCH] = "batch",
4312 [SCHED_IDLE] = "idle",
4313 [SCHED_FIFO] = "fifo",
4317 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4319 static const char* const rlimit_table[] = {
4320 [RLIMIT_CPU] = "LimitCPU",
4321 [RLIMIT_FSIZE] = "LimitFSIZE",
4322 [RLIMIT_DATA] = "LimitDATA",
4323 [RLIMIT_STACK] = "LimitSTACK",
4324 [RLIMIT_CORE] = "LimitCORE",
4325 [RLIMIT_RSS] = "LimitRSS",
4326 [RLIMIT_NOFILE] = "LimitNOFILE",
4327 [RLIMIT_AS] = "LimitAS",
4328 [RLIMIT_NPROC] = "LimitNPROC",
4329 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4330 [RLIMIT_LOCKS] = "LimitLOCKS",
4331 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4332 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4333 [RLIMIT_NICE] = "LimitNICE",
4334 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4335 [RLIMIT_RTTIME] = "LimitRTTIME"
4338 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4340 static const char* const ip_tos_table[] = {
4341 [IPTOS_LOWDELAY] = "low-delay",
4342 [IPTOS_THROUGHPUT] = "throughput",
4343 [IPTOS_RELIABILITY] = "reliability",
4344 [IPTOS_LOWCOST] = "low-cost",
4347 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4349 static const char *const signal_table[] = {
4366 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4377 [SIGVTALRM] = "VTALRM",
4379 [SIGWINCH] = "WINCH",
4385 DEFINE_STRING_TABLE_LOOKUP(signal, int);