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) {
2140 * If a TTY is in the process of being closed opening it might
2141 * cause EIO. This is horribly awful, but unlikely to be
2142 * changed in the kernel. Hence we work around this problem by
2143 * retrying a couple of times.
2145 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2149 if ((fd = open(name, mode)) >= 0)
2158 usleep(50 * USEC_PER_MSEC);
2165 if ((r = isatty(fd)) < 0) {
2166 close_nointr_nofail(fd);
2171 close_nointr_nofail(fd);
2178 int flush_fd(int fd) {
2179 struct pollfd pollfd;
2183 pollfd.events = POLLIN;
2190 if ((r = poll(&pollfd, 1, 0)) < 0) {
2201 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2206 if (errno == EAGAIN)
2217 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2218 int fd = -1, notify = -1, r, wd = -1;
2222 /* We use inotify to be notified when the tty is closed. We
2223 * create the watch before checking if we can actually acquire
2224 * it, so that we don't lose any event.
2226 * Note: strictly speaking this actually watches for the
2227 * device being closed, it does *not* really watch whether a
2228 * tty loses its controlling process. However, unless some
2229 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2230 * its tty otherwise this will not become a problem. As long
2231 * as the administrator makes sure not configure any service
2232 * on the same tty as an untrusted user this should not be a
2233 * problem. (Which he probably should not do anyway.) */
2235 if (!fail && !force) {
2236 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2241 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2249 if ((r = flush_fd(notify)) < 0)
2252 /* We pass here O_NOCTTY only so that we can check the return
2253 * value TIOCSCTTY and have a reliable way to figure out if we
2254 * successfully became the controlling process of the tty */
2255 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2258 /* First, try to get the tty */
2259 r = ioctl(fd, TIOCSCTTY, force);
2261 /* Sometimes it makes sense to ignore TIOCSCTTY
2262 * returning EPERM, i.e. when very likely we already
2263 * are have this controlling terminal. */
2264 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2267 if (r < 0 && (force || fail || errno != EPERM)) {
2277 assert(notify >= 0);
2280 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2282 struct inotify_event *e;
2284 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2293 e = (struct inotify_event*) inotify_buffer;
2298 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2303 step = sizeof(struct inotify_event) + e->len;
2304 assert(step <= (size_t) l);
2306 e = (struct inotify_event*) ((uint8_t*) e + step);
2313 /* We close the tty fd here since if the old session
2314 * ended our handle will be dead. It's important that
2315 * we do this after sleeping, so that we don't enter
2316 * an endless loop. */
2317 close_nointr_nofail(fd);
2321 close_nointr_nofail(notify);
2323 if ((r = reset_terminal(fd)) < 0)
2324 log_warning("Failed to reset terminal: %s", strerror(-r));
2330 close_nointr_nofail(fd);
2333 close_nointr_nofail(notify);
2338 int release_terminal(void) {
2340 struct sigaction sa_old, sa_new;
2342 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2345 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2346 * by our own TIOCNOTTY */
2349 sa_new.sa_handler = SIG_IGN;
2350 sa_new.sa_flags = SA_RESTART;
2351 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2353 if (ioctl(fd, TIOCNOTTY) < 0)
2356 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2358 close_nointr_nofail(fd);
2362 int sigaction_many(const struct sigaction *sa, ...) {
2367 while ((sig = va_arg(ap, int)) > 0)
2368 if (sigaction(sig, sa, NULL) < 0)
2375 int ignore_signals(int sig, ...) {
2376 struct sigaction sa;
2381 sa.sa_handler = SIG_IGN;
2382 sa.sa_flags = SA_RESTART;
2384 if (sigaction(sig, &sa, NULL) < 0)
2388 while ((sig = va_arg(ap, int)) > 0)
2389 if (sigaction(sig, &sa, NULL) < 0)
2396 int default_signals(int sig, ...) {
2397 struct sigaction sa;
2402 sa.sa_handler = SIG_DFL;
2403 sa.sa_flags = SA_RESTART;
2405 if (sigaction(sig, &sa, NULL) < 0)
2409 while ((sig = va_arg(ap, int)) > 0)
2410 if (sigaction(sig, &sa, NULL) < 0)
2417 int close_pipe(int p[]) {
2423 a = close_nointr(p[0]);
2428 b = close_nointr(p[1]);
2432 return a < 0 ? a : b;
2435 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2444 while (nbytes > 0) {
2447 if ((k = read(fd, p, nbytes)) <= 0) {
2449 if (k < 0 && errno == EINTR)
2452 if (k < 0 && errno == EAGAIN && do_poll) {
2453 struct pollfd pollfd;
2457 pollfd.events = POLLIN;
2459 if (poll(&pollfd, 1, -1) < 0) {
2463 return n > 0 ? n : -errno;
2466 if (pollfd.revents != POLLIN)
2467 return n > 0 ? n : -EIO;
2472 return n > 0 ? n : (k < 0 ? -errno : 0);
2483 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2492 while (nbytes > 0) {
2495 if ((k = write(fd, p, nbytes)) <= 0) {
2497 if (k < 0 && errno == EINTR)
2500 if (k < 0 && errno == EAGAIN && do_poll) {
2501 struct pollfd pollfd;
2505 pollfd.events = POLLOUT;
2507 if (poll(&pollfd, 1, -1) < 0) {
2511 return n > 0 ? n : -errno;
2514 if (pollfd.revents != POLLOUT)
2515 return n > 0 ? n : -EIO;
2520 return n > 0 ? n : (k < 0 ? -errno : 0);
2531 int path_is_mount_point(const char *t) {
2536 if (lstat(t, &a) < 0) {
2537 if (errno == ENOENT)
2543 if ((r = parent_of_path(t, &parent)) < 0)
2546 r = lstat(parent, &b);
2552 return a.st_dev != b.st_dev;
2555 int parse_usec(const char *t, usec_t *usec) {
2556 static const struct {
2560 { "sec", USEC_PER_SEC },
2561 { "s", USEC_PER_SEC },
2562 { "min", USEC_PER_MINUTE },
2563 { "hr", USEC_PER_HOUR },
2564 { "h", USEC_PER_HOUR },
2565 { "d", USEC_PER_DAY },
2566 { "w", USEC_PER_WEEK },
2567 { "msec", USEC_PER_MSEC },
2568 { "ms", USEC_PER_MSEC },
2569 { "m", USEC_PER_MINUTE },
2572 { "", USEC_PER_SEC },
2588 l = strtoll(p, &e, 10);
2599 e += strspn(e, WHITESPACE);
2601 for (i = 0; i < ELEMENTSOF(table); i++)
2602 if (startswith(e, table[i].suffix)) {
2603 r += (usec_t) l * table[i].usec;
2604 p = e + strlen(table[i].suffix);
2608 if (i >= ELEMENTSOF(table))
2618 int make_stdio(int fd) {
2623 r = dup2(fd, STDIN_FILENO);
2624 s = dup2(fd, STDOUT_FILENO);
2625 t = dup2(fd, STDERR_FILENO);
2628 close_nointr_nofail(fd);
2630 if (r < 0 || s < 0 || t < 0)
2636 int make_null_stdio(void) {
2639 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2642 return make_stdio(null_fd);
2645 bool is_device_path(const char *path) {
2647 /* Returns true on paths that refer to a device, either in
2648 * sysfs or in /dev */
2651 path_startswith(path, "/dev/") ||
2652 path_startswith(path, "/sys/");
2655 int dir_is_empty(const char *path) {
2658 struct dirent buf, *de;
2660 if (!(d = opendir(path)))
2664 if ((r = readdir_r(d, &buf, &de)) > 0) {
2674 if (!ignore_file(de->d_name)) {
2684 unsigned long long random_ull(void) {
2689 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2692 r = loop_read(fd, &ull, sizeof(ull), true);
2693 close_nointr_nofail(fd);
2695 if (r != sizeof(ull))
2701 return random() * RAND_MAX + random();
2704 void rename_process(const char name[8]) {
2707 prctl(PR_SET_NAME, name);
2709 /* This is a like a poor man's setproctitle(). The string
2710 * passed should fit in 7 chars (i.e. the length of
2713 if (program_invocation_name)
2714 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2717 void sigset_add_many(sigset_t *ss, ...) {
2724 while ((sig = va_arg(ap, int)) > 0)
2725 assert_se(sigaddset(ss, sig) == 0);
2729 char* gethostname_malloc(void) {
2732 assert_se(uname(&u) >= 0);
2735 return strdup(u.nodename);
2737 return strdup(u.sysname);
2740 char* getlogname_malloc(void) {
2744 struct passwd pwbuf, *pw = NULL;
2747 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2752 /* Shortcut things to avoid NSS lookups */
2754 return strdup("root");
2756 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2759 if (!(buf = malloc(bufsize)))
2762 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2763 name = strdup(pw->pw_name);
2770 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2776 int getttyname_malloc(int fd, char **r) {
2777 char path[PATH_MAX], *c;
2782 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2787 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2794 int getttyname_harder(int fd, char **r) {
2798 if ((k = getttyname_malloc(fd, &s)) < 0)
2801 if (streq(s, "tty")) {
2810 int get_ctty_devnr(dev_t *d) {
2813 unsigned long ttynr;
2816 if (!(f = fopen("/proc/self/stat", "r")))
2819 if (!(fgets(line, sizeof(line), f))) {
2827 if (!(p = strrchr(line, ')')))
2836 "%*d " /* session */
2845 int get_ctty(char **r) {
2847 char fn[128], *s, *b, *p;
2852 if ((k = get_ctty_devnr(&devnr)) < 0)
2855 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2858 if ((k = readlink_malloc(fn, &s)) < 0) {
2863 /* Probably something like the ptys which have no
2864 * symlink in /dev/char. Let's return something
2865 * vaguely useful. */
2867 if (!(b = strdup(fn + 5)))
2874 if (startswith(s, "/dev/"))
2876 else if (startswith(s, "../"))
2891 static int rm_rf_children(int fd, bool only_dirs) {
2897 /* This returns the first error we run into, but nevertheless
2900 if (!(d = fdopendir(fd))) {
2901 close_nointr_nofail(fd);
2903 return errno == ENOENT ? 0 : -errno;
2907 struct dirent buf, *de;
2911 if ((r = readdir_r(d, &buf, &de)) != 0) {
2920 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2923 if (de->d_type == DT_UNKNOWN) {
2926 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2927 if (ret == 0 && errno != ENOENT)
2932 is_dir = S_ISDIR(st.st_mode);
2934 is_dir = de->d_type == DT_DIR;
2939 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2940 if (ret == 0 && errno != ENOENT)
2945 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2950 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2951 if (ret == 0 && errno != ENOENT)
2954 } else if (!only_dirs) {
2956 if (unlinkat(fd, de->d_name, 0) < 0) {
2957 if (ret == 0 && errno != ENOENT)
2968 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2974 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2976 if (errno != ENOTDIR)
2979 if (delete_root && !only_dirs)
2980 if (unlink(path) < 0)
2986 r = rm_rf_children(fd, only_dirs);
2989 if (rmdir(path) < 0) {
2997 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3000 /* Under the assumption that we are running privileged we
3001 * first change the access mode and only then hand out
3002 * ownership to avoid a window where access is too open. */
3004 if (chmod(path, mode) < 0)
3007 if (chown(path, uid, gid) < 0)
3013 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3017 /* Allocates the cpuset in the right size */
3020 if (!(r = CPU_ALLOC(n)))
3023 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3024 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3034 if (errno != EINVAL)
3041 void status_vprintf(const char *format, va_list ap) {
3047 /* This independent of logging, as status messages are
3048 * optional and go exclusively to the console. */
3050 if (vasprintf(&s, format, ap) < 0)
3053 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3056 write(fd, s, strlen(s));
3062 close_nointr_nofail(fd);
3065 void status_printf(const char *format, ...) {
3070 va_start(ap, format);
3071 status_vprintf(format, ap);
3075 void status_welcome(void) {
3076 char *pretty_name = NULL, *ansi_color = NULL;
3077 const char *const_pretty = NULL, *const_color = NULL;
3080 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3081 "PRETTY_NAME", &pretty_name,
3082 "ANSI_COLOR", &ansi_color,
3086 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3089 #if defined(TARGET_FEDORA)
3091 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3094 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3096 truncate_nl(pretty_name);
3099 if (!ansi_color && pretty_name) {
3101 /* This tries to mimic the color magic the old Red Hat sysinit
3104 if (startswith(pretty_name, "Red Hat"))
3105 const_color = "0;31"; /* Red for RHEL */
3106 else if (startswith(pretty_name, "Fedora"))
3107 const_color = "0;34"; /* Blue for Fedora */
3110 #elif defined(TARGET_SUSE)
3113 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3116 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3118 truncate_nl(pretty_name);
3122 const_color = "0;32"; /* Green for openSUSE */
3124 #elif defined(TARGET_GENTOO)
3127 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3130 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3132 truncate_nl(pretty_name);
3136 const_color = "1;34"; /* Light Blue for Gentoo */
3138 #elif defined(TARGET_ALTLINUX)
3141 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3144 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3146 truncate_nl(pretty_name);
3150 const_color = "0;36"; /* Cyan for ALTLinux */
3153 #elif defined(TARGET_DEBIAN)
3158 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3161 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3163 truncate_nl(version);
3164 pretty_name = strappend("Debian ", version);
3168 log_warning("Failed to allocate Debian version string.");
3173 const_color = "1;31"; /* Light Red for Debian */
3175 #elif defined(TARGET_UBUNTU)
3177 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3178 "DISTRIB_DESCRIPTION", &pretty_name,
3182 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3186 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3190 if (!pretty_name && !const_pretty)
3191 const_pretty = "Linux";
3193 if (!ansi_color && !const_color)
3196 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3197 const_color ? const_color : ansi_color,
3198 const_pretty ? const_pretty : pretty_name);
3204 char *replace_env(const char *format, char **env) {
3211 const char *e, *word = format;
3216 for (e = format; *e; e ++) {
3227 if (!(k = strnappend(r, word, e-word-1)))
3236 } else if (*e == '$') {
3237 if (!(k = strnappend(r, word, e-word)))
3253 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3256 if (!(k = strappend(r, t)))
3269 if (!(k = strnappend(r, word, e-word)))
3280 char **replace_env_argv(char **argv, char **env) {
3282 unsigned k = 0, l = 0;
3284 l = strv_length(argv);
3286 if (!(r = new(char*, l+1)))
3289 STRV_FOREACH(i, argv) {
3291 /* If $FOO appears as single word, replace it by the split up variable */
3292 if ((*i)[0] == '$' && (*i)[1] != '{') {
3297 if ((e = strv_env_get(env, *i+1))) {
3299 if (!(m = strv_split_quoted(e))) {
3310 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3319 memcpy(r + k, m, q * sizeof(char*));
3327 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3328 if (!(r[k++] = replace_env(*i, env))) {
3339 static __thread int parsed_columns = 0;
3342 if (parsed_columns > 0)
3343 return parsed_columns;
3345 if ((e = getenv("COLUMNS")))
3346 parsed_columns = atoi(e);
3348 if (parsed_columns <= 0) {
3352 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3353 parsed_columns = ws.ws_col;
3356 if (parsed_columns <= 0)
3357 parsed_columns = 80;
3359 return parsed_columns;
3362 int running_in_chroot(void) {
3368 /* Only works as root */
3370 if (stat("/proc/1/root", &a) < 0)
3373 if (stat("/", &b) < 0)
3377 a.st_dev != b.st_dev ||
3378 a.st_ino != b.st_ino;
3381 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3386 assert(percent <= 100);
3387 assert(length >= 3);
3391 if (l <= 3 || l <= length)
3394 if (!(r = new0(char, length+1)))
3397 x = (length * percent) / 100;
3407 s + l - (length - x - 3),
3413 int touch(const char *path) {
3418 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3421 close_nointr_nofail(fd);
3425 char *unquote(const char *s, const char* quotes) {
3429 if ((l = strlen(s)) < 2)
3432 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3433 return strndup(s+1, l-2);
3438 char *normalize_env_assignment(const char *s) {
3439 char *name, *value, *p, *r;
3444 if (!(r = strdup(s)))
3450 if (!(name = strndup(s, p - s)))
3453 if (!(p = strdup(p+1))) {
3458 value = unquote(strstrip(p), QUOTES);
3467 if (asprintf(&r, "%s=%s", name, value) < 0)
3476 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3483 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3495 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3502 if ((r = wait_for_terminate(pid, &status)) < 0) {
3503 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3507 if (status.si_code == CLD_EXITED) {
3508 if (status.si_status != 0) {
3509 log_warning("%s failed with error code %i.", name, status.si_status);
3513 log_debug("%s succeeded.", name);
3516 } else if (status.si_code == CLD_KILLED ||
3517 status.si_code == CLD_DUMPED) {
3519 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3523 log_warning("%s failed due to unknown reason.", name);
3535 bool null_or_empty(struct stat *st) {
3538 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3541 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3547 DIR *xopendirat(int fd, const char *name, int flags) {
3551 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3554 if (!(d = fdopendir(nfd))) {
3555 close_nointr_nofail(nfd);
3562 int signal_from_string_try_harder(const char *s) {
3566 if ((signo = signal_from_string(s)) <= 0)
3567 if (startswith(s, "SIG"))
3568 return signal_from_string(s+3);
3573 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3579 if (!dual_timestamp_is_set(t))
3582 fprintf(f, "%s=%llu %llu\n",
3584 (unsigned long long) t->realtime,
3585 (unsigned long long) t->monotonic);
3588 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3589 unsigned long long a, b;
3594 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3595 log_debug("Failed to parse finish timestamp value %s", value);
3602 char *fstab_node_to_udev_node(const char *p) {
3606 /* FIXME: to follow udev's logic 100% we need to leave valid
3607 * UTF8 chars unescaped */
3609 if (startswith(p, "LABEL=")) {
3611 if (!(u = unquote(p+6, "\"\'")))
3614 t = xescape(u, "/ ");
3620 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3629 if (startswith(p, "UUID=")) {
3631 if (!(u = unquote(p+5, "\"\'")))
3634 t = xescape(u, "/ ");
3640 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3652 void filter_environ(const char *prefix) {
3659 for (i = 0, j = 0; environ[i]; i++) {
3661 if (startswith(environ[i], prefix))
3664 environ[j++] = environ[i];
3670 bool tty_is_vc(const char *tty) {
3673 if (startswith(tty, "/dev/"))
3676 return startswith(tty, "tty") &&
3677 tty[3] >= '0' && tty[3] <= '9';
3680 const char *default_term_for_tty(const char *tty) {
3681 char *active = NULL;
3686 if (startswith(tty, "/dev/"))
3689 /* Resolve where /dev/console is pointing when determining
3691 if (streq(tty, "console"))
3692 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3693 truncate_nl(active);
3695 /* If multiple log outputs are configured the
3696 * last one is what /dev/console points to */
3697 if ((tty = strrchr(active, ' ')))
3703 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3709 /* Returns a short identifier for the various VM implementations */
3710 int detect_vm(const char **id) {
3712 #if defined(__i386__) || defined(__x86_64__)
3714 /* Both CPUID and DMI are x86 specific interfaces... */
3716 static const char *const dmi_vendors[] = {
3717 "/sys/class/dmi/id/sys_vendor",
3718 "/sys/class/dmi/id/board_vendor",
3719 "/sys/class/dmi/id/bios_vendor"
3722 static const char dmi_vendor_table[] =
3724 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3725 "VMware\0" "vmware\0"
3727 "Microsoft Corporation\0" "microsoft\0"
3728 "innotek GmbH\0" "oracle\0"
3733 static const char cpuid_vendor_table[] =
3734 "XenVMMXenVMM\0" "xen\0"
3735 "KVMKVMKVM\0" "kvm\0"
3736 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3737 "VMwareVMware\0" "vmware\0"
3738 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3739 "Microsoft Hv\0" "microsoft\0"
3751 /* http://lwn.net/Articles/301888/ */
3754 #if defined (__i386__)
3757 #elif defined (__amd64__)
3762 /* First detect whether there is a hypervisor */
3764 __asm__ __volatile__ (
3765 /* ebx/rbx is being used for PIC! */
3766 " push %%"REG_b" \n\t"
3768 " pop %%"REG_b" \n\t"
3770 : "=a" (eax), "=c" (ecx)
3774 hypervisor = !!(ecx & ecx & 0x80000000U);
3778 /* There is a hypervisor, see what it is */
3780 __asm__ __volatile__ (
3781 /* ebx/rbx is being used for PIC! */
3782 " push %%"REG_b" \n\t"
3784 " mov %%ebx, %1 \n\t"
3785 " pop %%"REG_b" \n\t"
3787 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3791 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3792 if (streq(sig.text, j)) {
3801 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3804 const char *found = NULL;
3806 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3813 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3814 if (startswith(s, j))
3837 /* Returns a short identifier for the various VM/container implementations */
3838 int detect_virtualization(const char **id) {
3841 /* Unfortunately most of these operations require root access
3842 * in one way or another */
3846 if ((r = running_in_chroot()) > 0) {
3853 /* /proc/vz exists in container and outside of the container,
3854 * /proc/bc only outside of the container. */
3855 if (access("/proc/vz", F_OK) >= 0 &&
3856 access("/proc/bc", F_OK) < 0) {
3864 return detect_vm(id);
3867 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3870 Hashmap *pids = NULL;
3874 /* Executes all binaries in a directory in parallel and waits
3875 * until all they all finished. */
3878 if (!(_d = opendir(directory))) {
3880 if (errno == ENOENT)
3883 log_error("Failed to enumerate directory %s: %m", directory);
3890 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3891 log_error("Failed to allocate set.");
3895 while ((de = readdir(d))) {
3900 if (ignore_file(de->d_name))
3903 if (de->d_type != DT_REG &&
3904 de->d_type != DT_LNK &&
3905 de->d_type != DT_UNKNOWN)
3908 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3909 log_error("Out of memory");
3913 if ((pid = fork()) < 0) {
3914 log_error("Failed to fork: %m");
3933 log_error("Failed to execute %s: %m", path);
3934 _exit(EXIT_FAILURE);
3937 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3939 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3940 log_error("Failed to add PID to set: %s", strerror(-k));
3945 while (!hashmap_isempty(pids)) {
3950 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
3955 log_error("waitid() failed: %m");
3959 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3960 if (!is_clean_exit(si.si_code, si.si_status)) {
3961 if (si.si_code == CLD_EXITED)
3962 log_error("%s exited with exit status %i.", path, si.si_status);
3964 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3966 log_debug("%s exited successfully.", path);
3977 hashmap_free_free(pids);
3980 static const char *const ioprio_class_table[] = {
3981 [IOPRIO_CLASS_NONE] = "none",
3982 [IOPRIO_CLASS_RT] = "realtime",
3983 [IOPRIO_CLASS_BE] = "best-effort",
3984 [IOPRIO_CLASS_IDLE] = "idle"
3987 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3989 static const char *const sigchld_code_table[] = {
3990 [CLD_EXITED] = "exited",
3991 [CLD_KILLED] = "killed",
3992 [CLD_DUMPED] = "dumped",
3993 [CLD_TRAPPED] = "trapped",
3994 [CLD_STOPPED] = "stopped",
3995 [CLD_CONTINUED] = "continued",
3998 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4000 static const char *const log_facility_table[LOG_NFACILITIES] = {
4001 [LOG_FAC(LOG_KERN)] = "kern",
4002 [LOG_FAC(LOG_USER)] = "user",
4003 [LOG_FAC(LOG_MAIL)] = "mail",
4004 [LOG_FAC(LOG_DAEMON)] = "daemon",
4005 [LOG_FAC(LOG_AUTH)] = "auth",
4006 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4007 [LOG_FAC(LOG_LPR)] = "lpr",
4008 [LOG_FAC(LOG_NEWS)] = "news",
4009 [LOG_FAC(LOG_UUCP)] = "uucp",
4010 [LOG_FAC(LOG_CRON)] = "cron",
4011 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4012 [LOG_FAC(LOG_FTP)] = "ftp",
4013 [LOG_FAC(LOG_LOCAL0)] = "local0",
4014 [LOG_FAC(LOG_LOCAL1)] = "local1",
4015 [LOG_FAC(LOG_LOCAL2)] = "local2",
4016 [LOG_FAC(LOG_LOCAL3)] = "local3",
4017 [LOG_FAC(LOG_LOCAL4)] = "local4",
4018 [LOG_FAC(LOG_LOCAL5)] = "local5",
4019 [LOG_FAC(LOG_LOCAL6)] = "local6",
4020 [LOG_FAC(LOG_LOCAL7)] = "local7"
4023 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
4025 static const char *const log_level_table[] = {
4026 [LOG_EMERG] = "emerg",
4027 [LOG_ALERT] = "alert",
4028 [LOG_CRIT] = "crit",
4030 [LOG_WARNING] = "warning",
4031 [LOG_NOTICE] = "notice",
4032 [LOG_INFO] = "info",
4033 [LOG_DEBUG] = "debug"
4036 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4038 static const char* const sched_policy_table[] = {
4039 [SCHED_OTHER] = "other",
4040 [SCHED_BATCH] = "batch",
4041 [SCHED_IDLE] = "idle",
4042 [SCHED_FIFO] = "fifo",
4046 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4048 static const char* const rlimit_table[] = {
4049 [RLIMIT_CPU] = "LimitCPU",
4050 [RLIMIT_FSIZE] = "LimitFSIZE",
4051 [RLIMIT_DATA] = "LimitDATA",
4052 [RLIMIT_STACK] = "LimitSTACK",
4053 [RLIMIT_CORE] = "LimitCORE",
4054 [RLIMIT_RSS] = "LimitRSS",
4055 [RLIMIT_NOFILE] = "LimitNOFILE",
4056 [RLIMIT_AS] = "LimitAS",
4057 [RLIMIT_NPROC] = "LimitNPROC",
4058 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4059 [RLIMIT_LOCKS] = "LimitLOCKS",
4060 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4061 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4062 [RLIMIT_NICE] = "LimitNICE",
4063 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4064 [RLIMIT_RTTIME] = "LimitRTTIME"
4067 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4069 static const char* const ip_tos_table[] = {
4070 [IPTOS_LOWDELAY] = "low-delay",
4071 [IPTOS_THROUGHPUT] = "throughput",
4072 [IPTOS_RELIABILITY] = "reliability",
4073 [IPTOS_LOWCOST] = "low-cost",
4076 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4078 static const char *const signal_table[] = {
4095 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4106 [SIGVTALRM] = "VTALRM",
4108 [SIGWINCH] = "WINCH",
4114 DEFINE_STRING_TABLE_LOOKUP(signal, int);