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"
63 bool streq_ptr(const char *a, const char *b) {
65 /* Like streq(), but tries to make sense of NULL pointers */
76 usec_t now(clockid_t clock_id) {
79 assert_se(clock_gettime(clock_id, &ts) == 0);
81 return timespec_load(&ts);
84 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
87 ts->realtime = now(CLOCK_REALTIME);
88 ts->monotonic = now(CLOCK_MONOTONIC);
93 usec_t timespec_load(const struct timespec *ts) {
97 (usec_t) ts->tv_sec * USEC_PER_SEC +
98 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
101 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
104 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
105 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
110 usec_t timeval_load(const struct timeval *tv) {
114 (usec_t) tv->tv_sec * USEC_PER_SEC +
115 (usec_t) tv->tv_usec;
118 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
121 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
122 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
127 bool endswith(const char *s, const char *postfix) {
134 pl = strlen(postfix);
142 return memcmp(s + sl - pl, postfix, pl) == 0;
145 bool startswith(const char *s, const char *prefix) {
160 return memcmp(s, prefix, pl) == 0;
163 bool startswith_no_case(const char *s, const char *prefix) {
179 for(i = 0; i < pl; ++i) {
180 if (tolower(s[i]) != tolower(prefix[i]))
187 bool first_word(const char *s, const char *word) {
202 if (memcmp(s, word, wl) != 0)
206 strchr(WHITESPACE, s[wl]);
209 int close_nointr(int fd) {
215 if ((r = close(fd)) >= 0)
223 void close_nointr_nofail(int fd) {
224 int saved_errno = errno;
226 /* like close_nointr() but cannot fail, and guarantees errno
229 assert_se(close_nointr(fd) == 0);
234 void close_many(const int fds[], unsigned n_fd) {
237 for (i = 0; i < n_fd; i++)
238 close_nointr_nofail(fds[i]);
241 int parse_boolean(const char *v) {
244 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
246 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
252 int parse_pid(const char *s, pid_t* ret_pid) {
253 unsigned long ul = 0;
260 if ((r = safe_atolu(s, &ul)) < 0)
265 if ((unsigned long) pid != ul)
275 int safe_atou(const char *s, unsigned *ret_u) {
283 l = strtoul(s, &x, 0);
285 if (!x || *x || errno)
286 return errno ? -errno : -EINVAL;
288 if ((unsigned long) (unsigned) l != l)
291 *ret_u = (unsigned) l;
295 int safe_atoi(const char *s, int *ret_i) {
303 l = strtol(s, &x, 0);
305 if (!x || *x || errno)
306 return errno ? -errno : -EINVAL;
308 if ((long) (int) l != l)
315 int safe_atollu(const char *s, long long unsigned *ret_llu) {
317 unsigned long long l;
323 l = strtoull(s, &x, 0);
325 if (!x || *x || errno)
326 return errno ? -errno : -EINVAL;
332 int safe_atolli(const char *s, long long int *ret_lli) {
340 l = strtoll(s, &x, 0);
342 if (!x || *x || errno)
343 return errno ? -errno : -EINVAL;
349 /* Split a string into words. */
350 char *split(const char *c, size_t *l, const char *separator, char **state) {
353 current = *state ? *state : (char*) c;
355 if (!*current || *c == 0)
358 current += strspn(current, separator);
359 *l = strcspn(current, separator);
362 return (char*) current;
365 /* Split a string into words, but consider strings enclosed in '' and
366 * "" as words even if they include spaces. */
367 char *split_quoted(const char *c, size_t *l, char **state) {
369 bool escaped = false;
371 current = *state ? *state : (char*) c;
373 if (!*current || *c == 0)
376 current += strspn(current, WHITESPACE);
378 if (*current == '\'') {
381 for (e = current; *e; e++) {
391 *state = *e == 0 ? e : e+1;
392 } else if (*current == '\"') {
395 for (e = current; *e; e++) {
405 *state = *e == 0 ? e : e+1;
407 for (e = current; *e; e++) {
412 else if (strchr(WHITESPACE, *e))
419 return (char*) current;
422 char **split_path_and_make_absolute(const char *p) {
426 if (!(l = strv_split(p, ":")))
429 if (!strv_path_make_absolute_cwd(l)) {
437 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
440 char fn[132], line[256], *p;
446 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
447 fn[sizeof(fn)-1] = 0;
449 if (!(f = fopen(fn, "r")))
452 if (!(fgets(line, sizeof(line), f))) {
460 /* Let's skip the pid and comm fields. The latter is enclosed
461 * in () but does not escape any () in its value, so let's
462 * skip over it manually */
464 if (!(p = strrchr(line, ')')))
475 if ((long unsigned) (pid_t) ppid != ppid)
478 *_ppid = (pid_t) ppid;
483 int write_one_line_file(const char *fn, const char *line) {
490 if (!(f = fopen(fn, "we")))
493 if (fputs(line, f) < 0) {
498 if (!endswith(line, "\n"))
507 int read_one_line_file(const char *fn, char **line) {
510 char t[LINE_MAX], *c;
515 if (!(f = fopen(fn, "re")))
518 if (!(fgets(t, sizeof(t), f))) {
523 if (!(c = strdup(t))) {
536 int read_full_file(const char *fn, char **contents) {
543 if (!(f = fopen(fn, "re")))
546 if (fstat(fileno(f), &st) < 0) {
551 n = st.st_size > 0 ? st.st_size : LINE_MAX;
558 if (!(t = realloc(buf, n+1))) {
564 k = fread(buf + l, 1, n - l, f);
579 if (n > 4*1024*1024) {
587 else if (!(buf = calloc(1, 1))) {
606 const char *separator, ...) {
614 if ((r = read_full_file(fname, &contents)) < 0)
619 const char *key = NULL;
621 p += strspn(p, separator);
622 p += strspn(p, WHITESPACE);
627 if (!strchr(COMMENTS, *p)) {
631 va_start(ap, separator);
632 while ((key = va_arg(ap, char *))) {
636 value = va_arg(ap, char **);
639 if (strncmp(p, key, n) != 0 ||
644 n = strcspn(p, separator);
647 strchr(QUOTES, p[0]) &&
649 v = strndup(p+1, n-2);
660 /* return empty value strings as NULL */
677 p += strcspn(p, separator);
685 char *truncate_nl(char *s) {
688 s[strcspn(s, NEWLINE)] = 0;
692 int get_process_name(pid_t pid, char **name) {
699 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
702 r = read_one_line_file(p, name);
712 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
720 assert(max_length > 0);
723 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
732 if (!(r = new(char, max_length))) {
739 while ((c = getc(f)) != EOF) {
761 size_t n = MIN(left-1, 3U);
769 /* Kernel threads have no argv[] */
776 if ((h = get_process_name(pid, &t)) < 0)
779 h = asprintf(&r, "[%s]", t);
790 char *strnappend(const char *s, const char *suffix, size_t b) {
798 return strndup(suffix, b);
808 if (!(r = new(char, a+b+1)))
812 memcpy(r+a, suffix, b);
818 char *strappend(const char *s, const char *suffix) {
819 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
822 int readlink_malloc(const char *p, char **r) {
832 if (!(c = new(char, l)))
835 if ((n = readlink(p, c, l-1)) < 0) {
841 if ((size_t) n < l-1) {
852 int readlink_and_make_absolute(const char *p, char **r) {
859 if ((j = readlink_malloc(p, &target)) < 0)
862 k = file_in_same_dir(p, target);
872 int parent_of_path(const char *path, char **_r) {
873 const char *e, *a = NULL, *b = NULL, *p;
883 for (e = path; *e; e++) {
885 if (!slash && *e == '/') {
889 } else if (slash && *e != '/')
904 r = strndup(path, p-path);
914 char *file_name_from_path(const char *p) {
919 if ((r = strrchr(p, '/')))
925 bool path_is_absolute(const char *p) {
931 bool is_path(const char *p) {
933 return !!strchr(p, '/');
936 char *path_make_absolute(const char *p, const char *prefix) {
941 /* Makes every item in the list an absolute path by prepending
942 * the prefix, if specified and necessary */
944 if (path_is_absolute(p) || !prefix)
947 if (asprintf(&r, "%s/%s", prefix, p) < 0)
953 char *path_make_absolute_cwd(const char *p) {
958 /* Similar to path_make_absolute(), but prefixes with the
959 * current working directory. */
961 if (path_is_absolute(p))
964 if (!(cwd = get_current_dir_name()))
967 r = path_make_absolute(p, cwd);
973 char **strv_path_make_absolute_cwd(char **l) {
976 /* Goes through every item in the string list and makes it
977 * absolute. This works in place and won't rollback any
978 * changes on failure. */
983 if (!(t = path_make_absolute_cwd(*s)))
993 char **strv_path_canonicalize(char **l) {
1001 /* Goes through every item in the string list and canonicalize
1002 * the path. This works in place and won't rollback any
1003 * changes on failure. */
1005 STRV_FOREACH(s, l) {
1008 t = path_make_absolute_cwd(*s);
1017 u = canonicalize_file_name(t);
1021 if (errno == ENOMEM || !errno)
1038 int reset_all_signal_handlers(void) {
1041 for (sig = 1; sig < _NSIG; sig++) {
1042 struct sigaction sa;
1044 if (sig == SIGKILL || sig == SIGSTOP)
1048 sa.sa_handler = SIG_DFL;
1049 sa.sa_flags = SA_RESTART;
1051 /* On Linux the first two RT signals are reserved by
1052 * glibc, and sigaction() will return EINVAL for them. */
1053 if ((sigaction(sig, &sa, NULL) < 0))
1054 if (errno != EINVAL)
1061 char *strstrip(char *s) {
1064 /* Drops trailing whitespace. Modifies the string in
1065 * place. Returns pointer to first non-space character */
1067 s += strspn(s, WHITESPACE);
1069 for (e = s; *e; e++)
1070 if (!strchr(WHITESPACE, *e))
1081 char *delete_chars(char *s, const char *bad) {
1084 /* Drops all whitespace, regardless where in the string */
1086 for (f = s, t = s; *f; f++) {
1087 if (strchr(bad, *f))
1098 char *file_in_same_dir(const char *path, const char *filename) {
1105 /* This removes the last component of path and appends
1106 * filename, unless the latter is absolute anyway or the
1109 if (path_is_absolute(filename))
1110 return strdup(filename);
1112 if (!(e = strrchr(path, '/')))
1113 return strdup(filename);
1115 k = strlen(filename);
1116 if (!(r = new(char, e-path+1+k+1)))
1119 memcpy(r, path, e-path+1);
1120 memcpy(r+(e-path)+1, filename, k+1);
1125 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1128 if (label_mkdir(path, mode) >= 0)
1129 if (chmod_and_chown(path, mode, uid, gid) < 0)
1132 if (lstat(path, &st) < 0)
1135 if ((st.st_mode & 0777) != mode ||
1138 !S_ISDIR(st.st_mode)) {
1147 int mkdir_parents(const char *path, mode_t mode) {
1152 /* Creates every parent directory in the path except the last
1155 p = path + strspn(path, "/");
1160 e = p + strcspn(p, "/");
1161 p = e + strspn(e, "/");
1163 /* Is this the last component? If so, then we're
1168 if (!(t = strndup(path, e - path)))
1171 r = label_mkdir(t, mode);
1174 if (r < 0 && errno != EEXIST)
1179 int mkdir_p(const char *path, mode_t mode) {
1184 if ((r = mkdir_parents(path, mode)) < 0)
1187 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1193 int rmdir_parents(const char *path, const char *stop) {
1202 /* Skip trailing slashes */
1203 while (l > 0 && path[l-1] == '/')
1209 /* Skip last component */
1210 while (l > 0 && path[l-1] != '/')
1213 /* Skip trailing slashes */
1214 while (l > 0 && path[l-1] == '/')
1220 if (!(t = strndup(path, l)))
1223 if (path_startswith(stop, t)) {
1232 if (errno != ENOENT)
1240 char hexchar(int x) {
1241 static const char table[16] = "0123456789abcdef";
1243 return table[x & 15];
1246 int unhexchar(char c) {
1248 if (c >= '0' && c <= '9')
1251 if (c >= 'a' && c <= 'f')
1252 return c - 'a' + 10;
1254 if (c >= 'A' && c <= 'F')
1255 return c - 'A' + 10;
1260 char octchar(int x) {
1261 return '0' + (x & 7);
1264 int unoctchar(char c) {
1266 if (c >= '0' && c <= '7')
1272 char decchar(int x) {
1273 return '0' + (x % 10);
1276 int undecchar(char c) {
1278 if (c >= '0' && c <= '9')
1284 char *cescape(const char *s) {
1290 /* Does C style string escaping. */
1292 if (!(r = new(char, strlen(s)*4 + 1)))
1295 for (f = s, t = r; *f; f++)
1341 /* For special chars we prefer octal over
1342 * hexadecimal encoding, simply because glib's
1343 * g_strescape() does the same */
1344 if ((*f < ' ') || (*f >= 127)) {
1346 *(t++) = octchar((unsigned char) *f >> 6);
1347 *(t++) = octchar((unsigned char) *f >> 3);
1348 *(t++) = octchar((unsigned char) *f);
1359 char *cunescape_length(const char *s, size_t length) {
1365 /* Undoes C style string escaping */
1367 if (!(r = new(char, length+1)))
1370 for (f = s, t = r; f < s + length; f++) {
1413 /* This is an extension of the XDG syntax files */
1418 /* hexadecimal encoding */
1421 if ((a = unhexchar(f[1])) < 0 ||
1422 (b = unhexchar(f[2])) < 0) {
1423 /* Invalid escape code, let's take it literal then */
1427 *(t++) = (char) ((a << 4) | b);
1442 /* octal encoding */
1445 if ((a = unoctchar(f[0])) < 0 ||
1446 (b = unoctchar(f[1])) < 0 ||
1447 (c = unoctchar(f[2])) < 0) {
1448 /* Invalid escape code, let's take it literal then */
1452 *(t++) = (char) ((a << 6) | (b << 3) | c);
1460 /* premature end of string.*/
1465 /* Invalid escape code, let's take it literal then */
1477 char *cunescape(const char *s) {
1478 return cunescape_length(s, strlen(s));
1481 char *xescape(const char *s, const char *bad) {
1485 /* Escapes all chars in bad, in addition to \ and all special
1486 * chars, in \xFF style escaping. May be reversed with
1489 if (!(r = new(char, strlen(s)*4+1)))
1492 for (f = s, t = r; *f; f++) {
1494 if ((*f < ' ') || (*f >= 127) ||
1495 (*f == '\\') || strchr(bad, *f)) {
1498 *(t++) = hexchar(*f >> 4);
1499 *(t++) = hexchar(*f);
1509 char *bus_path_escape(const char *s) {
1515 /* Escapes all chars that D-Bus' object path cannot deal
1516 * with. Can be reverse with bus_path_unescape() */
1518 if (!(r = new(char, strlen(s)*3+1)))
1521 for (f = s, t = r; *f; f++) {
1523 if (!(*f >= 'A' && *f <= 'Z') &&
1524 !(*f >= 'a' && *f <= 'z') &&
1525 !(*f >= '0' && *f <= '9')) {
1527 *(t++) = hexchar(*f >> 4);
1528 *(t++) = hexchar(*f);
1538 char *bus_path_unescape(const char *f) {
1543 if (!(r = strdup(f)))
1546 for (t = r; *f; f++) {
1551 if ((a = unhexchar(f[1])) < 0 ||
1552 (b = unhexchar(f[2])) < 0) {
1553 /* Invalid escape code, let's take it literal then */
1556 *(t++) = (char) ((a << 4) | b);
1568 char *path_kill_slashes(char *path) {
1572 /* Removes redundant inner and trailing slashes. Modifies the
1573 * passed string in-place.
1575 * ///foo///bar/ becomes /foo/bar
1578 for (f = path, t = path; *f; f++) {
1593 /* Special rule, if we are talking of the root directory, a
1594 trailing slash is good */
1596 if (t == path && slash)
1603 bool path_startswith(const char *path, const char *prefix) {
1607 if ((path[0] == '/') != (prefix[0] == '/'))
1613 path += strspn(path, "/");
1614 prefix += strspn(prefix, "/");
1622 a = strcspn(path, "/");
1623 b = strcspn(prefix, "/");
1628 if (memcmp(path, prefix, a) != 0)
1636 bool path_equal(const char *a, const char *b) {
1640 if ((a[0] == '/') != (b[0] == '/'))
1646 a += strspn(a, "/");
1647 b += strspn(b, "/");
1649 if (*a == 0 && *b == 0)
1652 if (*a == 0 || *b == 0)
1655 j = strcspn(a, "/");
1656 k = strcspn(b, "/");
1661 if (memcmp(a, b, j) != 0)
1669 char *ascii_strlower(char *t) {
1674 for (p = t; *p; p++)
1675 if (*p >= 'A' && *p <= 'Z')
1676 *p = *p - 'A' + 'a';
1681 bool ignore_file(const char *filename) {
1685 filename[0] == '.' ||
1686 streq(filename, "lost+found") ||
1687 streq(filename, "aquota.user") ||
1688 streq(filename, "aquota.group") ||
1689 endswith(filename, "~") ||
1690 endswith(filename, ".rpmnew") ||
1691 endswith(filename, ".rpmsave") ||
1692 endswith(filename, ".rpmorig") ||
1693 endswith(filename, ".dpkg-old") ||
1694 endswith(filename, ".dpkg-new") ||
1695 endswith(filename, ".swp");
1698 int fd_nonblock(int fd, bool nonblock) {
1703 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1707 flags |= O_NONBLOCK;
1709 flags &= ~O_NONBLOCK;
1711 if (fcntl(fd, F_SETFL, flags) < 0)
1717 int fd_cloexec(int fd, bool cloexec) {
1722 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1726 flags |= FD_CLOEXEC;
1728 flags &= ~FD_CLOEXEC;
1730 if (fcntl(fd, F_SETFD, flags) < 0)
1736 int close_all_fds(const int except[], unsigned n_except) {
1741 if (!(d = opendir("/proc/self/fd")))
1744 while ((de = readdir(d))) {
1747 if (ignore_file(de->d_name))
1750 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1764 for (i = 0; i < n_except; i++)
1765 if (except[i] == fd) {
1774 if ((r = close_nointr(fd)) < 0) {
1775 /* Valgrind has its own FD and doesn't want to have it closed */
1788 bool chars_intersect(const char *a, const char *b) {
1791 /* Returns true if any of the chars in a are in b. */
1792 for (p = a; *p; p++)
1799 char *format_timestamp(char *buf, size_t l, usec_t t) {
1809 sec = (time_t) (t / USEC_PER_SEC);
1811 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1817 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1820 n = now(CLOCK_REALTIME);
1822 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1827 if (d >= USEC_PER_YEAR)
1828 snprintf(buf, l, "%llu years and %llu months ago",
1829 (unsigned long long) (d / USEC_PER_YEAR),
1830 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1831 else if (d >= USEC_PER_MONTH)
1832 snprintf(buf, l, "%llu months and %llu days ago",
1833 (unsigned long long) (d / USEC_PER_MONTH),
1834 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1835 else if (d >= USEC_PER_WEEK)
1836 snprintf(buf, l, "%llu weeks and %llu days ago",
1837 (unsigned long long) (d / USEC_PER_WEEK),
1838 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1839 else if (d >= 2*USEC_PER_DAY)
1840 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1841 else if (d >= 25*USEC_PER_HOUR)
1842 snprintf(buf, l, "1 day and %lluh ago",
1843 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1844 else if (d >= 6*USEC_PER_HOUR)
1845 snprintf(buf, l, "%lluh ago",
1846 (unsigned long long) (d / USEC_PER_HOUR));
1847 else if (d >= USEC_PER_HOUR)
1848 snprintf(buf, l, "%lluh %llumin ago",
1849 (unsigned long long) (d / USEC_PER_HOUR),
1850 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1851 else if (d >= 5*USEC_PER_MINUTE)
1852 snprintf(buf, l, "%llumin ago",
1853 (unsigned long long) (d / USEC_PER_MINUTE));
1854 else if (d >= USEC_PER_MINUTE)
1855 snprintf(buf, l, "%llumin %llus ago",
1856 (unsigned long long) (d / USEC_PER_MINUTE),
1857 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1858 else if (d >= USEC_PER_SEC)
1859 snprintf(buf, l, "%llus ago",
1860 (unsigned long long) (d / USEC_PER_SEC));
1861 else if (d >= USEC_PER_MSEC)
1862 snprintf(buf, l, "%llums ago",
1863 (unsigned long long) (d / USEC_PER_MSEC));
1865 snprintf(buf, l, "%lluus ago",
1866 (unsigned long long) d);
1868 snprintf(buf, l, "now");
1874 char *format_timespan(char *buf, size_t l, usec_t t) {
1875 static const struct {
1879 { "w", USEC_PER_WEEK },
1880 { "d", USEC_PER_DAY },
1881 { "h", USEC_PER_HOUR },
1882 { "min", USEC_PER_MINUTE },
1883 { "s", USEC_PER_SEC },
1884 { "ms", USEC_PER_MSEC },
1894 if (t == (usec_t) -1)
1898 snprintf(p, l, "0");
1903 /* The result of this function can be parsed with parse_usec */
1905 for (i = 0; i < ELEMENTSOF(table); i++) {
1909 if (t < table[i].usec)
1915 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1916 n = MIN((size_t) k, l);
1929 bool fstype_is_network(const char *fstype) {
1930 static const char * const table[] = {
1942 for (i = 0; i < ELEMENTSOF(table); i++)
1943 if (streq(table[i], fstype))
1952 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1957 TIOCL_GETKMSGREDIRECT,
1961 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1964 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1967 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1970 close_nointr_nofail(r);
1974 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1975 struct termios old_termios, new_termios;
1982 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1983 new_termios = old_termios;
1985 new_termios.c_lflag &= ~ICANON;
1986 new_termios.c_cc[VMIN] = 1;
1987 new_termios.c_cc[VTIME] = 0;
1989 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1992 k = fread(&c, 1, 1, f);
1994 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2000 *need_nl = c != '\n';
2007 if (!(fgets(line, sizeof(line), f)))
2012 if (strlen(line) != 1)
2022 int ask(char *ret, const char *replies, const char *text, ...) {
2029 on_tty = isatty(STDOUT_FILENO);
2035 bool need_nl = true;
2038 fputs("\x1B[1m", stdout);
2045 fputs("\x1B[0m", stdout);
2049 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2051 if (r == -EBADMSG) {
2052 puts("Bad input, please try again.");
2063 if (strchr(replies, c)) {
2068 puts("Read unexpected character, please try again.");
2072 int reset_terminal(int fd) {
2073 struct termios termios;
2077 /* Set terminal to some sane defaults */
2081 /* We leave locked terminal attributes untouched, so that
2082 * Plymouth may set whatever it wants to set, and we don't
2083 * interfere with that. */
2085 /* Disable exclusive mode, just in case */
2086 ioctl(fd, TIOCNXCL);
2088 /* Enable console unicode mode */
2090 ioctl(fd, KDSKBMODE, &arg);
2092 if (tcgetattr(fd, &termios) < 0) {
2097 /* We only reset the stuff that matters to the software. How
2098 * hardware is set up we don't touch assuming that somebody
2099 * else will do that for us */
2101 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2102 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2103 termios.c_oflag |= ONLCR;
2104 termios.c_cflag |= CREAD;
2105 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2107 termios.c_cc[VINTR] = 03; /* ^C */
2108 termios.c_cc[VQUIT] = 034; /* ^\ */
2109 termios.c_cc[VERASE] = 0177;
2110 termios.c_cc[VKILL] = 025; /* ^X */
2111 termios.c_cc[VEOF] = 04; /* ^D */
2112 termios.c_cc[VSTART] = 021; /* ^Q */
2113 termios.c_cc[VSTOP] = 023; /* ^S */
2114 termios.c_cc[VSUSP] = 032; /* ^Z */
2115 termios.c_cc[VLNEXT] = 026; /* ^V */
2116 termios.c_cc[VWERASE] = 027; /* ^W */
2117 termios.c_cc[VREPRINT] = 022; /* ^R */
2118 termios.c_cc[VEOL] = 0;
2119 termios.c_cc[VEOL2] = 0;
2121 termios.c_cc[VTIME] = 0;
2122 termios.c_cc[VMIN] = 1;
2124 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2128 /* Just in case, flush all crap out */
2129 tcflush(fd, TCIOFLUSH);
2134 int open_terminal(const char *name, int mode) {
2137 if ((fd = open(name, mode)) < 0)
2140 if ((r = isatty(fd)) < 0) {
2141 close_nointr_nofail(fd);
2146 close_nointr_nofail(fd);
2153 int flush_fd(int fd) {
2154 struct pollfd pollfd;
2158 pollfd.events = POLLIN;
2165 if ((r = poll(&pollfd, 1, 0)) < 0) {
2176 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2181 if (errno == EAGAIN)
2192 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2193 int fd = -1, notify = -1, r, wd = -1;
2197 /* We use inotify to be notified when the tty is closed. We
2198 * create the watch before checking if we can actually acquire
2199 * it, so that we don't lose any event.
2201 * Note: strictly speaking this actually watches for the
2202 * device being closed, it does *not* really watch whether a
2203 * tty loses its controlling process. However, unless some
2204 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2205 * its tty otherwise this will not become a problem. As long
2206 * as the administrator makes sure not configure any service
2207 * on the same tty as an untrusted user this should not be a
2208 * problem. (Which he probably should not do anyway.) */
2210 if (!fail && !force) {
2211 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2216 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2224 if ((r = flush_fd(notify)) < 0)
2227 /* We pass here O_NOCTTY only so that we can check the return
2228 * value TIOCSCTTY and have a reliable way to figure out if we
2229 * successfully became the controlling process of the tty */
2230 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2233 /* First, try to get the tty */
2234 r = ioctl(fd, TIOCSCTTY, force);
2236 /* Sometimes it makes sense to ignore TIOCSCTTY
2237 * returning EPERM, i.e. when very likely we already
2238 * are have this controlling terminal. */
2239 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2242 if (r < 0 && (force || fail || errno != EPERM)) {
2252 assert(notify >= 0);
2255 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2257 struct inotify_event *e;
2259 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2268 e = (struct inotify_event*) inotify_buffer;
2273 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2278 step = sizeof(struct inotify_event) + e->len;
2279 assert(step <= (size_t) l);
2281 e = (struct inotify_event*) ((uint8_t*) e + step);
2288 /* We close the tty fd here since if the old session
2289 * ended our handle will be dead. It's important that
2290 * we do this after sleeping, so that we don't enter
2291 * an endless loop. */
2292 close_nointr_nofail(fd);
2296 close_nointr_nofail(notify);
2298 if ((r = reset_terminal(fd)) < 0)
2299 log_warning("Failed to reset terminal: %s", strerror(-r));
2305 close_nointr_nofail(fd);
2308 close_nointr_nofail(notify);
2313 int release_terminal(void) {
2315 struct sigaction sa_old, sa_new;
2317 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2320 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2321 * by our own TIOCNOTTY */
2324 sa_new.sa_handler = SIG_IGN;
2325 sa_new.sa_flags = SA_RESTART;
2326 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2328 if (ioctl(fd, TIOCNOTTY) < 0)
2331 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2333 close_nointr_nofail(fd);
2337 int sigaction_many(const struct sigaction *sa, ...) {
2342 while ((sig = va_arg(ap, int)) > 0)
2343 if (sigaction(sig, sa, NULL) < 0)
2350 int ignore_signals(int sig, ...) {
2351 struct sigaction sa;
2356 sa.sa_handler = SIG_IGN;
2357 sa.sa_flags = SA_RESTART;
2359 if (sigaction(sig, &sa, NULL) < 0)
2363 while ((sig = va_arg(ap, int)) > 0)
2364 if (sigaction(sig, &sa, NULL) < 0)
2371 int default_signals(int sig, ...) {
2372 struct sigaction sa;
2377 sa.sa_handler = SIG_DFL;
2378 sa.sa_flags = SA_RESTART;
2380 if (sigaction(sig, &sa, NULL) < 0)
2384 while ((sig = va_arg(ap, int)) > 0)
2385 if (sigaction(sig, &sa, NULL) < 0)
2392 int close_pipe(int p[]) {
2398 a = close_nointr(p[0]);
2403 b = close_nointr(p[1]);
2407 return a < 0 ? a : b;
2410 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2419 while (nbytes > 0) {
2422 if ((k = read(fd, p, nbytes)) <= 0) {
2424 if (k < 0 && errno == EINTR)
2427 if (k < 0 && errno == EAGAIN && do_poll) {
2428 struct pollfd pollfd;
2432 pollfd.events = POLLIN;
2434 if (poll(&pollfd, 1, -1) < 0) {
2438 return n > 0 ? n : -errno;
2441 if (pollfd.revents != POLLIN)
2442 return n > 0 ? n : -EIO;
2447 return n > 0 ? n : (k < 0 ? -errno : 0);
2458 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2467 while (nbytes > 0) {
2470 if ((k = write(fd, p, nbytes)) <= 0) {
2472 if (k < 0 && errno == EINTR)
2475 if (k < 0 && errno == EAGAIN && do_poll) {
2476 struct pollfd pollfd;
2480 pollfd.events = POLLOUT;
2482 if (poll(&pollfd, 1, -1) < 0) {
2486 return n > 0 ? n : -errno;
2489 if (pollfd.revents != POLLOUT)
2490 return n > 0 ? n : -EIO;
2495 return n > 0 ? n : (k < 0 ? -errno : 0);
2506 int path_is_mount_point(const char *t) {
2511 if (lstat(t, &a) < 0) {
2512 if (errno == ENOENT)
2518 if ((r = parent_of_path(t, &parent)) < 0)
2521 r = lstat(parent, &b);
2527 return a.st_dev != b.st_dev;
2530 int parse_usec(const char *t, usec_t *usec) {
2531 static const struct {
2535 { "sec", USEC_PER_SEC },
2536 { "s", USEC_PER_SEC },
2537 { "min", USEC_PER_MINUTE },
2538 { "hr", USEC_PER_HOUR },
2539 { "h", USEC_PER_HOUR },
2540 { "d", USEC_PER_DAY },
2541 { "w", USEC_PER_WEEK },
2542 { "msec", USEC_PER_MSEC },
2543 { "ms", USEC_PER_MSEC },
2544 { "m", USEC_PER_MINUTE },
2547 { "", USEC_PER_SEC },
2563 l = strtoll(p, &e, 10);
2574 e += strspn(e, WHITESPACE);
2576 for (i = 0; i < ELEMENTSOF(table); i++)
2577 if (startswith(e, table[i].suffix)) {
2578 r += (usec_t) l * table[i].usec;
2579 p = e + strlen(table[i].suffix);
2583 if (i >= ELEMENTSOF(table))
2593 int make_stdio(int fd) {
2598 r = dup2(fd, STDIN_FILENO);
2599 s = dup2(fd, STDOUT_FILENO);
2600 t = dup2(fd, STDERR_FILENO);
2603 close_nointr_nofail(fd);
2605 if (r < 0 || s < 0 || t < 0)
2611 int make_null_stdio(void) {
2614 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2617 return make_stdio(null_fd);
2620 bool is_device_path(const char *path) {
2622 /* Returns true on paths that refer to a device, either in
2623 * sysfs or in /dev */
2626 path_startswith(path, "/dev/") ||
2627 path_startswith(path, "/sys/");
2630 int dir_is_empty(const char *path) {
2633 struct dirent buf, *de;
2635 if (!(d = opendir(path)))
2639 if ((r = readdir_r(d, &buf, &de)) > 0) {
2649 if (!ignore_file(de->d_name)) {
2659 unsigned long long random_ull(void) {
2664 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2667 r = loop_read(fd, &ull, sizeof(ull), true);
2668 close_nointr_nofail(fd);
2670 if (r != sizeof(ull))
2676 return random() * RAND_MAX + random();
2679 void rename_process(const char name[8]) {
2682 prctl(PR_SET_NAME, name);
2684 /* This is a like a poor man's setproctitle(). The string
2685 * passed should fit in 7 chars (i.e. the length of
2688 if (program_invocation_name)
2689 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2692 void sigset_add_many(sigset_t *ss, ...) {
2699 while ((sig = va_arg(ap, int)) > 0)
2700 assert_se(sigaddset(ss, sig) == 0);
2704 char* gethostname_malloc(void) {
2707 assert_se(uname(&u) >= 0);
2710 return strdup(u.nodename);
2712 return strdup(u.sysname);
2715 char* getlogname_malloc(void) {
2719 struct passwd pwbuf, *pw = NULL;
2722 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2727 /* Shortcut things to avoid NSS lookups */
2729 return strdup("root");
2731 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2734 if (!(buf = malloc(bufsize)))
2737 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2738 name = strdup(pw->pw_name);
2745 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2751 int getttyname_malloc(char **r) {
2752 char path[PATH_MAX], *p, *c;
2757 if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2763 if (startswith(path, "/dev/"))
2766 if (!(c = strdup(p)))
2773 static int rm_rf_children(int fd, bool only_dirs) {
2779 /* This returns the first error we run into, but nevertheless
2782 if (!(d = fdopendir(fd))) {
2783 close_nointr_nofail(fd);
2785 return errno == ENOENT ? 0 : -errno;
2789 struct dirent buf, *de;
2793 if ((r = readdir_r(d, &buf, &de)) != 0) {
2802 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2805 if (de->d_type == DT_UNKNOWN) {
2808 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2809 if (ret == 0 && errno != ENOENT)
2814 is_dir = S_ISDIR(st.st_mode);
2816 is_dir = de->d_type == DT_DIR;
2821 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2822 if (ret == 0 && errno != ENOENT)
2827 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2832 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2833 if (ret == 0 && errno != ENOENT)
2836 } else if (!only_dirs) {
2838 if (unlinkat(fd, de->d_name, 0) < 0) {
2839 if (ret == 0 && errno != ENOENT)
2850 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2856 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2858 if (errno != ENOTDIR)
2861 if (delete_root && !only_dirs)
2862 if (unlink(path) < 0)
2868 r = rm_rf_children(fd, only_dirs);
2871 if (rmdir(path) < 0) {
2879 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2882 /* Under the assumption that we are running privileged we
2883 * first change the access mode and only then hand out
2884 * ownership to avoid a window where access is too open. */
2886 if (chmod(path, mode) < 0)
2889 if (chown(path, uid, gid) < 0)
2895 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2899 /* Allocates the cpuset in the right size */
2902 if (!(r = CPU_ALLOC(n)))
2905 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2906 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2916 if (errno != EINVAL)
2923 void status_vprintf(const char *format, va_list ap) {
2929 /* This independent of logging, as status messages are
2930 * optional and go exclusively to the console. */
2932 if (vasprintf(&s, format, ap) < 0)
2935 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2938 write(fd, s, strlen(s));
2944 close_nointr_nofail(fd);
2947 void status_printf(const char *format, ...) {
2952 va_start(ap, format);
2953 status_vprintf(format, ap);
2957 void status_welcome(void) {
2958 char *pretty_name = NULL, *ansi_color = NULL;
2959 const char *const_pretty = NULL, *const_color = NULL;
2962 if ((r = parse_env_file("/etc/os-release", NEWLINE,
2963 "PRETTY_NAME", &pretty_name,
2964 "ANSI_COLOR", &ansi_color,
2968 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2971 #if defined(TARGET_FEDORA)
2973 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
2976 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
2978 truncate_nl(pretty_name);
2981 if (!ansi_color && pretty_name) {
2983 /* This tries to mimic the color magic the old Red Hat sysinit
2986 if (startswith(pretty_name, "Red Hat"))
2987 const_color = "0;31"; /* Red for RHEL */
2988 else if (startswith(pretty_name, "Fedora"))
2989 const_color = "0;34"; /* Blue for Fedora */
2992 #elif defined(TARGET_SUSE)
2995 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
2998 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3000 truncate_nl(pretty_name);
3004 const_color = "0;32"; /* Green for openSUSE */
3006 #elif defined(TARGET_GENTOO)
3009 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3012 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3014 truncate_nl(pretty_name);
3018 const_color = "1;34"; /* Light Blue for Gentoo */
3020 #elif defined(TARGET_DEBIAN)
3025 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3028 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3030 truncate_nl(version);
3031 pretty_name = strappend("Debian ", version);
3035 log_warning("Failed to allocate Debian version string.");
3040 const_color = "1;31"; /* Light Red for Debian */
3042 #elif defined(TARGET_UBUNTU)
3044 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3045 "DISTRIB_DESCRIPTION", &pretty_name,
3049 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3053 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3057 if (!pretty_name && !const_pretty)
3058 const_pretty = "Linux";
3060 if (!ansi_color && !const_color)
3063 status_printf("Welcome to \x1B[%sm%s\x1B[0m!\n",
3064 const_color ? const_color : ansi_color,
3065 const_pretty ? const_pretty : pretty_name);
3071 char *replace_env(const char *format, char **env) {
3078 const char *e, *word = format;
3083 for (e = format; *e; e ++) {
3094 if (!(k = strnappend(r, word, e-word-1)))
3103 } else if (*e == '$') {
3104 if (!(k = strnappend(r, word, e-word)))
3120 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3123 if (!(k = strappend(r, t)))
3136 if (!(k = strnappend(r, word, e-word)))
3147 char **replace_env_argv(char **argv, char **env) {
3149 unsigned k = 0, l = 0;
3151 l = strv_length(argv);
3153 if (!(r = new(char*, l+1)))
3156 STRV_FOREACH(i, argv) {
3158 /* If $FOO appears as single word, replace it by the split up variable */
3159 if ((*i)[0] == '$' && (*i)[1] != '{') {
3164 if ((e = strv_env_get(env, *i+1))) {
3166 if (!(m = strv_split_quoted(e))) {
3177 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3186 memcpy(r + k, m, q * sizeof(char*));
3194 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3195 if (!(r[k++] = replace_env(*i, env))) {
3206 static __thread int parsed_columns = 0;
3209 if (parsed_columns > 0)
3210 return parsed_columns;
3212 if ((e = getenv("COLUMNS")))
3213 parsed_columns = atoi(e);
3215 if (parsed_columns <= 0) {
3219 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3220 parsed_columns = ws.ws_col;
3223 if (parsed_columns <= 0)
3224 parsed_columns = 80;
3226 return parsed_columns;
3229 int running_in_chroot(void) {
3235 /* Only works as root */
3237 if (stat("/proc/1/root", &a) < 0)
3240 if (stat("/", &b) < 0)
3244 a.st_dev != b.st_dev ||
3245 a.st_ino != b.st_ino;
3248 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3253 assert(percent <= 100);
3254 assert(length >= 3);
3258 if (l <= 3 || l <= length)
3261 if (!(r = new0(char, length+1)))
3264 x = (length * percent) / 100;
3274 s + l - (length - x - 3),
3280 int touch(const char *path) {
3285 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3288 close_nointr_nofail(fd);
3292 char *unquote(const char *s, const char* quotes) {
3296 if ((l = strlen(s)) < 2)
3299 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3300 return strndup(s+1, l-2);
3305 char *normalize_env_assignment(const char *s) {
3306 char *name, *value, *p, *r;
3311 if (!(r = strdup(s)))
3317 if (!(name = strndup(s, p - s)))
3320 if (!(p = strdup(p+1))) {
3325 value = unquote(strstrip(p), QUOTES);
3334 if (asprintf(&r, "%s=%s", name, value) < 0)
3343 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3350 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3362 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3369 if ((r = wait_for_terminate(pid, &status)) < 0) {
3370 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3374 if (status.si_code == CLD_EXITED) {
3375 if (status.si_status != 0) {
3376 log_warning("%s failed with error code %i.", name, status.si_status);
3380 log_debug("%s succeeded.", name);
3383 } else if (status.si_code == CLD_KILLED ||
3384 status.si_code == CLD_DUMPED) {
3386 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3390 log_warning("%s failed due to unknown reason.", name);
3402 bool null_or_empty(struct stat *st) {
3405 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3408 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3414 DIR *xopendirat(int fd, const char *name, int flags) {
3418 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3421 if (!(d = fdopendir(nfd))) {
3422 close_nointr_nofail(nfd);
3429 int signal_from_string_try_harder(const char *s) {
3433 if ((signo = signal_from_string(s)) <= 0)
3434 if (startswith(s, "SIG"))
3435 return signal_from_string(s+3);
3440 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3446 if (!dual_timestamp_is_set(t))
3449 fprintf(f, "%s=%llu %llu\n",
3451 (unsigned long long) t->realtime,
3452 (unsigned long long) t->monotonic);
3455 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3456 unsigned long long a, b;
3461 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3462 log_debug("Failed to parse finish timestamp value %s", value);
3469 char *fstab_node_to_udev_node(const char *p) {
3473 /* FIXME: to follow udev's logic 100% we need to leave valid
3474 * UTF8 chars unescaped */
3476 if (startswith(p, "LABEL=")) {
3478 if (!(u = unquote(p+6, "\"\'")))
3481 t = xescape(u, "/ ");
3487 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3496 if (startswith(p, "UUID=")) {
3498 if (!(u = unquote(p+5, "\"\'")))
3501 t = xescape(u, "/ ");
3507 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3519 void filter_environ(const char *prefix) {
3526 for (i = 0, j = 0; environ[i]; i++) {
3528 if (startswith(environ[i], prefix))
3531 environ[j++] = environ[i];
3537 const char *default_term_for_tty(const char *tty) {
3540 if (startswith(tty, "/dev/"))
3543 if (startswith(tty, "tty") &&
3544 tty[3] >= '0' && tty[3] <= '9')
3545 return "TERM=linux";
3547 /* FIXME: Proper handling of /dev/console would be cool */
3549 return "TERM=vt100";
3552 static const char *const ioprio_class_table[] = {
3553 [IOPRIO_CLASS_NONE] = "none",
3554 [IOPRIO_CLASS_RT] = "realtime",
3555 [IOPRIO_CLASS_BE] = "best-effort",
3556 [IOPRIO_CLASS_IDLE] = "idle"
3559 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3561 static const char *const sigchld_code_table[] = {
3562 [CLD_EXITED] = "exited",
3563 [CLD_KILLED] = "killed",
3564 [CLD_DUMPED] = "dumped",
3565 [CLD_TRAPPED] = "trapped",
3566 [CLD_STOPPED] = "stopped",
3567 [CLD_CONTINUED] = "continued",
3570 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3572 static const char *const log_facility_table[LOG_NFACILITIES] = {
3573 [LOG_FAC(LOG_KERN)] = "kern",
3574 [LOG_FAC(LOG_USER)] = "user",
3575 [LOG_FAC(LOG_MAIL)] = "mail",
3576 [LOG_FAC(LOG_DAEMON)] = "daemon",
3577 [LOG_FAC(LOG_AUTH)] = "auth",
3578 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3579 [LOG_FAC(LOG_LPR)] = "lpr",
3580 [LOG_FAC(LOG_NEWS)] = "news",
3581 [LOG_FAC(LOG_UUCP)] = "uucp",
3582 [LOG_FAC(LOG_CRON)] = "cron",
3583 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3584 [LOG_FAC(LOG_FTP)] = "ftp",
3585 [LOG_FAC(LOG_LOCAL0)] = "local0",
3586 [LOG_FAC(LOG_LOCAL1)] = "local1",
3587 [LOG_FAC(LOG_LOCAL2)] = "local2",
3588 [LOG_FAC(LOG_LOCAL3)] = "local3",
3589 [LOG_FAC(LOG_LOCAL4)] = "local4",
3590 [LOG_FAC(LOG_LOCAL5)] = "local5",
3591 [LOG_FAC(LOG_LOCAL6)] = "local6",
3592 [LOG_FAC(LOG_LOCAL7)] = "local7"
3595 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3597 static const char *const log_level_table[] = {
3598 [LOG_EMERG] = "emerg",
3599 [LOG_ALERT] = "alert",
3600 [LOG_CRIT] = "crit",
3602 [LOG_WARNING] = "warning",
3603 [LOG_NOTICE] = "notice",
3604 [LOG_INFO] = "info",
3605 [LOG_DEBUG] = "debug"
3608 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3610 static const char* const sched_policy_table[] = {
3611 [SCHED_OTHER] = "other",
3612 [SCHED_BATCH] = "batch",
3613 [SCHED_IDLE] = "idle",
3614 [SCHED_FIFO] = "fifo",
3618 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3620 static const char* const rlimit_table[] = {
3621 [RLIMIT_CPU] = "LimitCPU",
3622 [RLIMIT_FSIZE] = "LimitFSIZE",
3623 [RLIMIT_DATA] = "LimitDATA",
3624 [RLIMIT_STACK] = "LimitSTACK",
3625 [RLIMIT_CORE] = "LimitCORE",
3626 [RLIMIT_RSS] = "LimitRSS",
3627 [RLIMIT_NOFILE] = "LimitNOFILE",
3628 [RLIMIT_AS] = "LimitAS",
3629 [RLIMIT_NPROC] = "LimitNPROC",
3630 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3631 [RLIMIT_LOCKS] = "LimitLOCKS",
3632 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3633 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3634 [RLIMIT_NICE] = "LimitNICE",
3635 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3636 [RLIMIT_RTTIME] = "LimitRTTIME"
3639 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3641 static const char* const ip_tos_table[] = {
3642 [IPTOS_LOWDELAY] = "low-delay",
3643 [IPTOS_THROUGHPUT] = "throughput",
3644 [IPTOS_RELIABILITY] = "reliability",
3645 [IPTOS_LOWCOST] = "low-cost",
3648 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3650 static const char *const signal_table[] = {
3667 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3678 [SIGVTALRM] = "VTALRM",
3680 [SIGWINCH] = "WINCH",
3686 DEFINE_STRING_TABLE_LOOKUP(signal, int);