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>
53 #include <sys/capability.h>
62 #include "exit-status.h"
65 size_t page_size(void) {
66 static __thread size_t pgsz = 0;
72 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
79 bool streq_ptr(const char *a, const char *b) {
81 /* Like streq(), but tries to make sense of NULL pointers */
92 usec_t now(clockid_t clock_id) {
95 assert_se(clock_gettime(clock_id, &ts) == 0);
97 return timespec_load(&ts);
100 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
103 ts->realtime = now(CLOCK_REALTIME);
104 ts->monotonic = now(CLOCK_MONOTONIC);
109 usec_t timespec_load(const struct timespec *ts) {
113 (usec_t) ts->tv_sec * USEC_PER_SEC +
114 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
117 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
120 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
121 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
126 usec_t timeval_load(const struct timeval *tv) {
130 (usec_t) tv->tv_sec * USEC_PER_SEC +
131 (usec_t) tv->tv_usec;
134 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
137 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
138 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
143 bool endswith(const char *s, const char *postfix) {
150 pl = strlen(postfix);
158 return memcmp(s + sl - pl, postfix, pl) == 0;
161 bool startswith(const char *s, const char *prefix) {
176 return memcmp(s, prefix, pl) == 0;
179 bool startswith_no_case(const char *s, const char *prefix) {
195 for(i = 0; i < pl; ++i) {
196 if (tolower(s[i]) != tolower(prefix[i]))
203 bool first_word(const char *s, const char *word) {
218 if (memcmp(s, word, wl) != 0)
222 strchr(WHITESPACE, s[wl]);
225 int close_nointr(int fd) {
231 if ((r = close(fd)) >= 0)
239 void close_nointr_nofail(int fd) {
240 int saved_errno = errno;
242 /* like close_nointr() but cannot fail, and guarantees errno
245 assert_se(close_nointr(fd) == 0);
250 void close_many(const int fds[], unsigned n_fd) {
253 for (i = 0; i < n_fd; i++)
254 close_nointr_nofail(fds[i]);
257 int parse_boolean(const char *v) {
260 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
262 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
268 int parse_pid(const char *s, pid_t* ret_pid) {
269 unsigned long ul = 0;
276 if ((r = safe_atolu(s, &ul)) < 0)
281 if ((unsigned long) pid != ul)
291 int safe_atou(const char *s, unsigned *ret_u) {
299 l = strtoul(s, &x, 0);
301 if (!x || *x || errno)
302 return errno ? -errno : -EINVAL;
304 if ((unsigned long) (unsigned) l != l)
307 *ret_u = (unsigned) l;
311 int safe_atoi(const char *s, int *ret_i) {
319 l = strtol(s, &x, 0);
321 if (!x || *x || errno)
322 return errno ? -errno : -EINVAL;
324 if ((long) (int) l != l)
331 int safe_atollu(const char *s, long long unsigned *ret_llu) {
333 unsigned long long l;
339 l = strtoull(s, &x, 0);
341 if (!x || *x || errno)
342 return errno ? -errno : -EINVAL;
348 int safe_atolli(const char *s, long long int *ret_lli) {
356 l = strtoll(s, &x, 0);
358 if (!x || *x || errno)
359 return errno ? -errno : -EINVAL;
365 /* Split a string into words. */
366 char *split(const char *c, size_t *l, const char *separator, char **state) {
369 current = *state ? *state : (char*) c;
371 if (!*current || *c == 0)
374 current += strspn(current, separator);
375 *l = strcspn(current, separator);
378 return (char*) current;
381 /* Split a string into words, but consider strings enclosed in '' and
382 * "" as words even if they include spaces. */
383 char *split_quoted(const char *c, size_t *l, char **state) {
385 bool escaped = false;
387 current = *state ? *state : (char*) c;
389 if (!*current || *c == 0)
392 current += strspn(current, WHITESPACE);
394 if (*current == '\'') {
397 for (e = current; *e; e++) {
407 *state = *e == 0 ? e : e+1;
408 } else if (*current == '\"') {
411 for (e = current; *e; e++) {
421 *state = *e == 0 ? e : e+1;
423 for (e = current; *e; e++) {
428 else if (strchr(WHITESPACE, *e))
435 return (char*) current;
438 char **split_path_and_make_absolute(const char *p) {
442 if (!(l = strv_split(p, ":")))
445 if (!strv_path_make_absolute_cwd(l)) {
453 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
456 char fn[PATH_MAX], line[LINE_MAX], *p;
462 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
465 if (!(f = fopen(fn, "r")))
468 if (!(fgets(line, sizeof(line), f))) {
476 /* Let's skip the pid and comm fields. The latter is enclosed
477 * in () but does not escape any () in its value, so let's
478 * skip over it manually */
480 if (!(p = strrchr(line, ')')))
491 if ((long unsigned) (pid_t) ppid != ppid)
494 *_ppid = (pid_t) ppid;
499 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
502 char fn[PATH_MAX], line[LINE_MAX], *p;
507 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
510 if (!(f = fopen(fn, "r")))
513 if (!(fgets(line, sizeof(line), f))) {
521 /* Let's skip the pid and comm fields. The latter is enclosed
522 * in () but does not escape any () in its value, so let's
523 * skip over it manually */
525 if (!(p = strrchr(line, ')')))
546 "%*d " /* priority */
548 "%*d " /* num_threads */
549 "%*d " /* itrealvalue */
550 "%llu " /* starttime */,
557 int write_one_line_file(const char *fn, const char *line) {
564 if (!(f = fopen(fn, "we")))
567 if (fputs(line, f) < 0) {
572 if (!endswith(line, "\n"))
590 int read_one_line_file(const char *fn, char **line) {
593 char t[LINE_MAX], *c;
598 if (!(f = fopen(fn, "re")))
601 if (!(fgets(t, sizeof(t), f))) {
606 if (!(c = strdup(t))) {
621 int read_full_file(const char *fn, char **contents) {
628 if (!(f = fopen(fn, "re")))
631 if (fstat(fileno(f), &st) < 0) {
636 n = st.st_size > 0 ? st.st_size : LINE_MAX;
643 if (!(t = realloc(buf, n+1))) {
649 k = fread(buf + l, 1, n - l, f);
664 if (n > 4*1024*1024) {
672 else if (!(buf = calloc(1, 1))) {
691 const char *separator, ...) {
699 if ((r = read_full_file(fname, &contents)) < 0)
704 const char *key = NULL;
706 p += strspn(p, separator);
707 p += strspn(p, WHITESPACE);
712 if (!strchr(COMMENTS, *p)) {
716 va_start(ap, separator);
717 while ((key = va_arg(ap, char *))) {
721 value = va_arg(ap, char **);
724 if (strncmp(p, key, n) != 0 ||
729 n = strcspn(p, separator);
732 strchr(QUOTES, p[0]) &&
734 v = strndup(p+1, n-2);
745 /* return empty value strings as NULL */
762 p += strcspn(p, separator);
781 if (!(f = fopen(fname, "re")))
785 char l[LINE_MAX], *p, *u;
788 if (!fgets(l, sizeof(l), f)) {
801 if (strchr(COMMENTS, *p))
804 if (!(u = normalize_env_assignment(p))) {
805 log_error("Out of memory");
810 t = strv_append(m, u);
814 log_error("Out of memory");
837 int write_env_file(const char *fname, char **l) {
843 f = fopen(fname, "we");
854 r = ferror(f) ? -errno : 0;
860 char *truncate_nl(char *s) {
863 s[strcspn(s, NEWLINE)] = 0;
867 int get_process_name(pid_t pid, char **name) {
874 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
877 r = read_one_line_file(p, name);
886 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
894 assert(max_length > 0);
897 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
906 if (!(r = new(char, max_length))) {
913 while ((c = getc(f)) != EOF) {
935 size_t n = MIN(left-1, 3U);
943 /* Kernel threads have no argv[] */
950 if ((h = get_process_name(pid, &t)) < 0)
953 h = asprintf(&r, "[%s]", t);
964 char *strnappend(const char *s, const char *suffix, size_t b) {
972 return strndup(suffix, b);
982 if (!(r = new(char, a+b+1)))
986 memcpy(r+a, suffix, b);
992 char *strappend(const char *s, const char *suffix) {
993 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
996 int readlink_malloc(const char *p, char **r) {
1006 if (!(c = new(char, l)))
1009 if ((n = readlink(p, c, l-1)) < 0) {
1015 if ((size_t) n < l-1) {
1026 int readlink_and_make_absolute(const char *p, char **r) {
1033 if ((j = readlink_malloc(p, &target)) < 0)
1036 k = file_in_same_dir(p, target);
1046 int parent_of_path(const char *path, char **_r) {
1047 const char *e, *a = NULL, *b = NULL, *p;
1057 for (e = path; *e; e++) {
1059 if (!slash && *e == '/') {
1063 } else if (slash && *e != '/')
1078 r = strndup(path, p-path);
1088 char *file_name_from_path(const char *p) {
1093 if ((r = strrchr(p, '/')))
1099 bool path_is_absolute(const char *p) {
1105 bool is_path(const char *p) {
1107 return !!strchr(p, '/');
1110 char *path_make_absolute(const char *p, const char *prefix) {
1115 /* Makes every item in the list an absolute path by prepending
1116 * the prefix, if specified and necessary */
1118 if (path_is_absolute(p) || !prefix)
1121 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1127 char *path_make_absolute_cwd(const char *p) {
1132 /* Similar to path_make_absolute(), but prefixes with the
1133 * current working directory. */
1135 if (path_is_absolute(p))
1138 if (!(cwd = get_current_dir_name()))
1141 r = path_make_absolute(p, cwd);
1147 char **strv_path_make_absolute_cwd(char **l) {
1150 /* Goes through every item in the string list and makes it
1151 * absolute. This works in place and won't rollback any
1152 * changes on failure. */
1154 STRV_FOREACH(s, l) {
1157 if (!(t = path_make_absolute_cwd(*s)))
1167 char **strv_path_canonicalize(char **l) {
1170 bool enomem = false;
1172 if (strv_isempty(l))
1175 /* Goes through every item in the string list and canonicalize
1176 * the path. This works in place and won't rollback any
1177 * changes on failure. */
1179 STRV_FOREACH(s, l) {
1182 t = path_make_absolute_cwd(*s);
1191 u = canonicalize_file_name(t);
1195 if (errno == ENOMEM || !errno)
1212 char **strv_path_remove_empty(char **l) {
1218 for (f = t = l; *f; f++) {
1220 if (dir_is_empty(*f) > 0) {
1232 int reset_all_signal_handlers(void) {
1235 for (sig = 1; sig < _NSIG; sig++) {
1236 struct sigaction sa;
1238 if (sig == SIGKILL || sig == SIGSTOP)
1242 sa.sa_handler = SIG_DFL;
1243 sa.sa_flags = SA_RESTART;
1245 /* On Linux the first two RT signals are reserved by
1246 * glibc, and sigaction() will return EINVAL for them. */
1247 if ((sigaction(sig, &sa, NULL) < 0))
1248 if (errno != EINVAL)
1255 char *strstrip(char *s) {
1258 /* Drops trailing whitespace. Modifies the string in
1259 * place. Returns pointer to first non-space character */
1261 s += strspn(s, WHITESPACE);
1263 for (e = s; *e; e++)
1264 if (!strchr(WHITESPACE, *e))
1275 char *delete_chars(char *s, const char *bad) {
1278 /* Drops all whitespace, regardless where in the string */
1280 for (f = s, t = s; *f; f++) {
1281 if (strchr(bad, *f))
1292 char *file_in_same_dir(const char *path, const char *filename) {
1299 /* This removes the last component of path and appends
1300 * filename, unless the latter is absolute anyway or the
1303 if (path_is_absolute(filename))
1304 return strdup(filename);
1306 if (!(e = strrchr(path, '/')))
1307 return strdup(filename);
1309 k = strlen(filename);
1310 if (!(r = new(char, e-path+1+k+1)))
1313 memcpy(r, path, e-path+1);
1314 memcpy(r+(e-path)+1, filename, k+1);
1319 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1322 if (label_mkdir(path, mode) >= 0)
1323 if (chmod_and_chown(path, mode, uid, gid) < 0)
1326 if (lstat(path, &st) < 0)
1329 if ((st.st_mode & 0777) != mode ||
1332 !S_ISDIR(st.st_mode)) {
1341 int mkdir_parents(const char *path, mode_t mode) {
1346 /* Creates every parent directory in the path except the last
1349 p = path + strspn(path, "/");
1354 e = p + strcspn(p, "/");
1355 p = e + strspn(e, "/");
1357 /* Is this the last component? If so, then we're
1362 if (!(t = strndup(path, e - path)))
1365 r = label_mkdir(t, mode);
1368 if (r < 0 && errno != EEXIST)
1373 int mkdir_p(const char *path, mode_t mode) {
1378 if ((r = mkdir_parents(path, mode)) < 0)
1381 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1387 int rmdir_parents(const char *path, const char *stop) {
1396 /* Skip trailing slashes */
1397 while (l > 0 && path[l-1] == '/')
1403 /* Skip last component */
1404 while (l > 0 && path[l-1] != '/')
1407 /* Skip trailing slashes */
1408 while (l > 0 && path[l-1] == '/')
1414 if (!(t = strndup(path, l)))
1417 if (path_startswith(stop, t)) {
1426 if (errno != ENOENT)
1434 char hexchar(int x) {
1435 static const char table[16] = "0123456789abcdef";
1437 return table[x & 15];
1440 int unhexchar(char c) {
1442 if (c >= '0' && c <= '9')
1445 if (c >= 'a' && c <= 'f')
1446 return c - 'a' + 10;
1448 if (c >= 'A' && c <= 'F')
1449 return c - 'A' + 10;
1454 char octchar(int x) {
1455 return '0' + (x & 7);
1458 int unoctchar(char c) {
1460 if (c >= '0' && c <= '7')
1466 char decchar(int x) {
1467 return '0' + (x % 10);
1470 int undecchar(char c) {
1472 if (c >= '0' && c <= '9')
1478 char *cescape(const char *s) {
1484 /* Does C style string escaping. */
1486 if (!(r = new(char, strlen(s)*4 + 1)))
1489 for (f = s, t = r; *f; f++)
1535 /* For special chars we prefer octal over
1536 * hexadecimal encoding, simply because glib's
1537 * g_strescape() does the same */
1538 if ((*f < ' ') || (*f >= 127)) {
1540 *(t++) = octchar((unsigned char) *f >> 6);
1541 *(t++) = octchar((unsigned char) *f >> 3);
1542 *(t++) = octchar((unsigned char) *f);
1553 char *cunescape_length(const char *s, size_t length) {
1559 /* Undoes C style string escaping */
1561 if (!(r = new(char, length+1)))
1564 for (f = s, t = r; f < s + length; f++) {
1607 /* This is an extension of the XDG syntax files */
1612 /* hexadecimal encoding */
1615 if ((a = unhexchar(f[1])) < 0 ||
1616 (b = unhexchar(f[2])) < 0) {
1617 /* Invalid escape code, let's take it literal then */
1621 *(t++) = (char) ((a << 4) | b);
1636 /* octal encoding */
1639 if ((a = unoctchar(f[0])) < 0 ||
1640 (b = unoctchar(f[1])) < 0 ||
1641 (c = unoctchar(f[2])) < 0) {
1642 /* Invalid escape code, let's take it literal then */
1646 *(t++) = (char) ((a << 6) | (b << 3) | c);
1654 /* premature end of string.*/
1659 /* Invalid escape code, let's take it literal then */
1671 char *cunescape(const char *s) {
1672 return cunescape_length(s, strlen(s));
1675 char *xescape(const char *s, const char *bad) {
1679 /* Escapes all chars in bad, in addition to \ and all special
1680 * chars, in \xFF style escaping. May be reversed with
1683 if (!(r = new(char, strlen(s)*4+1)))
1686 for (f = s, t = r; *f; f++) {
1688 if ((*f < ' ') || (*f >= 127) ||
1689 (*f == '\\') || strchr(bad, *f)) {
1692 *(t++) = hexchar(*f >> 4);
1693 *(t++) = hexchar(*f);
1703 char *bus_path_escape(const char *s) {
1709 /* Escapes all chars that D-Bus' object path cannot deal
1710 * with. Can be reverse with bus_path_unescape() */
1712 if (!(r = new(char, strlen(s)*3+1)))
1715 for (f = s, t = r; *f; f++) {
1717 if (!(*f >= 'A' && *f <= 'Z') &&
1718 !(*f >= 'a' && *f <= 'z') &&
1719 !(*f >= '0' && *f <= '9')) {
1721 *(t++) = hexchar(*f >> 4);
1722 *(t++) = hexchar(*f);
1732 char *bus_path_unescape(const char *f) {
1737 if (!(r = strdup(f)))
1740 for (t = r; *f; f++) {
1745 if ((a = unhexchar(f[1])) < 0 ||
1746 (b = unhexchar(f[2])) < 0) {
1747 /* Invalid escape code, let's take it literal then */
1750 *(t++) = (char) ((a << 4) | b);
1762 char *path_kill_slashes(char *path) {
1766 /* Removes redundant inner and trailing slashes. Modifies the
1767 * passed string in-place.
1769 * ///foo///bar/ becomes /foo/bar
1772 for (f = path, t = path; *f; f++) {
1787 /* Special rule, if we are talking of the root directory, a
1788 trailing slash is good */
1790 if (t == path && slash)
1797 bool path_startswith(const char *path, const char *prefix) {
1801 if ((path[0] == '/') != (prefix[0] == '/'))
1807 path += strspn(path, "/");
1808 prefix += strspn(prefix, "/");
1816 a = strcspn(path, "/");
1817 b = strcspn(prefix, "/");
1822 if (memcmp(path, prefix, a) != 0)
1830 bool path_equal(const char *a, const char *b) {
1834 if ((a[0] == '/') != (b[0] == '/'))
1840 a += strspn(a, "/");
1841 b += strspn(b, "/");
1843 if (*a == 0 && *b == 0)
1846 if (*a == 0 || *b == 0)
1849 j = strcspn(a, "/");
1850 k = strcspn(b, "/");
1855 if (memcmp(a, b, j) != 0)
1863 char *ascii_strlower(char *t) {
1868 for (p = t; *p; p++)
1869 if (*p >= 'A' && *p <= 'Z')
1870 *p = *p - 'A' + 'a';
1875 bool ignore_file(const char *filename) {
1879 filename[0] == '.' ||
1880 streq(filename, "lost+found") ||
1881 streq(filename, "aquota.user") ||
1882 streq(filename, "aquota.group") ||
1883 endswith(filename, "~") ||
1884 endswith(filename, ".rpmnew") ||
1885 endswith(filename, ".rpmsave") ||
1886 endswith(filename, ".rpmorig") ||
1887 endswith(filename, ".dpkg-old") ||
1888 endswith(filename, ".dpkg-new") ||
1889 endswith(filename, ".swp");
1892 int fd_nonblock(int fd, bool nonblock) {
1897 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1901 flags |= O_NONBLOCK;
1903 flags &= ~O_NONBLOCK;
1905 if (fcntl(fd, F_SETFL, flags) < 0)
1911 int fd_cloexec(int fd, bool cloexec) {
1916 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1920 flags |= FD_CLOEXEC;
1922 flags &= ~FD_CLOEXEC;
1924 if (fcntl(fd, F_SETFD, flags) < 0)
1930 int close_all_fds(const int except[], unsigned n_except) {
1935 if (!(d = opendir("/proc/self/fd")))
1938 while ((de = readdir(d))) {
1941 if (ignore_file(de->d_name))
1944 if (safe_atoi(de->d_name, &fd) < 0)
1945 /* Let's better ignore this, just in case */
1959 for (i = 0; i < n_except; i++)
1960 if (except[i] == fd) {
1969 if (close_nointr(fd) < 0) {
1970 /* Valgrind has its own FD and doesn't want to have it closed */
1971 if (errno != EBADF && r == 0)
1980 bool chars_intersect(const char *a, const char *b) {
1983 /* Returns true if any of the chars in a are in b. */
1984 for (p = a; *p; p++)
1991 char *format_timestamp(char *buf, size_t l, usec_t t) {
2001 sec = (time_t) (t / USEC_PER_SEC);
2003 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2009 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2012 n = now(CLOCK_REALTIME);
2014 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2019 if (d >= USEC_PER_YEAR)
2020 snprintf(buf, l, "%llu years and %llu months ago",
2021 (unsigned long long) (d / USEC_PER_YEAR),
2022 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2023 else if (d >= USEC_PER_MONTH)
2024 snprintf(buf, l, "%llu months and %llu days ago",
2025 (unsigned long long) (d / USEC_PER_MONTH),
2026 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2027 else if (d >= USEC_PER_WEEK)
2028 snprintf(buf, l, "%llu weeks and %llu days ago",
2029 (unsigned long long) (d / USEC_PER_WEEK),
2030 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2031 else if (d >= 2*USEC_PER_DAY)
2032 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2033 else if (d >= 25*USEC_PER_HOUR)
2034 snprintf(buf, l, "1 day and %lluh ago",
2035 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2036 else if (d >= 6*USEC_PER_HOUR)
2037 snprintf(buf, l, "%lluh ago",
2038 (unsigned long long) (d / USEC_PER_HOUR));
2039 else if (d >= USEC_PER_HOUR)
2040 snprintf(buf, l, "%lluh %llumin ago",
2041 (unsigned long long) (d / USEC_PER_HOUR),
2042 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2043 else if (d >= 5*USEC_PER_MINUTE)
2044 snprintf(buf, l, "%llumin ago",
2045 (unsigned long long) (d / USEC_PER_MINUTE));
2046 else if (d >= USEC_PER_MINUTE)
2047 snprintf(buf, l, "%llumin %llus ago",
2048 (unsigned long long) (d / USEC_PER_MINUTE),
2049 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2050 else if (d >= USEC_PER_SEC)
2051 snprintf(buf, l, "%llus ago",
2052 (unsigned long long) (d / USEC_PER_SEC));
2053 else if (d >= USEC_PER_MSEC)
2054 snprintf(buf, l, "%llums ago",
2055 (unsigned long long) (d / USEC_PER_MSEC));
2057 snprintf(buf, l, "%lluus ago",
2058 (unsigned long long) d);
2060 snprintf(buf, l, "now");
2066 char *format_timespan(char *buf, size_t l, usec_t t) {
2067 static const struct {
2071 { "w", USEC_PER_WEEK },
2072 { "d", USEC_PER_DAY },
2073 { "h", USEC_PER_HOUR },
2074 { "min", USEC_PER_MINUTE },
2075 { "s", USEC_PER_SEC },
2076 { "ms", USEC_PER_MSEC },
2086 if (t == (usec_t) -1)
2090 snprintf(p, l, "0");
2095 /* The result of this function can be parsed with parse_usec */
2097 for (i = 0; i < ELEMENTSOF(table); i++) {
2101 if (t < table[i].usec)
2107 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2108 n = MIN((size_t) k, l);
2121 bool fstype_is_network(const char *fstype) {
2122 static const char * const table[] = {
2134 for (i = 0; i < ELEMENTSOF(table); i++)
2135 if (streq(table[i], fstype))
2144 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2149 TIOCL_GETKMSGREDIRECT,
2153 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2156 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2159 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2162 close_nointr_nofail(r);
2166 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2167 struct termios old_termios, new_termios;
2169 char line[LINE_MAX];
2174 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2175 new_termios = old_termios;
2177 new_termios.c_lflag &= ~ICANON;
2178 new_termios.c_cc[VMIN] = 1;
2179 new_termios.c_cc[VTIME] = 0;
2181 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2184 k = fread(&c, 1, 1, f);
2186 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2192 *need_nl = c != '\n';
2199 if (!(fgets(line, sizeof(line), f)))
2204 if (strlen(line) != 1)
2214 int ask(char *ret, const char *replies, const char *text, ...) {
2221 on_tty = isatty(STDOUT_FILENO);
2227 bool need_nl = true;
2230 fputs("\x1B[1m", stdout);
2237 fputs("\x1B[0m", stdout);
2241 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2243 if (r == -EBADMSG) {
2244 puts("Bad input, please try again.");
2255 if (strchr(replies, c)) {
2260 puts("Read unexpected character, please try again.");
2264 int reset_terminal(int fd) {
2265 struct termios termios;
2269 /* Set terminal to some sane defaults */
2273 /* We leave locked terminal attributes untouched, so that
2274 * Plymouth may set whatever it wants to set, and we don't
2275 * interfere with that. */
2277 /* Disable exclusive mode, just in case */
2278 ioctl(fd, TIOCNXCL);
2280 /* Enable console unicode mode */
2282 ioctl(fd, KDSKBMODE, &arg);
2284 if (tcgetattr(fd, &termios) < 0) {
2289 /* We only reset the stuff that matters to the software. How
2290 * hardware is set up we don't touch assuming that somebody
2291 * else will do that for us */
2293 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2294 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2295 termios.c_oflag |= ONLCR;
2296 termios.c_cflag |= CREAD;
2297 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2299 termios.c_cc[VINTR] = 03; /* ^C */
2300 termios.c_cc[VQUIT] = 034; /* ^\ */
2301 termios.c_cc[VERASE] = 0177;
2302 termios.c_cc[VKILL] = 025; /* ^X */
2303 termios.c_cc[VEOF] = 04; /* ^D */
2304 termios.c_cc[VSTART] = 021; /* ^Q */
2305 termios.c_cc[VSTOP] = 023; /* ^S */
2306 termios.c_cc[VSUSP] = 032; /* ^Z */
2307 termios.c_cc[VLNEXT] = 026; /* ^V */
2308 termios.c_cc[VWERASE] = 027; /* ^W */
2309 termios.c_cc[VREPRINT] = 022; /* ^R */
2310 termios.c_cc[VEOL] = 0;
2311 termios.c_cc[VEOL2] = 0;
2313 termios.c_cc[VTIME] = 0;
2314 termios.c_cc[VMIN] = 1;
2316 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2320 /* Just in case, flush all crap out */
2321 tcflush(fd, TCIOFLUSH);
2326 int open_terminal(const char *name, int mode) {
2331 * If a TTY is in the process of being closed opening it might
2332 * cause EIO. This is horribly awful, but unlikely to be
2333 * changed in the kernel. Hence we work around this problem by
2334 * retrying a couple of times.
2336 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2340 if ((fd = open(name, mode)) >= 0)
2349 usleep(50 * USEC_PER_MSEC);
2356 if ((r = isatty(fd)) < 0) {
2357 close_nointr_nofail(fd);
2362 close_nointr_nofail(fd);
2369 int flush_fd(int fd) {
2370 struct pollfd pollfd;
2374 pollfd.events = POLLIN;
2381 if ((r = poll(&pollfd, 1, 0)) < 0) {
2392 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2397 if (errno == EAGAIN)
2408 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2409 int fd = -1, notify = -1, r, wd = -1;
2413 /* We use inotify to be notified when the tty is closed. We
2414 * create the watch before checking if we can actually acquire
2415 * it, so that we don't lose any event.
2417 * Note: strictly speaking this actually watches for the
2418 * device being closed, it does *not* really watch whether a
2419 * tty loses its controlling process. However, unless some
2420 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2421 * its tty otherwise this will not become a problem. As long
2422 * as the administrator makes sure not configure any service
2423 * on the same tty as an untrusted user this should not be a
2424 * problem. (Which he probably should not do anyway.) */
2426 if (!fail && !force) {
2427 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2432 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2440 if ((r = flush_fd(notify)) < 0)
2443 /* We pass here O_NOCTTY only so that we can check the return
2444 * value TIOCSCTTY and have a reliable way to figure out if we
2445 * successfully became the controlling process of the tty */
2446 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2449 /* First, try to get the tty */
2450 r = ioctl(fd, TIOCSCTTY, force);
2452 /* Sometimes it makes sense to ignore TIOCSCTTY
2453 * returning EPERM, i.e. when very likely we already
2454 * are have this controlling terminal. */
2455 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2458 if (r < 0 && (force || fail || errno != EPERM)) {
2468 assert(notify >= 0);
2471 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2473 struct inotify_event *e;
2475 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2484 e = (struct inotify_event*) inotify_buffer;
2489 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2494 step = sizeof(struct inotify_event) + e->len;
2495 assert(step <= (size_t) l);
2497 e = (struct inotify_event*) ((uint8_t*) e + step);
2504 /* We close the tty fd here since if the old session
2505 * ended our handle will be dead. It's important that
2506 * we do this after sleeping, so that we don't enter
2507 * an endless loop. */
2508 close_nointr_nofail(fd);
2512 close_nointr_nofail(notify);
2514 if ((r = reset_terminal(fd)) < 0)
2515 log_warning("Failed to reset terminal: %s", strerror(-r));
2521 close_nointr_nofail(fd);
2524 close_nointr_nofail(notify);
2529 int release_terminal(void) {
2531 struct sigaction sa_old, sa_new;
2533 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2536 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2537 * by our own TIOCNOTTY */
2540 sa_new.sa_handler = SIG_IGN;
2541 sa_new.sa_flags = SA_RESTART;
2542 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2544 if (ioctl(fd, TIOCNOTTY) < 0)
2547 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2549 close_nointr_nofail(fd);
2553 int sigaction_many(const struct sigaction *sa, ...) {
2558 while ((sig = va_arg(ap, int)) > 0)
2559 if (sigaction(sig, sa, NULL) < 0)
2566 int ignore_signals(int sig, ...) {
2567 struct sigaction sa;
2572 sa.sa_handler = SIG_IGN;
2573 sa.sa_flags = SA_RESTART;
2575 if (sigaction(sig, &sa, NULL) < 0)
2579 while ((sig = va_arg(ap, int)) > 0)
2580 if (sigaction(sig, &sa, NULL) < 0)
2587 int default_signals(int sig, ...) {
2588 struct sigaction sa;
2593 sa.sa_handler = SIG_DFL;
2594 sa.sa_flags = SA_RESTART;
2596 if (sigaction(sig, &sa, NULL) < 0)
2600 while ((sig = va_arg(ap, int)) > 0)
2601 if (sigaction(sig, &sa, NULL) < 0)
2608 int close_pipe(int p[]) {
2614 a = close_nointr(p[0]);
2619 b = close_nointr(p[1]);
2623 return a < 0 ? a : b;
2626 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2635 while (nbytes > 0) {
2638 if ((k = read(fd, p, nbytes)) <= 0) {
2640 if (k < 0 && errno == EINTR)
2643 if (k < 0 && errno == EAGAIN && do_poll) {
2644 struct pollfd pollfd;
2648 pollfd.events = POLLIN;
2650 if (poll(&pollfd, 1, -1) < 0) {
2654 return n > 0 ? n : -errno;
2657 if (pollfd.revents != POLLIN)
2658 return n > 0 ? n : -EIO;
2663 return n > 0 ? n : (k < 0 ? -errno : 0);
2674 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2683 while (nbytes > 0) {
2686 if ((k = write(fd, p, nbytes)) <= 0) {
2688 if (k < 0 && errno == EINTR)
2691 if (k < 0 && errno == EAGAIN && do_poll) {
2692 struct pollfd pollfd;
2696 pollfd.events = POLLOUT;
2698 if (poll(&pollfd, 1, -1) < 0) {
2702 return n > 0 ? n : -errno;
2705 if (pollfd.revents != POLLOUT)
2706 return n > 0 ? n : -EIO;
2711 return n > 0 ? n : (k < 0 ? -errno : 0);
2722 int path_is_mount_point(const char *t) {
2727 if (lstat(t, &a) < 0) {
2728 if (errno == ENOENT)
2734 if ((r = parent_of_path(t, &parent)) < 0)
2737 r = lstat(parent, &b);
2743 return a.st_dev != b.st_dev;
2746 int parse_usec(const char *t, usec_t *usec) {
2747 static const struct {
2751 { "sec", USEC_PER_SEC },
2752 { "s", USEC_PER_SEC },
2753 { "min", USEC_PER_MINUTE },
2754 { "hr", USEC_PER_HOUR },
2755 { "h", USEC_PER_HOUR },
2756 { "d", USEC_PER_DAY },
2757 { "w", USEC_PER_WEEK },
2758 { "msec", USEC_PER_MSEC },
2759 { "ms", USEC_PER_MSEC },
2760 { "m", USEC_PER_MINUTE },
2763 { "", USEC_PER_SEC },
2779 l = strtoll(p, &e, 10);
2790 e += strspn(e, WHITESPACE);
2792 for (i = 0; i < ELEMENTSOF(table); i++)
2793 if (startswith(e, table[i].suffix)) {
2794 r += (usec_t) l * table[i].usec;
2795 p = e + strlen(table[i].suffix);
2799 if (i >= ELEMENTSOF(table))
2809 int make_stdio(int fd) {
2814 r = dup2(fd, STDIN_FILENO);
2815 s = dup2(fd, STDOUT_FILENO);
2816 t = dup2(fd, STDERR_FILENO);
2819 close_nointr_nofail(fd);
2821 if (r < 0 || s < 0 || t < 0)
2827 int make_null_stdio(void) {
2830 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2833 return make_stdio(null_fd);
2836 bool is_device_path(const char *path) {
2838 /* Returns true on paths that refer to a device, either in
2839 * sysfs or in /dev */
2842 path_startswith(path, "/dev/") ||
2843 path_startswith(path, "/sys/");
2846 int dir_is_empty(const char *path) {
2849 struct dirent buf, *de;
2851 if (!(d = opendir(path)))
2855 if ((r = readdir_r(d, &buf, &de)) > 0) {
2865 if (!ignore_file(de->d_name)) {
2875 unsigned long long random_ull(void) {
2880 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2883 r = loop_read(fd, &ull, sizeof(ull), true);
2884 close_nointr_nofail(fd);
2886 if (r != sizeof(ull))
2892 return random() * RAND_MAX + random();
2895 void rename_process(const char name[8]) {
2898 prctl(PR_SET_NAME, name);
2900 /* This is a like a poor man's setproctitle(). The string
2901 * passed should fit in 7 chars (i.e. the length of
2904 if (program_invocation_name)
2905 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2908 void sigset_add_many(sigset_t *ss, ...) {
2915 while ((sig = va_arg(ap, int)) > 0)
2916 assert_se(sigaddset(ss, sig) == 0);
2920 char* gethostname_malloc(void) {
2923 assert_se(uname(&u) >= 0);
2926 return strdup(u.nodename);
2928 return strdup(u.sysname);
2931 char* getlogname_malloc(void) {
2935 struct passwd pwbuf, *pw = NULL;
2938 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2943 /* Shortcut things to avoid NSS lookups */
2945 return strdup("root");
2947 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2950 if (!(buf = malloc(bufsize)))
2953 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2954 name = strdup(pw->pw_name);
2961 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2967 int getttyname_malloc(int fd, char **r) {
2968 char path[PATH_MAX], *c;
2973 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2978 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2985 int getttyname_harder(int fd, char **r) {
2989 if ((k = getttyname_malloc(fd, &s)) < 0)
2992 if (streq(s, "tty")) {
2994 return get_ctty(r, NULL);
3001 int get_ctty_devnr(dev_t *d) {
3003 char line[LINE_MAX], *p;
3004 unsigned long ttynr;
3007 if (!(f = fopen("/proc/self/stat", "r")))
3010 if (!(fgets(line, sizeof(line), f))) {
3018 if (!(p = strrchr(line, ')')))
3027 "%*d " /* session */
3036 int get_ctty(char **r, dev_t *_devnr) {
3038 char fn[PATH_MAX], *s, *b, *p;
3043 if ((k = get_ctty_devnr(&devnr)) < 0)
3046 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3049 if ((k = readlink_malloc(fn, &s)) < 0) {
3054 /* This is an ugly hack */
3055 if (major(devnr) == 136) {
3056 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3066 /* Probably something like the ptys which have no
3067 * symlink in /dev/char. Let's return something
3068 * vaguely useful. */
3070 if (!(b = strdup(fn + 5)))
3080 if (startswith(s, "/dev/"))
3082 else if (startswith(s, "../"))
3100 static int rm_rf_children(int fd, bool only_dirs) {
3106 /* This returns the first error we run into, but nevertheless
3109 if (!(d = fdopendir(fd))) {
3110 close_nointr_nofail(fd);
3112 return errno == ENOENT ? 0 : -errno;
3116 struct dirent buf, *de;
3120 if ((r = readdir_r(d, &buf, &de)) != 0) {
3129 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3132 if (de->d_type == DT_UNKNOWN) {
3135 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3136 if (ret == 0 && errno != ENOENT)
3141 is_dir = S_ISDIR(st.st_mode);
3143 is_dir = de->d_type == DT_DIR;
3148 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3149 if (ret == 0 && errno != ENOENT)
3154 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3159 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3160 if (ret == 0 && errno != ENOENT)
3163 } else if (!only_dirs) {
3165 if (unlinkat(fd, de->d_name, 0) < 0) {
3166 if (ret == 0 && errno != ENOENT)
3177 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3183 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3185 if (errno != ENOTDIR)
3188 if (delete_root && !only_dirs)
3189 if (unlink(path) < 0)
3195 r = rm_rf_children(fd, only_dirs);
3198 if (rmdir(path) < 0) {
3206 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3209 /* Under the assumption that we are running privileged we
3210 * first change the access mode and only then hand out
3211 * ownership to avoid a window where access is too open. */
3213 if (chmod(path, mode) < 0)
3216 if (chown(path, uid, gid) < 0)
3222 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3226 /* Allocates the cpuset in the right size */
3229 if (!(r = CPU_ALLOC(n)))
3232 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3233 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3243 if (errno != EINVAL)
3250 void status_vprintf(const char *format, va_list ap) {
3256 /* This independent of logging, as status messages are
3257 * optional and go exclusively to the console. */
3259 if (vasprintf(&s, format, ap) < 0)
3262 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3265 write(fd, s, strlen(s));
3271 close_nointr_nofail(fd);
3274 void status_printf(const char *format, ...) {
3279 va_start(ap, format);
3280 status_vprintf(format, ap);
3284 void status_welcome(void) {
3285 char *pretty_name = NULL, *ansi_color = NULL;
3286 const char *const_pretty = NULL, *const_color = NULL;
3289 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3290 "PRETTY_NAME", &pretty_name,
3291 "ANSI_COLOR", &ansi_color,
3295 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3298 #if defined(TARGET_FEDORA)
3300 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3303 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3307 if (!ansi_color && pretty_name) {
3309 /* This tries to mimic the color magic the old Red Hat sysinit
3312 if (startswith(pretty_name, "Red Hat"))
3313 const_color = "0;31"; /* Red for RHEL */
3314 else if (startswith(pretty_name, "Fedora"))
3315 const_color = "0;34"; /* Blue for Fedora */
3318 #elif defined(TARGET_SUSE)
3321 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3324 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3329 const_color = "0;32"; /* Green for openSUSE */
3331 #elif defined(TARGET_GENTOO)
3334 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3337 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3342 const_color = "1;34"; /* Light Blue for Gentoo */
3344 #elif defined(TARGET_ALTLINUX)
3347 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3350 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3355 const_color = "0;36"; /* Cyan for ALTLinux */
3358 #elif defined(TARGET_DEBIAN)
3363 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3366 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3368 pretty_name = strappend("Debian ", version);
3372 log_warning("Failed to allocate Debian version string.");
3377 const_color = "1;31"; /* Light Red for Debian */
3379 #elif defined(TARGET_UBUNTU)
3381 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3382 "DISTRIB_DESCRIPTION", &pretty_name,
3386 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3390 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3392 #elif defined(TARGET_MANDRIVA)
3397 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3399 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3401 p = strstr(s, " release ");
3405 p[strcspn(p, " ")] = '\0';
3407 /* This corresponds to standard rc.sysinit */
3408 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3409 const_color = "1;36";
3411 log_warning("Failed to allocate Mandriva version string.");
3413 log_warning("Failed to parse /etc/mandriva-release");
3417 #elif defined(TARGET_MEEGO)
3420 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3423 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3428 const_color = "1;35"; /* Bright Magenta for MeeGo */
3431 if (!pretty_name && !const_pretty)
3432 const_pretty = "Linux";
3434 if (!ansi_color && !const_color)
3437 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3438 const_color ? const_color : ansi_color,
3439 const_pretty ? const_pretty : pretty_name);
3445 char *replace_env(const char *format, char **env) {
3452 const char *e, *word = format;
3457 for (e = format; *e; e ++) {
3468 if (!(k = strnappend(r, word, e-word-1)))
3477 } else if (*e == '$') {
3478 if (!(k = strnappend(r, word, e-word)))
3494 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3497 if (!(k = strappend(r, t)))
3510 if (!(k = strnappend(r, word, e-word)))
3521 char **replace_env_argv(char **argv, char **env) {
3523 unsigned k = 0, l = 0;
3525 l = strv_length(argv);
3527 if (!(r = new(char*, l+1)))
3530 STRV_FOREACH(i, argv) {
3532 /* If $FOO appears as single word, replace it by the split up variable */
3533 if ((*i)[0] == '$' && (*i)[1] != '{') {
3538 if ((e = strv_env_get(env, *i+1))) {
3540 if (!(m = strv_split_quoted(e))) {
3551 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3560 memcpy(r + k, m, q * sizeof(char*));
3568 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3569 if (!(r[k++] = replace_env(*i, env))) {
3580 static __thread int parsed_columns = 0;
3583 if (parsed_columns > 0)
3584 return parsed_columns;
3586 if ((e = getenv("COLUMNS")))
3587 parsed_columns = atoi(e);
3589 if (parsed_columns <= 0) {
3593 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3594 parsed_columns = ws.ws_col;
3597 if (parsed_columns <= 0)
3598 parsed_columns = 80;
3600 return parsed_columns;
3603 int running_in_chroot(void) {
3609 /* Only works as root */
3611 if (stat("/proc/1/root", &a) < 0)
3614 if (stat("/", &b) < 0)
3618 a.st_dev != b.st_dev ||
3619 a.st_ino != b.st_ino;
3622 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3627 assert(percent <= 100);
3628 assert(length >= 3);
3632 if (l <= 3 || l <= length)
3635 if (!(r = new0(char, length+1)))
3638 x = (length * percent) / 100;
3648 s + l - (length - x - 3),
3654 int touch(const char *path) {
3659 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3662 close_nointr_nofail(fd);
3666 char *unquote(const char *s, const char* quotes) {
3670 if ((l = strlen(s)) < 2)
3673 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3674 return strndup(s+1, l-2);
3679 char *normalize_env_assignment(const char *s) {
3680 char *name, *value, *p, *r;
3685 if (!(r = strdup(s)))
3691 if (!(name = strndup(s, p - s)))
3694 if (!(p = strdup(p+1))) {
3699 value = unquote(strstrip(p), QUOTES);
3707 if (asprintf(&r, "%s=%s", name, value) < 0)
3716 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3723 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3735 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3742 if ((r = wait_for_terminate(pid, &status)) < 0) {
3743 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3747 if (status.si_code == CLD_EXITED) {
3748 if (status.si_status != 0) {
3749 log_warning("%s failed with error code %i.", name, status.si_status);
3750 return status.si_status;
3753 log_debug("%s succeeded.", name);
3756 } else if (status.si_code == CLD_KILLED ||
3757 status.si_code == CLD_DUMPED) {
3759 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3763 log_warning("%s failed due to unknown reason.", name);
3770 /* Make sure nobody waits for us on a socket anymore */
3771 close_all_fds(NULL, 0);
3779 bool null_or_empty(struct stat *st) {
3782 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3785 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3791 DIR *xopendirat(int fd, const char *name, int flags) {
3795 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3798 if (!(d = fdopendir(nfd))) {
3799 close_nointr_nofail(nfd);
3806 int signal_from_string_try_harder(const char *s) {
3810 if ((signo = signal_from_string(s)) <= 0)
3811 if (startswith(s, "SIG"))
3812 return signal_from_string(s+3);
3817 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3823 if (!dual_timestamp_is_set(t))
3826 fprintf(f, "%s=%llu %llu\n",
3828 (unsigned long long) t->realtime,
3829 (unsigned long long) t->monotonic);
3832 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3833 unsigned long long a, b;
3838 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3839 log_debug("Failed to parse finish timestamp value %s", value);
3846 char *fstab_node_to_udev_node(const char *p) {
3850 /* FIXME: to follow udev's logic 100% we need to leave valid
3851 * UTF8 chars unescaped */
3853 if (startswith(p, "LABEL=")) {
3855 if (!(u = unquote(p+6, "\"\'")))
3858 t = xescape(u, "/ ");
3864 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3873 if (startswith(p, "UUID=")) {
3875 if (!(u = unquote(p+5, "\"\'")))
3878 t = xescape(u, "/ ");
3884 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3896 void filter_environ(const char *prefix) {
3903 for (i = 0, j = 0; environ[i]; i++) {
3905 if (startswith(environ[i], prefix))
3908 environ[j++] = environ[i];
3914 bool tty_is_vc(const char *tty) {
3917 if (startswith(tty, "/dev/"))
3920 return startswith(tty, "tty") &&
3921 tty[3] >= '0' && tty[3] <= '9';
3924 const char *default_term_for_tty(const char *tty) {
3925 char *active = NULL;
3930 if (startswith(tty, "/dev/"))
3933 /* Resolve where /dev/console is pointing when determining
3935 if (streq(tty, "console"))
3936 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3937 /* If multiple log outputs are configured the
3938 * last one is what /dev/console points to */
3939 if ((tty = strrchr(active, ' ')))
3945 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3951 /* Returns a short identifier for the various VM implementations */
3952 int detect_vm(const char **id) {
3954 #if defined(__i386__) || defined(__x86_64__)
3956 /* Both CPUID and DMI are x86 specific interfaces... */
3958 static const char *const dmi_vendors[] = {
3959 "/sys/class/dmi/id/sys_vendor",
3960 "/sys/class/dmi/id/board_vendor",
3961 "/sys/class/dmi/id/bios_vendor"
3964 static const char dmi_vendor_table[] =
3966 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3967 "VMware\0" "vmware\0"
3969 "Microsoft Corporation\0" "microsoft\0"
3970 "innotek GmbH\0" "oracle\0"
3972 "Bochs\0" "bochs\0";
3974 static const char cpuid_vendor_table[] =
3975 "XenVMMXenVMM\0" "xen\0"
3976 "KVMKVMKVM\0" "kvm\0"
3977 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3978 "VMwareVMware\0" "vmware\0"
3979 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3980 "Microsoft Hv\0" "microsoft\0";
3991 /* http://lwn.net/Articles/301888/ */
3994 #if defined (__i386__)
3997 #elif defined (__amd64__)
4002 /* First detect whether there is a hypervisor */
4004 __asm__ __volatile__ (
4005 /* ebx/rbx is being used for PIC! */
4006 " push %%"REG_b" \n\t"
4008 " pop %%"REG_b" \n\t"
4010 : "=a" (eax), "=c" (ecx)
4014 hypervisor = !!(ecx & ecx & 0x80000000U);
4018 /* There is a hypervisor, see what it is */
4020 __asm__ __volatile__ (
4021 /* ebx/rbx is being used for PIC! */
4022 " push %%"REG_b" \n\t"
4024 " mov %%ebx, %1 \n\t"
4025 " pop %%"REG_b" \n\t"
4027 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4031 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4032 if (streq(sig.text, j)) {
4041 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4044 const char *found = NULL;
4046 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4053 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4054 if (startswith(s, j))
4077 int detect_container(const char **id) {
4080 /* Unfortunately many of these operations require root access
4081 * in one way or another */
4086 if (running_in_chroot() > 0) {
4094 /* /proc/vz exists in container and outside of the container,
4095 * /proc/bc only outside of the container. */
4096 if (access("/proc/vz", F_OK) >= 0 &&
4097 access("/proc/bc", F_OK) < 0) {
4105 if ((f = fopen("/proc/self/cgroup", "r"))) {
4108 char line[LINE_MAX], *p;
4110 if (!fgets(line, sizeof(line), f))
4113 if (!(p = strchr(strstrip(line), ':')))
4116 if (strncmp(p, ":ns:", 4))
4119 if (!streq(p, ":ns:/")) {
4135 /* Returns a short identifier for the various VM/container implementations */
4136 int detect_virtualization(const char **id) {
4137 static __thread const char *cached_id = NULL;
4143 if (cached_id == (const char*) -1)
4152 if ((r = detect_container(&_id)) != 0)
4155 r = detect_vm(&_id);
4164 cached_id = (const char*) -1;
4169 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4172 Hashmap *pids = NULL;
4176 /* Executes all binaries in a directory in parallel and waits
4177 * until all they all finished. */
4180 if (!(_d = opendir(directory))) {
4182 if (errno == ENOENT)
4185 log_error("Failed to enumerate directory %s: %m", directory);
4192 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4193 log_error("Failed to allocate set.");
4197 while ((de = readdir(d))) {
4202 if (ignore_file(de->d_name))
4205 if (de->d_type != DT_REG &&
4206 de->d_type != DT_LNK &&
4207 de->d_type != DT_UNKNOWN)
4210 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4211 log_error("Out of memory");
4215 if ((pid = fork()) < 0) {
4216 log_error("Failed to fork: %m");
4235 log_error("Failed to execute %s: %m", path);
4236 _exit(EXIT_FAILURE);
4239 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4241 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4242 log_error("Failed to add PID to set: %s", strerror(-k));
4247 while (!hashmap_isempty(pids)) {
4252 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4257 log_error("waitid() failed: %m");
4261 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4262 if (!is_clean_exit(si.si_code, si.si_status)) {
4263 if (si.si_code == CLD_EXITED)
4264 log_error("%s exited with exit status %i.", path, si.si_status);
4266 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4268 log_debug("%s exited successfully.", path);
4279 hashmap_free_free(pids);
4282 int kill_and_sigcont(pid_t pid, int sig) {
4285 r = kill(pid, sig) < 0 ? -errno : 0;
4293 bool nulstr_contains(const char*nulstr, const char *needle) {
4299 NULSTR_FOREACH(i, nulstr)
4300 if (streq(i, needle))
4306 bool plymouth_running(void) {
4307 return access("/run/plymouth/pid", F_OK) >= 0;
4310 void parse_syslog_priority(char **p, int *priority) {
4311 int a = 0, b = 0, c = 0;
4321 if (!strchr(*p, '>'))
4324 if ((*p)[2] == '>') {
4325 c = undecchar((*p)[1]);
4327 } else if ((*p)[3] == '>') {
4328 b = undecchar((*p)[1]);
4329 c = undecchar((*p)[2]);
4331 } else if ((*p)[4] == '>') {
4332 a = undecchar((*p)[1]);
4333 b = undecchar((*p)[2]);
4334 c = undecchar((*p)[3]);
4339 if (a < 0 || b < 0 || c < 0)
4342 *priority = a*100+b*10+c;
4346 int have_effective_cap(int value) {
4348 cap_flag_value_t fv;
4351 if (!(cap = cap_get_proc()))
4354 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4363 char* strshorten(char *s, size_t l) {
4372 static bool hostname_valid_char(char c) {
4374 (c >= 'a' && c <= 'z') ||
4375 (c >= 'A' && c <= 'Z') ||
4376 (c >= '0' && c <= '9') ||
4382 bool hostname_is_valid(const char *s) {
4388 for (p = s; *p; p++)
4389 if (!hostname_valid_char(*p))
4392 if (p-s > HOST_NAME_MAX)
4398 char* hostname_cleanup(char *s) {
4401 for (p = s, d = s; *p; p++)
4402 if ((*p >= 'a' && *p <= 'z') ||
4403 (*p >= 'A' && *p <= 'Z') ||
4404 (*p >= '0' && *p <= '9') ||
4412 strshorten(s, HOST_NAME_MAX);
4416 static const char *const ioprio_class_table[] = {
4417 [IOPRIO_CLASS_NONE] = "none",
4418 [IOPRIO_CLASS_RT] = "realtime",
4419 [IOPRIO_CLASS_BE] = "best-effort",
4420 [IOPRIO_CLASS_IDLE] = "idle"
4423 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4425 static const char *const sigchld_code_table[] = {
4426 [CLD_EXITED] = "exited",
4427 [CLD_KILLED] = "killed",
4428 [CLD_DUMPED] = "dumped",
4429 [CLD_TRAPPED] = "trapped",
4430 [CLD_STOPPED] = "stopped",
4431 [CLD_CONTINUED] = "continued",
4434 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4436 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4437 [LOG_FAC(LOG_KERN)] = "kern",
4438 [LOG_FAC(LOG_USER)] = "user",
4439 [LOG_FAC(LOG_MAIL)] = "mail",
4440 [LOG_FAC(LOG_DAEMON)] = "daemon",
4441 [LOG_FAC(LOG_AUTH)] = "auth",
4442 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4443 [LOG_FAC(LOG_LPR)] = "lpr",
4444 [LOG_FAC(LOG_NEWS)] = "news",
4445 [LOG_FAC(LOG_UUCP)] = "uucp",
4446 [LOG_FAC(LOG_CRON)] = "cron",
4447 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4448 [LOG_FAC(LOG_FTP)] = "ftp",
4449 [LOG_FAC(LOG_LOCAL0)] = "local0",
4450 [LOG_FAC(LOG_LOCAL1)] = "local1",
4451 [LOG_FAC(LOG_LOCAL2)] = "local2",
4452 [LOG_FAC(LOG_LOCAL3)] = "local3",
4453 [LOG_FAC(LOG_LOCAL4)] = "local4",
4454 [LOG_FAC(LOG_LOCAL5)] = "local5",
4455 [LOG_FAC(LOG_LOCAL6)] = "local6",
4456 [LOG_FAC(LOG_LOCAL7)] = "local7"
4459 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4461 static const char *const log_level_table[] = {
4462 [LOG_EMERG] = "emerg",
4463 [LOG_ALERT] = "alert",
4464 [LOG_CRIT] = "crit",
4466 [LOG_WARNING] = "warning",
4467 [LOG_NOTICE] = "notice",
4468 [LOG_INFO] = "info",
4469 [LOG_DEBUG] = "debug"
4472 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4474 static const char* const sched_policy_table[] = {
4475 [SCHED_OTHER] = "other",
4476 [SCHED_BATCH] = "batch",
4477 [SCHED_IDLE] = "idle",
4478 [SCHED_FIFO] = "fifo",
4482 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4484 static const char* const rlimit_table[] = {
4485 [RLIMIT_CPU] = "LimitCPU",
4486 [RLIMIT_FSIZE] = "LimitFSIZE",
4487 [RLIMIT_DATA] = "LimitDATA",
4488 [RLIMIT_STACK] = "LimitSTACK",
4489 [RLIMIT_CORE] = "LimitCORE",
4490 [RLIMIT_RSS] = "LimitRSS",
4491 [RLIMIT_NOFILE] = "LimitNOFILE",
4492 [RLIMIT_AS] = "LimitAS",
4493 [RLIMIT_NPROC] = "LimitNPROC",
4494 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4495 [RLIMIT_LOCKS] = "LimitLOCKS",
4496 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4497 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4498 [RLIMIT_NICE] = "LimitNICE",
4499 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4500 [RLIMIT_RTTIME] = "LimitRTTIME"
4503 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4505 static const char* const ip_tos_table[] = {
4506 [IPTOS_LOWDELAY] = "low-delay",
4507 [IPTOS_THROUGHPUT] = "throughput",
4508 [IPTOS_RELIABILITY] = "reliability",
4509 [IPTOS_LOWCOST] = "low-cost",
4512 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4514 static const char *const signal_table[] = {
4531 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4542 [SIGVTALRM] = "VTALRM",
4544 [SIGWINCH] = "WINCH",
4550 DEFINE_STRING_TABLE_LOOKUP(signal, int);
4552 static int file_is_conf(const struct dirent *d, const char *suffix) {
4555 if (ignore_file(d->d_name))
4558 if (d->d_type != DT_REG &&
4559 d->d_type != DT_LNK &&
4560 d->d_type != DT_UNKNOWN)
4563 return endswith(d->d_name, suffix);
4566 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4571 dir = opendir(path);
4573 if (errno == ENOENT)
4578 for (de = readdir(dir); de; de = readdir(dir)) {
4582 if (!file_is_conf(de, suffix))
4585 if (asprintf(&f, "%s/%s", path, de->d_name) < 0) {
4590 log_debug("found: %s\n", f);
4591 base = f + strlen(path) + 1;
4592 if (hashmap_put(h, base, f) <= 0)
4601 static int base_cmp(const void *a, const void *b) {
4602 const char *s1, *s2;
4604 s1 = *(char * const *)a;
4605 s2 = *(char * const *)b;
4606 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4609 char **conf_files_list(const char *suffix, const char *dir, ...) {
4611 char **files = NULL;
4615 fh = hashmap_new(string_hash_func, string_compare_func);
4623 if (files_add(fh, dir, suffix) < 0) {
4624 log_error("Failed to search for files.");
4628 dir = va_arg(ap, const char *);
4632 files = hashmap_get_strv(fh);
4633 if (files == NULL) {
4634 log_error("Failed to compose list of files.");
4639 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);