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>
61 #include "exit-status.h"
64 bool streq_ptr(const char *a, const char *b) {
66 /* Like streq(), but tries to make sense of NULL pointers */
77 usec_t now(clockid_t clock_id) {
80 assert_se(clock_gettime(clock_id, &ts) == 0);
82 return timespec_load(&ts);
85 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
88 ts->realtime = now(CLOCK_REALTIME);
89 ts->monotonic = now(CLOCK_MONOTONIC);
94 usec_t timespec_load(const struct timespec *ts) {
98 (usec_t) ts->tv_sec * USEC_PER_SEC +
99 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
102 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
105 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
106 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
111 usec_t timeval_load(const struct timeval *tv) {
115 (usec_t) tv->tv_sec * USEC_PER_SEC +
116 (usec_t) tv->tv_usec;
119 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
122 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
123 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
128 bool endswith(const char *s, const char *postfix) {
135 pl = strlen(postfix);
143 return memcmp(s + sl - pl, postfix, pl) == 0;
146 bool startswith(const char *s, const char *prefix) {
161 return memcmp(s, prefix, pl) == 0;
164 bool startswith_no_case(const char *s, const char *prefix) {
180 for(i = 0; i < pl; ++i) {
181 if (tolower(s[i]) != tolower(prefix[i]))
188 bool first_word(const char *s, const char *word) {
203 if (memcmp(s, word, wl) != 0)
207 strchr(WHITESPACE, s[wl]);
210 int close_nointr(int fd) {
216 if ((r = close(fd)) >= 0)
224 void close_nointr_nofail(int fd) {
225 int saved_errno = errno;
227 /* like close_nointr() but cannot fail, and guarantees errno
230 assert_se(close_nointr(fd) == 0);
235 void close_many(const int fds[], unsigned n_fd) {
238 for (i = 0; i < n_fd; i++)
239 close_nointr_nofail(fds[i]);
242 int parse_boolean(const char *v) {
245 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
247 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
253 int parse_pid(const char *s, pid_t* ret_pid) {
254 unsigned long ul = 0;
261 if ((r = safe_atolu(s, &ul)) < 0)
266 if ((unsigned long) pid != ul)
276 int safe_atou(const char *s, unsigned *ret_u) {
284 l = strtoul(s, &x, 0);
286 if (!x || *x || errno)
287 return errno ? -errno : -EINVAL;
289 if ((unsigned long) (unsigned) l != l)
292 *ret_u = (unsigned) l;
296 int safe_atoi(const char *s, int *ret_i) {
304 l = strtol(s, &x, 0);
306 if (!x || *x || errno)
307 return errno ? -errno : -EINVAL;
309 if ((long) (int) l != l)
316 int safe_atollu(const char *s, long long unsigned *ret_llu) {
318 unsigned long long l;
324 l = strtoull(s, &x, 0);
326 if (!x || *x || errno)
327 return errno ? -errno : -EINVAL;
333 int safe_atolli(const char *s, long long int *ret_lli) {
341 l = strtoll(s, &x, 0);
343 if (!x || *x || errno)
344 return errno ? -errno : -EINVAL;
350 /* Split a string into words. */
351 char *split(const char *c, size_t *l, const char *separator, char **state) {
354 current = *state ? *state : (char*) c;
356 if (!*current || *c == 0)
359 current += strspn(current, separator);
360 *l = strcspn(current, separator);
363 return (char*) current;
366 /* Split a string into words, but consider strings enclosed in '' and
367 * "" as words even if they include spaces. */
368 char *split_quoted(const char *c, size_t *l, char **state) {
370 bool escaped = false;
372 current = *state ? *state : (char*) c;
374 if (!*current || *c == 0)
377 current += strspn(current, WHITESPACE);
379 if (*current == '\'') {
382 for (e = current; *e; e++) {
392 *state = *e == 0 ? e : e+1;
393 } else if (*current == '\"') {
396 for (e = current; *e; e++) {
406 *state = *e == 0 ? e : e+1;
408 for (e = current; *e; e++) {
413 else if (strchr(WHITESPACE, *e))
420 return (char*) current;
423 char **split_path_and_make_absolute(const char *p) {
427 if (!(l = strv_split(p, ":")))
430 if (!strv_path_make_absolute_cwd(l)) {
438 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
441 char fn[132], line[256], *p;
447 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
448 fn[sizeof(fn)-1] = 0;
450 if (!(f = fopen(fn, "r")))
453 if (!(fgets(line, sizeof(line), f))) {
461 /* Let's skip the pid and comm fields. The latter is enclosed
462 * in () but does not escape any () in its value, so let's
463 * skip over it manually */
465 if (!(p = strrchr(line, ')')))
476 if ((long unsigned) (pid_t) ppid != ppid)
479 *_ppid = (pid_t) ppid;
484 int write_one_line_file(const char *fn, const char *line) {
491 if (!(f = fopen(fn, "we")))
494 if (fputs(line, f) < 0) {
499 if (!endswith(line, "\n"))
508 int read_one_line_file(const char *fn, char **line) {
511 char t[LINE_MAX], *c;
516 if (!(f = fopen(fn, "re")))
519 if (!(fgets(t, sizeof(t), f))) {
524 if (!(c = strdup(t))) {
537 int read_full_file(const char *fn, char **contents) {
544 if (!(f = fopen(fn, "re")))
547 if (fstat(fileno(f), &st) < 0) {
552 n = st.st_size > 0 ? st.st_size : LINE_MAX;
559 if (!(t = realloc(buf, n+1))) {
565 k = fread(buf + l, 1, n - l, f);
580 if (n > 4*1024*1024) {
588 else if (!(buf = calloc(1, 1))) {
607 const char *separator, ...) {
615 if ((r = read_full_file(fname, &contents)) < 0)
620 const char *key = NULL;
622 p += strspn(p, separator);
623 p += strspn(p, WHITESPACE);
628 if (!strchr(COMMENTS, *p)) {
632 va_start(ap, separator);
633 while ((key = va_arg(ap, char *))) {
637 value = va_arg(ap, char **);
640 if (strncmp(p, key, n) != 0 ||
645 n = strcspn(p, separator);
648 strchr(QUOTES, p[0]) &&
650 v = strndup(p+1, n-2);
661 /* return empty value strings as NULL */
678 p += strcspn(p, separator);
686 char *truncate_nl(char *s) {
689 s[strcspn(s, NEWLINE)] = 0;
693 int get_process_name(pid_t pid, char **name) {
700 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
703 r = read_one_line_file(p, name);
713 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
721 assert(max_length > 0);
724 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
733 if (!(r = new(char, max_length))) {
740 while ((c = getc(f)) != EOF) {
762 size_t n = MIN(left-1, 3U);
770 /* Kernel threads have no argv[] */
777 if ((h = get_process_name(pid, &t)) < 0)
780 h = asprintf(&r, "[%s]", t);
791 char *strnappend(const char *s, const char *suffix, size_t b) {
799 return strndup(suffix, b);
809 if (!(r = new(char, a+b+1)))
813 memcpy(r+a, suffix, b);
819 char *strappend(const char *s, const char *suffix) {
820 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
823 int readlink_malloc(const char *p, char **r) {
833 if (!(c = new(char, l)))
836 if ((n = readlink(p, c, l-1)) < 0) {
842 if ((size_t) n < l-1) {
853 int readlink_and_make_absolute(const char *p, char **r) {
860 if ((j = readlink_malloc(p, &target)) < 0)
863 k = file_in_same_dir(p, target);
873 int parent_of_path(const char *path, char **_r) {
874 const char *e, *a = NULL, *b = NULL, *p;
884 for (e = path; *e; e++) {
886 if (!slash && *e == '/') {
890 } else if (slash && *e != '/')
905 r = strndup(path, p-path);
915 char *file_name_from_path(const char *p) {
920 if ((r = strrchr(p, '/')))
926 bool path_is_absolute(const char *p) {
932 bool is_path(const char *p) {
934 return !!strchr(p, '/');
937 char *path_make_absolute(const char *p, const char *prefix) {
942 /* Makes every item in the list an absolute path by prepending
943 * the prefix, if specified and necessary */
945 if (path_is_absolute(p) || !prefix)
948 if (asprintf(&r, "%s/%s", prefix, p) < 0)
954 char *path_make_absolute_cwd(const char *p) {
959 /* Similar to path_make_absolute(), but prefixes with the
960 * current working directory. */
962 if (path_is_absolute(p))
965 if (!(cwd = get_current_dir_name()))
968 r = path_make_absolute(p, cwd);
974 char **strv_path_make_absolute_cwd(char **l) {
977 /* Goes through every item in the string list and makes it
978 * absolute. This works in place and won't rollback any
979 * changes on failure. */
984 if (!(t = path_make_absolute_cwd(*s)))
994 char **strv_path_canonicalize(char **l) {
1002 /* Goes through every item in the string list and canonicalize
1003 * the path. This works in place and won't rollback any
1004 * changes on failure. */
1006 STRV_FOREACH(s, l) {
1009 t = path_make_absolute_cwd(*s);
1018 u = canonicalize_file_name(t);
1022 if (errno == ENOMEM || !errno)
1039 int reset_all_signal_handlers(void) {
1042 for (sig = 1; sig < _NSIG; sig++) {
1043 struct sigaction sa;
1045 if (sig == SIGKILL || sig == SIGSTOP)
1049 sa.sa_handler = SIG_DFL;
1050 sa.sa_flags = SA_RESTART;
1052 /* On Linux the first two RT signals are reserved by
1053 * glibc, and sigaction() will return EINVAL for them. */
1054 if ((sigaction(sig, &sa, NULL) < 0))
1055 if (errno != EINVAL)
1062 char *strstrip(char *s) {
1065 /* Drops trailing whitespace. Modifies the string in
1066 * place. Returns pointer to first non-space character */
1068 s += strspn(s, WHITESPACE);
1070 for (e = s; *e; e++)
1071 if (!strchr(WHITESPACE, *e))
1082 char *delete_chars(char *s, const char *bad) {
1085 /* Drops all whitespace, regardless where in the string */
1087 for (f = s, t = s; *f; f++) {
1088 if (strchr(bad, *f))
1099 char *file_in_same_dir(const char *path, const char *filename) {
1106 /* This removes the last component of path and appends
1107 * filename, unless the latter is absolute anyway or the
1110 if (path_is_absolute(filename))
1111 return strdup(filename);
1113 if (!(e = strrchr(path, '/')))
1114 return strdup(filename);
1116 k = strlen(filename);
1117 if (!(r = new(char, e-path+1+k+1)))
1120 memcpy(r, path, e-path+1);
1121 memcpy(r+(e-path)+1, filename, k+1);
1126 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1129 if (label_mkdir(path, mode) >= 0)
1130 if (chmod_and_chown(path, mode, uid, gid) < 0)
1133 if (lstat(path, &st) < 0)
1136 if ((st.st_mode & 0777) != mode ||
1139 !S_ISDIR(st.st_mode)) {
1148 int mkdir_parents(const char *path, mode_t mode) {
1153 /* Creates every parent directory in the path except the last
1156 p = path + strspn(path, "/");
1161 e = p + strcspn(p, "/");
1162 p = e + strspn(e, "/");
1164 /* Is this the last component? If so, then we're
1169 if (!(t = strndup(path, e - path)))
1172 r = label_mkdir(t, mode);
1175 if (r < 0 && errno != EEXIST)
1180 int mkdir_p(const char *path, mode_t mode) {
1185 if ((r = mkdir_parents(path, mode)) < 0)
1188 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1194 int rmdir_parents(const char *path, const char *stop) {
1203 /* Skip trailing slashes */
1204 while (l > 0 && path[l-1] == '/')
1210 /* Skip last component */
1211 while (l > 0 && path[l-1] != '/')
1214 /* Skip trailing slashes */
1215 while (l > 0 && path[l-1] == '/')
1221 if (!(t = strndup(path, l)))
1224 if (path_startswith(stop, t)) {
1233 if (errno != ENOENT)
1241 char hexchar(int x) {
1242 static const char table[16] = "0123456789abcdef";
1244 return table[x & 15];
1247 int unhexchar(char c) {
1249 if (c >= '0' && c <= '9')
1252 if (c >= 'a' && c <= 'f')
1253 return c - 'a' + 10;
1255 if (c >= 'A' && c <= 'F')
1256 return c - 'A' + 10;
1261 char octchar(int x) {
1262 return '0' + (x & 7);
1265 int unoctchar(char c) {
1267 if (c >= '0' && c <= '7')
1273 char decchar(int x) {
1274 return '0' + (x % 10);
1277 int undecchar(char c) {
1279 if (c >= '0' && c <= '9')
1285 char *cescape(const char *s) {
1291 /* Does C style string escaping. */
1293 if (!(r = new(char, strlen(s)*4 + 1)))
1296 for (f = s, t = r; *f; f++)
1342 /* For special chars we prefer octal over
1343 * hexadecimal encoding, simply because glib's
1344 * g_strescape() does the same */
1345 if ((*f < ' ') || (*f >= 127)) {
1347 *(t++) = octchar((unsigned char) *f >> 6);
1348 *(t++) = octchar((unsigned char) *f >> 3);
1349 *(t++) = octchar((unsigned char) *f);
1360 char *cunescape_length(const char *s, size_t length) {
1366 /* Undoes C style string escaping */
1368 if (!(r = new(char, length+1)))
1371 for (f = s, t = r; f < s + length; f++) {
1414 /* This is an extension of the XDG syntax files */
1419 /* hexadecimal encoding */
1422 if ((a = unhexchar(f[1])) < 0 ||
1423 (b = unhexchar(f[2])) < 0) {
1424 /* Invalid escape code, let's take it literal then */
1428 *(t++) = (char) ((a << 4) | b);
1443 /* octal encoding */
1446 if ((a = unoctchar(f[0])) < 0 ||
1447 (b = unoctchar(f[1])) < 0 ||
1448 (c = unoctchar(f[2])) < 0) {
1449 /* Invalid escape code, let's take it literal then */
1453 *(t++) = (char) ((a << 6) | (b << 3) | c);
1461 /* premature end of string.*/
1466 /* Invalid escape code, let's take it literal then */
1478 char *cunescape(const char *s) {
1479 return cunescape_length(s, strlen(s));
1482 char *xescape(const char *s, const char *bad) {
1486 /* Escapes all chars in bad, in addition to \ and all special
1487 * chars, in \xFF style escaping. May be reversed with
1490 if (!(r = new(char, strlen(s)*4+1)))
1493 for (f = s, t = r; *f; f++) {
1495 if ((*f < ' ') || (*f >= 127) ||
1496 (*f == '\\') || strchr(bad, *f)) {
1499 *(t++) = hexchar(*f >> 4);
1500 *(t++) = hexchar(*f);
1510 char *bus_path_escape(const char *s) {
1516 /* Escapes all chars that D-Bus' object path cannot deal
1517 * with. Can be reverse with bus_path_unescape() */
1519 if (!(r = new(char, strlen(s)*3+1)))
1522 for (f = s, t = r; *f; f++) {
1524 if (!(*f >= 'A' && *f <= 'Z') &&
1525 !(*f >= 'a' && *f <= 'z') &&
1526 !(*f >= '0' && *f <= '9')) {
1528 *(t++) = hexchar(*f >> 4);
1529 *(t++) = hexchar(*f);
1539 char *bus_path_unescape(const char *f) {
1544 if (!(r = strdup(f)))
1547 for (t = r; *f; f++) {
1552 if ((a = unhexchar(f[1])) < 0 ||
1553 (b = unhexchar(f[2])) < 0) {
1554 /* Invalid escape code, let's take it literal then */
1557 *(t++) = (char) ((a << 4) | b);
1569 char *path_kill_slashes(char *path) {
1573 /* Removes redundant inner and trailing slashes. Modifies the
1574 * passed string in-place.
1576 * ///foo///bar/ becomes /foo/bar
1579 for (f = path, t = path; *f; f++) {
1594 /* Special rule, if we are talking of the root directory, a
1595 trailing slash is good */
1597 if (t == path && slash)
1604 bool path_startswith(const char *path, const char *prefix) {
1608 if ((path[0] == '/') != (prefix[0] == '/'))
1614 path += strspn(path, "/");
1615 prefix += strspn(prefix, "/");
1623 a = strcspn(path, "/");
1624 b = strcspn(prefix, "/");
1629 if (memcmp(path, prefix, a) != 0)
1637 bool path_equal(const char *a, const char *b) {
1641 if ((a[0] == '/') != (b[0] == '/'))
1647 a += strspn(a, "/");
1648 b += strspn(b, "/");
1650 if (*a == 0 && *b == 0)
1653 if (*a == 0 || *b == 0)
1656 j = strcspn(a, "/");
1657 k = strcspn(b, "/");
1662 if (memcmp(a, b, j) != 0)
1670 char *ascii_strlower(char *t) {
1675 for (p = t; *p; p++)
1676 if (*p >= 'A' && *p <= 'Z')
1677 *p = *p - 'A' + 'a';
1682 bool ignore_file(const char *filename) {
1686 filename[0] == '.' ||
1687 streq(filename, "lost+found") ||
1688 streq(filename, "aquota.user") ||
1689 streq(filename, "aquota.group") ||
1690 endswith(filename, "~") ||
1691 endswith(filename, ".rpmnew") ||
1692 endswith(filename, ".rpmsave") ||
1693 endswith(filename, ".rpmorig") ||
1694 endswith(filename, ".dpkg-old") ||
1695 endswith(filename, ".dpkg-new") ||
1696 endswith(filename, ".swp");
1699 int fd_nonblock(int fd, bool nonblock) {
1704 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1708 flags |= O_NONBLOCK;
1710 flags &= ~O_NONBLOCK;
1712 if (fcntl(fd, F_SETFL, flags) < 0)
1718 int fd_cloexec(int fd, bool cloexec) {
1723 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1727 flags |= FD_CLOEXEC;
1729 flags &= ~FD_CLOEXEC;
1731 if (fcntl(fd, F_SETFD, flags) < 0)
1737 int close_all_fds(const int except[], unsigned n_except) {
1742 if (!(d = opendir("/proc/self/fd")))
1745 while ((de = readdir(d))) {
1748 if (ignore_file(de->d_name))
1751 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1765 for (i = 0; i < n_except; i++)
1766 if (except[i] == fd) {
1775 if ((r = close_nointr(fd)) < 0) {
1776 /* Valgrind has its own FD and doesn't want to have it closed */
1789 bool chars_intersect(const char *a, const char *b) {
1792 /* Returns true if any of the chars in a are in b. */
1793 for (p = a; *p; p++)
1800 char *format_timestamp(char *buf, size_t l, usec_t t) {
1810 sec = (time_t) (t / USEC_PER_SEC);
1812 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1818 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1821 n = now(CLOCK_REALTIME);
1823 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1828 if (d >= USEC_PER_YEAR)
1829 snprintf(buf, l, "%llu years and %llu months ago",
1830 (unsigned long long) (d / USEC_PER_YEAR),
1831 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1832 else if (d >= USEC_PER_MONTH)
1833 snprintf(buf, l, "%llu months and %llu days ago",
1834 (unsigned long long) (d / USEC_PER_MONTH),
1835 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1836 else if (d >= USEC_PER_WEEK)
1837 snprintf(buf, l, "%llu weeks and %llu days ago",
1838 (unsigned long long) (d / USEC_PER_WEEK),
1839 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1840 else if (d >= 2*USEC_PER_DAY)
1841 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1842 else if (d >= 25*USEC_PER_HOUR)
1843 snprintf(buf, l, "1 day and %lluh ago",
1844 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1845 else if (d >= 6*USEC_PER_HOUR)
1846 snprintf(buf, l, "%lluh ago",
1847 (unsigned long long) (d / USEC_PER_HOUR));
1848 else if (d >= USEC_PER_HOUR)
1849 snprintf(buf, l, "%lluh %llumin ago",
1850 (unsigned long long) (d / USEC_PER_HOUR),
1851 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1852 else if (d >= 5*USEC_PER_MINUTE)
1853 snprintf(buf, l, "%llumin ago",
1854 (unsigned long long) (d / USEC_PER_MINUTE));
1855 else if (d >= USEC_PER_MINUTE)
1856 snprintf(buf, l, "%llumin %llus ago",
1857 (unsigned long long) (d / USEC_PER_MINUTE),
1858 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1859 else if (d >= USEC_PER_SEC)
1860 snprintf(buf, l, "%llus ago",
1861 (unsigned long long) (d / USEC_PER_SEC));
1862 else if (d >= USEC_PER_MSEC)
1863 snprintf(buf, l, "%llums ago",
1864 (unsigned long long) (d / USEC_PER_MSEC));
1866 snprintf(buf, l, "%lluus ago",
1867 (unsigned long long) d);
1869 snprintf(buf, l, "now");
1875 char *format_timespan(char *buf, size_t l, usec_t t) {
1876 static const struct {
1880 { "w", USEC_PER_WEEK },
1881 { "d", USEC_PER_DAY },
1882 { "h", USEC_PER_HOUR },
1883 { "min", USEC_PER_MINUTE },
1884 { "s", USEC_PER_SEC },
1885 { "ms", USEC_PER_MSEC },
1895 if (t == (usec_t) -1)
1899 snprintf(p, l, "0");
1904 /* The result of this function can be parsed with parse_usec */
1906 for (i = 0; i < ELEMENTSOF(table); i++) {
1910 if (t < table[i].usec)
1916 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1917 n = MIN((size_t) k, l);
1930 bool fstype_is_network(const char *fstype) {
1931 static const char * const table[] = {
1943 for (i = 0; i < ELEMENTSOF(table); i++)
1944 if (streq(table[i], fstype))
1953 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1958 TIOCL_GETKMSGREDIRECT,
1962 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1965 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1968 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1971 close_nointr_nofail(r);
1975 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1976 struct termios old_termios, new_termios;
1983 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1984 new_termios = old_termios;
1986 new_termios.c_lflag &= ~ICANON;
1987 new_termios.c_cc[VMIN] = 1;
1988 new_termios.c_cc[VTIME] = 0;
1990 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1993 k = fread(&c, 1, 1, f);
1995 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2001 *need_nl = c != '\n';
2008 if (!(fgets(line, sizeof(line), f)))
2013 if (strlen(line) != 1)
2023 int ask(char *ret, const char *replies, const char *text, ...) {
2030 on_tty = isatty(STDOUT_FILENO);
2036 bool need_nl = true;
2039 fputs("\x1B[1m", stdout);
2046 fputs("\x1B[0m", stdout);
2050 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2052 if (r == -EBADMSG) {
2053 puts("Bad input, please try again.");
2064 if (strchr(replies, c)) {
2069 puts("Read unexpected character, please try again.");
2073 int reset_terminal(int fd) {
2074 struct termios termios;
2078 /* Set terminal to some sane defaults */
2082 /* We leave locked terminal attributes untouched, so that
2083 * Plymouth may set whatever it wants to set, and we don't
2084 * interfere with that. */
2086 /* Disable exclusive mode, just in case */
2087 ioctl(fd, TIOCNXCL);
2089 /* Enable console unicode mode */
2091 ioctl(fd, KDSKBMODE, &arg);
2093 if (tcgetattr(fd, &termios) < 0) {
2098 /* We only reset the stuff that matters to the software. How
2099 * hardware is set up we don't touch assuming that somebody
2100 * else will do that for us */
2102 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2103 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2104 termios.c_oflag |= ONLCR;
2105 termios.c_cflag |= CREAD;
2106 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2108 termios.c_cc[VINTR] = 03; /* ^C */
2109 termios.c_cc[VQUIT] = 034; /* ^\ */
2110 termios.c_cc[VERASE] = 0177;
2111 termios.c_cc[VKILL] = 025; /* ^X */
2112 termios.c_cc[VEOF] = 04; /* ^D */
2113 termios.c_cc[VSTART] = 021; /* ^Q */
2114 termios.c_cc[VSTOP] = 023; /* ^S */
2115 termios.c_cc[VSUSP] = 032; /* ^Z */
2116 termios.c_cc[VLNEXT] = 026; /* ^V */
2117 termios.c_cc[VWERASE] = 027; /* ^W */
2118 termios.c_cc[VREPRINT] = 022; /* ^R */
2119 termios.c_cc[VEOL] = 0;
2120 termios.c_cc[VEOL2] = 0;
2122 termios.c_cc[VTIME] = 0;
2123 termios.c_cc[VMIN] = 1;
2125 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2129 /* Just in case, flush all crap out */
2130 tcflush(fd, TCIOFLUSH);
2135 int open_terminal(const char *name, int mode) {
2138 if ((fd = open(name, mode)) < 0)
2141 if ((r = isatty(fd)) < 0) {
2142 close_nointr_nofail(fd);
2147 close_nointr_nofail(fd);
2154 int flush_fd(int fd) {
2155 struct pollfd pollfd;
2159 pollfd.events = POLLIN;
2166 if ((r = poll(&pollfd, 1, 0)) < 0) {
2177 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2182 if (errno == EAGAIN)
2193 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2194 int fd = -1, notify = -1, r, wd = -1;
2198 /* We use inotify to be notified when the tty is closed. We
2199 * create the watch before checking if we can actually acquire
2200 * it, so that we don't lose any event.
2202 * Note: strictly speaking this actually watches for the
2203 * device being closed, it does *not* really watch whether a
2204 * tty loses its controlling process. However, unless some
2205 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2206 * its tty otherwise this will not become a problem. As long
2207 * as the administrator makes sure not configure any service
2208 * on the same tty as an untrusted user this should not be a
2209 * problem. (Which he probably should not do anyway.) */
2211 if (!fail && !force) {
2212 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2217 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2225 if ((r = flush_fd(notify)) < 0)
2228 /* We pass here O_NOCTTY only so that we can check the return
2229 * value TIOCSCTTY and have a reliable way to figure out if we
2230 * successfully became the controlling process of the tty */
2231 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2234 /* First, try to get the tty */
2235 r = ioctl(fd, TIOCSCTTY, force);
2237 /* Sometimes it makes sense to ignore TIOCSCTTY
2238 * returning EPERM, i.e. when very likely we already
2239 * are have this controlling terminal. */
2240 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2243 if (r < 0 && (force || fail || errno != EPERM)) {
2253 assert(notify >= 0);
2256 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2258 struct inotify_event *e;
2260 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2269 e = (struct inotify_event*) inotify_buffer;
2274 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2279 step = sizeof(struct inotify_event) + e->len;
2280 assert(step <= (size_t) l);
2282 e = (struct inotify_event*) ((uint8_t*) e + step);
2289 /* We close the tty fd here since if the old session
2290 * ended our handle will be dead. It's important that
2291 * we do this after sleeping, so that we don't enter
2292 * an endless loop. */
2293 close_nointr_nofail(fd);
2297 close_nointr_nofail(notify);
2299 if ((r = reset_terminal(fd)) < 0)
2300 log_warning("Failed to reset terminal: %s", strerror(-r));
2306 close_nointr_nofail(fd);
2309 close_nointr_nofail(notify);
2314 int release_terminal(void) {
2316 struct sigaction sa_old, sa_new;
2318 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2321 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2322 * by our own TIOCNOTTY */
2325 sa_new.sa_handler = SIG_IGN;
2326 sa_new.sa_flags = SA_RESTART;
2327 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2329 if (ioctl(fd, TIOCNOTTY) < 0)
2332 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2334 close_nointr_nofail(fd);
2338 int sigaction_many(const struct sigaction *sa, ...) {
2343 while ((sig = va_arg(ap, int)) > 0)
2344 if (sigaction(sig, sa, NULL) < 0)
2351 int ignore_signals(int sig, ...) {
2352 struct sigaction sa;
2357 sa.sa_handler = SIG_IGN;
2358 sa.sa_flags = SA_RESTART;
2360 if (sigaction(sig, &sa, NULL) < 0)
2364 while ((sig = va_arg(ap, int)) > 0)
2365 if (sigaction(sig, &sa, NULL) < 0)
2372 int default_signals(int sig, ...) {
2373 struct sigaction sa;
2378 sa.sa_handler = SIG_DFL;
2379 sa.sa_flags = SA_RESTART;
2381 if (sigaction(sig, &sa, NULL) < 0)
2385 while ((sig = va_arg(ap, int)) > 0)
2386 if (sigaction(sig, &sa, NULL) < 0)
2393 int close_pipe(int p[]) {
2399 a = close_nointr(p[0]);
2404 b = close_nointr(p[1]);
2408 return a < 0 ? a : b;
2411 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2420 while (nbytes > 0) {
2423 if ((k = read(fd, p, nbytes)) <= 0) {
2425 if (k < 0 && errno == EINTR)
2428 if (k < 0 && errno == EAGAIN && do_poll) {
2429 struct pollfd pollfd;
2433 pollfd.events = POLLIN;
2435 if (poll(&pollfd, 1, -1) < 0) {
2439 return n > 0 ? n : -errno;
2442 if (pollfd.revents != POLLIN)
2443 return n > 0 ? n : -EIO;
2448 return n > 0 ? n : (k < 0 ? -errno : 0);
2459 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2468 while (nbytes > 0) {
2471 if ((k = write(fd, p, nbytes)) <= 0) {
2473 if (k < 0 && errno == EINTR)
2476 if (k < 0 && errno == EAGAIN && do_poll) {
2477 struct pollfd pollfd;
2481 pollfd.events = POLLOUT;
2483 if (poll(&pollfd, 1, -1) < 0) {
2487 return n > 0 ? n : -errno;
2490 if (pollfd.revents != POLLOUT)
2491 return n > 0 ? n : -EIO;
2496 return n > 0 ? n : (k < 0 ? -errno : 0);
2507 int path_is_mount_point(const char *t) {
2512 if (lstat(t, &a) < 0) {
2513 if (errno == ENOENT)
2519 if ((r = parent_of_path(t, &parent)) < 0)
2522 r = lstat(parent, &b);
2528 return a.st_dev != b.st_dev;
2531 int parse_usec(const char *t, usec_t *usec) {
2532 static const struct {
2536 { "sec", USEC_PER_SEC },
2537 { "s", USEC_PER_SEC },
2538 { "min", USEC_PER_MINUTE },
2539 { "hr", USEC_PER_HOUR },
2540 { "h", USEC_PER_HOUR },
2541 { "d", USEC_PER_DAY },
2542 { "w", USEC_PER_WEEK },
2543 { "msec", USEC_PER_MSEC },
2544 { "ms", USEC_PER_MSEC },
2545 { "m", USEC_PER_MINUTE },
2548 { "", USEC_PER_SEC },
2564 l = strtoll(p, &e, 10);
2575 e += strspn(e, WHITESPACE);
2577 for (i = 0; i < ELEMENTSOF(table); i++)
2578 if (startswith(e, table[i].suffix)) {
2579 r += (usec_t) l * table[i].usec;
2580 p = e + strlen(table[i].suffix);
2584 if (i >= ELEMENTSOF(table))
2594 int make_stdio(int fd) {
2599 r = dup2(fd, STDIN_FILENO);
2600 s = dup2(fd, STDOUT_FILENO);
2601 t = dup2(fd, STDERR_FILENO);
2604 close_nointr_nofail(fd);
2606 if (r < 0 || s < 0 || t < 0)
2612 int make_null_stdio(void) {
2615 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2618 return make_stdio(null_fd);
2621 bool is_device_path(const char *path) {
2623 /* Returns true on paths that refer to a device, either in
2624 * sysfs or in /dev */
2627 path_startswith(path, "/dev/") ||
2628 path_startswith(path, "/sys/");
2631 int dir_is_empty(const char *path) {
2634 struct dirent buf, *de;
2636 if (!(d = opendir(path)))
2640 if ((r = readdir_r(d, &buf, &de)) > 0) {
2650 if (!ignore_file(de->d_name)) {
2660 unsigned long long random_ull(void) {
2665 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2668 r = loop_read(fd, &ull, sizeof(ull), true);
2669 close_nointr_nofail(fd);
2671 if (r != sizeof(ull))
2677 return random() * RAND_MAX + random();
2680 void rename_process(const char name[8]) {
2683 prctl(PR_SET_NAME, name);
2685 /* This is a like a poor man's setproctitle(). The string
2686 * passed should fit in 7 chars (i.e. the length of
2689 if (program_invocation_name)
2690 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2693 void sigset_add_many(sigset_t *ss, ...) {
2700 while ((sig = va_arg(ap, int)) > 0)
2701 assert_se(sigaddset(ss, sig) == 0);
2705 char* gethostname_malloc(void) {
2708 assert_se(uname(&u) >= 0);
2711 return strdup(u.nodename);
2713 return strdup(u.sysname);
2716 char* getlogname_malloc(void) {
2720 struct passwd pwbuf, *pw = NULL;
2723 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2728 /* Shortcut things to avoid NSS lookups */
2730 return strdup("root");
2732 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2735 if (!(buf = malloc(bufsize)))
2738 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2739 name = strdup(pw->pw_name);
2746 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2752 int getttyname_malloc(char **r) {
2753 char path[PATH_MAX], *p, *c;
2758 if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2764 if (startswith(path, "/dev/"))
2767 if (!(c = strdup(p)))
2774 static int rm_rf_children(int fd, bool only_dirs) {
2780 /* This returns the first error we run into, but nevertheless
2783 if (!(d = fdopendir(fd))) {
2784 close_nointr_nofail(fd);
2786 return errno == ENOENT ? 0 : -errno;
2790 struct dirent buf, *de;
2794 if ((r = readdir_r(d, &buf, &de)) != 0) {
2803 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2806 if (de->d_type == DT_UNKNOWN) {
2809 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2810 if (ret == 0 && errno != ENOENT)
2815 is_dir = S_ISDIR(st.st_mode);
2817 is_dir = de->d_type == DT_DIR;
2822 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2823 if (ret == 0 && errno != ENOENT)
2828 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2833 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2834 if (ret == 0 && errno != ENOENT)
2837 } else if (!only_dirs) {
2839 if (unlinkat(fd, de->d_name, 0) < 0) {
2840 if (ret == 0 && errno != ENOENT)
2851 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2857 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2859 if (errno != ENOTDIR)
2862 if (delete_root && !only_dirs)
2863 if (unlink(path) < 0)
2869 r = rm_rf_children(fd, only_dirs);
2872 if (rmdir(path) < 0) {
2880 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2883 /* Under the assumption that we are running privileged we
2884 * first change the access mode and only then hand out
2885 * ownership to avoid a window where access is too open. */
2887 if (chmod(path, mode) < 0)
2890 if (chown(path, uid, gid) < 0)
2896 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2900 /* Allocates the cpuset in the right size */
2903 if (!(r = CPU_ALLOC(n)))
2906 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2907 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2917 if (errno != EINVAL)
2924 void status_vprintf(const char *format, va_list ap) {
2930 /* This independent of logging, as status messages are
2931 * optional and go exclusively to the console. */
2933 if (vasprintf(&s, format, ap) < 0)
2936 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2939 write(fd, s, strlen(s));
2945 close_nointr_nofail(fd);
2948 void status_printf(const char *format, ...) {
2953 va_start(ap, format);
2954 status_vprintf(format, ap);
2958 void status_welcome(void) {
2959 char *pretty_name = NULL, *ansi_color = NULL;
2960 const char *const_pretty = NULL, *const_color = NULL;
2963 if ((r = parse_env_file("/etc/os-release", NEWLINE,
2964 "PRETTY_NAME", &pretty_name,
2965 "ANSI_COLOR", &ansi_color,
2969 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2972 #if defined(TARGET_FEDORA)
2974 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
2977 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
2979 truncate_nl(pretty_name);
2982 if (!ansi_color && pretty_name) {
2984 /* This tries to mimic the color magic the old Red Hat sysinit
2987 if (startswith(pretty_name, "Red Hat"))
2988 const_color = "0;31"; /* Red for RHEL */
2989 else if (startswith(pretty_name, "Fedora"))
2990 const_color = "0;34"; /* Blue for Fedora */
2993 #elif defined(TARGET_SUSE)
2996 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
2999 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3001 truncate_nl(pretty_name);
3005 const_color = "0;32"; /* Green for openSUSE */
3007 #elif defined(TARGET_GENTOO)
3010 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3013 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3015 truncate_nl(pretty_name);
3019 const_color = "1;34"; /* Light Blue for Gentoo */
3021 #elif defined(TARGET_ALTLINUX)
3024 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3027 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3029 truncate_nl(pretty_name);
3033 const_color = "0;36"; /* Cyan for ALTLinux */
3036 #elif defined(TARGET_DEBIAN)
3041 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3044 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3046 truncate_nl(version);
3047 pretty_name = strappend("Debian ", version);
3051 log_warning("Failed to allocate Debian version string.");
3056 const_color = "1;31"; /* Light Red for Debian */
3058 #elif defined(TARGET_UBUNTU)
3060 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3061 "DISTRIB_DESCRIPTION", &pretty_name,
3065 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3069 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3073 if (!pretty_name && !const_pretty)
3074 const_pretty = "Linux";
3076 if (!ansi_color && !const_color)
3079 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3080 const_color ? const_color : ansi_color,
3081 const_pretty ? const_pretty : pretty_name);
3087 char *replace_env(const char *format, char **env) {
3094 const char *e, *word = format;
3099 for (e = format; *e; e ++) {
3110 if (!(k = strnappend(r, word, e-word-1)))
3119 } else if (*e == '$') {
3120 if (!(k = strnappend(r, word, e-word)))
3136 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3139 if (!(k = strappend(r, t)))
3152 if (!(k = strnappend(r, word, e-word)))
3163 char **replace_env_argv(char **argv, char **env) {
3165 unsigned k = 0, l = 0;
3167 l = strv_length(argv);
3169 if (!(r = new(char*, l+1)))
3172 STRV_FOREACH(i, argv) {
3174 /* If $FOO appears as single word, replace it by the split up variable */
3175 if ((*i)[0] == '$' && (*i)[1] != '{') {
3180 if ((e = strv_env_get(env, *i+1))) {
3182 if (!(m = strv_split_quoted(e))) {
3193 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3202 memcpy(r + k, m, q * sizeof(char*));
3210 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3211 if (!(r[k++] = replace_env(*i, env))) {
3222 static __thread int parsed_columns = 0;
3225 if (parsed_columns > 0)
3226 return parsed_columns;
3228 if ((e = getenv("COLUMNS")))
3229 parsed_columns = atoi(e);
3231 if (parsed_columns <= 0) {
3235 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3236 parsed_columns = ws.ws_col;
3239 if (parsed_columns <= 0)
3240 parsed_columns = 80;
3242 return parsed_columns;
3245 int running_in_chroot(void) {
3251 /* Only works as root */
3253 if (stat("/proc/1/root", &a) < 0)
3256 if (stat("/", &b) < 0)
3260 a.st_dev != b.st_dev ||
3261 a.st_ino != b.st_ino;
3264 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3269 assert(percent <= 100);
3270 assert(length >= 3);
3274 if (l <= 3 || l <= length)
3277 if (!(r = new0(char, length+1)))
3280 x = (length * percent) / 100;
3290 s + l - (length - x - 3),
3296 int touch(const char *path) {
3301 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3304 close_nointr_nofail(fd);
3308 char *unquote(const char *s, const char* quotes) {
3312 if ((l = strlen(s)) < 2)
3315 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3316 return strndup(s+1, l-2);
3321 char *normalize_env_assignment(const char *s) {
3322 char *name, *value, *p, *r;
3327 if (!(r = strdup(s)))
3333 if (!(name = strndup(s, p - s)))
3336 if (!(p = strdup(p+1))) {
3341 value = unquote(strstrip(p), QUOTES);
3350 if (asprintf(&r, "%s=%s", name, value) < 0)
3359 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3366 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3378 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3385 if ((r = wait_for_terminate(pid, &status)) < 0) {
3386 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3390 if (status.si_code == CLD_EXITED) {
3391 if (status.si_status != 0) {
3392 log_warning("%s failed with error code %i.", name, status.si_status);
3396 log_debug("%s succeeded.", name);
3399 } else if (status.si_code == CLD_KILLED ||
3400 status.si_code == CLD_DUMPED) {
3402 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3406 log_warning("%s failed due to unknown reason.", name);
3418 bool null_or_empty(struct stat *st) {
3421 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3424 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3430 DIR *xopendirat(int fd, const char *name, int flags) {
3434 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3437 if (!(d = fdopendir(nfd))) {
3438 close_nointr_nofail(nfd);
3445 int signal_from_string_try_harder(const char *s) {
3449 if ((signo = signal_from_string(s)) <= 0)
3450 if (startswith(s, "SIG"))
3451 return signal_from_string(s+3);
3456 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3462 if (!dual_timestamp_is_set(t))
3465 fprintf(f, "%s=%llu %llu\n",
3467 (unsigned long long) t->realtime,
3468 (unsigned long long) t->monotonic);
3471 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3472 unsigned long long a, b;
3477 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3478 log_debug("Failed to parse finish timestamp value %s", value);
3485 char *fstab_node_to_udev_node(const char *p) {
3489 /* FIXME: to follow udev's logic 100% we need to leave valid
3490 * UTF8 chars unescaped */
3492 if (startswith(p, "LABEL=")) {
3494 if (!(u = unquote(p+6, "\"\'")))
3497 t = xescape(u, "/ ");
3503 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3512 if (startswith(p, "UUID=")) {
3514 if (!(u = unquote(p+5, "\"\'")))
3517 t = xescape(u, "/ ");
3523 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3535 void filter_environ(const char *prefix) {
3542 for (i = 0, j = 0; environ[i]; i++) {
3544 if (startswith(environ[i], prefix))
3547 environ[j++] = environ[i];
3553 bool tty_is_vc(const char *tty) {
3556 if (startswith(tty, "/dev/"))
3559 return startswith(tty, "tty") &&
3560 tty[3] >= '0' && tty[3] <= '9';
3563 const char *default_term_for_tty(const char *tty) {
3564 char *active = NULL;
3569 if (startswith(tty, "/dev/"))
3572 /* Resolve where /dev/console is pointing when determining
3574 if (streq(tty, "console"))
3575 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3576 truncate_nl(active);
3578 /* If multiple log outputs are configured the
3579 * last one is what /dev/console points to */
3580 if ((tty = strrchr(active, ' ')))
3586 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3592 bool running_in_vm(void) {
3594 #if defined(__i386__) || defined(__x86_64__)
3596 /* Both CPUID and DMI are x86 specific interfaces... */
3598 const char *const dmi_vendors[] = {
3599 "/sys/class/dmi/id/sys_vendor",
3600 "/sys/class/dmi/id/board_vendor",
3601 "/sys/class/dmi/id/bios_vendor"
3604 uint32_t eax = 0x40000000;
3612 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3616 if (read_one_line_file(dmi_vendors[i], &s) < 0)
3619 b = startswith(s, "QEMU") ||
3620 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3621 startswith(s, "VMware") ||
3622 startswith(s, "VMW") ||
3623 startswith(s, "Microsoft Corporation") ||
3624 startswith(s, "innotek GmbH") ||
3625 startswith(s, "Xen");
3633 /* http://lwn.net/Articles/301888/ */
3637 #if defined (__i386__)
3640 #elif defined (__amd64__)
3645 __asm__ __volatile__ (
3646 /* ebx/rbx is being used for PIC! */
3647 " push %%"REG_b" \n\t"
3649 " mov %%ebx, %1 \n\t"
3650 " pop %%"REG_b" \n\t"
3652 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3656 if (streq(sig.text, "XenVMMXenVMM") ||
3657 streq(sig.text, "KVMKVMKVM") ||
3658 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3659 streq(sig.text, "VMwareVMware") ||
3660 /* http://msdn.microsoft.com/en-us/library/bb969719.aspx */
3661 streq(sig.text, "Microsoft Hv"))
3668 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3671 Hashmap *pids = NULL;
3675 /* Executes all binaries in a directory in parallel and waits
3676 * until all they all finished. */
3679 if (!(_d = opendir(directory))) {
3681 if (errno == ENOENT)
3684 log_error("Failed to enumerate directory %s: %m", directory);
3691 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3692 log_error("Failed to allocate set.");
3696 while ((de = readdir(d))) {
3701 if (ignore_file(de->d_name))
3704 if (de->d_type != DT_REG &&
3705 de->d_type != DT_LNK &&
3706 de->d_type != DT_UNKNOWN)
3709 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3710 log_error("Out of memory");
3714 if ((pid = fork()) < 0) {
3715 log_error("Failed to fork: %m");
3734 log_error("Failed to execute %s: %m", path);
3735 _exit(EXIT_FAILURE);
3738 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3740 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3741 log_error("Failed to add PID to set: %s", strerror(-k));
3746 while (!hashmap_isempty(pids)) {
3751 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
3756 log_error("waitid() failed: %m");
3760 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3761 if (!is_clean_exit(si.si_code, si.si_status)) {
3762 if (si.si_code == CLD_EXITED)
3763 log_error("%s exited with exit status %i.", path, si.si_status);
3765 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3767 log_debug("%s exited successfully.", path);
3778 hashmap_free_free(pids);
3781 static const char *const ioprio_class_table[] = {
3782 [IOPRIO_CLASS_NONE] = "none",
3783 [IOPRIO_CLASS_RT] = "realtime",
3784 [IOPRIO_CLASS_BE] = "best-effort",
3785 [IOPRIO_CLASS_IDLE] = "idle"
3788 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3790 static const char *const sigchld_code_table[] = {
3791 [CLD_EXITED] = "exited",
3792 [CLD_KILLED] = "killed",
3793 [CLD_DUMPED] = "dumped",
3794 [CLD_TRAPPED] = "trapped",
3795 [CLD_STOPPED] = "stopped",
3796 [CLD_CONTINUED] = "continued",
3799 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3801 static const char *const log_facility_table[LOG_NFACILITIES] = {
3802 [LOG_FAC(LOG_KERN)] = "kern",
3803 [LOG_FAC(LOG_USER)] = "user",
3804 [LOG_FAC(LOG_MAIL)] = "mail",
3805 [LOG_FAC(LOG_DAEMON)] = "daemon",
3806 [LOG_FAC(LOG_AUTH)] = "auth",
3807 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3808 [LOG_FAC(LOG_LPR)] = "lpr",
3809 [LOG_FAC(LOG_NEWS)] = "news",
3810 [LOG_FAC(LOG_UUCP)] = "uucp",
3811 [LOG_FAC(LOG_CRON)] = "cron",
3812 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3813 [LOG_FAC(LOG_FTP)] = "ftp",
3814 [LOG_FAC(LOG_LOCAL0)] = "local0",
3815 [LOG_FAC(LOG_LOCAL1)] = "local1",
3816 [LOG_FAC(LOG_LOCAL2)] = "local2",
3817 [LOG_FAC(LOG_LOCAL3)] = "local3",
3818 [LOG_FAC(LOG_LOCAL4)] = "local4",
3819 [LOG_FAC(LOG_LOCAL5)] = "local5",
3820 [LOG_FAC(LOG_LOCAL6)] = "local6",
3821 [LOG_FAC(LOG_LOCAL7)] = "local7"
3824 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3826 static const char *const log_level_table[] = {
3827 [LOG_EMERG] = "emerg",
3828 [LOG_ALERT] = "alert",
3829 [LOG_CRIT] = "crit",
3831 [LOG_WARNING] = "warning",
3832 [LOG_NOTICE] = "notice",
3833 [LOG_INFO] = "info",
3834 [LOG_DEBUG] = "debug"
3837 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3839 static const char* const sched_policy_table[] = {
3840 [SCHED_OTHER] = "other",
3841 [SCHED_BATCH] = "batch",
3842 [SCHED_IDLE] = "idle",
3843 [SCHED_FIFO] = "fifo",
3847 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3849 static const char* const rlimit_table[] = {
3850 [RLIMIT_CPU] = "LimitCPU",
3851 [RLIMIT_FSIZE] = "LimitFSIZE",
3852 [RLIMIT_DATA] = "LimitDATA",
3853 [RLIMIT_STACK] = "LimitSTACK",
3854 [RLIMIT_CORE] = "LimitCORE",
3855 [RLIMIT_RSS] = "LimitRSS",
3856 [RLIMIT_NOFILE] = "LimitNOFILE",
3857 [RLIMIT_AS] = "LimitAS",
3858 [RLIMIT_NPROC] = "LimitNPROC",
3859 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3860 [RLIMIT_LOCKS] = "LimitLOCKS",
3861 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3862 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3863 [RLIMIT_NICE] = "LimitNICE",
3864 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3865 [RLIMIT_RTTIME] = "LimitRTTIME"
3868 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3870 static const char* const ip_tos_table[] = {
3871 [IPTOS_LOWDELAY] = "low-delay",
3872 [IPTOS_THROUGHPUT] = "throughput",
3873 [IPTOS_RELIABILITY] = "reliability",
3874 [IPTOS_LOWCOST] = "low-cost",
3877 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3879 static const char *const signal_table[] = {
3896 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3907 [SIGVTALRM] = "VTALRM",
3909 [SIGWINCH] = "WINCH",
3915 DEFINE_STRING_TABLE_LOOKUP(signal, int);