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 size_t page_size(void) {
65 static __thread size_t pgsz = 0;
71 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
78 bool streq_ptr(const char *a, const char *b) {
80 /* Like streq(), but tries to make sense of NULL pointers */
91 usec_t now(clockid_t clock_id) {
94 assert_se(clock_gettime(clock_id, &ts) == 0);
96 return timespec_load(&ts);
99 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
102 ts->realtime = now(CLOCK_REALTIME);
103 ts->monotonic = now(CLOCK_MONOTONIC);
108 usec_t timespec_load(const struct timespec *ts) {
112 (usec_t) ts->tv_sec * USEC_PER_SEC +
113 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
116 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
119 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
120 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
125 usec_t timeval_load(const struct timeval *tv) {
129 (usec_t) tv->tv_sec * USEC_PER_SEC +
130 (usec_t) tv->tv_usec;
133 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
136 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
137 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
142 bool endswith(const char *s, const char *postfix) {
149 pl = strlen(postfix);
157 return memcmp(s + sl - pl, postfix, pl) == 0;
160 bool startswith(const char *s, const char *prefix) {
175 return memcmp(s, prefix, pl) == 0;
178 bool startswith_no_case(const char *s, const char *prefix) {
194 for(i = 0; i < pl; ++i) {
195 if (tolower(s[i]) != tolower(prefix[i]))
202 bool first_word(const char *s, const char *word) {
217 if (memcmp(s, word, wl) != 0)
221 strchr(WHITESPACE, s[wl]);
224 int close_nointr(int fd) {
230 if ((r = close(fd)) >= 0)
238 void close_nointr_nofail(int fd) {
239 int saved_errno = errno;
241 /* like close_nointr() but cannot fail, and guarantees errno
244 assert_se(close_nointr(fd) == 0);
249 void close_many(const int fds[], unsigned n_fd) {
252 for (i = 0; i < n_fd; i++)
253 close_nointr_nofail(fds[i]);
256 int parse_boolean(const char *v) {
259 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
261 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
267 int parse_pid(const char *s, pid_t* ret_pid) {
268 unsigned long ul = 0;
275 if ((r = safe_atolu(s, &ul)) < 0)
280 if ((unsigned long) pid != ul)
290 int safe_atou(const char *s, unsigned *ret_u) {
298 l = strtoul(s, &x, 0);
300 if (!x || *x || errno)
301 return errno ? -errno : -EINVAL;
303 if ((unsigned long) (unsigned) l != l)
306 *ret_u = (unsigned) l;
310 int safe_atoi(const char *s, int *ret_i) {
318 l = strtol(s, &x, 0);
320 if (!x || *x || errno)
321 return errno ? -errno : -EINVAL;
323 if ((long) (int) l != l)
330 int safe_atollu(const char *s, long long unsigned *ret_llu) {
332 unsigned long long l;
338 l = strtoull(s, &x, 0);
340 if (!x || *x || errno)
341 return errno ? -errno : -EINVAL;
347 int safe_atolli(const char *s, long long int *ret_lli) {
355 l = strtoll(s, &x, 0);
357 if (!x || *x || errno)
358 return errno ? -errno : -EINVAL;
364 /* Split a string into words. */
365 char *split(const char *c, size_t *l, const char *separator, char **state) {
368 current = *state ? *state : (char*) c;
370 if (!*current || *c == 0)
373 current += strspn(current, separator);
374 *l = strcspn(current, separator);
377 return (char*) current;
380 /* Split a string into words, but consider strings enclosed in '' and
381 * "" as words even if they include spaces. */
382 char *split_quoted(const char *c, size_t *l, char **state) {
384 bool escaped = false;
386 current = *state ? *state : (char*) c;
388 if (!*current || *c == 0)
391 current += strspn(current, WHITESPACE);
393 if (*current == '\'') {
396 for (e = current; *e; e++) {
406 *state = *e == 0 ? e : e+1;
407 } else if (*current == '\"') {
410 for (e = current; *e; e++) {
420 *state = *e == 0 ? e : e+1;
422 for (e = current; *e; e++) {
427 else if (strchr(WHITESPACE, *e))
434 return (char*) current;
437 char **split_path_and_make_absolute(const char *p) {
441 if (!(l = strv_split(p, ":")))
444 if (!strv_path_make_absolute_cwd(l)) {
452 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
455 char fn[132], line[256], *p;
461 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
462 fn[sizeof(fn)-1] = 0;
464 if (!(f = fopen(fn, "r")))
467 if (!(fgets(line, sizeof(line), f))) {
475 /* Let's skip the pid and comm fields. The latter is enclosed
476 * in () but does not escape any () in its value, so let's
477 * skip over it manually */
479 if (!(p = strrchr(line, ')')))
490 if ((long unsigned) (pid_t) ppid != ppid)
493 *_ppid = (pid_t) ppid;
498 int write_one_line_file(const char *fn, const char *line) {
505 if (!(f = fopen(fn, "we")))
508 if (fputs(line, f) < 0) {
513 if (!endswith(line, "\n"))
522 int read_one_line_file(const char *fn, char **line) {
525 char t[LINE_MAX], *c;
530 if (!(f = fopen(fn, "re")))
533 if (!(fgets(t, sizeof(t), f))) {
538 if (!(c = strdup(t))) {
551 int read_full_file(const char *fn, char **contents) {
558 if (!(f = fopen(fn, "re")))
561 if (fstat(fileno(f), &st) < 0) {
566 n = st.st_size > 0 ? st.st_size : LINE_MAX;
573 if (!(t = realloc(buf, n+1))) {
579 k = fread(buf + l, 1, n - l, f);
594 if (n > 4*1024*1024) {
602 else if (!(buf = calloc(1, 1))) {
621 const char *separator, ...) {
629 if ((r = read_full_file(fname, &contents)) < 0)
634 const char *key = NULL;
636 p += strspn(p, separator);
637 p += strspn(p, WHITESPACE);
642 if (!strchr(COMMENTS, *p)) {
646 va_start(ap, separator);
647 while ((key = va_arg(ap, char *))) {
651 value = va_arg(ap, char **);
654 if (strncmp(p, key, n) != 0 ||
659 n = strcspn(p, separator);
662 strchr(QUOTES, p[0]) &&
664 v = strndup(p+1, n-2);
675 /* return empty value strings as NULL */
692 p += strcspn(p, separator);
711 if (!(f = fopen(fname, "re")))
715 char l[LINE_MAX], *p, *u;
718 if (!fgets(l, sizeof(l), f)) {
731 if (strchr(COMMENTS, *p))
734 if (!(u = normalize_env_assignment(p))) {
735 log_error("Out of memory");
740 t = strv_append(m, u);
744 log_error("Out of memory");
767 char *truncate_nl(char *s) {
770 s[strcspn(s, NEWLINE)] = 0;
774 int get_process_name(pid_t pid, char **name) {
781 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
784 r = read_one_line_file(p, name);
794 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
802 assert(max_length > 0);
805 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
814 if (!(r = new(char, max_length))) {
821 while ((c = getc(f)) != EOF) {
843 size_t n = MIN(left-1, 3U);
851 /* Kernel threads have no argv[] */
858 if ((h = get_process_name(pid, &t)) < 0)
861 h = asprintf(&r, "[%s]", t);
872 char *strnappend(const char *s, const char *suffix, size_t b) {
880 return strndup(suffix, b);
890 if (!(r = new(char, a+b+1)))
894 memcpy(r+a, suffix, b);
900 char *strappend(const char *s, const char *suffix) {
901 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
904 int readlink_malloc(const char *p, char **r) {
914 if (!(c = new(char, l)))
917 if ((n = readlink(p, c, l-1)) < 0) {
923 if ((size_t) n < l-1) {
934 int readlink_and_make_absolute(const char *p, char **r) {
941 if ((j = readlink_malloc(p, &target)) < 0)
944 k = file_in_same_dir(p, target);
954 int parent_of_path(const char *path, char **_r) {
955 const char *e, *a = NULL, *b = NULL, *p;
965 for (e = path; *e; e++) {
967 if (!slash && *e == '/') {
971 } else if (slash && *e != '/')
986 r = strndup(path, p-path);
996 char *file_name_from_path(const char *p) {
1001 if ((r = strrchr(p, '/')))
1007 bool path_is_absolute(const char *p) {
1013 bool is_path(const char *p) {
1015 return !!strchr(p, '/');
1018 char *path_make_absolute(const char *p, const char *prefix) {
1023 /* Makes every item in the list an absolute path by prepending
1024 * the prefix, if specified and necessary */
1026 if (path_is_absolute(p) || !prefix)
1029 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1035 char *path_make_absolute_cwd(const char *p) {
1040 /* Similar to path_make_absolute(), but prefixes with the
1041 * current working directory. */
1043 if (path_is_absolute(p))
1046 if (!(cwd = get_current_dir_name()))
1049 r = path_make_absolute(p, cwd);
1055 char **strv_path_make_absolute_cwd(char **l) {
1058 /* Goes through every item in the string list and makes it
1059 * absolute. This works in place and won't rollback any
1060 * changes on failure. */
1062 STRV_FOREACH(s, l) {
1065 if (!(t = path_make_absolute_cwd(*s)))
1075 char **strv_path_canonicalize(char **l) {
1078 bool enomem = false;
1080 if (strv_isempty(l))
1083 /* Goes through every item in the string list and canonicalize
1084 * the path. This works in place and won't rollback any
1085 * changes on failure. */
1087 STRV_FOREACH(s, l) {
1090 t = path_make_absolute_cwd(*s);
1099 u = canonicalize_file_name(t);
1103 if (errno == ENOMEM || !errno)
1120 int reset_all_signal_handlers(void) {
1123 for (sig = 1; sig < _NSIG; sig++) {
1124 struct sigaction sa;
1126 if (sig == SIGKILL || sig == SIGSTOP)
1130 sa.sa_handler = SIG_DFL;
1131 sa.sa_flags = SA_RESTART;
1133 /* On Linux the first two RT signals are reserved by
1134 * glibc, and sigaction() will return EINVAL for them. */
1135 if ((sigaction(sig, &sa, NULL) < 0))
1136 if (errno != EINVAL)
1143 char *strstrip(char *s) {
1146 /* Drops trailing whitespace. Modifies the string in
1147 * place. Returns pointer to first non-space character */
1149 s += strspn(s, WHITESPACE);
1151 for (e = s; *e; e++)
1152 if (!strchr(WHITESPACE, *e))
1163 char *delete_chars(char *s, const char *bad) {
1166 /* Drops all whitespace, regardless where in the string */
1168 for (f = s, t = s; *f; f++) {
1169 if (strchr(bad, *f))
1180 char *file_in_same_dir(const char *path, const char *filename) {
1187 /* This removes the last component of path and appends
1188 * filename, unless the latter is absolute anyway or the
1191 if (path_is_absolute(filename))
1192 return strdup(filename);
1194 if (!(e = strrchr(path, '/')))
1195 return strdup(filename);
1197 k = strlen(filename);
1198 if (!(r = new(char, e-path+1+k+1)))
1201 memcpy(r, path, e-path+1);
1202 memcpy(r+(e-path)+1, filename, k+1);
1207 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1210 if (label_mkdir(path, mode) >= 0)
1211 if (chmod_and_chown(path, mode, uid, gid) < 0)
1214 if (lstat(path, &st) < 0)
1217 if ((st.st_mode & 0777) != mode ||
1220 !S_ISDIR(st.st_mode)) {
1229 int mkdir_parents(const char *path, mode_t mode) {
1234 /* Creates every parent directory in the path except the last
1237 p = path + strspn(path, "/");
1242 e = p + strcspn(p, "/");
1243 p = e + strspn(e, "/");
1245 /* Is this the last component? If so, then we're
1250 if (!(t = strndup(path, e - path)))
1253 r = label_mkdir(t, mode);
1256 if (r < 0 && errno != EEXIST)
1261 int mkdir_p(const char *path, mode_t mode) {
1266 if ((r = mkdir_parents(path, mode)) < 0)
1269 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1275 int rmdir_parents(const char *path, const char *stop) {
1284 /* Skip trailing slashes */
1285 while (l > 0 && path[l-1] == '/')
1291 /* Skip last component */
1292 while (l > 0 && path[l-1] != '/')
1295 /* Skip trailing slashes */
1296 while (l > 0 && path[l-1] == '/')
1302 if (!(t = strndup(path, l)))
1305 if (path_startswith(stop, t)) {
1314 if (errno != ENOENT)
1322 char hexchar(int x) {
1323 static const char table[16] = "0123456789abcdef";
1325 return table[x & 15];
1328 int unhexchar(char c) {
1330 if (c >= '0' && c <= '9')
1333 if (c >= 'a' && c <= 'f')
1334 return c - 'a' + 10;
1336 if (c >= 'A' && c <= 'F')
1337 return c - 'A' + 10;
1342 char octchar(int x) {
1343 return '0' + (x & 7);
1346 int unoctchar(char c) {
1348 if (c >= '0' && c <= '7')
1354 char decchar(int x) {
1355 return '0' + (x % 10);
1358 int undecchar(char c) {
1360 if (c >= '0' && c <= '9')
1366 char *cescape(const char *s) {
1372 /* Does C style string escaping. */
1374 if (!(r = new(char, strlen(s)*4 + 1)))
1377 for (f = s, t = r; *f; f++)
1423 /* For special chars we prefer octal over
1424 * hexadecimal encoding, simply because glib's
1425 * g_strescape() does the same */
1426 if ((*f < ' ') || (*f >= 127)) {
1428 *(t++) = octchar((unsigned char) *f >> 6);
1429 *(t++) = octchar((unsigned char) *f >> 3);
1430 *(t++) = octchar((unsigned char) *f);
1441 char *cunescape_length(const char *s, size_t length) {
1447 /* Undoes C style string escaping */
1449 if (!(r = new(char, length+1)))
1452 for (f = s, t = r; f < s + length; f++) {
1495 /* This is an extension of the XDG syntax files */
1500 /* hexadecimal encoding */
1503 if ((a = unhexchar(f[1])) < 0 ||
1504 (b = unhexchar(f[2])) < 0) {
1505 /* Invalid escape code, let's take it literal then */
1509 *(t++) = (char) ((a << 4) | b);
1524 /* octal encoding */
1527 if ((a = unoctchar(f[0])) < 0 ||
1528 (b = unoctchar(f[1])) < 0 ||
1529 (c = unoctchar(f[2])) < 0) {
1530 /* Invalid escape code, let's take it literal then */
1534 *(t++) = (char) ((a << 6) | (b << 3) | c);
1542 /* premature end of string.*/
1547 /* Invalid escape code, let's take it literal then */
1559 char *cunescape(const char *s) {
1560 return cunescape_length(s, strlen(s));
1563 char *xescape(const char *s, const char *bad) {
1567 /* Escapes all chars in bad, in addition to \ and all special
1568 * chars, in \xFF style escaping. May be reversed with
1571 if (!(r = new(char, strlen(s)*4+1)))
1574 for (f = s, t = r; *f; f++) {
1576 if ((*f < ' ') || (*f >= 127) ||
1577 (*f == '\\') || strchr(bad, *f)) {
1580 *(t++) = hexchar(*f >> 4);
1581 *(t++) = hexchar(*f);
1591 char *bus_path_escape(const char *s) {
1597 /* Escapes all chars that D-Bus' object path cannot deal
1598 * with. Can be reverse with bus_path_unescape() */
1600 if (!(r = new(char, strlen(s)*3+1)))
1603 for (f = s, t = r; *f; f++) {
1605 if (!(*f >= 'A' && *f <= 'Z') &&
1606 !(*f >= 'a' && *f <= 'z') &&
1607 !(*f >= '0' && *f <= '9')) {
1609 *(t++) = hexchar(*f >> 4);
1610 *(t++) = hexchar(*f);
1620 char *bus_path_unescape(const char *f) {
1625 if (!(r = strdup(f)))
1628 for (t = r; *f; f++) {
1633 if ((a = unhexchar(f[1])) < 0 ||
1634 (b = unhexchar(f[2])) < 0) {
1635 /* Invalid escape code, let's take it literal then */
1638 *(t++) = (char) ((a << 4) | b);
1650 char *path_kill_slashes(char *path) {
1654 /* Removes redundant inner and trailing slashes. Modifies the
1655 * passed string in-place.
1657 * ///foo///bar/ becomes /foo/bar
1660 for (f = path, t = path; *f; f++) {
1675 /* Special rule, if we are talking of the root directory, a
1676 trailing slash is good */
1678 if (t == path && slash)
1685 bool path_startswith(const char *path, const char *prefix) {
1689 if ((path[0] == '/') != (prefix[0] == '/'))
1695 path += strspn(path, "/");
1696 prefix += strspn(prefix, "/");
1704 a = strcspn(path, "/");
1705 b = strcspn(prefix, "/");
1710 if (memcmp(path, prefix, a) != 0)
1718 bool path_equal(const char *a, const char *b) {
1722 if ((a[0] == '/') != (b[0] == '/'))
1728 a += strspn(a, "/");
1729 b += strspn(b, "/");
1731 if (*a == 0 && *b == 0)
1734 if (*a == 0 || *b == 0)
1737 j = strcspn(a, "/");
1738 k = strcspn(b, "/");
1743 if (memcmp(a, b, j) != 0)
1751 char *ascii_strlower(char *t) {
1756 for (p = t; *p; p++)
1757 if (*p >= 'A' && *p <= 'Z')
1758 *p = *p - 'A' + 'a';
1763 bool ignore_file(const char *filename) {
1767 filename[0] == '.' ||
1768 streq(filename, "lost+found") ||
1769 streq(filename, "aquota.user") ||
1770 streq(filename, "aquota.group") ||
1771 endswith(filename, "~") ||
1772 endswith(filename, ".rpmnew") ||
1773 endswith(filename, ".rpmsave") ||
1774 endswith(filename, ".rpmorig") ||
1775 endswith(filename, ".dpkg-old") ||
1776 endswith(filename, ".dpkg-new") ||
1777 endswith(filename, ".swp");
1780 int fd_nonblock(int fd, bool nonblock) {
1785 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1789 flags |= O_NONBLOCK;
1791 flags &= ~O_NONBLOCK;
1793 if (fcntl(fd, F_SETFL, flags) < 0)
1799 int fd_cloexec(int fd, bool cloexec) {
1804 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1808 flags |= FD_CLOEXEC;
1810 flags &= ~FD_CLOEXEC;
1812 if (fcntl(fd, F_SETFD, flags) < 0)
1818 int close_all_fds(const int except[], unsigned n_except) {
1823 if (!(d = opendir("/proc/self/fd")))
1826 while ((de = readdir(d))) {
1829 if (ignore_file(de->d_name))
1832 if (safe_atoi(de->d_name, &fd) < 0)
1833 /* Let's better ignore this, just in case */
1847 for (i = 0; i < n_except; i++)
1848 if (except[i] == fd) {
1857 if (close_nointr(fd) < 0) {
1858 /* Valgrind has its own FD and doesn't want to have it closed */
1859 if (errno != EBADF && r == 0)
1868 bool chars_intersect(const char *a, const char *b) {
1871 /* Returns true if any of the chars in a are in b. */
1872 for (p = a; *p; p++)
1879 char *format_timestamp(char *buf, size_t l, usec_t t) {
1889 sec = (time_t) (t / USEC_PER_SEC);
1891 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1897 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1900 n = now(CLOCK_REALTIME);
1902 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1907 if (d >= USEC_PER_YEAR)
1908 snprintf(buf, l, "%llu years and %llu months ago",
1909 (unsigned long long) (d / USEC_PER_YEAR),
1910 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1911 else if (d >= USEC_PER_MONTH)
1912 snprintf(buf, l, "%llu months and %llu days ago",
1913 (unsigned long long) (d / USEC_PER_MONTH),
1914 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1915 else if (d >= USEC_PER_WEEK)
1916 snprintf(buf, l, "%llu weeks and %llu days ago",
1917 (unsigned long long) (d / USEC_PER_WEEK),
1918 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1919 else if (d >= 2*USEC_PER_DAY)
1920 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1921 else if (d >= 25*USEC_PER_HOUR)
1922 snprintf(buf, l, "1 day and %lluh ago",
1923 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1924 else if (d >= 6*USEC_PER_HOUR)
1925 snprintf(buf, l, "%lluh ago",
1926 (unsigned long long) (d / USEC_PER_HOUR));
1927 else if (d >= USEC_PER_HOUR)
1928 snprintf(buf, l, "%lluh %llumin ago",
1929 (unsigned long long) (d / USEC_PER_HOUR),
1930 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1931 else if (d >= 5*USEC_PER_MINUTE)
1932 snprintf(buf, l, "%llumin ago",
1933 (unsigned long long) (d / USEC_PER_MINUTE));
1934 else if (d >= USEC_PER_MINUTE)
1935 snprintf(buf, l, "%llumin %llus ago",
1936 (unsigned long long) (d / USEC_PER_MINUTE),
1937 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1938 else if (d >= USEC_PER_SEC)
1939 snprintf(buf, l, "%llus ago",
1940 (unsigned long long) (d / USEC_PER_SEC));
1941 else if (d >= USEC_PER_MSEC)
1942 snprintf(buf, l, "%llums ago",
1943 (unsigned long long) (d / USEC_PER_MSEC));
1945 snprintf(buf, l, "%lluus ago",
1946 (unsigned long long) d);
1948 snprintf(buf, l, "now");
1954 char *format_timespan(char *buf, size_t l, usec_t t) {
1955 static const struct {
1959 { "w", USEC_PER_WEEK },
1960 { "d", USEC_PER_DAY },
1961 { "h", USEC_PER_HOUR },
1962 { "min", USEC_PER_MINUTE },
1963 { "s", USEC_PER_SEC },
1964 { "ms", USEC_PER_MSEC },
1974 if (t == (usec_t) -1)
1978 snprintf(p, l, "0");
1983 /* The result of this function can be parsed with parse_usec */
1985 for (i = 0; i < ELEMENTSOF(table); i++) {
1989 if (t < table[i].usec)
1995 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1996 n = MIN((size_t) k, l);
2009 bool fstype_is_network(const char *fstype) {
2010 static const char * const table[] = {
2022 for (i = 0; i < ELEMENTSOF(table); i++)
2023 if (streq(table[i], fstype))
2032 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2037 TIOCL_GETKMSGREDIRECT,
2041 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2044 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2047 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2050 close_nointr_nofail(r);
2054 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2055 struct termios old_termios, new_termios;
2062 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2063 new_termios = old_termios;
2065 new_termios.c_lflag &= ~ICANON;
2066 new_termios.c_cc[VMIN] = 1;
2067 new_termios.c_cc[VTIME] = 0;
2069 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2072 k = fread(&c, 1, 1, f);
2074 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2080 *need_nl = c != '\n';
2087 if (!(fgets(line, sizeof(line), f)))
2092 if (strlen(line) != 1)
2102 int ask(char *ret, const char *replies, const char *text, ...) {
2109 on_tty = isatty(STDOUT_FILENO);
2115 bool need_nl = true;
2118 fputs("\x1B[1m", stdout);
2125 fputs("\x1B[0m", stdout);
2129 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2131 if (r == -EBADMSG) {
2132 puts("Bad input, please try again.");
2143 if (strchr(replies, c)) {
2148 puts("Read unexpected character, please try again.");
2152 int reset_terminal(int fd) {
2153 struct termios termios;
2157 /* Set terminal to some sane defaults */
2161 /* We leave locked terminal attributes untouched, so that
2162 * Plymouth may set whatever it wants to set, and we don't
2163 * interfere with that. */
2165 /* Disable exclusive mode, just in case */
2166 ioctl(fd, TIOCNXCL);
2168 /* Enable console unicode mode */
2170 ioctl(fd, KDSKBMODE, &arg);
2172 if (tcgetattr(fd, &termios) < 0) {
2177 /* We only reset the stuff that matters to the software. How
2178 * hardware is set up we don't touch assuming that somebody
2179 * else will do that for us */
2181 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2182 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2183 termios.c_oflag |= ONLCR;
2184 termios.c_cflag |= CREAD;
2185 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2187 termios.c_cc[VINTR] = 03; /* ^C */
2188 termios.c_cc[VQUIT] = 034; /* ^\ */
2189 termios.c_cc[VERASE] = 0177;
2190 termios.c_cc[VKILL] = 025; /* ^X */
2191 termios.c_cc[VEOF] = 04; /* ^D */
2192 termios.c_cc[VSTART] = 021; /* ^Q */
2193 termios.c_cc[VSTOP] = 023; /* ^S */
2194 termios.c_cc[VSUSP] = 032; /* ^Z */
2195 termios.c_cc[VLNEXT] = 026; /* ^V */
2196 termios.c_cc[VWERASE] = 027; /* ^W */
2197 termios.c_cc[VREPRINT] = 022; /* ^R */
2198 termios.c_cc[VEOL] = 0;
2199 termios.c_cc[VEOL2] = 0;
2201 termios.c_cc[VTIME] = 0;
2202 termios.c_cc[VMIN] = 1;
2204 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2208 /* Just in case, flush all crap out */
2209 tcflush(fd, TCIOFLUSH);
2214 int open_terminal(const char *name, int mode) {
2219 * If a TTY is in the process of being closed opening it might
2220 * cause EIO. This is horribly awful, but unlikely to be
2221 * changed in the kernel. Hence we work around this problem by
2222 * retrying a couple of times.
2224 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2228 if ((fd = open(name, mode)) >= 0)
2237 usleep(50 * USEC_PER_MSEC);
2244 if ((r = isatty(fd)) < 0) {
2245 close_nointr_nofail(fd);
2250 close_nointr_nofail(fd);
2257 int flush_fd(int fd) {
2258 struct pollfd pollfd;
2262 pollfd.events = POLLIN;
2269 if ((r = poll(&pollfd, 1, 0)) < 0) {
2280 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2285 if (errno == EAGAIN)
2296 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2297 int fd = -1, notify = -1, r, wd = -1;
2301 /* We use inotify to be notified when the tty is closed. We
2302 * create the watch before checking if we can actually acquire
2303 * it, so that we don't lose any event.
2305 * Note: strictly speaking this actually watches for the
2306 * device being closed, it does *not* really watch whether a
2307 * tty loses its controlling process. However, unless some
2308 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2309 * its tty otherwise this will not become a problem. As long
2310 * as the administrator makes sure not configure any service
2311 * on the same tty as an untrusted user this should not be a
2312 * problem. (Which he probably should not do anyway.) */
2314 if (!fail && !force) {
2315 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2320 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2328 if ((r = flush_fd(notify)) < 0)
2331 /* We pass here O_NOCTTY only so that we can check the return
2332 * value TIOCSCTTY and have a reliable way to figure out if we
2333 * successfully became the controlling process of the tty */
2334 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2337 /* First, try to get the tty */
2338 r = ioctl(fd, TIOCSCTTY, force);
2340 /* Sometimes it makes sense to ignore TIOCSCTTY
2341 * returning EPERM, i.e. when very likely we already
2342 * are have this controlling terminal. */
2343 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2346 if (r < 0 && (force || fail || errno != EPERM)) {
2356 assert(notify >= 0);
2359 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2361 struct inotify_event *e;
2363 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2372 e = (struct inotify_event*) inotify_buffer;
2377 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2382 step = sizeof(struct inotify_event) + e->len;
2383 assert(step <= (size_t) l);
2385 e = (struct inotify_event*) ((uint8_t*) e + step);
2392 /* We close the tty fd here since if the old session
2393 * ended our handle will be dead. It's important that
2394 * we do this after sleeping, so that we don't enter
2395 * an endless loop. */
2396 close_nointr_nofail(fd);
2400 close_nointr_nofail(notify);
2402 if ((r = reset_terminal(fd)) < 0)
2403 log_warning("Failed to reset terminal: %s", strerror(-r));
2409 close_nointr_nofail(fd);
2412 close_nointr_nofail(notify);
2417 int release_terminal(void) {
2419 struct sigaction sa_old, sa_new;
2421 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2424 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2425 * by our own TIOCNOTTY */
2428 sa_new.sa_handler = SIG_IGN;
2429 sa_new.sa_flags = SA_RESTART;
2430 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2432 if (ioctl(fd, TIOCNOTTY) < 0)
2435 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2437 close_nointr_nofail(fd);
2441 int sigaction_many(const struct sigaction *sa, ...) {
2446 while ((sig = va_arg(ap, int)) > 0)
2447 if (sigaction(sig, sa, NULL) < 0)
2454 int ignore_signals(int sig, ...) {
2455 struct sigaction sa;
2460 sa.sa_handler = SIG_IGN;
2461 sa.sa_flags = SA_RESTART;
2463 if (sigaction(sig, &sa, NULL) < 0)
2467 while ((sig = va_arg(ap, int)) > 0)
2468 if (sigaction(sig, &sa, NULL) < 0)
2475 int default_signals(int sig, ...) {
2476 struct sigaction sa;
2481 sa.sa_handler = SIG_DFL;
2482 sa.sa_flags = SA_RESTART;
2484 if (sigaction(sig, &sa, NULL) < 0)
2488 while ((sig = va_arg(ap, int)) > 0)
2489 if (sigaction(sig, &sa, NULL) < 0)
2496 int close_pipe(int p[]) {
2502 a = close_nointr(p[0]);
2507 b = close_nointr(p[1]);
2511 return a < 0 ? a : b;
2514 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2523 while (nbytes > 0) {
2526 if ((k = read(fd, p, nbytes)) <= 0) {
2528 if (k < 0 && errno == EINTR)
2531 if (k < 0 && errno == EAGAIN && do_poll) {
2532 struct pollfd pollfd;
2536 pollfd.events = POLLIN;
2538 if (poll(&pollfd, 1, -1) < 0) {
2542 return n > 0 ? n : -errno;
2545 if (pollfd.revents != POLLIN)
2546 return n > 0 ? n : -EIO;
2551 return n > 0 ? n : (k < 0 ? -errno : 0);
2562 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2571 while (nbytes > 0) {
2574 if ((k = write(fd, p, nbytes)) <= 0) {
2576 if (k < 0 && errno == EINTR)
2579 if (k < 0 && errno == EAGAIN && do_poll) {
2580 struct pollfd pollfd;
2584 pollfd.events = POLLOUT;
2586 if (poll(&pollfd, 1, -1) < 0) {
2590 return n > 0 ? n : -errno;
2593 if (pollfd.revents != POLLOUT)
2594 return n > 0 ? n : -EIO;
2599 return n > 0 ? n : (k < 0 ? -errno : 0);
2610 int path_is_mount_point(const char *t) {
2615 if (lstat(t, &a) < 0) {
2616 if (errno == ENOENT)
2622 if ((r = parent_of_path(t, &parent)) < 0)
2625 r = lstat(parent, &b);
2631 return a.st_dev != b.st_dev;
2634 int parse_usec(const char *t, usec_t *usec) {
2635 static const struct {
2639 { "sec", USEC_PER_SEC },
2640 { "s", USEC_PER_SEC },
2641 { "min", USEC_PER_MINUTE },
2642 { "hr", USEC_PER_HOUR },
2643 { "h", USEC_PER_HOUR },
2644 { "d", USEC_PER_DAY },
2645 { "w", USEC_PER_WEEK },
2646 { "msec", USEC_PER_MSEC },
2647 { "ms", USEC_PER_MSEC },
2648 { "m", USEC_PER_MINUTE },
2651 { "", USEC_PER_SEC },
2667 l = strtoll(p, &e, 10);
2678 e += strspn(e, WHITESPACE);
2680 for (i = 0; i < ELEMENTSOF(table); i++)
2681 if (startswith(e, table[i].suffix)) {
2682 r += (usec_t) l * table[i].usec;
2683 p = e + strlen(table[i].suffix);
2687 if (i >= ELEMENTSOF(table))
2697 int make_stdio(int fd) {
2702 r = dup2(fd, STDIN_FILENO);
2703 s = dup2(fd, STDOUT_FILENO);
2704 t = dup2(fd, STDERR_FILENO);
2707 close_nointr_nofail(fd);
2709 if (r < 0 || s < 0 || t < 0)
2715 int make_null_stdio(void) {
2718 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2721 return make_stdio(null_fd);
2724 bool is_device_path(const char *path) {
2726 /* Returns true on paths that refer to a device, either in
2727 * sysfs or in /dev */
2730 path_startswith(path, "/dev/") ||
2731 path_startswith(path, "/sys/");
2734 int dir_is_empty(const char *path) {
2737 struct dirent buf, *de;
2739 if (!(d = opendir(path)))
2743 if ((r = readdir_r(d, &buf, &de)) > 0) {
2753 if (!ignore_file(de->d_name)) {
2763 unsigned long long random_ull(void) {
2768 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2771 r = loop_read(fd, &ull, sizeof(ull), true);
2772 close_nointr_nofail(fd);
2774 if (r != sizeof(ull))
2780 return random() * RAND_MAX + random();
2783 void rename_process(const char name[8]) {
2786 prctl(PR_SET_NAME, name);
2788 /* This is a like a poor man's setproctitle(). The string
2789 * passed should fit in 7 chars (i.e. the length of
2792 if (program_invocation_name)
2793 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2796 void sigset_add_many(sigset_t *ss, ...) {
2803 while ((sig = va_arg(ap, int)) > 0)
2804 assert_se(sigaddset(ss, sig) == 0);
2808 char* gethostname_malloc(void) {
2811 assert_se(uname(&u) >= 0);
2814 return strdup(u.nodename);
2816 return strdup(u.sysname);
2819 char* getlogname_malloc(void) {
2823 struct passwd pwbuf, *pw = NULL;
2826 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2831 /* Shortcut things to avoid NSS lookups */
2833 return strdup("root");
2835 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2838 if (!(buf = malloc(bufsize)))
2841 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2842 name = strdup(pw->pw_name);
2849 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2855 int getttyname_malloc(int fd, char **r) {
2856 char path[PATH_MAX], *c;
2861 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2866 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2873 int getttyname_harder(int fd, char **r) {
2877 if ((k = getttyname_malloc(fd, &s)) < 0)
2880 if (streq(s, "tty")) {
2882 return get_ctty(r, NULL);
2889 int get_ctty_devnr(dev_t *d) {
2892 unsigned long ttynr;
2895 if (!(f = fopen("/proc/self/stat", "r")))
2898 if (!(fgets(line, sizeof(line), f))) {
2906 if (!(p = strrchr(line, ')')))
2915 "%*d " /* session */
2924 int get_ctty(char **r, dev_t *_devnr) {
2926 char fn[128], *s, *b, *p;
2931 if ((k = get_ctty_devnr(&devnr)) < 0)
2934 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2937 if ((k = readlink_malloc(fn, &s)) < 0) {
2942 /* This is an ugly hack */
2943 if (major(devnr) == 136) {
2944 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2954 /* Probably something like the ptys which have no
2955 * symlink in /dev/char. Let's return something
2956 * vaguely useful. */
2958 if (!(b = strdup(fn + 5)))
2968 if (startswith(s, "/dev/"))
2970 else if (startswith(s, "../"))
2988 static int rm_rf_children(int fd, bool only_dirs) {
2994 /* This returns the first error we run into, but nevertheless
2997 if (!(d = fdopendir(fd))) {
2998 close_nointr_nofail(fd);
3000 return errno == ENOENT ? 0 : -errno;
3004 struct dirent buf, *de;
3008 if ((r = readdir_r(d, &buf, &de)) != 0) {
3017 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3020 if (de->d_type == DT_UNKNOWN) {
3023 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3024 if (ret == 0 && errno != ENOENT)
3029 is_dir = S_ISDIR(st.st_mode);
3031 is_dir = de->d_type == DT_DIR;
3036 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3037 if (ret == 0 && errno != ENOENT)
3042 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3047 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3048 if (ret == 0 && errno != ENOENT)
3051 } else if (!only_dirs) {
3053 if (unlinkat(fd, de->d_name, 0) < 0) {
3054 if (ret == 0 && errno != ENOENT)
3065 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3071 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3073 if (errno != ENOTDIR)
3076 if (delete_root && !only_dirs)
3077 if (unlink(path) < 0)
3083 r = rm_rf_children(fd, only_dirs);
3086 if (rmdir(path) < 0) {
3094 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3097 /* Under the assumption that we are running privileged we
3098 * first change the access mode and only then hand out
3099 * ownership to avoid a window where access is too open. */
3101 if (chmod(path, mode) < 0)
3104 if (chown(path, uid, gid) < 0)
3110 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3114 /* Allocates the cpuset in the right size */
3117 if (!(r = CPU_ALLOC(n)))
3120 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3121 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3131 if (errno != EINVAL)
3138 void status_vprintf(const char *format, va_list ap) {
3144 /* This independent of logging, as status messages are
3145 * optional and go exclusively to the console. */
3147 if (vasprintf(&s, format, ap) < 0)
3150 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3153 write(fd, s, strlen(s));
3159 close_nointr_nofail(fd);
3162 void status_printf(const char *format, ...) {
3167 va_start(ap, format);
3168 status_vprintf(format, ap);
3172 void status_welcome(void) {
3173 char *pretty_name = NULL, *ansi_color = NULL;
3174 const char *const_pretty = NULL, *const_color = NULL;
3177 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3178 "PRETTY_NAME", &pretty_name,
3179 "ANSI_COLOR", &ansi_color,
3183 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3186 #if defined(TARGET_FEDORA)
3188 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3191 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3193 truncate_nl(pretty_name);
3196 if (!ansi_color && pretty_name) {
3198 /* This tries to mimic the color magic the old Red Hat sysinit
3201 if (startswith(pretty_name, "Red Hat"))
3202 const_color = "0;31"; /* Red for RHEL */
3203 else if (startswith(pretty_name, "Fedora"))
3204 const_color = "0;34"; /* Blue for Fedora */
3207 #elif defined(TARGET_SUSE)
3210 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3213 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3215 truncate_nl(pretty_name);
3219 const_color = "0;32"; /* Green for openSUSE */
3221 #elif defined(TARGET_GENTOO)
3224 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3227 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3229 truncate_nl(pretty_name);
3233 const_color = "1;34"; /* Light Blue for Gentoo */
3235 #elif defined(TARGET_ALTLINUX)
3238 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3241 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3243 truncate_nl(pretty_name);
3247 const_color = "0;36"; /* Cyan for ALTLinux */
3250 #elif defined(TARGET_DEBIAN)
3255 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3258 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3260 truncate_nl(version);
3261 pretty_name = strappend("Debian ", version);
3265 log_warning("Failed to allocate Debian version string.");
3270 const_color = "1;31"; /* Light Red for Debian */
3272 #elif defined(TARGET_UBUNTU)
3274 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3275 "DISTRIB_DESCRIPTION", &pretty_name,
3279 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3283 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3285 #elif defined(TARGET_MANDRIVA)
3290 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3292 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3294 p = strstr(s, " release ");
3298 p[strcspn(p, " ")] = '\0';
3300 /* This corresponds to standard rc.sysinit */
3301 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3302 const_color = "1;36";
3304 log_warning("Failed to allocate Mandriva version string.");
3306 log_warning("Failed to parse /etc/mandriva-release");
3313 if (!pretty_name && !const_pretty)
3314 const_pretty = "Linux";
3316 if (!ansi_color && !const_color)
3319 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3320 const_color ? const_color : ansi_color,
3321 const_pretty ? const_pretty : pretty_name);
3327 char *replace_env(const char *format, char **env) {
3334 const char *e, *word = format;
3339 for (e = format; *e; e ++) {
3350 if (!(k = strnappend(r, word, e-word-1)))
3359 } else if (*e == '$') {
3360 if (!(k = strnappend(r, word, e-word)))
3376 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3379 if (!(k = strappend(r, t)))
3392 if (!(k = strnappend(r, word, e-word)))
3403 char **replace_env_argv(char **argv, char **env) {
3405 unsigned k = 0, l = 0;
3407 l = strv_length(argv);
3409 if (!(r = new(char*, l+1)))
3412 STRV_FOREACH(i, argv) {
3414 /* If $FOO appears as single word, replace it by the split up variable */
3415 if ((*i)[0] == '$' && (*i)[1] != '{') {
3420 if ((e = strv_env_get(env, *i+1))) {
3422 if (!(m = strv_split_quoted(e))) {
3433 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3442 memcpy(r + k, m, q * sizeof(char*));
3450 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3451 if (!(r[k++] = replace_env(*i, env))) {
3462 static __thread int parsed_columns = 0;
3465 if (parsed_columns > 0)
3466 return parsed_columns;
3468 if ((e = getenv("COLUMNS")))
3469 parsed_columns = atoi(e);
3471 if (parsed_columns <= 0) {
3475 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3476 parsed_columns = ws.ws_col;
3479 if (parsed_columns <= 0)
3480 parsed_columns = 80;
3482 return parsed_columns;
3485 int running_in_chroot(void) {
3491 /* Only works as root */
3493 if (stat("/proc/1/root", &a) < 0)
3496 if (stat("/", &b) < 0)
3500 a.st_dev != b.st_dev ||
3501 a.st_ino != b.st_ino;
3504 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3509 assert(percent <= 100);
3510 assert(length >= 3);
3514 if (l <= 3 || l <= length)
3517 if (!(r = new0(char, length+1)))
3520 x = (length * percent) / 100;
3530 s + l - (length - x - 3),
3536 int touch(const char *path) {
3541 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3544 close_nointr_nofail(fd);
3548 char *unquote(const char *s, const char* quotes) {
3552 if ((l = strlen(s)) < 2)
3555 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3556 return strndup(s+1, l-2);
3561 char *normalize_env_assignment(const char *s) {
3562 char *name, *value, *p, *r;
3567 if (!(r = strdup(s)))
3573 if (!(name = strndup(s, p - s)))
3576 if (!(p = strdup(p+1))) {
3581 value = unquote(strstrip(p), QUOTES);
3589 if (asprintf(&r, "%s=%s", name, value) < 0)
3598 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3605 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3617 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3624 if ((r = wait_for_terminate(pid, &status)) < 0) {
3625 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3629 if (status.si_code == CLD_EXITED) {
3630 if (status.si_status != 0) {
3631 log_warning("%s failed with error code %i.", name, status.si_status);
3632 return status.si_status;
3635 log_debug("%s succeeded.", name);
3638 } else if (status.si_code == CLD_KILLED ||
3639 status.si_code == CLD_DUMPED) {
3641 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3645 log_warning("%s failed due to unknown reason.", name);
3652 /* Make sure nobody waits for us on a socket anymore */
3653 close_all_fds(NULL, 0);
3661 bool null_or_empty(struct stat *st) {
3664 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3667 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3673 DIR *xopendirat(int fd, const char *name, int flags) {
3677 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3680 if (!(d = fdopendir(nfd))) {
3681 close_nointr_nofail(nfd);
3688 int signal_from_string_try_harder(const char *s) {
3692 if ((signo = signal_from_string(s)) <= 0)
3693 if (startswith(s, "SIG"))
3694 return signal_from_string(s+3);
3699 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3705 if (!dual_timestamp_is_set(t))
3708 fprintf(f, "%s=%llu %llu\n",
3710 (unsigned long long) t->realtime,
3711 (unsigned long long) t->monotonic);
3714 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3715 unsigned long long a, b;
3720 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3721 log_debug("Failed to parse finish timestamp value %s", value);
3728 char *fstab_node_to_udev_node(const char *p) {
3732 /* FIXME: to follow udev's logic 100% we need to leave valid
3733 * UTF8 chars unescaped */
3735 if (startswith(p, "LABEL=")) {
3737 if (!(u = unquote(p+6, "\"\'")))
3740 t = xescape(u, "/ ");
3746 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3755 if (startswith(p, "UUID=")) {
3757 if (!(u = unquote(p+5, "\"\'")))
3760 t = xescape(u, "/ ");
3766 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3778 void filter_environ(const char *prefix) {
3785 for (i = 0, j = 0; environ[i]; i++) {
3787 if (startswith(environ[i], prefix))
3790 environ[j++] = environ[i];
3796 bool tty_is_vc(const char *tty) {
3799 if (startswith(tty, "/dev/"))
3802 return startswith(tty, "tty") &&
3803 tty[3] >= '0' && tty[3] <= '9';
3806 const char *default_term_for_tty(const char *tty) {
3807 char *active = NULL;
3812 if (startswith(tty, "/dev/"))
3815 /* Resolve where /dev/console is pointing when determining
3817 if (streq(tty, "console"))
3818 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3819 truncate_nl(active);
3821 /* If multiple log outputs are configured the
3822 * last one is what /dev/console points to */
3823 if ((tty = strrchr(active, ' ')))
3829 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3835 /* Returns a short identifier for the various VM implementations */
3836 int detect_vm(const char **id) {
3838 #if defined(__i386__) || defined(__x86_64__)
3840 /* Both CPUID and DMI are x86 specific interfaces... */
3842 static const char *const dmi_vendors[] = {
3843 "/sys/class/dmi/id/sys_vendor",
3844 "/sys/class/dmi/id/board_vendor",
3845 "/sys/class/dmi/id/bios_vendor"
3848 static const char dmi_vendor_table[] =
3850 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3851 "VMware\0" "vmware\0"
3853 "Microsoft Corporation\0" "microsoft\0"
3854 "innotek GmbH\0" "oracle\0"
3856 "Bochs\0" "bochs\0";
3858 static const char cpuid_vendor_table[] =
3859 "XenVMMXenVMM\0" "xen\0"
3860 "KVMKVMKVM\0" "kvm\0"
3861 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3862 "VMwareVMware\0" "vmware\0"
3863 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3864 "Microsoft Hv\0" "microsoft\0";
3875 /* http://lwn.net/Articles/301888/ */
3878 #if defined (__i386__)
3881 #elif defined (__amd64__)
3886 /* First detect whether there is a hypervisor */
3888 __asm__ __volatile__ (
3889 /* ebx/rbx is being used for PIC! */
3890 " push %%"REG_b" \n\t"
3892 " pop %%"REG_b" \n\t"
3894 : "=a" (eax), "=c" (ecx)
3898 hypervisor = !!(ecx & ecx & 0x80000000U);
3902 /* There is a hypervisor, see what it is */
3904 __asm__ __volatile__ (
3905 /* ebx/rbx is being used for PIC! */
3906 " push %%"REG_b" \n\t"
3908 " mov %%ebx, %1 \n\t"
3909 " pop %%"REG_b" \n\t"
3911 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3915 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3916 if (streq(sig.text, j)) {
3925 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3928 const char *found = NULL;
3930 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3937 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3938 if (startswith(s, j))
3961 int detect_container(const char **id) {
3964 /* Unfortunately many of these operations require root access
3965 * in one way or another */
3970 if (running_in_chroot() > 0) {
3978 /* /proc/vz exists in container and outside of the container,
3979 * /proc/bc only outside of the container. */
3980 if (access("/proc/vz", F_OK) >= 0 &&
3981 access("/proc/bc", F_OK) < 0) {
3989 if ((f = fopen("/proc/self/cgroup", "r"))) {
3992 char line[LINE_MAX], *p;
3994 if (!fgets(line, sizeof(line), f))
3997 if (!(p = strchr(strstrip(line), ':')))
4000 if (strncmp(p, ":ns:", 4))
4003 if (!streq(p, ":ns:/")) {
4019 /* Returns a short identifier for the various VM/container implementations */
4020 int detect_virtualization(const char **id) {
4021 static __thread const char *cached_id = NULL;
4027 if (cached_id == (const char*) -1)
4036 if ((r = detect_container(&_id)) != 0)
4039 r = detect_vm(&_id);
4048 cached_id = (const char*) -1;
4053 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4056 Hashmap *pids = NULL;
4060 /* Executes all binaries in a directory in parallel and waits
4061 * until all they all finished. */
4064 if (!(_d = opendir(directory))) {
4066 if (errno == ENOENT)
4069 log_error("Failed to enumerate directory %s: %m", directory);
4076 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4077 log_error("Failed to allocate set.");
4081 while ((de = readdir(d))) {
4086 if (ignore_file(de->d_name))
4089 if (de->d_type != DT_REG &&
4090 de->d_type != DT_LNK &&
4091 de->d_type != DT_UNKNOWN)
4094 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4095 log_error("Out of memory");
4099 if ((pid = fork()) < 0) {
4100 log_error("Failed to fork: %m");
4119 log_error("Failed to execute %s: %m", path);
4120 _exit(EXIT_FAILURE);
4123 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4125 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4126 log_error("Failed to add PID to set: %s", strerror(-k));
4131 while (!hashmap_isempty(pids)) {
4136 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4141 log_error("waitid() failed: %m");
4145 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4146 if (!is_clean_exit(si.si_code, si.si_status)) {
4147 if (si.si_code == CLD_EXITED)
4148 log_error("%s exited with exit status %i.", path, si.si_status);
4150 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4152 log_debug("%s exited successfully.", path);
4163 hashmap_free_free(pids);
4166 int kill_and_sigcont(pid_t pid, int sig) {
4169 r = kill(pid, sig) < 0 ? -errno : 0;
4177 bool nulstr_contains(const char*nulstr, const char *needle) {
4183 NULSTR_FOREACH(i, nulstr)
4184 if (streq(i, needle))
4190 bool plymouth_running(void) {
4191 return access("/run/plymouth/pid", F_OK) >= 0;
4194 static const char *const ioprio_class_table[] = {
4195 [IOPRIO_CLASS_NONE] = "none",
4196 [IOPRIO_CLASS_RT] = "realtime",
4197 [IOPRIO_CLASS_BE] = "best-effort",
4198 [IOPRIO_CLASS_IDLE] = "idle"
4201 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4203 static const char *const sigchld_code_table[] = {
4204 [CLD_EXITED] = "exited",
4205 [CLD_KILLED] = "killed",
4206 [CLD_DUMPED] = "dumped",
4207 [CLD_TRAPPED] = "trapped",
4208 [CLD_STOPPED] = "stopped",
4209 [CLD_CONTINUED] = "continued",
4212 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4214 static const char *const log_facility_table[LOG_NFACILITIES] = {
4215 [LOG_FAC(LOG_KERN)] = "kern",
4216 [LOG_FAC(LOG_USER)] = "user",
4217 [LOG_FAC(LOG_MAIL)] = "mail",
4218 [LOG_FAC(LOG_DAEMON)] = "daemon",
4219 [LOG_FAC(LOG_AUTH)] = "auth",
4220 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4221 [LOG_FAC(LOG_LPR)] = "lpr",
4222 [LOG_FAC(LOG_NEWS)] = "news",
4223 [LOG_FAC(LOG_UUCP)] = "uucp",
4224 [LOG_FAC(LOG_CRON)] = "cron",
4225 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4226 [LOG_FAC(LOG_FTP)] = "ftp",
4227 [LOG_FAC(LOG_LOCAL0)] = "local0",
4228 [LOG_FAC(LOG_LOCAL1)] = "local1",
4229 [LOG_FAC(LOG_LOCAL2)] = "local2",
4230 [LOG_FAC(LOG_LOCAL3)] = "local3",
4231 [LOG_FAC(LOG_LOCAL4)] = "local4",
4232 [LOG_FAC(LOG_LOCAL5)] = "local5",
4233 [LOG_FAC(LOG_LOCAL6)] = "local6",
4234 [LOG_FAC(LOG_LOCAL7)] = "local7"
4237 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
4239 static const char *const log_level_table[] = {
4240 [LOG_EMERG] = "emerg",
4241 [LOG_ALERT] = "alert",
4242 [LOG_CRIT] = "crit",
4244 [LOG_WARNING] = "warning",
4245 [LOG_NOTICE] = "notice",
4246 [LOG_INFO] = "info",
4247 [LOG_DEBUG] = "debug"
4250 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4252 static const char* const sched_policy_table[] = {
4253 [SCHED_OTHER] = "other",
4254 [SCHED_BATCH] = "batch",
4255 [SCHED_IDLE] = "idle",
4256 [SCHED_FIFO] = "fifo",
4260 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4262 static const char* const rlimit_table[] = {
4263 [RLIMIT_CPU] = "LimitCPU",
4264 [RLIMIT_FSIZE] = "LimitFSIZE",
4265 [RLIMIT_DATA] = "LimitDATA",
4266 [RLIMIT_STACK] = "LimitSTACK",
4267 [RLIMIT_CORE] = "LimitCORE",
4268 [RLIMIT_RSS] = "LimitRSS",
4269 [RLIMIT_NOFILE] = "LimitNOFILE",
4270 [RLIMIT_AS] = "LimitAS",
4271 [RLIMIT_NPROC] = "LimitNPROC",
4272 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4273 [RLIMIT_LOCKS] = "LimitLOCKS",
4274 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4275 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4276 [RLIMIT_NICE] = "LimitNICE",
4277 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4278 [RLIMIT_RTTIME] = "LimitRTTIME"
4281 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4283 static const char* const ip_tos_table[] = {
4284 [IPTOS_LOWDELAY] = "low-delay",
4285 [IPTOS_THROUGHPUT] = "throughput",
4286 [IPTOS_RELIABILITY] = "reliability",
4287 [IPTOS_LOWCOST] = "low-cost",
4290 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4292 static const char *const signal_table[] = {
4309 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4320 [SIGVTALRM] = "VTALRM",
4322 [SIGWINCH] = "WINCH",
4328 DEFINE_STRING_TABLE_LOOKUP(signal, int);