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));
463 fn[sizeof(fn)-1] = 0;
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))) {
561 int read_full_file(const char *fn, char **contents) {
568 if (!(f = fopen(fn, "re")))
571 if (fstat(fileno(f), &st) < 0) {
576 n = st.st_size > 0 ? st.st_size : LINE_MAX;
583 if (!(t = realloc(buf, n+1))) {
589 k = fread(buf + l, 1, n - l, f);
604 if (n > 4*1024*1024) {
612 else if (!(buf = calloc(1, 1))) {
631 const char *separator, ...) {
639 if ((r = read_full_file(fname, &contents)) < 0)
644 const char *key = NULL;
646 p += strspn(p, separator);
647 p += strspn(p, WHITESPACE);
652 if (!strchr(COMMENTS, *p)) {
656 va_start(ap, separator);
657 while ((key = va_arg(ap, char *))) {
661 value = va_arg(ap, char **);
664 if (strncmp(p, key, n) != 0 ||
669 n = strcspn(p, separator);
672 strchr(QUOTES, p[0]) &&
674 v = strndup(p+1, n-2);
685 /* return empty value strings as NULL */
702 p += strcspn(p, separator);
721 if (!(f = fopen(fname, "re")))
725 char l[LINE_MAX], *p, *u;
728 if (!fgets(l, sizeof(l), f)) {
741 if (strchr(COMMENTS, *p))
744 if (!(u = normalize_env_assignment(p))) {
745 log_error("Out of memory");
750 t = strv_append(m, u);
754 log_error("Out of memory");
777 char *truncate_nl(char *s) {
780 s[strcspn(s, NEWLINE)] = 0;
784 int get_process_name(pid_t pid, char **name) {
791 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
794 r = read_one_line_file(p, name);
804 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
812 assert(max_length > 0);
815 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
824 if (!(r = new(char, max_length))) {
831 while ((c = getc(f)) != EOF) {
853 size_t n = MIN(left-1, 3U);
861 /* Kernel threads have no argv[] */
868 if ((h = get_process_name(pid, &t)) < 0)
871 h = asprintf(&r, "[%s]", t);
882 char *strnappend(const char *s, const char *suffix, size_t b) {
890 return strndup(suffix, b);
900 if (!(r = new(char, a+b+1)))
904 memcpy(r+a, suffix, b);
910 char *strappend(const char *s, const char *suffix) {
911 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
914 int readlink_malloc(const char *p, char **r) {
924 if (!(c = new(char, l)))
927 if ((n = readlink(p, c, l-1)) < 0) {
933 if ((size_t) n < l-1) {
944 int readlink_and_make_absolute(const char *p, char **r) {
951 if ((j = readlink_malloc(p, &target)) < 0)
954 k = file_in_same_dir(p, target);
964 int parent_of_path(const char *path, char **_r) {
965 const char *e, *a = NULL, *b = NULL, *p;
975 for (e = path; *e; e++) {
977 if (!slash && *e == '/') {
981 } else if (slash && *e != '/')
996 r = strndup(path, p-path);
1006 char *file_name_from_path(const char *p) {
1011 if ((r = strrchr(p, '/')))
1017 bool path_is_absolute(const char *p) {
1023 bool is_path(const char *p) {
1025 return !!strchr(p, '/');
1028 char *path_make_absolute(const char *p, const char *prefix) {
1033 /* Makes every item in the list an absolute path by prepending
1034 * the prefix, if specified and necessary */
1036 if (path_is_absolute(p) || !prefix)
1039 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1045 char *path_make_absolute_cwd(const char *p) {
1050 /* Similar to path_make_absolute(), but prefixes with the
1051 * current working directory. */
1053 if (path_is_absolute(p))
1056 if (!(cwd = get_current_dir_name()))
1059 r = path_make_absolute(p, cwd);
1065 char **strv_path_make_absolute_cwd(char **l) {
1068 /* Goes through every item in the string list and makes it
1069 * absolute. This works in place and won't rollback any
1070 * changes on failure. */
1072 STRV_FOREACH(s, l) {
1075 if (!(t = path_make_absolute_cwd(*s)))
1085 char **strv_path_canonicalize(char **l) {
1088 bool enomem = false;
1090 if (strv_isempty(l))
1093 /* Goes through every item in the string list and canonicalize
1094 * the path. This works in place and won't rollback any
1095 * changes on failure. */
1097 STRV_FOREACH(s, l) {
1100 t = path_make_absolute_cwd(*s);
1109 u = canonicalize_file_name(t);
1113 if (errno == ENOMEM || !errno)
1130 int reset_all_signal_handlers(void) {
1133 for (sig = 1; sig < _NSIG; sig++) {
1134 struct sigaction sa;
1136 if (sig == SIGKILL || sig == SIGSTOP)
1140 sa.sa_handler = SIG_DFL;
1141 sa.sa_flags = SA_RESTART;
1143 /* On Linux the first two RT signals are reserved by
1144 * glibc, and sigaction() will return EINVAL for them. */
1145 if ((sigaction(sig, &sa, NULL) < 0))
1146 if (errno != EINVAL)
1153 char *strstrip(char *s) {
1156 /* Drops trailing whitespace. Modifies the string in
1157 * place. Returns pointer to first non-space character */
1159 s += strspn(s, WHITESPACE);
1161 for (e = s; *e; e++)
1162 if (!strchr(WHITESPACE, *e))
1173 char *delete_chars(char *s, const char *bad) {
1176 /* Drops all whitespace, regardless where in the string */
1178 for (f = s, t = s; *f; f++) {
1179 if (strchr(bad, *f))
1190 char *file_in_same_dir(const char *path, const char *filename) {
1197 /* This removes the last component of path and appends
1198 * filename, unless the latter is absolute anyway or the
1201 if (path_is_absolute(filename))
1202 return strdup(filename);
1204 if (!(e = strrchr(path, '/')))
1205 return strdup(filename);
1207 k = strlen(filename);
1208 if (!(r = new(char, e-path+1+k+1)))
1211 memcpy(r, path, e-path+1);
1212 memcpy(r+(e-path)+1, filename, k+1);
1217 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1220 if (label_mkdir(path, mode) >= 0)
1221 if (chmod_and_chown(path, mode, uid, gid) < 0)
1224 if (lstat(path, &st) < 0)
1227 if ((st.st_mode & 0777) != mode ||
1230 !S_ISDIR(st.st_mode)) {
1239 int mkdir_parents(const char *path, mode_t mode) {
1244 /* Creates every parent directory in the path except the last
1247 p = path + strspn(path, "/");
1252 e = p + strcspn(p, "/");
1253 p = e + strspn(e, "/");
1255 /* Is this the last component? If so, then we're
1260 if (!(t = strndup(path, e - path)))
1263 r = label_mkdir(t, mode);
1266 if (r < 0 && errno != EEXIST)
1271 int mkdir_p(const char *path, mode_t mode) {
1276 if ((r = mkdir_parents(path, mode)) < 0)
1279 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1285 int rmdir_parents(const char *path, const char *stop) {
1294 /* Skip trailing slashes */
1295 while (l > 0 && path[l-1] == '/')
1301 /* Skip last component */
1302 while (l > 0 && path[l-1] != '/')
1305 /* Skip trailing slashes */
1306 while (l > 0 && path[l-1] == '/')
1312 if (!(t = strndup(path, l)))
1315 if (path_startswith(stop, t)) {
1324 if (errno != ENOENT)
1332 char hexchar(int x) {
1333 static const char table[16] = "0123456789abcdef";
1335 return table[x & 15];
1338 int unhexchar(char c) {
1340 if (c >= '0' && c <= '9')
1343 if (c >= 'a' && c <= 'f')
1344 return c - 'a' + 10;
1346 if (c >= 'A' && c <= 'F')
1347 return c - 'A' + 10;
1352 char octchar(int x) {
1353 return '0' + (x & 7);
1356 int unoctchar(char c) {
1358 if (c >= '0' && c <= '7')
1364 char decchar(int x) {
1365 return '0' + (x % 10);
1368 int undecchar(char c) {
1370 if (c >= '0' && c <= '9')
1376 char *cescape(const char *s) {
1382 /* Does C style string escaping. */
1384 if (!(r = new(char, strlen(s)*4 + 1)))
1387 for (f = s, t = r; *f; f++)
1433 /* For special chars we prefer octal over
1434 * hexadecimal encoding, simply because glib's
1435 * g_strescape() does the same */
1436 if ((*f < ' ') || (*f >= 127)) {
1438 *(t++) = octchar((unsigned char) *f >> 6);
1439 *(t++) = octchar((unsigned char) *f >> 3);
1440 *(t++) = octchar((unsigned char) *f);
1451 char *cunescape_length(const char *s, size_t length) {
1457 /* Undoes C style string escaping */
1459 if (!(r = new(char, length+1)))
1462 for (f = s, t = r; f < s + length; f++) {
1505 /* This is an extension of the XDG syntax files */
1510 /* hexadecimal encoding */
1513 if ((a = unhexchar(f[1])) < 0 ||
1514 (b = unhexchar(f[2])) < 0) {
1515 /* Invalid escape code, let's take it literal then */
1519 *(t++) = (char) ((a << 4) | b);
1534 /* octal encoding */
1537 if ((a = unoctchar(f[0])) < 0 ||
1538 (b = unoctchar(f[1])) < 0 ||
1539 (c = unoctchar(f[2])) < 0) {
1540 /* Invalid escape code, let's take it literal then */
1544 *(t++) = (char) ((a << 6) | (b << 3) | c);
1552 /* premature end of string.*/
1557 /* Invalid escape code, let's take it literal then */
1569 char *cunescape(const char *s) {
1570 return cunescape_length(s, strlen(s));
1573 char *xescape(const char *s, const char *bad) {
1577 /* Escapes all chars in bad, in addition to \ and all special
1578 * chars, in \xFF style escaping. May be reversed with
1581 if (!(r = new(char, strlen(s)*4+1)))
1584 for (f = s, t = r; *f; f++) {
1586 if ((*f < ' ') || (*f >= 127) ||
1587 (*f == '\\') || strchr(bad, *f)) {
1590 *(t++) = hexchar(*f >> 4);
1591 *(t++) = hexchar(*f);
1601 char *bus_path_escape(const char *s) {
1607 /* Escapes all chars that D-Bus' object path cannot deal
1608 * with. Can be reverse with bus_path_unescape() */
1610 if (!(r = new(char, strlen(s)*3+1)))
1613 for (f = s, t = r; *f; f++) {
1615 if (!(*f >= 'A' && *f <= 'Z') &&
1616 !(*f >= 'a' && *f <= 'z') &&
1617 !(*f >= '0' && *f <= '9')) {
1619 *(t++) = hexchar(*f >> 4);
1620 *(t++) = hexchar(*f);
1630 char *bus_path_unescape(const char *f) {
1635 if (!(r = strdup(f)))
1638 for (t = r; *f; f++) {
1643 if ((a = unhexchar(f[1])) < 0 ||
1644 (b = unhexchar(f[2])) < 0) {
1645 /* Invalid escape code, let's take it literal then */
1648 *(t++) = (char) ((a << 4) | b);
1660 char *path_kill_slashes(char *path) {
1664 /* Removes redundant inner and trailing slashes. Modifies the
1665 * passed string in-place.
1667 * ///foo///bar/ becomes /foo/bar
1670 for (f = path, t = path; *f; f++) {
1685 /* Special rule, if we are talking of the root directory, a
1686 trailing slash is good */
1688 if (t == path && slash)
1695 bool path_startswith(const char *path, const char *prefix) {
1699 if ((path[0] == '/') != (prefix[0] == '/'))
1705 path += strspn(path, "/");
1706 prefix += strspn(prefix, "/");
1714 a = strcspn(path, "/");
1715 b = strcspn(prefix, "/");
1720 if (memcmp(path, prefix, a) != 0)
1728 bool path_equal(const char *a, const char *b) {
1732 if ((a[0] == '/') != (b[0] == '/'))
1738 a += strspn(a, "/");
1739 b += strspn(b, "/");
1741 if (*a == 0 && *b == 0)
1744 if (*a == 0 || *b == 0)
1747 j = strcspn(a, "/");
1748 k = strcspn(b, "/");
1753 if (memcmp(a, b, j) != 0)
1761 char *ascii_strlower(char *t) {
1766 for (p = t; *p; p++)
1767 if (*p >= 'A' && *p <= 'Z')
1768 *p = *p - 'A' + 'a';
1773 bool ignore_file(const char *filename) {
1777 filename[0] == '.' ||
1778 streq(filename, "lost+found") ||
1779 streq(filename, "aquota.user") ||
1780 streq(filename, "aquota.group") ||
1781 endswith(filename, "~") ||
1782 endswith(filename, ".rpmnew") ||
1783 endswith(filename, ".rpmsave") ||
1784 endswith(filename, ".rpmorig") ||
1785 endswith(filename, ".dpkg-old") ||
1786 endswith(filename, ".dpkg-new") ||
1787 endswith(filename, ".swp");
1790 int fd_nonblock(int fd, bool nonblock) {
1795 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1799 flags |= O_NONBLOCK;
1801 flags &= ~O_NONBLOCK;
1803 if (fcntl(fd, F_SETFL, flags) < 0)
1809 int fd_cloexec(int fd, bool cloexec) {
1814 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1818 flags |= FD_CLOEXEC;
1820 flags &= ~FD_CLOEXEC;
1822 if (fcntl(fd, F_SETFD, flags) < 0)
1828 int close_all_fds(const int except[], unsigned n_except) {
1833 if (!(d = opendir("/proc/self/fd")))
1836 while ((de = readdir(d))) {
1839 if (ignore_file(de->d_name))
1842 if (safe_atoi(de->d_name, &fd) < 0)
1843 /* Let's better ignore this, just in case */
1857 for (i = 0; i < n_except; i++)
1858 if (except[i] == fd) {
1867 if (close_nointr(fd) < 0) {
1868 /* Valgrind has its own FD and doesn't want to have it closed */
1869 if (errno != EBADF && r == 0)
1878 bool chars_intersect(const char *a, const char *b) {
1881 /* Returns true if any of the chars in a are in b. */
1882 for (p = a; *p; p++)
1889 char *format_timestamp(char *buf, size_t l, usec_t t) {
1899 sec = (time_t) (t / USEC_PER_SEC);
1901 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1907 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1910 n = now(CLOCK_REALTIME);
1912 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1917 if (d >= USEC_PER_YEAR)
1918 snprintf(buf, l, "%llu years and %llu months ago",
1919 (unsigned long long) (d / USEC_PER_YEAR),
1920 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1921 else if (d >= USEC_PER_MONTH)
1922 snprintf(buf, l, "%llu months and %llu days ago",
1923 (unsigned long long) (d / USEC_PER_MONTH),
1924 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1925 else if (d >= USEC_PER_WEEK)
1926 snprintf(buf, l, "%llu weeks and %llu days ago",
1927 (unsigned long long) (d / USEC_PER_WEEK),
1928 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1929 else if (d >= 2*USEC_PER_DAY)
1930 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1931 else if (d >= 25*USEC_PER_HOUR)
1932 snprintf(buf, l, "1 day and %lluh ago",
1933 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1934 else if (d >= 6*USEC_PER_HOUR)
1935 snprintf(buf, l, "%lluh ago",
1936 (unsigned long long) (d / USEC_PER_HOUR));
1937 else if (d >= USEC_PER_HOUR)
1938 snprintf(buf, l, "%lluh %llumin ago",
1939 (unsigned long long) (d / USEC_PER_HOUR),
1940 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1941 else if (d >= 5*USEC_PER_MINUTE)
1942 snprintf(buf, l, "%llumin ago",
1943 (unsigned long long) (d / USEC_PER_MINUTE));
1944 else if (d >= USEC_PER_MINUTE)
1945 snprintf(buf, l, "%llumin %llus ago",
1946 (unsigned long long) (d / USEC_PER_MINUTE),
1947 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1948 else if (d >= USEC_PER_SEC)
1949 snprintf(buf, l, "%llus ago",
1950 (unsigned long long) (d / USEC_PER_SEC));
1951 else if (d >= USEC_PER_MSEC)
1952 snprintf(buf, l, "%llums ago",
1953 (unsigned long long) (d / USEC_PER_MSEC));
1955 snprintf(buf, l, "%lluus ago",
1956 (unsigned long long) d);
1958 snprintf(buf, l, "now");
1964 char *format_timespan(char *buf, size_t l, usec_t t) {
1965 static const struct {
1969 { "w", USEC_PER_WEEK },
1970 { "d", USEC_PER_DAY },
1971 { "h", USEC_PER_HOUR },
1972 { "min", USEC_PER_MINUTE },
1973 { "s", USEC_PER_SEC },
1974 { "ms", USEC_PER_MSEC },
1984 if (t == (usec_t) -1)
1988 snprintf(p, l, "0");
1993 /* The result of this function can be parsed with parse_usec */
1995 for (i = 0; i < ELEMENTSOF(table); i++) {
1999 if (t < table[i].usec)
2005 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2006 n = MIN((size_t) k, l);
2019 bool fstype_is_network(const char *fstype) {
2020 static const char * const table[] = {
2032 for (i = 0; i < ELEMENTSOF(table); i++)
2033 if (streq(table[i], fstype))
2042 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2047 TIOCL_GETKMSGREDIRECT,
2051 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2054 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2057 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2060 close_nointr_nofail(r);
2064 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2065 struct termios old_termios, new_termios;
2067 char line[LINE_MAX];
2072 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2073 new_termios = old_termios;
2075 new_termios.c_lflag &= ~ICANON;
2076 new_termios.c_cc[VMIN] = 1;
2077 new_termios.c_cc[VTIME] = 0;
2079 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2082 k = fread(&c, 1, 1, f);
2084 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2090 *need_nl = c != '\n';
2097 if (!(fgets(line, sizeof(line), f)))
2102 if (strlen(line) != 1)
2112 int ask(char *ret, const char *replies, const char *text, ...) {
2119 on_tty = isatty(STDOUT_FILENO);
2125 bool need_nl = true;
2128 fputs("\x1B[1m", stdout);
2135 fputs("\x1B[0m", stdout);
2139 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2141 if (r == -EBADMSG) {
2142 puts("Bad input, please try again.");
2153 if (strchr(replies, c)) {
2158 puts("Read unexpected character, please try again.");
2162 int reset_terminal(int fd) {
2163 struct termios termios;
2167 /* Set terminal to some sane defaults */
2171 /* We leave locked terminal attributes untouched, so that
2172 * Plymouth may set whatever it wants to set, and we don't
2173 * interfere with that. */
2175 /* Disable exclusive mode, just in case */
2176 ioctl(fd, TIOCNXCL);
2178 /* Enable console unicode mode */
2180 ioctl(fd, KDSKBMODE, &arg);
2182 if (tcgetattr(fd, &termios) < 0) {
2187 /* We only reset the stuff that matters to the software. How
2188 * hardware is set up we don't touch assuming that somebody
2189 * else will do that for us */
2191 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2192 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2193 termios.c_oflag |= ONLCR;
2194 termios.c_cflag |= CREAD;
2195 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2197 termios.c_cc[VINTR] = 03; /* ^C */
2198 termios.c_cc[VQUIT] = 034; /* ^\ */
2199 termios.c_cc[VERASE] = 0177;
2200 termios.c_cc[VKILL] = 025; /* ^X */
2201 termios.c_cc[VEOF] = 04; /* ^D */
2202 termios.c_cc[VSTART] = 021; /* ^Q */
2203 termios.c_cc[VSTOP] = 023; /* ^S */
2204 termios.c_cc[VSUSP] = 032; /* ^Z */
2205 termios.c_cc[VLNEXT] = 026; /* ^V */
2206 termios.c_cc[VWERASE] = 027; /* ^W */
2207 termios.c_cc[VREPRINT] = 022; /* ^R */
2208 termios.c_cc[VEOL] = 0;
2209 termios.c_cc[VEOL2] = 0;
2211 termios.c_cc[VTIME] = 0;
2212 termios.c_cc[VMIN] = 1;
2214 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2218 /* Just in case, flush all crap out */
2219 tcflush(fd, TCIOFLUSH);
2224 int open_terminal(const char *name, int mode) {
2229 * If a TTY is in the process of being closed opening it might
2230 * cause EIO. This is horribly awful, but unlikely to be
2231 * changed in the kernel. Hence we work around this problem by
2232 * retrying a couple of times.
2234 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2238 if ((fd = open(name, mode)) >= 0)
2247 usleep(50 * USEC_PER_MSEC);
2254 if ((r = isatty(fd)) < 0) {
2255 close_nointr_nofail(fd);
2260 close_nointr_nofail(fd);
2267 int flush_fd(int fd) {
2268 struct pollfd pollfd;
2272 pollfd.events = POLLIN;
2279 if ((r = poll(&pollfd, 1, 0)) < 0) {
2290 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2295 if (errno == EAGAIN)
2306 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2307 int fd = -1, notify = -1, r, wd = -1;
2311 /* We use inotify to be notified when the tty is closed. We
2312 * create the watch before checking if we can actually acquire
2313 * it, so that we don't lose any event.
2315 * Note: strictly speaking this actually watches for the
2316 * device being closed, it does *not* really watch whether a
2317 * tty loses its controlling process. However, unless some
2318 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2319 * its tty otherwise this will not become a problem. As long
2320 * as the administrator makes sure not configure any service
2321 * on the same tty as an untrusted user this should not be a
2322 * problem. (Which he probably should not do anyway.) */
2324 if (!fail && !force) {
2325 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2330 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2338 if ((r = flush_fd(notify)) < 0)
2341 /* We pass here O_NOCTTY only so that we can check the return
2342 * value TIOCSCTTY and have a reliable way to figure out if we
2343 * successfully became the controlling process of the tty */
2344 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2347 /* First, try to get the tty */
2348 r = ioctl(fd, TIOCSCTTY, force);
2350 /* Sometimes it makes sense to ignore TIOCSCTTY
2351 * returning EPERM, i.e. when very likely we already
2352 * are have this controlling terminal. */
2353 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2356 if (r < 0 && (force || fail || errno != EPERM)) {
2366 assert(notify >= 0);
2369 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2371 struct inotify_event *e;
2373 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2382 e = (struct inotify_event*) inotify_buffer;
2387 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2392 step = sizeof(struct inotify_event) + e->len;
2393 assert(step <= (size_t) l);
2395 e = (struct inotify_event*) ((uint8_t*) e + step);
2402 /* We close the tty fd here since if the old session
2403 * ended our handle will be dead. It's important that
2404 * we do this after sleeping, so that we don't enter
2405 * an endless loop. */
2406 close_nointr_nofail(fd);
2410 close_nointr_nofail(notify);
2412 if ((r = reset_terminal(fd)) < 0)
2413 log_warning("Failed to reset terminal: %s", strerror(-r));
2419 close_nointr_nofail(fd);
2422 close_nointr_nofail(notify);
2427 int release_terminal(void) {
2429 struct sigaction sa_old, sa_new;
2431 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2434 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2435 * by our own TIOCNOTTY */
2438 sa_new.sa_handler = SIG_IGN;
2439 sa_new.sa_flags = SA_RESTART;
2440 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2442 if (ioctl(fd, TIOCNOTTY) < 0)
2445 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2447 close_nointr_nofail(fd);
2451 int sigaction_many(const struct sigaction *sa, ...) {
2456 while ((sig = va_arg(ap, int)) > 0)
2457 if (sigaction(sig, sa, NULL) < 0)
2464 int ignore_signals(int sig, ...) {
2465 struct sigaction sa;
2470 sa.sa_handler = SIG_IGN;
2471 sa.sa_flags = SA_RESTART;
2473 if (sigaction(sig, &sa, NULL) < 0)
2477 while ((sig = va_arg(ap, int)) > 0)
2478 if (sigaction(sig, &sa, NULL) < 0)
2485 int default_signals(int sig, ...) {
2486 struct sigaction sa;
2491 sa.sa_handler = SIG_DFL;
2492 sa.sa_flags = SA_RESTART;
2494 if (sigaction(sig, &sa, NULL) < 0)
2498 while ((sig = va_arg(ap, int)) > 0)
2499 if (sigaction(sig, &sa, NULL) < 0)
2506 int close_pipe(int p[]) {
2512 a = close_nointr(p[0]);
2517 b = close_nointr(p[1]);
2521 return a < 0 ? a : b;
2524 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2533 while (nbytes > 0) {
2536 if ((k = read(fd, p, nbytes)) <= 0) {
2538 if (k < 0 && errno == EINTR)
2541 if (k < 0 && errno == EAGAIN && do_poll) {
2542 struct pollfd pollfd;
2546 pollfd.events = POLLIN;
2548 if (poll(&pollfd, 1, -1) < 0) {
2552 return n > 0 ? n : -errno;
2555 if (pollfd.revents != POLLIN)
2556 return n > 0 ? n : -EIO;
2561 return n > 0 ? n : (k < 0 ? -errno : 0);
2572 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2581 while (nbytes > 0) {
2584 if ((k = write(fd, p, nbytes)) <= 0) {
2586 if (k < 0 && errno == EINTR)
2589 if (k < 0 && errno == EAGAIN && do_poll) {
2590 struct pollfd pollfd;
2594 pollfd.events = POLLOUT;
2596 if (poll(&pollfd, 1, -1) < 0) {
2600 return n > 0 ? n : -errno;
2603 if (pollfd.revents != POLLOUT)
2604 return n > 0 ? n : -EIO;
2609 return n > 0 ? n : (k < 0 ? -errno : 0);
2620 int path_is_mount_point(const char *t) {
2625 if (lstat(t, &a) < 0) {
2626 if (errno == ENOENT)
2632 if ((r = parent_of_path(t, &parent)) < 0)
2635 r = lstat(parent, &b);
2641 return a.st_dev != b.st_dev;
2644 int parse_usec(const char *t, usec_t *usec) {
2645 static const struct {
2649 { "sec", USEC_PER_SEC },
2650 { "s", USEC_PER_SEC },
2651 { "min", USEC_PER_MINUTE },
2652 { "hr", USEC_PER_HOUR },
2653 { "h", USEC_PER_HOUR },
2654 { "d", USEC_PER_DAY },
2655 { "w", USEC_PER_WEEK },
2656 { "msec", USEC_PER_MSEC },
2657 { "ms", USEC_PER_MSEC },
2658 { "m", USEC_PER_MINUTE },
2661 { "", USEC_PER_SEC },
2677 l = strtoll(p, &e, 10);
2688 e += strspn(e, WHITESPACE);
2690 for (i = 0; i < ELEMENTSOF(table); i++)
2691 if (startswith(e, table[i].suffix)) {
2692 r += (usec_t) l * table[i].usec;
2693 p = e + strlen(table[i].suffix);
2697 if (i >= ELEMENTSOF(table))
2707 int make_stdio(int fd) {
2712 r = dup2(fd, STDIN_FILENO);
2713 s = dup2(fd, STDOUT_FILENO);
2714 t = dup2(fd, STDERR_FILENO);
2717 close_nointr_nofail(fd);
2719 if (r < 0 || s < 0 || t < 0)
2725 int make_null_stdio(void) {
2728 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2731 return make_stdio(null_fd);
2734 bool is_device_path(const char *path) {
2736 /* Returns true on paths that refer to a device, either in
2737 * sysfs or in /dev */
2740 path_startswith(path, "/dev/") ||
2741 path_startswith(path, "/sys/");
2744 int dir_is_empty(const char *path) {
2747 struct dirent buf, *de;
2749 if (!(d = opendir(path)))
2753 if ((r = readdir_r(d, &buf, &de)) > 0) {
2763 if (!ignore_file(de->d_name)) {
2773 unsigned long long random_ull(void) {
2778 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2781 r = loop_read(fd, &ull, sizeof(ull), true);
2782 close_nointr_nofail(fd);
2784 if (r != sizeof(ull))
2790 return random() * RAND_MAX + random();
2793 void rename_process(const char name[8]) {
2796 prctl(PR_SET_NAME, name);
2798 /* This is a like a poor man's setproctitle(). The string
2799 * passed should fit in 7 chars (i.e. the length of
2802 if (program_invocation_name)
2803 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2806 void sigset_add_many(sigset_t *ss, ...) {
2813 while ((sig = va_arg(ap, int)) > 0)
2814 assert_se(sigaddset(ss, sig) == 0);
2818 char* gethostname_malloc(void) {
2821 assert_se(uname(&u) >= 0);
2824 return strdup(u.nodename);
2826 return strdup(u.sysname);
2829 char* getlogname_malloc(void) {
2833 struct passwd pwbuf, *pw = NULL;
2836 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2841 /* Shortcut things to avoid NSS lookups */
2843 return strdup("root");
2845 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2848 if (!(buf = malloc(bufsize)))
2851 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2852 name = strdup(pw->pw_name);
2859 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2865 int getttyname_malloc(int fd, char **r) {
2866 char path[PATH_MAX], *c;
2871 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2876 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2883 int getttyname_harder(int fd, char **r) {
2887 if ((k = getttyname_malloc(fd, &s)) < 0)
2890 if (streq(s, "tty")) {
2892 return get_ctty(r, NULL);
2899 int get_ctty_devnr(dev_t *d) {
2901 char line[LINE_MAX], *p;
2902 unsigned long ttynr;
2905 if (!(f = fopen("/proc/self/stat", "r")))
2908 if (!(fgets(line, sizeof(line), f))) {
2916 if (!(p = strrchr(line, ')')))
2925 "%*d " /* session */
2934 int get_ctty(char **r, dev_t *_devnr) {
2936 char fn[PATH_MAX], *s, *b, *p;
2941 if ((k = get_ctty_devnr(&devnr)) < 0)
2944 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2947 if ((k = readlink_malloc(fn, &s)) < 0) {
2952 /* This is an ugly hack */
2953 if (major(devnr) == 136) {
2954 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2964 /* Probably something like the ptys which have no
2965 * symlink in /dev/char. Let's return something
2966 * vaguely useful. */
2968 if (!(b = strdup(fn + 5)))
2978 if (startswith(s, "/dev/"))
2980 else if (startswith(s, "../"))
2998 static int rm_rf_children(int fd, bool only_dirs) {
3004 /* This returns the first error we run into, but nevertheless
3007 if (!(d = fdopendir(fd))) {
3008 close_nointr_nofail(fd);
3010 return errno == ENOENT ? 0 : -errno;
3014 struct dirent buf, *de;
3018 if ((r = readdir_r(d, &buf, &de)) != 0) {
3027 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3030 if (de->d_type == DT_UNKNOWN) {
3033 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3034 if (ret == 0 && errno != ENOENT)
3039 is_dir = S_ISDIR(st.st_mode);
3041 is_dir = de->d_type == DT_DIR;
3046 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3047 if (ret == 0 && errno != ENOENT)
3052 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3057 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3058 if (ret == 0 && errno != ENOENT)
3061 } else if (!only_dirs) {
3063 if (unlinkat(fd, de->d_name, 0) < 0) {
3064 if (ret == 0 && errno != ENOENT)
3075 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3081 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3083 if (errno != ENOTDIR)
3086 if (delete_root && !only_dirs)
3087 if (unlink(path) < 0)
3093 r = rm_rf_children(fd, only_dirs);
3096 if (rmdir(path) < 0) {
3104 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3107 /* Under the assumption that we are running privileged we
3108 * first change the access mode and only then hand out
3109 * ownership to avoid a window where access is too open. */
3111 if (chmod(path, mode) < 0)
3114 if (chown(path, uid, gid) < 0)
3120 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3124 /* Allocates the cpuset in the right size */
3127 if (!(r = CPU_ALLOC(n)))
3130 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3131 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3141 if (errno != EINVAL)
3148 void status_vprintf(const char *format, va_list ap) {
3154 /* This independent of logging, as status messages are
3155 * optional and go exclusively to the console. */
3157 if (vasprintf(&s, format, ap) < 0)
3160 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3163 write(fd, s, strlen(s));
3169 close_nointr_nofail(fd);
3172 void status_printf(const char *format, ...) {
3177 va_start(ap, format);
3178 status_vprintf(format, ap);
3182 void status_welcome(void) {
3183 char *pretty_name = NULL, *ansi_color = NULL;
3184 const char *const_pretty = NULL, *const_color = NULL;
3187 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3188 "PRETTY_NAME", &pretty_name,
3189 "ANSI_COLOR", &ansi_color,
3193 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3196 #if defined(TARGET_FEDORA)
3198 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3201 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3203 truncate_nl(pretty_name);
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));
3225 truncate_nl(pretty_name);
3229 const_color = "0;32"; /* Green for openSUSE */
3231 #elif defined(TARGET_GENTOO)
3234 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3237 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3239 truncate_nl(pretty_name);
3243 const_color = "1;34"; /* Light Blue for Gentoo */
3245 #elif defined(TARGET_ALTLINUX)
3248 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3251 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3253 truncate_nl(pretty_name);
3257 const_color = "0;36"; /* Cyan for ALTLinux */
3260 #elif defined(TARGET_DEBIAN)
3265 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3268 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3270 truncate_nl(version);
3271 pretty_name = strappend("Debian ", version);
3275 log_warning("Failed to allocate Debian version string.");
3280 const_color = "1;31"; /* Light Red for Debian */
3282 #elif defined(TARGET_UBUNTU)
3284 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3285 "DISTRIB_DESCRIPTION", &pretty_name,
3289 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3293 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3295 #elif defined(TARGET_MANDRIVA)
3300 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3302 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3304 p = strstr(s, " release ");
3308 p[strcspn(p, " ")] = '\0';
3310 /* This corresponds to standard rc.sysinit */
3311 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3312 const_color = "1;36";
3314 log_warning("Failed to allocate Mandriva version string.");
3316 log_warning("Failed to parse /etc/mandriva-release");
3323 if (!pretty_name && !const_pretty)
3324 const_pretty = "Linux";
3326 if (!ansi_color && !const_color)
3329 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3330 const_color ? const_color : ansi_color,
3331 const_pretty ? const_pretty : pretty_name);
3337 char *replace_env(const char *format, char **env) {
3344 const char *e, *word = format;
3349 for (e = format; *e; e ++) {
3360 if (!(k = strnappend(r, word, e-word-1)))
3369 } else if (*e == '$') {
3370 if (!(k = strnappend(r, word, e-word)))
3386 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3389 if (!(k = strappend(r, t)))
3402 if (!(k = strnappend(r, word, e-word)))
3413 char **replace_env_argv(char **argv, char **env) {
3415 unsigned k = 0, l = 0;
3417 l = strv_length(argv);
3419 if (!(r = new(char*, l+1)))
3422 STRV_FOREACH(i, argv) {
3424 /* If $FOO appears as single word, replace it by the split up variable */
3425 if ((*i)[0] == '$' && (*i)[1] != '{') {
3430 if ((e = strv_env_get(env, *i+1))) {
3432 if (!(m = strv_split_quoted(e))) {
3443 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3452 memcpy(r + k, m, q * sizeof(char*));
3460 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3461 if (!(r[k++] = replace_env(*i, env))) {
3472 static __thread int parsed_columns = 0;
3475 if (parsed_columns > 0)
3476 return parsed_columns;
3478 if ((e = getenv("COLUMNS")))
3479 parsed_columns = atoi(e);
3481 if (parsed_columns <= 0) {
3485 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3486 parsed_columns = ws.ws_col;
3489 if (parsed_columns <= 0)
3490 parsed_columns = 80;
3492 return parsed_columns;
3495 int running_in_chroot(void) {
3501 /* Only works as root */
3503 if (stat("/proc/1/root", &a) < 0)
3506 if (stat("/", &b) < 0)
3510 a.st_dev != b.st_dev ||
3511 a.st_ino != b.st_ino;
3514 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3519 assert(percent <= 100);
3520 assert(length >= 3);
3524 if (l <= 3 || l <= length)
3527 if (!(r = new0(char, length+1)))
3530 x = (length * percent) / 100;
3540 s + l - (length - x - 3),
3546 int touch(const char *path) {
3551 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3554 close_nointr_nofail(fd);
3558 char *unquote(const char *s, const char* quotes) {
3562 if ((l = strlen(s)) < 2)
3565 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3566 return strndup(s+1, l-2);
3571 char *normalize_env_assignment(const char *s) {
3572 char *name, *value, *p, *r;
3577 if (!(r = strdup(s)))
3583 if (!(name = strndup(s, p - s)))
3586 if (!(p = strdup(p+1))) {
3591 value = unquote(strstrip(p), QUOTES);
3599 if (asprintf(&r, "%s=%s", name, value) < 0)
3608 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3615 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3627 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3634 if ((r = wait_for_terminate(pid, &status)) < 0) {
3635 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3639 if (status.si_code == CLD_EXITED) {
3640 if (status.si_status != 0) {
3641 log_warning("%s failed with error code %i.", name, status.si_status);
3642 return status.si_status;
3645 log_debug("%s succeeded.", name);
3648 } else if (status.si_code == CLD_KILLED ||
3649 status.si_code == CLD_DUMPED) {
3651 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3655 log_warning("%s failed due to unknown reason.", name);
3662 /* Make sure nobody waits for us on a socket anymore */
3663 close_all_fds(NULL, 0);
3671 bool null_or_empty(struct stat *st) {
3674 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3677 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3683 DIR *xopendirat(int fd, const char *name, int flags) {
3687 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3690 if (!(d = fdopendir(nfd))) {
3691 close_nointr_nofail(nfd);
3698 int signal_from_string_try_harder(const char *s) {
3702 if ((signo = signal_from_string(s)) <= 0)
3703 if (startswith(s, "SIG"))
3704 return signal_from_string(s+3);
3709 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3715 if (!dual_timestamp_is_set(t))
3718 fprintf(f, "%s=%llu %llu\n",
3720 (unsigned long long) t->realtime,
3721 (unsigned long long) t->monotonic);
3724 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3725 unsigned long long a, b;
3730 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3731 log_debug("Failed to parse finish timestamp value %s", value);
3738 char *fstab_node_to_udev_node(const char *p) {
3742 /* FIXME: to follow udev's logic 100% we need to leave valid
3743 * UTF8 chars unescaped */
3745 if (startswith(p, "LABEL=")) {
3747 if (!(u = unquote(p+6, "\"\'")))
3750 t = xescape(u, "/ ");
3756 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3765 if (startswith(p, "UUID=")) {
3767 if (!(u = unquote(p+5, "\"\'")))
3770 t = xescape(u, "/ ");
3776 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3788 void filter_environ(const char *prefix) {
3795 for (i = 0, j = 0; environ[i]; i++) {
3797 if (startswith(environ[i], prefix))
3800 environ[j++] = environ[i];
3806 bool tty_is_vc(const char *tty) {
3809 if (startswith(tty, "/dev/"))
3812 return startswith(tty, "tty") &&
3813 tty[3] >= '0' && tty[3] <= '9';
3816 const char *default_term_for_tty(const char *tty) {
3817 char *active = NULL;
3822 if (startswith(tty, "/dev/"))
3825 /* Resolve where /dev/console is pointing when determining
3827 if (streq(tty, "console"))
3828 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3829 truncate_nl(active);
3831 /* If multiple log outputs are configured the
3832 * last one is what /dev/console points to */
3833 if ((tty = strrchr(active, ' ')))
3839 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3845 /* Returns a short identifier for the various VM implementations */
3846 int detect_vm(const char **id) {
3848 #if defined(__i386__) || defined(__x86_64__)
3850 /* Both CPUID and DMI are x86 specific interfaces... */
3852 static const char *const dmi_vendors[] = {
3853 "/sys/class/dmi/id/sys_vendor",
3854 "/sys/class/dmi/id/board_vendor",
3855 "/sys/class/dmi/id/bios_vendor"
3858 static const char dmi_vendor_table[] =
3860 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3861 "VMware\0" "vmware\0"
3863 "Microsoft Corporation\0" "microsoft\0"
3864 "innotek GmbH\0" "oracle\0"
3866 "Bochs\0" "bochs\0";
3868 static const char cpuid_vendor_table[] =
3869 "XenVMMXenVMM\0" "xen\0"
3870 "KVMKVMKVM\0" "kvm\0"
3871 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3872 "VMwareVMware\0" "vmware\0"
3873 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3874 "Microsoft Hv\0" "microsoft\0";
3885 /* http://lwn.net/Articles/301888/ */
3888 #if defined (__i386__)
3891 #elif defined (__amd64__)
3896 /* First detect whether there is a hypervisor */
3898 __asm__ __volatile__ (
3899 /* ebx/rbx is being used for PIC! */
3900 " push %%"REG_b" \n\t"
3902 " pop %%"REG_b" \n\t"
3904 : "=a" (eax), "=c" (ecx)
3908 hypervisor = !!(ecx & ecx & 0x80000000U);
3912 /* There is a hypervisor, see what it is */
3914 __asm__ __volatile__ (
3915 /* ebx/rbx is being used for PIC! */
3916 " push %%"REG_b" \n\t"
3918 " mov %%ebx, %1 \n\t"
3919 " pop %%"REG_b" \n\t"
3921 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3925 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3926 if (streq(sig.text, j)) {
3935 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3938 const char *found = NULL;
3940 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3947 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3948 if (startswith(s, j))
3971 int detect_container(const char **id) {
3974 /* Unfortunately many of these operations require root access
3975 * in one way or another */
3980 if (running_in_chroot() > 0) {
3988 /* /proc/vz exists in container and outside of the container,
3989 * /proc/bc only outside of the container. */
3990 if (access("/proc/vz", F_OK) >= 0 &&
3991 access("/proc/bc", F_OK) < 0) {
3999 if ((f = fopen("/proc/self/cgroup", "r"))) {
4002 char line[LINE_MAX], *p;
4004 if (!fgets(line, sizeof(line), f))
4007 if (!(p = strchr(strstrip(line), ':')))
4010 if (strncmp(p, ":ns:", 4))
4013 if (!streq(p, ":ns:/")) {
4029 /* Returns a short identifier for the various VM/container implementations */
4030 int detect_virtualization(const char **id) {
4031 static __thread const char *cached_id = NULL;
4037 if (cached_id == (const char*) -1)
4046 if ((r = detect_container(&_id)) != 0)
4049 r = detect_vm(&_id);
4058 cached_id = (const char*) -1;
4063 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4066 Hashmap *pids = NULL;
4070 /* Executes all binaries in a directory in parallel and waits
4071 * until all they all finished. */
4074 if (!(_d = opendir(directory))) {
4076 if (errno == ENOENT)
4079 log_error("Failed to enumerate directory %s: %m", directory);
4086 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4087 log_error("Failed to allocate set.");
4091 while ((de = readdir(d))) {
4096 if (ignore_file(de->d_name))
4099 if (de->d_type != DT_REG &&
4100 de->d_type != DT_LNK &&
4101 de->d_type != DT_UNKNOWN)
4104 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4105 log_error("Out of memory");
4109 if ((pid = fork()) < 0) {
4110 log_error("Failed to fork: %m");
4129 log_error("Failed to execute %s: %m", path);
4130 _exit(EXIT_FAILURE);
4133 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4135 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4136 log_error("Failed to add PID to set: %s", strerror(-k));
4141 while (!hashmap_isempty(pids)) {
4146 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4151 log_error("waitid() failed: %m");
4155 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4156 if (!is_clean_exit(si.si_code, si.si_status)) {
4157 if (si.si_code == CLD_EXITED)
4158 log_error("%s exited with exit status %i.", path, si.si_status);
4160 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4162 log_debug("%s exited successfully.", path);
4173 hashmap_free_free(pids);
4176 int kill_and_sigcont(pid_t pid, int sig) {
4179 r = kill(pid, sig) < 0 ? -errno : 0;
4187 bool nulstr_contains(const char*nulstr, const char *needle) {
4193 NULSTR_FOREACH(i, nulstr)
4194 if (streq(i, needle))
4200 bool plymouth_running(void) {
4201 return access("/run/plymouth/pid", F_OK) >= 0;
4204 void parse_syslog_priority(char **p, int *priority) {
4205 int a = 0, b = 0, c = 0;
4215 if (!strchr(*p, '>'))
4218 if ((*p)[2] == '>') {
4219 c = undecchar((*p)[1]);
4221 } else if ((*p)[3] == '>') {
4222 b = undecchar((*p)[1]);
4223 c = undecchar((*p)[2]);
4225 } else if ((*p)[4] == '>') {
4226 a = undecchar((*p)[1]);
4227 b = undecchar((*p)[2]);
4228 c = undecchar((*p)[3]);
4233 if (a < 0 || b < 0 || c < 0)
4236 *priority = a*100+b*10+c;
4240 int have_effective_cap(int value) {
4242 cap_flag_value_t fv;
4245 if (!(cap = cap_get_proc()))
4248 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4257 static const char *const ioprio_class_table[] = {
4258 [IOPRIO_CLASS_NONE] = "none",
4259 [IOPRIO_CLASS_RT] = "realtime",
4260 [IOPRIO_CLASS_BE] = "best-effort",
4261 [IOPRIO_CLASS_IDLE] = "idle"
4264 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4266 static const char *const sigchld_code_table[] = {
4267 [CLD_EXITED] = "exited",
4268 [CLD_KILLED] = "killed",
4269 [CLD_DUMPED] = "dumped",
4270 [CLD_TRAPPED] = "trapped",
4271 [CLD_STOPPED] = "stopped",
4272 [CLD_CONTINUED] = "continued",
4275 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4277 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4278 [LOG_FAC(LOG_KERN)] = "kern",
4279 [LOG_FAC(LOG_USER)] = "user",
4280 [LOG_FAC(LOG_MAIL)] = "mail",
4281 [LOG_FAC(LOG_DAEMON)] = "daemon",
4282 [LOG_FAC(LOG_AUTH)] = "auth",
4283 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4284 [LOG_FAC(LOG_LPR)] = "lpr",
4285 [LOG_FAC(LOG_NEWS)] = "news",
4286 [LOG_FAC(LOG_UUCP)] = "uucp",
4287 [LOG_FAC(LOG_CRON)] = "cron",
4288 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4289 [LOG_FAC(LOG_FTP)] = "ftp",
4290 [LOG_FAC(LOG_LOCAL0)] = "local0",
4291 [LOG_FAC(LOG_LOCAL1)] = "local1",
4292 [LOG_FAC(LOG_LOCAL2)] = "local2",
4293 [LOG_FAC(LOG_LOCAL3)] = "local3",
4294 [LOG_FAC(LOG_LOCAL4)] = "local4",
4295 [LOG_FAC(LOG_LOCAL5)] = "local5",
4296 [LOG_FAC(LOG_LOCAL6)] = "local6",
4297 [LOG_FAC(LOG_LOCAL7)] = "local7"
4300 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4302 static const char *const log_level_table[] = {
4303 [LOG_EMERG] = "emerg",
4304 [LOG_ALERT] = "alert",
4305 [LOG_CRIT] = "crit",
4307 [LOG_WARNING] = "warning",
4308 [LOG_NOTICE] = "notice",
4309 [LOG_INFO] = "info",
4310 [LOG_DEBUG] = "debug"
4313 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4315 static const char* const sched_policy_table[] = {
4316 [SCHED_OTHER] = "other",
4317 [SCHED_BATCH] = "batch",
4318 [SCHED_IDLE] = "idle",
4319 [SCHED_FIFO] = "fifo",
4323 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4325 static const char* const rlimit_table[] = {
4326 [RLIMIT_CPU] = "LimitCPU",
4327 [RLIMIT_FSIZE] = "LimitFSIZE",
4328 [RLIMIT_DATA] = "LimitDATA",
4329 [RLIMIT_STACK] = "LimitSTACK",
4330 [RLIMIT_CORE] = "LimitCORE",
4331 [RLIMIT_RSS] = "LimitRSS",
4332 [RLIMIT_NOFILE] = "LimitNOFILE",
4333 [RLIMIT_AS] = "LimitAS",
4334 [RLIMIT_NPROC] = "LimitNPROC",
4335 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4336 [RLIMIT_LOCKS] = "LimitLOCKS",
4337 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4338 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4339 [RLIMIT_NICE] = "LimitNICE",
4340 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4341 [RLIMIT_RTTIME] = "LimitRTTIME"
4344 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4346 static const char* const ip_tos_table[] = {
4347 [IPTOS_LOWDELAY] = "low-delay",
4348 [IPTOS_THROUGHPUT] = "throughput",
4349 [IPTOS_RELIABILITY] = "reliability",
4350 [IPTOS_LOWCOST] = "low-cost",
4353 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4355 static const char *const signal_table[] = {
4372 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4383 [SIGVTALRM] = "VTALRM",
4385 [SIGWINCH] = "WINCH",
4391 DEFINE_STRING_TABLE_LOOKUP(signal, int);