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);
697 if (!(f = fopen(fname, "re")))
701 char l[LINE_MAX], *p, *u;
704 if (!fgets(l, sizeof(l), f)) {
717 if (strchr(COMMENTS, *p))
720 if (!(u = normalize_env_assignment(p))) {
721 log_error("Out of memory");
726 t = strv_append(m, u);
730 log_error("Out of memory");
753 char *truncate_nl(char *s) {
756 s[strcspn(s, NEWLINE)] = 0;
760 int get_process_name(pid_t pid, char **name) {
767 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
770 r = read_one_line_file(p, name);
780 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
788 assert(max_length > 0);
791 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
800 if (!(r = new(char, max_length))) {
807 while ((c = getc(f)) != EOF) {
829 size_t n = MIN(left-1, 3U);
837 /* Kernel threads have no argv[] */
844 if ((h = get_process_name(pid, &t)) < 0)
847 h = asprintf(&r, "[%s]", t);
858 char *strnappend(const char *s, const char *suffix, size_t b) {
866 return strndup(suffix, b);
876 if (!(r = new(char, a+b+1)))
880 memcpy(r+a, suffix, b);
886 char *strappend(const char *s, const char *suffix) {
887 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
890 int readlink_malloc(const char *p, char **r) {
900 if (!(c = new(char, l)))
903 if ((n = readlink(p, c, l-1)) < 0) {
909 if ((size_t) n < l-1) {
920 int readlink_and_make_absolute(const char *p, char **r) {
927 if ((j = readlink_malloc(p, &target)) < 0)
930 k = file_in_same_dir(p, target);
940 int parent_of_path(const char *path, char **_r) {
941 const char *e, *a = NULL, *b = NULL, *p;
951 for (e = path; *e; e++) {
953 if (!slash && *e == '/') {
957 } else if (slash && *e != '/')
972 r = strndup(path, p-path);
982 char *file_name_from_path(const char *p) {
987 if ((r = strrchr(p, '/')))
993 bool path_is_absolute(const char *p) {
999 bool is_path(const char *p) {
1001 return !!strchr(p, '/');
1004 char *path_make_absolute(const char *p, const char *prefix) {
1009 /* Makes every item in the list an absolute path by prepending
1010 * the prefix, if specified and necessary */
1012 if (path_is_absolute(p) || !prefix)
1015 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1021 char *path_make_absolute_cwd(const char *p) {
1026 /* Similar to path_make_absolute(), but prefixes with the
1027 * current working directory. */
1029 if (path_is_absolute(p))
1032 if (!(cwd = get_current_dir_name()))
1035 r = path_make_absolute(p, cwd);
1041 char **strv_path_make_absolute_cwd(char **l) {
1044 /* Goes through every item in the string list and makes it
1045 * absolute. This works in place and won't rollback any
1046 * changes on failure. */
1048 STRV_FOREACH(s, l) {
1051 if (!(t = path_make_absolute_cwd(*s)))
1061 char **strv_path_canonicalize(char **l) {
1064 bool enomem = false;
1066 if (strv_isempty(l))
1069 /* Goes through every item in the string list and canonicalize
1070 * the path. This works in place and won't rollback any
1071 * changes on failure. */
1073 STRV_FOREACH(s, l) {
1076 t = path_make_absolute_cwd(*s);
1085 u = canonicalize_file_name(t);
1089 if (errno == ENOMEM || !errno)
1106 int reset_all_signal_handlers(void) {
1109 for (sig = 1; sig < _NSIG; sig++) {
1110 struct sigaction sa;
1112 if (sig == SIGKILL || sig == SIGSTOP)
1116 sa.sa_handler = SIG_DFL;
1117 sa.sa_flags = SA_RESTART;
1119 /* On Linux the first two RT signals are reserved by
1120 * glibc, and sigaction() will return EINVAL for them. */
1121 if ((sigaction(sig, &sa, NULL) < 0))
1122 if (errno != EINVAL)
1129 char *strstrip(char *s) {
1132 /* Drops trailing whitespace. Modifies the string in
1133 * place. Returns pointer to first non-space character */
1135 s += strspn(s, WHITESPACE);
1137 for (e = s; *e; e++)
1138 if (!strchr(WHITESPACE, *e))
1149 char *delete_chars(char *s, const char *bad) {
1152 /* Drops all whitespace, regardless where in the string */
1154 for (f = s, t = s; *f; f++) {
1155 if (strchr(bad, *f))
1166 char *file_in_same_dir(const char *path, const char *filename) {
1173 /* This removes the last component of path and appends
1174 * filename, unless the latter is absolute anyway or the
1177 if (path_is_absolute(filename))
1178 return strdup(filename);
1180 if (!(e = strrchr(path, '/')))
1181 return strdup(filename);
1183 k = strlen(filename);
1184 if (!(r = new(char, e-path+1+k+1)))
1187 memcpy(r, path, e-path+1);
1188 memcpy(r+(e-path)+1, filename, k+1);
1193 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1196 if (label_mkdir(path, mode) >= 0)
1197 if (chmod_and_chown(path, mode, uid, gid) < 0)
1200 if (lstat(path, &st) < 0)
1203 if ((st.st_mode & 0777) != mode ||
1206 !S_ISDIR(st.st_mode)) {
1215 int mkdir_parents(const char *path, mode_t mode) {
1220 /* Creates every parent directory in the path except the last
1223 p = path + strspn(path, "/");
1228 e = p + strcspn(p, "/");
1229 p = e + strspn(e, "/");
1231 /* Is this the last component? If so, then we're
1236 if (!(t = strndup(path, e - path)))
1239 r = label_mkdir(t, mode);
1242 if (r < 0 && errno != EEXIST)
1247 int mkdir_p(const char *path, mode_t mode) {
1252 if ((r = mkdir_parents(path, mode)) < 0)
1255 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1261 int rmdir_parents(const char *path, const char *stop) {
1270 /* Skip trailing slashes */
1271 while (l > 0 && path[l-1] == '/')
1277 /* Skip last component */
1278 while (l > 0 && path[l-1] != '/')
1281 /* Skip trailing slashes */
1282 while (l > 0 && path[l-1] == '/')
1288 if (!(t = strndup(path, l)))
1291 if (path_startswith(stop, t)) {
1300 if (errno != ENOENT)
1308 char hexchar(int x) {
1309 static const char table[16] = "0123456789abcdef";
1311 return table[x & 15];
1314 int unhexchar(char c) {
1316 if (c >= '0' && c <= '9')
1319 if (c >= 'a' && c <= 'f')
1320 return c - 'a' + 10;
1322 if (c >= 'A' && c <= 'F')
1323 return c - 'A' + 10;
1328 char octchar(int x) {
1329 return '0' + (x & 7);
1332 int unoctchar(char c) {
1334 if (c >= '0' && c <= '7')
1340 char decchar(int x) {
1341 return '0' + (x % 10);
1344 int undecchar(char c) {
1346 if (c >= '0' && c <= '9')
1352 char *cescape(const char *s) {
1358 /* Does C style string escaping. */
1360 if (!(r = new(char, strlen(s)*4 + 1)))
1363 for (f = s, t = r; *f; f++)
1409 /* For special chars we prefer octal over
1410 * hexadecimal encoding, simply because glib's
1411 * g_strescape() does the same */
1412 if ((*f < ' ') || (*f >= 127)) {
1414 *(t++) = octchar((unsigned char) *f >> 6);
1415 *(t++) = octchar((unsigned char) *f >> 3);
1416 *(t++) = octchar((unsigned char) *f);
1427 char *cunescape_length(const char *s, size_t length) {
1433 /* Undoes C style string escaping */
1435 if (!(r = new(char, length+1)))
1438 for (f = s, t = r; f < s + length; f++) {
1481 /* This is an extension of the XDG syntax files */
1486 /* hexadecimal encoding */
1489 if ((a = unhexchar(f[1])) < 0 ||
1490 (b = unhexchar(f[2])) < 0) {
1491 /* Invalid escape code, let's take it literal then */
1495 *(t++) = (char) ((a << 4) | b);
1510 /* octal encoding */
1513 if ((a = unoctchar(f[0])) < 0 ||
1514 (b = unoctchar(f[1])) < 0 ||
1515 (c = unoctchar(f[2])) < 0) {
1516 /* Invalid escape code, let's take it literal then */
1520 *(t++) = (char) ((a << 6) | (b << 3) | c);
1528 /* premature end of string.*/
1533 /* Invalid escape code, let's take it literal then */
1545 char *cunescape(const char *s) {
1546 return cunescape_length(s, strlen(s));
1549 char *xescape(const char *s, const char *bad) {
1553 /* Escapes all chars in bad, in addition to \ and all special
1554 * chars, in \xFF style escaping. May be reversed with
1557 if (!(r = new(char, strlen(s)*4+1)))
1560 for (f = s, t = r; *f; f++) {
1562 if ((*f < ' ') || (*f >= 127) ||
1563 (*f == '\\') || strchr(bad, *f)) {
1566 *(t++) = hexchar(*f >> 4);
1567 *(t++) = hexchar(*f);
1577 char *bus_path_escape(const char *s) {
1583 /* Escapes all chars that D-Bus' object path cannot deal
1584 * with. Can be reverse with bus_path_unescape() */
1586 if (!(r = new(char, strlen(s)*3+1)))
1589 for (f = s, t = r; *f; f++) {
1591 if (!(*f >= 'A' && *f <= 'Z') &&
1592 !(*f >= 'a' && *f <= 'z') &&
1593 !(*f >= '0' && *f <= '9')) {
1595 *(t++) = hexchar(*f >> 4);
1596 *(t++) = hexchar(*f);
1606 char *bus_path_unescape(const char *f) {
1611 if (!(r = strdup(f)))
1614 for (t = r; *f; f++) {
1619 if ((a = unhexchar(f[1])) < 0 ||
1620 (b = unhexchar(f[2])) < 0) {
1621 /* Invalid escape code, let's take it literal then */
1624 *(t++) = (char) ((a << 4) | b);
1636 char *path_kill_slashes(char *path) {
1640 /* Removes redundant inner and trailing slashes. Modifies the
1641 * passed string in-place.
1643 * ///foo///bar/ becomes /foo/bar
1646 for (f = path, t = path; *f; f++) {
1661 /* Special rule, if we are talking of the root directory, a
1662 trailing slash is good */
1664 if (t == path && slash)
1671 bool path_startswith(const char *path, const char *prefix) {
1675 if ((path[0] == '/') != (prefix[0] == '/'))
1681 path += strspn(path, "/");
1682 prefix += strspn(prefix, "/");
1690 a = strcspn(path, "/");
1691 b = strcspn(prefix, "/");
1696 if (memcmp(path, prefix, a) != 0)
1704 bool path_equal(const char *a, const char *b) {
1708 if ((a[0] == '/') != (b[0] == '/'))
1714 a += strspn(a, "/");
1715 b += strspn(b, "/");
1717 if (*a == 0 && *b == 0)
1720 if (*a == 0 || *b == 0)
1723 j = strcspn(a, "/");
1724 k = strcspn(b, "/");
1729 if (memcmp(a, b, j) != 0)
1737 char *ascii_strlower(char *t) {
1742 for (p = t; *p; p++)
1743 if (*p >= 'A' && *p <= 'Z')
1744 *p = *p - 'A' + 'a';
1749 bool ignore_file(const char *filename) {
1753 filename[0] == '.' ||
1754 streq(filename, "lost+found") ||
1755 streq(filename, "aquota.user") ||
1756 streq(filename, "aquota.group") ||
1757 endswith(filename, "~") ||
1758 endswith(filename, ".rpmnew") ||
1759 endswith(filename, ".rpmsave") ||
1760 endswith(filename, ".rpmorig") ||
1761 endswith(filename, ".dpkg-old") ||
1762 endswith(filename, ".dpkg-new") ||
1763 endswith(filename, ".swp");
1766 int fd_nonblock(int fd, bool nonblock) {
1771 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1775 flags |= O_NONBLOCK;
1777 flags &= ~O_NONBLOCK;
1779 if (fcntl(fd, F_SETFL, flags) < 0)
1785 int fd_cloexec(int fd, bool cloexec) {
1790 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1794 flags |= FD_CLOEXEC;
1796 flags &= ~FD_CLOEXEC;
1798 if (fcntl(fd, F_SETFD, flags) < 0)
1804 int close_all_fds(const int except[], unsigned n_except) {
1809 if (!(d = opendir("/proc/self/fd")))
1812 while ((de = readdir(d))) {
1815 if (ignore_file(de->d_name))
1818 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1832 for (i = 0; i < n_except; i++)
1833 if (except[i] == fd) {
1842 if ((r = close_nointr(fd)) < 0) {
1843 /* Valgrind has its own FD and doesn't want to have it closed */
1856 bool chars_intersect(const char *a, const char *b) {
1859 /* Returns true if any of the chars in a are in b. */
1860 for (p = a; *p; p++)
1867 char *format_timestamp(char *buf, size_t l, usec_t t) {
1877 sec = (time_t) (t / USEC_PER_SEC);
1879 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1885 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1888 n = now(CLOCK_REALTIME);
1890 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1895 if (d >= USEC_PER_YEAR)
1896 snprintf(buf, l, "%llu years and %llu months ago",
1897 (unsigned long long) (d / USEC_PER_YEAR),
1898 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1899 else if (d >= USEC_PER_MONTH)
1900 snprintf(buf, l, "%llu months and %llu days ago",
1901 (unsigned long long) (d / USEC_PER_MONTH),
1902 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1903 else if (d >= USEC_PER_WEEK)
1904 snprintf(buf, l, "%llu weeks and %llu days ago",
1905 (unsigned long long) (d / USEC_PER_WEEK),
1906 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1907 else if (d >= 2*USEC_PER_DAY)
1908 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1909 else if (d >= 25*USEC_PER_HOUR)
1910 snprintf(buf, l, "1 day and %lluh ago",
1911 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1912 else if (d >= 6*USEC_PER_HOUR)
1913 snprintf(buf, l, "%lluh ago",
1914 (unsigned long long) (d / USEC_PER_HOUR));
1915 else if (d >= USEC_PER_HOUR)
1916 snprintf(buf, l, "%lluh %llumin ago",
1917 (unsigned long long) (d / USEC_PER_HOUR),
1918 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1919 else if (d >= 5*USEC_PER_MINUTE)
1920 snprintf(buf, l, "%llumin ago",
1921 (unsigned long long) (d / USEC_PER_MINUTE));
1922 else if (d >= USEC_PER_MINUTE)
1923 snprintf(buf, l, "%llumin %llus ago",
1924 (unsigned long long) (d / USEC_PER_MINUTE),
1925 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1926 else if (d >= USEC_PER_SEC)
1927 snprintf(buf, l, "%llus ago",
1928 (unsigned long long) (d / USEC_PER_SEC));
1929 else if (d >= USEC_PER_MSEC)
1930 snprintf(buf, l, "%llums ago",
1931 (unsigned long long) (d / USEC_PER_MSEC));
1933 snprintf(buf, l, "%lluus ago",
1934 (unsigned long long) d);
1936 snprintf(buf, l, "now");
1942 char *format_timespan(char *buf, size_t l, usec_t t) {
1943 static const struct {
1947 { "w", USEC_PER_WEEK },
1948 { "d", USEC_PER_DAY },
1949 { "h", USEC_PER_HOUR },
1950 { "min", USEC_PER_MINUTE },
1951 { "s", USEC_PER_SEC },
1952 { "ms", USEC_PER_MSEC },
1962 if (t == (usec_t) -1)
1966 snprintf(p, l, "0");
1971 /* The result of this function can be parsed with parse_usec */
1973 for (i = 0; i < ELEMENTSOF(table); i++) {
1977 if (t < table[i].usec)
1983 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1984 n = MIN((size_t) k, l);
1997 bool fstype_is_network(const char *fstype) {
1998 static const char * const table[] = {
2010 for (i = 0; i < ELEMENTSOF(table); i++)
2011 if (streq(table[i], fstype))
2020 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2025 TIOCL_GETKMSGREDIRECT,
2029 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2032 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2035 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2038 close_nointr_nofail(r);
2042 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2043 struct termios old_termios, new_termios;
2050 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2051 new_termios = old_termios;
2053 new_termios.c_lflag &= ~ICANON;
2054 new_termios.c_cc[VMIN] = 1;
2055 new_termios.c_cc[VTIME] = 0;
2057 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2060 k = fread(&c, 1, 1, f);
2062 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2068 *need_nl = c != '\n';
2075 if (!(fgets(line, sizeof(line), f)))
2080 if (strlen(line) != 1)
2090 int ask(char *ret, const char *replies, const char *text, ...) {
2097 on_tty = isatty(STDOUT_FILENO);
2103 bool need_nl = true;
2106 fputs("\x1B[1m", stdout);
2113 fputs("\x1B[0m", stdout);
2117 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2119 if (r == -EBADMSG) {
2120 puts("Bad input, please try again.");
2131 if (strchr(replies, c)) {
2136 puts("Read unexpected character, please try again.");
2140 int reset_terminal(int fd) {
2141 struct termios termios;
2145 /* Set terminal to some sane defaults */
2149 /* We leave locked terminal attributes untouched, so that
2150 * Plymouth may set whatever it wants to set, and we don't
2151 * interfere with that. */
2153 /* Disable exclusive mode, just in case */
2154 ioctl(fd, TIOCNXCL);
2156 /* Enable console unicode mode */
2158 ioctl(fd, KDSKBMODE, &arg);
2160 if (tcgetattr(fd, &termios) < 0) {
2165 /* We only reset the stuff that matters to the software. How
2166 * hardware is set up we don't touch assuming that somebody
2167 * else will do that for us */
2169 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2170 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2171 termios.c_oflag |= ONLCR;
2172 termios.c_cflag |= CREAD;
2173 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2175 termios.c_cc[VINTR] = 03; /* ^C */
2176 termios.c_cc[VQUIT] = 034; /* ^\ */
2177 termios.c_cc[VERASE] = 0177;
2178 termios.c_cc[VKILL] = 025; /* ^X */
2179 termios.c_cc[VEOF] = 04; /* ^D */
2180 termios.c_cc[VSTART] = 021; /* ^Q */
2181 termios.c_cc[VSTOP] = 023; /* ^S */
2182 termios.c_cc[VSUSP] = 032; /* ^Z */
2183 termios.c_cc[VLNEXT] = 026; /* ^V */
2184 termios.c_cc[VWERASE] = 027; /* ^W */
2185 termios.c_cc[VREPRINT] = 022; /* ^R */
2186 termios.c_cc[VEOL] = 0;
2187 termios.c_cc[VEOL2] = 0;
2189 termios.c_cc[VTIME] = 0;
2190 termios.c_cc[VMIN] = 1;
2192 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2196 /* Just in case, flush all crap out */
2197 tcflush(fd, TCIOFLUSH);
2202 int open_terminal(const char *name, int mode) {
2207 * If a TTY is in the process of being closed opening it might
2208 * cause EIO. This is horribly awful, but unlikely to be
2209 * changed in the kernel. Hence we work around this problem by
2210 * retrying a couple of times.
2212 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2216 if ((fd = open(name, mode)) >= 0)
2225 usleep(50 * USEC_PER_MSEC);
2232 if ((r = isatty(fd)) < 0) {
2233 close_nointr_nofail(fd);
2238 close_nointr_nofail(fd);
2245 int flush_fd(int fd) {
2246 struct pollfd pollfd;
2250 pollfd.events = POLLIN;
2257 if ((r = poll(&pollfd, 1, 0)) < 0) {
2268 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2273 if (errno == EAGAIN)
2284 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2285 int fd = -1, notify = -1, r, wd = -1;
2289 /* We use inotify to be notified when the tty is closed. We
2290 * create the watch before checking if we can actually acquire
2291 * it, so that we don't lose any event.
2293 * Note: strictly speaking this actually watches for the
2294 * device being closed, it does *not* really watch whether a
2295 * tty loses its controlling process. However, unless some
2296 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2297 * its tty otherwise this will not become a problem. As long
2298 * as the administrator makes sure not configure any service
2299 * on the same tty as an untrusted user this should not be a
2300 * problem. (Which he probably should not do anyway.) */
2302 if (!fail && !force) {
2303 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2308 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2316 if ((r = flush_fd(notify)) < 0)
2319 /* We pass here O_NOCTTY only so that we can check the return
2320 * value TIOCSCTTY and have a reliable way to figure out if we
2321 * successfully became the controlling process of the tty */
2322 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2325 /* First, try to get the tty */
2326 r = ioctl(fd, TIOCSCTTY, force);
2328 /* Sometimes it makes sense to ignore TIOCSCTTY
2329 * returning EPERM, i.e. when very likely we already
2330 * are have this controlling terminal. */
2331 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2334 if (r < 0 && (force || fail || errno != EPERM)) {
2344 assert(notify >= 0);
2347 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2349 struct inotify_event *e;
2351 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2360 e = (struct inotify_event*) inotify_buffer;
2365 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2370 step = sizeof(struct inotify_event) + e->len;
2371 assert(step <= (size_t) l);
2373 e = (struct inotify_event*) ((uint8_t*) e + step);
2380 /* We close the tty fd here since if the old session
2381 * ended our handle will be dead. It's important that
2382 * we do this after sleeping, so that we don't enter
2383 * an endless loop. */
2384 close_nointr_nofail(fd);
2388 close_nointr_nofail(notify);
2390 if ((r = reset_terminal(fd)) < 0)
2391 log_warning("Failed to reset terminal: %s", strerror(-r));
2397 close_nointr_nofail(fd);
2400 close_nointr_nofail(notify);
2405 int release_terminal(void) {
2407 struct sigaction sa_old, sa_new;
2409 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2412 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2413 * by our own TIOCNOTTY */
2416 sa_new.sa_handler = SIG_IGN;
2417 sa_new.sa_flags = SA_RESTART;
2418 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2420 if (ioctl(fd, TIOCNOTTY) < 0)
2423 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2425 close_nointr_nofail(fd);
2429 int sigaction_many(const struct sigaction *sa, ...) {
2434 while ((sig = va_arg(ap, int)) > 0)
2435 if (sigaction(sig, sa, NULL) < 0)
2442 int ignore_signals(int sig, ...) {
2443 struct sigaction sa;
2448 sa.sa_handler = SIG_IGN;
2449 sa.sa_flags = SA_RESTART;
2451 if (sigaction(sig, &sa, NULL) < 0)
2455 while ((sig = va_arg(ap, int)) > 0)
2456 if (sigaction(sig, &sa, NULL) < 0)
2463 int default_signals(int sig, ...) {
2464 struct sigaction sa;
2469 sa.sa_handler = SIG_DFL;
2470 sa.sa_flags = SA_RESTART;
2472 if (sigaction(sig, &sa, NULL) < 0)
2476 while ((sig = va_arg(ap, int)) > 0)
2477 if (sigaction(sig, &sa, NULL) < 0)
2484 int close_pipe(int p[]) {
2490 a = close_nointr(p[0]);
2495 b = close_nointr(p[1]);
2499 return a < 0 ? a : b;
2502 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2511 while (nbytes > 0) {
2514 if ((k = read(fd, p, nbytes)) <= 0) {
2516 if (k < 0 && errno == EINTR)
2519 if (k < 0 && errno == EAGAIN && do_poll) {
2520 struct pollfd pollfd;
2524 pollfd.events = POLLIN;
2526 if (poll(&pollfd, 1, -1) < 0) {
2530 return n > 0 ? n : -errno;
2533 if (pollfd.revents != POLLIN)
2534 return n > 0 ? n : -EIO;
2539 return n > 0 ? n : (k < 0 ? -errno : 0);
2550 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2559 while (nbytes > 0) {
2562 if ((k = write(fd, p, nbytes)) <= 0) {
2564 if (k < 0 && errno == EINTR)
2567 if (k < 0 && errno == EAGAIN && do_poll) {
2568 struct pollfd pollfd;
2572 pollfd.events = POLLOUT;
2574 if (poll(&pollfd, 1, -1) < 0) {
2578 return n > 0 ? n : -errno;
2581 if (pollfd.revents != POLLOUT)
2582 return n > 0 ? n : -EIO;
2587 return n > 0 ? n : (k < 0 ? -errno : 0);
2598 int path_is_mount_point(const char *t) {
2603 if (lstat(t, &a) < 0) {
2604 if (errno == ENOENT)
2610 if ((r = parent_of_path(t, &parent)) < 0)
2613 r = lstat(parent, &b);
2619 return a.st_dev != b.st_dev;
2622 int parse_usec(const char *t, usec_t *usec) {
2623 static const struct {
2627 { "sec", USEC_PER_SEC },
2628 { "s", USEC_PER_SEC },
2629 { "min", USEC_PER_MINUTE },
2630 { "hr", USEC_PER_HOUR },
2631 { "h", USEC_PER_HOUR },
2632 { "d", USEC_PER_DAY },
2633 { "w", USEC_PER_WEEK },
2634 { "msec", USEC_PER_MSEC },
2635 { "ms", USEC_PER_MSEC },
2636 { "m", USEC_PER_MINUTE },
2639 { "", USEC_PER_SEC },
2655 l = strtoll(p, &e, 10);
2666 e += strspn(e, WHITESPACE);
2668 for (i = 0; i < ELEMENTSOF(table); i++)
2669 if (startswith(e, table[i].suffix)) {
2670 r += (usec_t) l * table[i].usec;
2671 p = e + strlen(table[i].suffix);
2675 if (i >= ELEMENTSOF(table))
2685 int make_stdio(int fd) {
2690 r = dup2(fd, STDIN_FILENO);
2691 s = dup2(fd, STDOUT_FILENO);
2692 t = dup2(fd, STDERR_FILENO);
2695 close_nointr_nofail(fd);
2697 if (r < 0 || s < 0 || t < 0)
2703 int make_null_stdio(void) {
2706 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2709 return make_stdio(null_fd);
2712 bool is_device_path(const char *path) {
2714 /* Returns true on paths that refer to a device, either in
2715 * sysfs or in /dev */
2718 path_startswith(path, "/dev/") ||
2719 path_startswith(path, "/sys/");
2722 int dir_is_empty(const char *path) {
2725 struct dirent buf, *de;
2727 if (!(d = opendir(path)))
2731 if ((r = readdir_r(d, &buf, &de)) > 0) {
2741 if (!ignore_file(de->d_name)) {
2751 unsigned long long random_ull(void) {
2756 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2759 r = loop_read(fd, &ull, sizeof(ull), true);
2760 close_nointr_nofail(fd);
2762 if (r != sizeof(ull))
2768 return random() * RAND_MAX + random();
2771 void rename_process(const char name[8]) {
2774 prctl(PR_SET_NAME, name);
2776 /* This is a like a poor man's setproctitle(). The string
2777 * passed should fit in 7 chars (i.e. the length of
2780 if (program_invocation_name)
2781 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2784 void sigset_add_many(sigset_t *ss, ...) {
2791 while ((sig = va_arg(ap, int)) > 0)
2792 assert_se(sigaddset(ss, sig) == 0);
2796 char* gethostname_malloc(void) {
2799 assert_se(uname(&u) >= 0);
2802 return strdup(u.nodename);
2804 return strdup(u.sysname);
2807 char* getlogname_malloc(void) {
2811 struct passwd pwbuf, *pw = NULL;
2814 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2819 /* Shortcut things to avoid NSS lookups */
2821 return strdup("root");
2823 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2826 if (!(buf = malloc(bufsize)))
2829 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2830 name = strdup(pw->pw_name);
2837 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2843 int getttyname_malloc(int fd, char **r) {
2844 char path[PATH_MAX], *c;
2849 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2854 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2861 int getttyname_harder(int fd, char **r) {
2865 if ((k = getttyname_malloc(fd, &s)) < 0)
2868 if (streq(s, "tty")) {
2877 int get_ctty_devnr(dev_t *d) {
2880 unsigned long ttynr;
2883 if (!(f = fopen("/proc/self/stat", "r")))
2886 if (!(fgets(line, sizeof(line), f))) {
2894 if (!(p = strrchr(line, ')')))
2903 "%*d " /* session */
2912 int get_ctty(char **r) {
2914 char fn[128], *s, *b, *p;
2919 if ((k = get_ctty_devnr(&devnr)) < 0)
2922 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2925 if ((k = readlink_malloc(fn, &s)) < 0) {
2930 /* Probably something like the ptys which have no
2931 * symlink in /dev/char. Let's return something
2932 * vaguely useful. */
2934 if (!(b = strdup(fn + 5)))
2941 if (startswith(s, "/dev/"))
2943 else if (startswith(s, "../"))
2958 static int rm_rf_children(int fd, bool only_dirs) {
2964 /* This returns the first error we run into, but nevertheless
2967 if (!(d = fdopendir(fd))) {
2968 close_nointr_nofail(fd);
2970 return errno == ENOENT ? 0 : -errno;
2974 struct dirent buf, *de;
2978 if ((r = readdir_r(d, &buf, &de)) != 0) {
2987 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2990 if (de->d_type == DT_UNKNOWN) {
2993 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2994 if (ret == 0 && errno != ENOENT)
2999 is_dir = S_ISDIR(st.st_mode);
3001 is_dir = de->d_type == DT_DIR;
3006 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3007 if (ret == 0 && errno != ENOENT)
3012 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3017 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3018 if (ret == 0 && errno != ENOENT)
3021 } else if (!only_dirs) {
3023 if (unlinkat(fd, de->d_name, 0) < 0) {
3024 if (ret == 0 && errno != ENOENT)
3035 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3041 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3043 if (errno != ENOTDIR)
3046 if (delete_root && !only_dirs)
3047 if (unlink(path) < 0)
3053 r = rm_rf_children(fd, only_dirs);
3056 if (rmdir(path) < 0) {
3064 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3067 /* Under the assumption that we are running privileged we
3068 * first change the access mode and only then hand out
3069 * ownership to avoid a window where access is too open. */
3071 if (chmod(path, mode) < 0)
3074 if (chown(path, uid, gid) < 0)
3080 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3084 /* Allocates the cpuset in the right size */
3087 if (!(r = CPU_ALLOC(n)))
3090 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3091 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3101 if (errno != EINVAL)
3108 void status_vprintf(const char *format, va_list ap) {
3114 /* This independent of logging, as status messages are
3115 * optional and go exclusively to the console. */
3117 if (vasprintf(&s, format, ap) < 0)
3120 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3123 write(fd, s, strlen(s));
3129 close_nointr_nofail(fd);
3132 void status_printf(const char *format, ...) {
3137 va_start(ap, format);
3138 status_vprintf(format, ap);
3142 void status_welcome(void) {
3143 char *pretty_name = NULL, *ansi_color = NULL;
3144 const char *const_pretty = NULL, *const_color = NULL;
3147 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3148 "PRETTY_NAME", &pretty_name,
3149 "ANSI_COLOR", &ansi_color,
3153 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3156 #if defined(TARGET_FEDORA)
3158 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3161 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3163 truncate_nl(pretty_name);
3166 if (!ansi_color && pretty_name) {
3168 /* This tries to mimic the color magic the old Red Hat sysinit
3171 if (startswith(pretty_name, "Red Hat"))
3172 const_color = "0;31"; /* Red for RHEL */
3173 else if (startswith(pretty_name, "Fedora"))
3174 const_color = "0;34"; /* Blue for Fedora */
3177 #elif defined(TARGET_SUSE)
3180 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3183 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3185 truncate_nl(pretty_name);
3189 const_color = "0;32"; /* Green for openSUSE */
3191 #elif defined(TARGET_GENTOO)
3194 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3197 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3199 truncate_nl(pretty_name);
3203 const_color = "1;34"; /* Light Blue for Gentoo */
3205 #elif defined(TARGET_ALTLINUX)
3208 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3211 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3213 truncate_nl(pretty_name);
3217 const_color = "0;36"; /* Cyan for ALTLinux */
3220 #elif defined(TARGET_DEBIAN)
3225 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3228 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3230 truncate_nl(version);
3231 pretty_name = strappend("Debian ", version);
3235 log_warning("Failed to allocate Debian version string.");
3240 const_color = "1;31"; /* Light Red for Debian */
3242 #elif defined(TARGET_UBUNTU)
3244 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3245 "DISTRIB_DESCRIPTION", &pretty_name,
3249 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3253 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3257 if (!pretty_name && !const_pretty)
3258 const_pretty = "Linux";
3260 if (!ansi_color && !const_color)
3263 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3264 const_color ? const_color : ansi_color,
3265 const_pretty ? const_pretty : pretty_name);
3271 char *replace_env(const char *format, char **env) {
3278 const char *e, *word = format;
3283 for (e = format; *e; e ++) {
3294 if (!(k = strnappend(r, word, e-word-1)))
3303 } else if (*e == '$') {
3304 if (!(k = strnappend(r, word, e-word)))
3320 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3323 if (!(k = strappend(r, t)))
3336 if (!(k = strnappend(r, word, e-word)))
3347 char **replace_env_argv(char **argv, char **env) {
3349 unsigned k = 0, l = 0;
3351 l = strv_length(argv);
3353 if (!(r = new(char*, l+1)))
3356 STRV_FOREACH(i, argv) {
3358 /* If $FOO appears as single word, replace it by the split up variable */
3359 if ((*i)[0] == '$' && (*i)[1] != '{') {
3364 if ((e = strv_env_get(env, *i+1))) {
3366 if (!(m = strv_split_quoted(e))) {
3377 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3386 memcpy(r + k, m, q * sizeof(char*));
3394 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3395 if (!(r[k++] = replace_env(*i, env))) {
3406 static __thread int parsed_columns = 0;
3409 if (parsed_columns > 0)
3410 return parsed_columns;
3412 if ((e = getenv("COLUMNS")))
3413 parsed_columns = atoi(e);
3415 if (parsed_columns <= 0) {
3419 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3420 parsed_columns = ws.ws_col;
3423 if (parsed_columns <= 0)
3424 parsed_columns = 80;
3426 return parsed_columns;
3429 int running_in_chroot(void) {
3435 /* Only works as root */
3437 if (stat("/proc/1/root", &a) < 0)
3440 if (stat("/", &b) < 0)
3444 a.st_dev != b.st_dev ||
3445 a.st_ino != b.st_ino;
3448 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3453 assert(percent <= 100);
3454 assert(length >= 3);
3458 if (l <= 3 || l <= length)
3461 if (!(r = new0(char, length+1)))
3464 x = (length * percent) / 100;
3474 s + l - (length - x - 3),
3480 int touch(const char *path) {
3485 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3488 close_nointr_nofail(fd);
3492 char *unquote(const char *s, const char* quotes) {
3496 if ((l = strlen(s)) < 2)
3499 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3500 return strndup(s+1, l-2);
3505 char *normalize_env_assignment(const char *s) {
3506 char *name, *value, *p, *r;
3511 if (!(r = strdup(s)))
3517 if (!(name = strndup(s, p - s)))
3520 if (!(p = strdup(p+1))) {
3525 value = unquote(strstrip(p), QUOTES);
3534 if (asprintf(&r, "%s=%s", name, value) < 0)
3543 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3550 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3562 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3569 if ((r = wait_for_terminate(pid, &status)) < 0) {
3570 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3574 if (status.si_code == CLD_EXITED) {
3575 if (status.si_status != 0) {
3576 log_warning("%s failed with error code %i.", name, status.si_status);
3580 log_debug("%s succeeded.", name);
3583 } else if (status.si_code == CLD_KILLED ||
3584 status.si_code == CLD_DUMPED) {
3586 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3590 log_warning("%s failed due to unknown reason.", name);
3602 bool null_or_empty(struct stat *st) {
3605 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3608 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3614 DIR *xopendirat(int fd, const char *name, int flags) {
3618 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3621 if (!(d = fdopendir(nfd))) {
3622 close_nointr_nofail(nfd);
3629 int signal_from_string_try_harder(const char *s) {
3633 if ((signo = signal_from_string(s)) <= 0)
3634 if (startswith(s, "SIG"))
3635 return signal_from_string(s+3);
3640 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3646 if (!dual_timestamp_is_set(t))
3649 fprintf(f, "%s=%llu %llu\n",
3651 (unsigned long long) t->realtime,
3652 (unsigned long long) t->monotonic);
3655 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3656 unsigned long long a, b;
3661 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3662 log_debug("Failed to parse finish timestamp value %s", value);
3669 char *fstab_node_to_udev_node(const char *p) {
3673 /* FIXME: to follow udev's logic 100% we need to leave valid
3674 * UTF8 chars unescaped */
3676 if (startswith(p, "LABEL=")) {
3678 if (!(u = unquote(p+6, "\"\'")))
3681 t = xescape(u, "/ ");
3687 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3696 if (startswith(p, "UUID=")) {
3698 if (!(u = unquote(p+5, "\"\'")))
3701 t = xescape(u, "/ ");
3707 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3719 void filter_environ(const char *prefix) {
3726 for (i = 0, j = 0; environ[i]; i++) {
3728 if (startswith(environ[i], prefix))
3731 environ[j++] = environ[i];
3737 bool tty_is_vc(const char *tty) {
3740 if (startswith(tty, "/dev/"))
3743 return startswith(tty, "tty") &&
3744 tty[3] >= '0' && tty[3] <= '9';
3747 const char *default_term_for_tty(const char *tty) {
3748 char *active = NULL;
3753 if (startswith(tty, "/dev/"))
3756 /* Resolve where /dev/console is pointing when determining
3758 if (streq(tty, "console"))
3759 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3760 truncate_nl(active);
3762 /* If multiple log outputs are configured the
3763 * last one is what /dev/console points to */
3764 if ((tty = strrchr(active, ' ')))
3770 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3776 /* Returns a short identifier for the various VM implementations */
3777 int detect_vm(const char **id) {
3779 #if defined(__i386__) || defined(__x86_64__)
3781 /* Both CPUID and DMI are x86 specific interfaces... */
3783 static const char *const dmi_vendors[] = {
3784 "/sys/class/dmi/id/sys_vendor",
3785 "/sys/class/dmi/id/board_vendor",
3786 "/sys/class/dmi/id/bios_vendor"
3789 static const char dmi_vendor_table[] =
3791 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3792 "VMware\0" "vmware\0"
3794 "Microsoft Corporation\0" "microsoft\0"
3795 "innotek GmbH\0" "oracle\0"
3800 static const char cpuid_vendor_table[] =
3801 "XenVMMXenVMM\0" "xen\0"
3802 "KVMKVMKVM\0" "kvm\0"
3803 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3804 "VMwareVMware\0" "vmware\0"
3805 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3806 "Microsoft Hv\0" "microsoft\0"
3818 /* http://lwn.net/Articles/301888/ */
3821 #if defined (__i386__)
3824 #elif defined (__amd64__)
3829 /* First detect whether there is a hypervisor */
3831 __asm__ __volatile__ (
3832 /* ebx/rbx is being used for PIC! */
3833 " push %%"REG_b" \n\t"
3835 " pop %%"REG_b" \n\t"
3837 : "=a" (eax), "=c" (ecx)
3841 hypervisor = !!(ecx & ecx & 0x80000000U);
3845 /* There is a hypervisor, see what it is */
3847 __asm__ __volatile__ (
3848 /* ebx/rbx is being used for PIC! */
3849 " push %%"REG_b" \n\t"
3851 " mov %%ebx, %1 \n\t"
3852 " pop %%"REG_b" \n\t"
3854 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3858 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3859 if (streq(sig.text, j)) {
3868 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3871 const char *found = NULL;
3873 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3880 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3881 if (startswith(s, j))
3904 /* Returns a short identifier for the various VM/container implementations */
3905 int detect_virtualization(const char **id) {
3908 /* Unfortunately most of these operations require root access
3909 * in one way or another */
3913 if ((r = running_in_chroot()) > 0) {
3920 /* /proc/vz exists in container and outside of the container,
3921 * /proc/bc only outside of the container. */
3922 if (access("/proc/vz", F_OK) >= 0 &&
3923 access("/proc/bc", F_OK) < 0) {
3931 return detect_vm(id);
3934 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3937 Hashmap *pids = NULL;
3941 /* Executes all binaries in a directory in parallel and waits
3942 * until all they all finished. */
3945 if (!(_d = opendir(directory))) {
3947 if (errno == ENOENT)
3950 log_error("Failed to enumerate directory %s: %m", directory);
3957 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3958 log_error("Failed to allocate set.");
3962 while ((de = readdir(d))) {
3967 if (ignore_file(de->d_name))
3970 if (de->d_type != DT_REG &&
3971 de->d_type != DT_LNK &&
3972 de->d_type != DT_UNKNOWN)
3975 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3976 log_error("Out of memory");
3980 if ((pid = fork()) < 0) {
3981 log_error("Failed to fork: %m");
4000 log_error("Failed to execute %s: %m", path);
4001 _exit(EXIT_FAILURE);
4004 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4006 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4007 log_error("Failed to add PID to set: %s", strerror(-k));
4012 while (!hashmap_isempty(pids)) {
4017 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4022 log_error("waitid() failed: %m");
4026 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4027 if (!is_clean_exit(si.si_code, si.si_status)) {
4028 if (si.si_code == CLD_EXITED)
4029 log_error("%s exited with exit status %i.", path, si.si_status);
4031 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4033 log_debug("%s exited successfully.", path);
4044 hashmap_free_free(pids);
4047 int kill_and_sigcont(pid_t pid, int sig) {
4050 r = kill(pid, sig) < 0 ? -errno : 0;
4058 static const char *const ioprio_class_table[] = {
4059 [IOPRIO_CLASS_NONE] = "none",
4060 [IOPRIO_CLASS_RT] = "realtime",
4061 [IOPRIO_CLASS_BE] = "best-effort",
4062 [IOPRIO_CLASS_IDLE] = "idle"
4065 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4067 static const char *const sigchld_code_table[] = {
4068 [CLD_EXITED] = "exited",
4069 [CLD_KILLED] = "killed",
4070 [CLD_DUMPED] = "dumped",
4071 [CLD_TRAPPED] = "trapped",
4072 [CLD_STOPPED] = "stopped",
4073 [CLD_CONTINUED] = "continued",
4076 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4078 static const char *const log_facility_table[LOG_NFACILITIES] = {
4079 [LOG_FAC(LOG_KERN)] = "kern",
4080 [LOG_FAC(LOG_USER)] = "user",
4081 [LOG_FAC(LOG_MAIL)] = "mail",
4082 [LOG_FAC(LOG_DAEMON)] = "daemon",
4083 [LOG_FAC(LOG_AUTH)] = "auth",
4084 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4085 [LOG_FAC(LOG_LPR)] = "lpr",
4086 [LOG_FAC(LOG_NEWS)] = "news",
4087 [LOG_FAC(LOG_UUCP)] = "uucp",
4088 [LOG_FAC(LOG_CRON)] = "cron",
4089 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4090 [LOG_FAC(LOG_FTP)] = "ftp",
4091 [LOG_FAC(LOG_LOCAL0)] = "local0",
4092 [LOG_FAC(LOG_LOCAL1)] = "local1",
4093 [LOG_FAC(LOG_LOCAL2)] = "local2",
4094 [LOG_FAC(LOG_LOCAL3)] = "local3",
4095 [LOG_FAC(LOG_LOCAL4)] = "local4",
4096 [LOG_FAC(LOG_LOCAL5)] = "local5",
4097 [LOG_FAC(LOG_LOCAL6)] = "local6",
4098 [LOG_FAC(LOG_LOCAL7)] = "local7"
4101 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
4103 static const char *const log_level_table[] = {
4104 [LOG_EMERG] = "emerg",
4105 [LOG_ALERT] = "alert",
4106 [LOG_CRIT] = "crit",
4108 [LOG_WARNING] = "warning",
4109 [LOG_NOTICE] = "notice",
4110 [LOG_INFO] = "info",
4111 [LOG_DEBUG] = "debug"
4114 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4116 static const char* const sched_policy_table[] = {
4117 [SCHED_OTHER] = "other",
4118 [SCHED_BATCH] = "batch",
4119 [SCHED_IDLE] = "idle",
4120 [SCHED_FIFO] = "fifo",
4124 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4126 static const char* const rlimit_table[] = {
4127 [RLIMIT_CPU] = "LimitCPU",
4128 [RLIMIT_FSIZE] = "LimitFSIZE",
4129 [RLIMIT_DATA] = "LimitDATA",
4130 [RLIMIT_STACK] = "LimitSTACK",
4131 [RLIMIT_CORE] = "LimitCORE",
4132 [RLIMIT_RSS] = "LimitRSS",
4133 [RLIMIT_NOFILE] = "LimitNOFILE",
4134 [RLIMIT_AS] = "LimitAS",
4135 [RLIMIT_NPROC] = "LimitNPROC",
4136 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4137 [RLIMIT_LOCKS] = "LimitLOCKS",
4138 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4139 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4140 [RLIMIT_NICE] = "LimitNICE",
4141 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4142 [RLIMIT_RTTIME] = "LimitRTTIME"
4145 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4147 static const char* const ip_tos_table[] = {
4148 [IPTOS_LOWDELAY] = "low-delay",
4149 [IPTOS_THROUGHPUT] = "throughput",
4150 [IPTOS_RELIABILITY] = "reliability",
4151 [IPTOS_LOWCOST] = "low-cost",
4154 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4156 static const char *const signal_table[] = {
4173 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4184 [SIGVTALRM] = "VTALRM",
4186 [SIGWINCH] = "WINCH",
4192 DEFINE_STRING_TABLE_LOOKUP(signal, int);