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 int reset_all_signal_handlers(void) {
1215 for (sig = 1; sig < _NSIG; sig++) {
1216 struct sigaction sa;
1218 if (sig == SIGKILL || sig == SIGSTOP)
1222 sa.sa_handler = SIG_DFL;
1223 sa.sa_flags = SA_RESTART;
1225 /* On Linux the first two RT signals are reserved by
1226 * glibc, and sigaction() will return EINVAL for them. */
1227 if ((sigaction(sig, &sa, NULL) < 0))
1228 if (errno != EINVAL)
1235 char *strstrip(char *s) {
1238 /* Drops trailing whitespace. Modifies the string in
1239 * place. Returns pointer to first non-space character */
1241 s += strspn(s, WHITESPACE);
1243 for (e = s; *e; e++)
1244 if (!strchr(WHITESPACE, *e))
1255 char *delete_chars(char *s, const char *bad) {
1258 /* Drops all whitespace, regardless where in the string */
1260 for (f = s, t = s; *f; f++) {
1261 if (strchr(bad, *f))
1272 char *file_in_same_dir(const char *path, const char *filename) {
1279 /* This removes the last component of path and appends
1280 * filename, unless the latter is absolute anyway or the
1283 if (path_is_absolute(filename))
1284 return strdup(filename);
1286 if (!(e = strrchr(path, '/')))
1287 return strdup(filename);
1289 k = strlen(filename);
1290 if (!(r = new(char, e-path+1+k+1)))
1293 memcpy(r, path, e-path+1);
1294 memcpy(r+(e-path)+1, filename, k+1);
1299 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1302 if (label_mkdir(path, mode) >= 0)
1303 if (chmod_and_chown(path, mode, uid, gid) < 0)
1306 if (lstat(path, &st) < 0)
1309 if ((st.st_mode & 0777) != mode ||
1312 !S_ISDIR(st.st_mode)) {
1321 int mkdir_parents(const char *path, mode_t mode) {
1326 /* Creates every parent directory in the path except the last
1329 p = path + strspn(path, "/");
1334 e = p + strcspn(p, "/");
1335 p = e + strspn(e, "/");
1337 /* Is this the last component? If so, then we're
1342 if (!(t = strndup(path, e - path)))
1345 r = label_mkdir(t, mode);
1348 if (r < 0 && errno != EEXIST)
1353 int mkdir_p(const char *path, mode_t mode) {
1358 if ((r = mkdir_parents(path, mode)) < 0)
1361 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1367 int rmdir_parents(const char *path, const char *stop) {
1376 /* Skip trailing slashes */
1377 while (l > 0 && path[l-1] == '/')
1383 /* Skip last component */
1384 while (l > 0 && path[l-1] != '/')
1387 /* Skip trailing slashes */
1388 while (l > 0 && path[l-1] == '/')
1394 if (!(t = strndup(path, l)))
1397 if (path_startswith(stop, t)) {
1406 if (errno != ENOENT)
1414 char hexchar(int x) {
1415 static const char table[16] = "0123456789abcdef";
1417 return table[x & 15];
1420 int unhexchar(char c) {
1422 if (c >= '0' && c <= '9')
1425 if (c >= 'a' && c <= 'f')
1426 return c - 'a' + 10;
1428 if (c >= 'A' && c <= 'F')
1429 return c - 'A' + 10;
1434 char octchar(int x) {
1435 return '0' + (x & 7);
1438 int unoctchar(char c) {
1440 if (c >= '0' && c <= '7')
1446 char decchar(int x) {
1447 return '0' + (x % 10);
1450 int undecchar(char c) {
1452 if (c >= '0' && c <= '9')
1458 char *cescape(const char *s) {
1464 /* Does C style string escaping. */
1466 if (!(r = new(char, strlen(s)*4 + 1)))
1469 for (f = s, t = r; *f; f++)
1515 /* For special chars we prefer octal over
1516 * hexadecimal encoding, simply because glib's
1517 * g_strescape() does the same */
1518 if ((*f < ' ') || (*f >= 127)) {
1520 *(t++) = octchar((unsigned char) *f >> 6);
1521 *(t++) = octchar((unsigned char) *f >> 3);
1522 *(t++) = octchar((unsigned char) *f);
1533 char *cunescape_length(const char *s, size_t length) {
1539 /* Undoes C style string escaping */
1541 if (!(r = new(char, length+1)))
1544 for (f = s, t = r; f < s + length; f++) {
1587 /* This is an extension of the XDG syntax files */
1592 /* hexadecimal encoding */
1595 if ((a = unhexchar(f[1])) < 0 ||
1596 (b = unhexchar(f[2])) < 0) {
1597 /* Invalid escape code, let's take it literal then */
1601 *(t++) = (char) ((a << 4) | b);
1616 /* octal encoding */
1619 if ((a = unoctchar(f[0])) < 0 ||
1620 (b = unoctchar(f[1])) < 0 ||
1621 (c = unoctchar(f[2])) < 0) {
1622 /* Invalid escape code, let's take it literal then */
1626 *(t++) = (char) ((a << 6) | (b << 3) | c);
1634 /* premature end of string.*/
1639 /* Invalid escape code, let's take it literal then */
1651 char *cunescape(const char *s) {
1652 return cunescape_length(s, strlen(s));
1655 char *xescape(const char *s, const char *bad) {
1659 /* Escapes all chars in bad, in addition to \ and all special
1660 * chars, in \xFF style escaping. May be reversed with
1663 if (!(r = new(char, strlen(s)*4+1)))
1666 for (f = s, t = r; *f; f++) {
1668 if ((*f < ' ') || (*f >= 127) ||
1669 (*f == '\\') || strchr(bad, *f)) {
1672 *(t++) = hexchar(*f >> 4);
1673 *(t++) = hexchar(*f);
1683 char *bus_path_escape(const char *s) {
1689 /* Escapes all chars that D-Bus' object path cannot deal
1690 * with. Can be reverse with bus_path_unescape() */
1692 if (!(r = new(char, strlen(s)*3+1)))
1695 for (f = s, t = r; *f; f++) {
1697 if (!(*f >= 'A' && *f <= 'Z') &&
1698 !(*f >= 'a' && *f <= 'z') &&
1699 !(*f >= '0' && *f <= '9')) {
1701 *(t++) = hexchar(*f >> 4);
1702 *(t++) = hexchar(*f);
1712 char *bus_path_unescape(const char *f) {
1717 if (!(r = strdup(f)))
1720 for (t = r; *f; f++) {
1725 if ((a = unhexchar(f[1])) < 0 ||
1726 (b = unhexchar(f[2])) < 0) {
1727 /* Invalid escape code, let's take it literal then */
1730 *(t++) = (char) ((a << 4) | b);
1742 char *path_kill_slashes(char *path) {
1746 /* Removes redundant inner and trailing slashes. Modifies the
1747 * passed string in-place.
1749 * ///foo///bar/ becomes /foo/bar
1752 for (f = path, t = path; *f; f++) {
1767 /* Special rule, if we are talking of the root directory, a
1768 trailing slash is good */
1770 if (t == path && slash)
1777 bool path_startswith(const char *path, const char *prefix) {
1781 if ((path[0] == '/') != (prefix[0] == '/'))
1787 path += strspn(path, "/");
1788 prefix += strspn(prefix, "/");
1796 a = strcspn(path, "/");
1797 b = strcspn(prefix, "/");
1802 if (memcmp(path, prefix, a) != 0)
1810 bool path_equal(const char *a, const char *b) {
1814 if ((a[0] == '/') != (b[0] == '/'))
1820 a += strspn(a, "/");
1821 b += strspn(b, "/");
1823 if (*a == 0 && *b == 0)
1826 if (*a == 0 || *b == 0)
1829 j = strcspn(a, "/");
1830 k = strcspn(b, "/");
1835 if (memcmp(a, b, j) != 0)
1843 char *ascii_strlower(char *t) {
1848 for (p = t; *p; p++)
1849 if (*p >= 'A' && *p <= 'Z')
1850 *p = *p - 'A' + 'a';
1855 bool ignore_file(const char *filename) {
1859 filename[0] == '.' ||
1860 streq(filename, "lost+found") ||
1861 streq(filename, "aquota.user") ||
1862 streq(filename, "aquota.group") ||
1863 endswith(filename, "~") ||
1864 endswith(filename, ".rpmnew") ||
1865 endswith(filename, ".rpmsave") ||
1866 endswith(filename, ".rpmorig") ||
1867 endswith(filename, ".dpkg-old") ||
1868 endswith(filename, ".dpkg-new") ||
1869 endswith(filename, ".swp");
1872 int fd_nonblock(int fd, bool nonblock) {
1877 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1881 flags |= O_NONBLOCK;
1883 flags &= ~O_NONBLOCK;
1885 if (fcntl(fd, F_SETFL, flags) < 0)
1891 int fd_cloexec(int fd, bool cloexec) {
1896 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1900 flags |= FD_CLOEXEC;
1902 flags &= ~FD_CLOEXEC;
1904 if (fcntl(fd, F_SETFD, flags) < 0)
1910 int close_all_fds(const int except[], unsigned n_except) {
1915 if (!(d = opendir("/proc/self/fd")))
1918 while ((de = readdir(d))) {
1921 if (ignore_file(de->d_name))
1924 if (safe_atoi(de->d_name, &fd) < 0)
1925 /* Let's better ignore this, just in case */
1939 for (i = 0; i < n_except; i++)
1940 if (except[i] == fd) {
1949 if (close_nointr(fd) < 0) {
1950 /* Valgrind has its own FD and doesn't want to have it closed */
1951 if (errno != EBADF && r == 0)
1960 bool chars_intersect(const char *a, const char *b) {
1963 /* Returns true if any of the chars in a are in b. */
1964 for (p = a; *p; p++)
1971 char *format_timestamp(char *buf, size_t l, usec_t t) {
1981 sec = (time_t) (t / USEC_PER_SEC);
1983 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1989 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1992 n = now(CLOCK_REALTIME);
1994 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1999 if (d >= USEC_PER_YEAR)
2000 snprintf(buf, l, "%llu years and %llu months ago",
2001 (unsigned long long) (d / USEC_PER_YEAR),
2002 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2003 else if (d >= USEC_PER_MONTH)
2004 snprintf(buf, l, "%llu months and %llu days ago",
2005 (unsigned long long) (d / USEC_PER_MONTH),
2006 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2007 else if (d >= USEC_PER_WEEK)
2008 snprintf(buf, l, "%llu weeks and %llu days ago",
2009 (unsigned long long) (d / USEC_PER_WEEK),
2010 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2011 else if (d >= 2*USEC_PER_DAY)
2012 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2013 else if (d >= 25*USEC_PER_HOUR)
2014 snprintf(buf, l, "1 day and %lluh ago",
2015 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2016 else if (d >= 6*USEC_PER_HOUR)
2017 snprintf(buf, l, "%lluh ago",
2018 (unsigned long long) (d / USEC_PER_HOUR));
2019 else if (d >= USEC_PER_HOUR)
2020 snprintf(buf, l, "%lluh %llumin ago",
2021 (unsigned long long) (d / USEC_PER_HOUR),
2022 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2023 else if (d >= 5*USEC_PER_MINUTE)
2024 snprintf(buf, l, "%llumin ago",
2025 (unsigned long long) (d / USEC_PER_MINUTE));
2026 else if (d >= USEC_PER_MINUTE)
2027 snprintf(buf, l, "%llumin %llus ago",
2028 (unsigned long long) (d / USEC_PER_MINUTE),
2029 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2030 else if (d >= USEC_PER_SEC)
2031 snprintf(buf, l, "%llus ago",
2032 (unsigned long long) (d / USEC_PER_SEC));
2033 else if (d >= USEC_PER_MSEC)
2034 snprintf(buf, l, "%llums ago",
2035 (unsigned long long) (d / USEC_PER_MSEC));
2037 snprintf(buf, l, "%lluus ago",
2038 (unsigned long long) d);
2040 snprintf(buf, l, "now");
2046 char *format_timespan(char *buf, size_t l, usec_t t) {
2047 static const struct {
2051 { "w", USEC_PER_WEEK },
2052 { "d", USEC_PER_DAY },
2053 { "h", USEC_PER_HOUR },
2054 { "min", USEC_PER_MINUTE },
2055 { "s", USEC_PER_SEC },
2056 { "ms", USEC_PER_MSEC },
2066 if (t == (usec_t) -1)
2070 snprintf(p, l, "0");
2075 /* The result of this function can be parsed with parse_usec */
2077 for (i = 0; i < ELEMENTSOF(table); i++) {
2081 if (t < table[i].usec)
2087 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2088 n = MIN((size_t) k, l);
2101 bool fstype_is_network(const char *fstype) {
2102 static const char * const table[] = {
2114 for (i = 0; i < ELEMENTSOF(table); i++)
2115 if (streq(table[i], fstype))
2124 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2129 TIOCL_GETKMSGREDIRECT,
2133 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2136 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2139 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2142 close_nointr_nofail(r);
2146 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2147 struct termios old_termios, new_termios;
2149 char line[LINE_MAX];
2154 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2155 new_termios = old_termios;
2157 new_termios.c_lflag &= ~ICANON;
2158 new_termios.c_cc[VMIN] = 1;
2159 new_termios.c_cc[VTIME] = 0;
2161 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2164 k = fread(&c, 1, 1, f);
2166 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2172 *need_nl = c != '\n';
2179 if (!(fgets(line, sizeof(line), f)))
2184 if (strlen(line) != 1)
2194 int ask(char *ret, const char *replies, const char *text, ...) {
2201 on_tty = isatty(STDOUT_FILENO);
2207 bool need_nl = true;
2210 fputs("\x1B[1m", stdout);
2217 fputs("\x1B[0m", stdout);
2221 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2223 if (r == -EBADMSG) {
2224 puts("Bad input, please try again.");
2235 if (strchr(replies, c)) {
2240 puts("Read unexpected character, please try again.");
2244 int reset_terminal(int fd) {
2245 struct termios termios;
2249 /* Set terminal to some sane defaults */
2253 /* We leave locked terminal attributes untouched, so that
2254 * Plymouth may set whatever it wants to set, and we don't
2255 * interfere with that. */
2257 /* Disable exclusive mode, just in case */
2258 ioctl(fd, TIOCNXCL);
2260 /* Enable console unicode mode */
2262 ioctl(fd, KDSKBMODE, &arg);
2264 if (tcgetattr(fd, &termios) < 0) {
2269 /* We only reset the stuff that matters to the software. How
2270 * hardware is set up we don't touch assuming that somebody
2271 * else will do that for us */
2273 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2274 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2275 termios.c_oflag |= ONLCR;
2276 termios.c_cflag |= CREAD;
2277 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2279 termios.c_cc[VINTR] = 03; /* ^C */
2280 termios.c_cc[VQUIT] = 034; /* ^\ */
2281 termios.c_cc[VERASE] = 0177;
2282 termios.c_cc[VKILL] = 025; /* ^X */
2283 termios.c_cc[VEOF] = 04; /* ^D */
2284 termios.c_cc[VSTART] = 021; /* ^Q */
2285 termios.c_cc[VSTOP] = 023; /* ^S */
2286 termios.c_cc[VSUSP] = 032; /* ^Z */
2287 termios.c_cc[VLNEXT] = 026; /* ^V */
2288 termios.c_cc[VWERASE] = 027; /* ^W */
2289 termios.c_cc[VREPRINT] = 022; /* ^R */
2290 termios.c_cc[VEOL] = 0;
2291 termios.c_cc[VEOL2] = 0;
2293 termios.c_cc[VTIME] = 0;
2294 termios.c_cc[VMIN] = 1;
2296 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2300 /* Just in case, flush all crap out */
2301 tcflush(fd, TCIOFLUSH);
2306 int open_terminal(const char *name, int mode) {
2311 * If a TTY is in the process of being closed opening it might
2312 * cause EIO. This is horribly awful, but unlikely to be
2313 * changed in the kernel. Hence we work around this problem by
2314 * retrying a couple of times.
2316 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2320 if ((fd = open(name, mode)) >= 0)
2329 usleep(50 * USEC_PER_MSEC);
2336 if ((r = isatty(fd)) < 0) {
2337 close_nointr_nofail(fd);
2342 close_nointr_nofail(fd);
2349 int flush_fd(int fd) {
2350 struct pollfd pollfd;
2354 pollfd.events = POLLIN;
2361 if ((r = poll(&pollfd, 1, 0)) < 0) {
2372 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2377 if (errno == EAGAIN)
2388 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2389 int fd = -1, notify = -1, r, wd = -1;
2393 /* We use inotify to be notified when the tty is closed. We
2394 * create the watch before checking if we can actually acquire
2395 * it, so that we don't lose any event.
2397 * Note: strictly speaking this actually watches for the
2398 * device being closed, it does *not* really watch whether a
2399 * tty loses its controlling process. However, unless some
2400 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2401 * its tty otherwise this will not become a problem. As long
2402 * as the administrator makes sure not configure any service
2403 * on the same tty as an untrusted user this should not be a
2404 * problem. (Which he probably should not do anyway.) */
2406 if (!fail && !force) {
2407 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2412 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2420 if ((r = flush_fd(notify)) < 0)
2423 /* We pass here O_NOCTTY only so that we can check the return
2424 * value TIOCSCTTY and have a reliable way to figure out if we
2425 * successfully became the controlling process of the tty */
2426 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2429 /* First, try to get the tty */
2430 r = ioctl(fd, TIOCSCTTY, force);
2432 /* Sometimes it makes sense to ignore TIOCSCTTY
2433 * returning EPERM, i.e. when very likely we already
2434 * are have this controlling terminal. */
2435 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2438 if (r < 0 && (force || fail || errno != EPERM)) {
2448 assert(notify >= 0);
2451 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2453 struct inotify_event *e;
2455 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2464 e = (struct inotify_event*) inotify_buffer;
2469 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2474 step = sizeof(struct inotify_event) + e->len;
2475 assert(step <= (size_t) l);
2477 e = (struct inotify_event*) ((uint8_t*) e + step);
2484 /* We close the tty fd here since if the old session
2485 * ended our handle will be dead. It's important that
2486 * we do this after sleeping, so that we don't enter
2487 * an endless loop. */
2488 close_nointr_nofail(fd);
2492 close_nointr_nofail(notify);
2494 if ((r = reset_terminal(fd)) < 0)
2495 log_warning("Failed to reset terminal: %s", strerror(-r));
2501 close_nointr_nofail(fd);
2504 close_nointr_nofail(notify);
2509 int release_terminal(void) {
2511 struct sigaction sa_old, sa_new;
2513 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2516 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2517 * by our own TIOCNOTTY */
2520 sa_new.sa_handler = SIG_IGN;
2521 sa_new.sa_flags = SA_RESTART;
2522 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2524 if (ioctl(fd, TIOCNOTTY) < 0)
2527 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2529 close_nointr_nofail(fd);
2533 int sigaction_many(const struct sigaction *sa, ...) {
2538 while ((sig = va_arg(ap, int)) > 0)
2539 if (sigaction(sig, sa, NULL) < 0)
2546 int ignore_signals(int sig, ...) {
2547 struct sigaction sa;
2552 sa.sa_handler = SIG_IGN;
2553 sa.sa_flags = SA_RESTART;
2555 if (sigaction(sig, &sa, NULL) < 0)
2559 while ((sig = va_arg(ap, int)) > 0)
2560 if (sigaction(sig, &sa, NULL) < 0)
2567 int default_signals(int sig, ...) {
2568 struct sigaction sa;
2573 sa.sa_handler = SIG_DFL;
2574 sa.sa_flags = SA_RESTART;
2576 if (sigaction(sig, &sa, NULL) < 0)
2580 while ((sig = va_arg(ap, int)) > 0)
2581 if (sigaction(sig, &sa, NULL) < 0)
2588 int close_pipe(int p[]) {
2594 a = close_nointr(p[0]);
2599 b = close_nointr(p[1]);
2603 return a < 0 ? a : b;
2606 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2615 while (nbytes > 0) {
2618 if ((k = read(fd, p, nbytes)) <= 0) {
2620 if (k < 0 && errno == EINTR)
2623 if (k < 0 && errno == EAGAIN && do_poll) {
2624 struct pollfd pollfd;
2628 pollfd.events = POLLIN;
2630 if (poll(&pollfd, 1, -1) < 0) {
2634 return n > 0 ? n : -errno;
2637 if (pollfd.revents != POLLIN)
2638 return n > 0 ? n : -EIO;
2643 return n > 0 ? n : (k < 0 ? -errno : 0);
2654 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2663 while (nbytes > 0) {
2666 if ((k = write(fd, p, nbytes)) <= 0) {
2668 if (k < 0 && errno == EINTR)
2671 if (k < 0 && errno == EAGAIN && do_poll) {
2672 struct pollfd pollfd;
2676 pollfd.events = POLLOUT;
2678 if (poll(&pollfd, 1, -1) < 0) {
2682 return n > 0 ? n : -errno;
2685 if (pollfd.revents != POLLOUT)
2686 return n > 0 ? n : -EIO;
2691 return n > 0 ? n : (k < 0 ? -errno : 0);
2702 int path_is_mount_point(const char *t) {
2707 if (lstat(t, &a) < 0) {
2708 if (errno == ENOENT)
2714 if ((r = parent_of_path(t, &parent)) < 0)
2717 r = lstat(parent, &b);
2723 return a.st_dev != b.st_dev;
2726 int parse_usec(const char *t, usec_t *usec) {
2727 static const struct {
2731 { "sec", USEC_PER_SEC },
2732 { "s", USEC_PER_SEC },
2733 { "min", USEC_PER_MINUTE },
2734 { "hr", USEC_PER_HOUR },
2735 { "h", USEC_PER_HOUR },
2736 { "d", USEC_PER_DAY },
2737 { "w", USEC_PER_WEEK },
2738 { "msec", USEC_PER_MSEC },
2739 { "ms", USEC_PER_MSEC },
2740 { "m", USEC_PER_MINUTE },
2743 { "", USEC_PER_SEC },
2759 l = strtoll(p, &e, 10);
2770 e += strspn(e, WHITESPACE);
2772 for (i = 0; i < ELEMENTSOF(table); i++)
2773 if (startswith(e, table[i].suffix)) {
2774 r += (usec_t) l * table[i].usec;
2775 p = e + strlen(table[i].suffix);
2779 if (i >= ELEMENTSOF(table))
2789 int make_stdio(int fd) {
2794 r = dup2(fd, STDIN_FILENO);
2795 s = dup2(fd, STDOUT_FILENO);
2796 t = dup2(fd, STDERR_FILENO);
2799 close_nointr_nofail(fd);
2801 if (r < 0 || s < 0 || t < 0)
2807 int make_null_stdio(void) {
2810 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2813 return make_stdio(null_fd);
2816 bool is_device_path(const char *path) {
2818 /* Returns true on paths that refer to a device, either in
2819 * sysfs or in /dev */
2822 path_startswith(path, "/dev/") ||
2823 path_startswith(path, "/sys/");
2826 int dir_is_empty(const char *path) {
2829 struct dirent buf, *de;
2831 if (!(d = opendir(path)))
2835 if ((r = readdir_r(d, &buf, &de)) > 0) {
2845 if (!ignore_file(de->d_name)) {
2855 unsigned long long random_ull(void) {
2860 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2863 r = loop_read(fd, &ull, sizeof(ull), true);
2864 close_nointr_nofail(fd);
2866 if (r != sizeof(ull))
2872 return random() * RAND_MAX + random();
2875 void rename_process(const char name[8]) {
2878 prctl(PR_SET_NAME, name);
2880 /* This is a like a poor man's setproctitle(). The string
2881 * passed should fit in 7 chars (i.e. the length of
2884 if (program_invocation_name)
2885 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2888 void sigset_add_many(sigset_t *ss, ...) {
2895 while ((sig = va_arg(ap, int)) > 0)
2896 assert_se(sigaddset(ss, sig) == 0);
2900 char* gethostname_malloc(void) {
2903 assert_se(uname(&u) >= 0);
2906 return strdup(u.nodename);
2908 return strdup(u.sysname);
2911 char* getlogname_malloc(void) {
2915 struct passwd pwbuf, *pw = NULL;
2918 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2923 /* Shortcut things to avoid NSS lookups */
2925 return strdup("root");
2927 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2930 if (!(buf = malloc(bufsize)))
2933 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2934 name = strdup(pw->pw_name);
2941 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2947 int getttyname_malloc(int fd, char **r) {
2948 char path[PATH_MAX], *c;
2953 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2958 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
2965 int getttyname_harder(int fd, char **r) {
2969 if ((k = getttyname_malloc(fd, &s)) < 0)
2972 if (streq(s, "tty")) {
2974 return get_ctty(r, NULL);
2981 int get_ctty_devnr(dev_t *d) {
2983 char line[LINE_MAX], *p;
2984 unsigned long ttynr;
2987 if (!(f = fopen("/proc/self/stat", "r")))
2990 if (!(fgets(line, sizeof(line), f))) {
2998 if (!(p = strrchr(line, ')')))
3007 "%*d " /* session */
3016 int get_ctty(char **r, dev_t *_devnr) {
3018 char fn[PATH_MAX], *s, *b, *p;
3023 if ((k = get_ctty_devnr(&devnr)) < 0)
3026 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3029 if ((k = readlink_malloc(fn, &s)) < 0) {
3034 /* This is an ugly hack */
3035 if (major(devnr) == 136) {
3036 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3046 /* Probably something like the ptys which have no
3047 * symlink in /dev/char. Let's return something
3048 * vaguely useful. */
3050 if (!(b = strdup(fn + 5)))
3060 if (startswith(s, "/dev/"))
3062 else if (startswith(s, "../"))
3080 static int rm_rf_children(int fd, bool only_dirs) {
3086 /* This returns the first error we run into, but nevertheless
3089 if (!(d = fdopendir(fd))) {
3090 close_nointr_nofail(fd);
3092 return errno == ENOENT ? 0 : -errno;
3096 struct dirent buf, *de;
3100 if ((r = readdir_r(d, &buf, &de)) != 0) {
3109 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3112 if (de->d_type == DT_UNKNOWN) {
3115 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3116 if (ret == 0 && errno != ENOENT)
3121 is_dir = S_ISDIR(st.st_mode);
3123 is_dir = de->d_type == DT_DIR;
3128 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3129 if (ret == 0 && errno != ENOENT)
3134 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3139 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3140 if (ret == 0 && errno != ENOENT)
3143 } else if (!only_dirs) {
3145 if (unlinkat(fd, de->d_name, 0) < 0) {
3146 if (ret == 0 && errno != ENOENT)
3157 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3163 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3165 if (errno != ENOTDIR)
3168 if (delete_root && !only_dirs)
3169 if (unlink(path) < 0)
3175 r = rm_rf_children(fd, only_dirs);
3178 if (rmdir(path) < 0) {
3186 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3189 /* Under the assumption that we are running privileged we
3190 * first change the access mode and only then hand out
3191 * ownership to avoid a window where access is too open. */
3193 if (chmod(path, mode) < 0)
3196 if (chown(path, uid, gid) < 0)
3202 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3206 /* Allocates the cpuset in the right size */
3209 if (!(r = CPU_ALLOC(n)))
3212 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3213 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3223 if (errno != EINVAL)
3230 void status_vprintf(const char *format, va_list ap) {
3236 /* This independent of logging, as status messages are
3237 * optional and go exclusively to the console. */
3239 if (vasprintf(&s, format, ap) < 0)
3242 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3245 write(fd, s, strlen(s));
3251 close_nointr_nofail(fd);
3254 void status_printf(const char *format, ...) {
3259 va_start(ap, format);
3260 status_vprintf(format, ap);
3264 void status_welcome(void) {
3265 char *pretty_name = NULL, *ansi_color = NULL;
3266 const char *const_pretty = NULL, *const_color = NULL;
3269 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3270 "PRETTY_NAME", &pretty_name,
3271 "ANSI_COLOR", &ansi_color,
3275 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3278 #if defined(TARGET_FEDORA)
3280 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3283 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3287 if (!ansi_color && pretty_name) {
3289 /* This tries to mimic the color magic the old Red Hat sysinit
3292 if (startswith(pretty_name, "Red Hat"))
3293 const_color = "0;31"; /* Red for RHEL */
3294 else if (startswith(pretty_name, "Fedora"))
3295 const_color = "0;34"; /* Blue for Fedora */
3298 #elif defined(TARGET_SUSE)
3301 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3304 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3309 const_color = "0;32"; /* Green for openSUSE */
3311 #elif defined(TARGET_GENTOO)
3314 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3317 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3322 const_color = "1;34"; /* Light Blue for Gentoo */
3324 #elif defined(TARGET_ALTLINUX)
3327 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3330 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3335 const_color = "0;36"; /* Cyan for ALTLinux */
3338 #elif defined(TARGET_DEBIAN)
3343 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3346 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3348 pretty_name = strappend("Debian ", version);
3352 log_warning("Failed to allocate Debian version string.");
3357 const_color = "1;31"; /* Light Red for Debian */
3359 #elif defined(TARGET_UBUNTU)
3361 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3362 "DISTRIB_DESCRIPTION", &pretty_name,
3366 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3370 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3372 #elif defined(TARGET_MANDRIVA)
3377 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3379 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3381 p = strstr(s, " release ");
3385 p[strcspn(p, " ")] = '\0';
3387 /* This corresponds to standard rc.sysinit */
3388 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3389 const_color = "1;36";
3391 log_warning("Failed to allocate Mandriva version string.");
3393 log_warning("Failed to parse /etc/mandriva-release");
3400 if (!pretty_name && !const_pretty)
3401 const_pretty = "Linux";
3403 if (!ansi_color && !const_color)
3406 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3407 const_color ? const_color : ansi_color,
3408 const_pretty ? const_pretty : pretty_name);
3414 char *replace_env(const char *format, char **env) {
3421 const char *e, *word = format;
3426 for (e = format; *e; e ++) {
3437 if (!(k = strnappend(r, word, e-word-1)))
3446 } else if (*e == '$') {
3447 if (!(k = strnappend(r, word, e-word)))
3463 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3466 if (!(k = strappend(r, t)))
3479 if (!(k = strnappend(r, word, e-word)))
3490 char **replace_env_argv(char **argv, char **env) {
3492 unsigned k = 0, l = 0;
3494 l = strv_length(argv);
3496 if (!(r = new(char*, l+1)))
3499 STRV_FOREACH(i, argv) {
3501 /* If $FOO appears as single word, replace it by the split up variable */
3502 if ((*i)[0] == '$' && (*i)[1] != '{') {
3507 if ((e = strv_env_get(env, *i+1))) {
3509 if (!(m = strv_split_quoted(e))) {
3520 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3529 memcpy(r + k, m, q * sizeof(char*));
3537 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3538 if (!(r[k++] = replace_env(*i, env))) {
3549 static __thread int parsed_columns = 0;
3552 if (parsed_columns > 0)
3553 return parsed_columns;
3555 if ((e = getenv("COLUMNS")))
3556 parsed_columns = atoi(e);
3558 if (parsed_columns <= 0) {
3562 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3563 parsed_columns = ws.ws_col;
3566 if (parsed_columns <= 0)
3567 parsed_columns = 80;
3569 return parsed_columns;
3572 int running_in_chroot(void) {
3578 /* Only works as root */
3580 if (stat("/proc/1/root", &a) < 0)
3583 if (stat("/", &b) < 0)
3587 a.st_dev != b.st_dev ||
3588 a.st_ino != b.st_ino;
3591 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3596 assert(percent <= 100);
3597 assert(length >= 3);
3601 if (l <= 3 || l <= length)
3604 if (!(r = new0(char, length+1)))
3607 x = (length * percent) / 100;
3617 s + l - (length - x - 3),
3623 int touch(const char *path) {
3628 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3631 close_nointr_nofail(fd);
3635 char *unquote(const char *s, const char* quotes) {
3639 if ((l = strlen(s)) < 2)
3642 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3643 return strndup(s+1, l-2);
3648 char *normalize_env_assignment(const char *s) {
3649 char *name, *value, *p, *r;
3654 if (!(r = strdup(s)))
3660 if (!(name = strndup(s, p - s)))
3663 if (!(p = strdup(p+1))) {
3668 value = unquote(strstrip(p), QUOTES);
3676 if (asprintf(&r, "%s=%s", name, value) < 0)
3685 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3692 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3704 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3711 if ((r = wait_for_terminate(pid, &status)) < 0) {
3712 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3716 if (status.si_code == CLD_EXITED) {
3717 if (status.si_status != 0) {
3718 log_warning("%s failed with error code %i.", name, status.si_status);
3719 return status.si_status;
3722 log_debug("%s succeeded.", name);
3725 } else if (status.si_code == CLD_KILLED ||
3726 status.si_code == CLD_DUMPED) {
3728 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3732 log_warning("%s failed due to unknown reason.", name);
3739 /* Make sure nobody waits for us on a socket anymore */
3740 close_all_fds(NULL, 0);
3748 bool null_or_empty(struct stat *st) {
3751 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3754 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3760 DIR *xopendirat(int fd, const char *name, int flags) {
3764 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3767 if (!(d = fdopendir(nfd))) {
3768 close_nointr_nofail(nfd);
3775 int signal_from_string_try_harder(const char *s) {
3779 if ((signo = signal_from_string(s)) <= 0)
3780 if (startswith(s, "SIG"))
3781 return signal_from_string(s+3);
3786 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3792 if (!dual_timestamp_is_set(t))
3795 fprintf(f, "%s=%llu %llu\n",
3797 (unsigned long long) t->realtime,
3798 (unsigned long long) t->monotonic);
3801 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3802 unsigned long long a, b;
3807 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3808 log_debug("Failed to parse finish timestamp value %s", value);
3815 char *fstab_node_to_udev_node(const char *p) {
3819 /* FIXME: to follow udev's logic 100% we need to leave valid
3820 * UTF8 chars unescaped */
3822 if (startswith(p, "LABEL=")) {
3824 if (!(u = unquote(p+6, "\"\'")))
3827 t = xescape(u, "/ ");
3833 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3842 if (startswith(p, "UUID=")) {
3844 if (!(u = unquote(p+5, "\"\'")))
3847 t = xescape(u, "/ ");
3853 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3865 void filter_environ(const char *prefix) {
3872 for (i = 0, j = 0; environ[i]; i++) {
3874 if (startswith(environ[i], prefix))
3877 environ[j++] = environ[i];
3883 bool tty_is_vc(const char *tty) {
3886 if (startswith(tty, "/dev/"))
3889 return startswith(tty, "tty") &&
3890 tty[3] >= '0' && tty[3] <= '9';
3893 const char *default_term_for_tty(const char *tty) {
3894 char *active = NULL;
3899 if (startswith(tty, "/dev/"))
3902 /* Resolve where /dev/console is pointing when determining
3904 if (streq(tty, "console"))
3905 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3906 /* If multiple log outputs are configured the
3907 * last one is what /dev/console points to */
3908 if ((tty = strrchr(active, ' ')))
3914 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3920 /* Returns a short identifier for the various VM implementations */
3921 int detect_vm(const char **id) {
3923 #if defined(__i386__) || defined(__x86_64__)
3925 /* Both CPUID and DMI are x86 specific interfaces... */
3927 static const char *const dmi_vendors[] = {
3928 "/sys/class/dmi/id/sys_vendor",
3929 "/sys/class/dmi/id/board_vendor",
3930 "/sys/class/dmi/id/bios_vendor"
3933 static const char dmi_vendor_table[] =
3935 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3936 "VMware\0" "vmware\0"
3938 "Microsoft Corporation\0" "microsoft\0"
3939 "innotek GmbH\0" "oracle\0"
3941 "Bochs\0" "bochs\0";
3943 static const char cpuid_vendor_table[] =
3944 "XenVMMXenVMM\0" "xen\0"
3945 "KVMKVMKVM\0" "kvm\0"
3946 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3947 "VMwareVMware\0" "vmware\0"
3948 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3949 "Microsoft Hv\0" "microsoft\0";
3960 /* http://lwn.net/Articles/301888/ */
3963 #if defined (__i386__)
3966 #elif defined (__amd64__)
3971 /* First detect whether there is a hypervisor */
3973 __asm__ __volatile__ (
3974 /* ebx/rbx is being used for PIC! */
3975 " push %%"REG_b" \n\t"
3977 " pop %%"REG_b" \n\t"
3979 : "=a" (eax), "=c" (ecx)
3983 hypervisor = !!(ecx & ecx & 0x80000000U);
3987 /* There is a hypervisor, see what it is */
3989 __asm__ __volatile__ (
3990 /* ebx/rbx is being used for PIC! */
3991 " push %%"REG_b" \n\t"
3993 " mov %%ebx, %1 \n\t"
3994 " pop %%"REG_b" \n\t"
3996 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4000 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4001 if (streq(sig.text, j)) {
4010 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4013 const char *found = NULL;
4015 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4022 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4023 if (startswith(s, j))
4046 int detect_container(const char **id) {
4049 /* Unfortunately many of these operations require root access
4050 * in one way or another */
4055 if (running_in_chroot() > 0) {
4063 /* /proc/vz exists in container and outside of the container,
4064 * /proc/bc only outside of the container. */
4065 if (access("/proc/vz", F_OK) >= 0 &&
4066 access("/proc/bc", F_OK) < 0) {
4074 if ((f = fopen("/proc/self/cgroup", "r"))) {
4077 char line[LINE_MAX], *p;
4079 if (!fgets(line, sizeof(line), f))
4082 if (!(p = strchr(strstrip(line), ':')))
4085 if (strncmp(p, ":ns:", 4))
4088 if (!streq(p, ":ns:/")) {
4104 /* Returns a short identifier for the various VM/container implementations */
4105 int detect_virtualization(const char **id) {
4106 static __thread const char *cached_id = NULL;
4112 if (cached_id == (const char*) -1)
4121 if ((r = detect_container(&_id)) != 0)
4124 r = detect_vm(&_id);
4133 cached_id = (const char*) -1;
4138 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4141 Hashmap *pids = NULL;
4145 /* Executes all binaries in a directory in parallel and waits
4146 * until all they all finished. */
4149 if (!(_d = opendir(directory))) {
4151 if (errno == ENOENT)
4154 log_error("Failed to enumerate directory %s: %m", directory);
4161 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4162 log_error("Failed to allocate set.");
4166 while ((de = readdir(d))) {
4171 if (ignore_file(de->d_name))
4174 if (de->d_type != DT_REG &&
4175 de->d_type != DT_LNK &&
4176 de->d_type != DT_UNKNOWN)
4179 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4180 log_error("Out of memory");
4184 if ((pid = fork()) < 0) {
4185 log_error("Failed to fork: %m");
4204 log_error("Failed to execute %s: %m", path);
4205 _exit(EXIT_FAILURE);
4208 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4210 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4211 log_error("Failed to add PID to set: %s", strerror(-k));
4216 while (!hashmap_isempty(pids)) {
4221 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4226 log_error("waitid() failed: %m");
4230 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4231 if (!is_clean_exit(si.si_code, si.si_status)) {
4232 if (si.si_code == CLD_EXITED)
4233 log_error("%s exited with exit status %i.", path, si.si_status);
4235 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4237 log_debug("%s exited successfully.", path);
4248 hashmap_free_free(pids);
4251 int kill_and_sigcont(pid_t pid, int sig) {
4254 r = kill(pid, sig) < 0 ? -errno : 0;
4262 bool nulstr_contains(const char*nulstr, const char *needle) {
4268 NULSTR_FOREACH(i, nulstr)
4269 if (streq(i, needle))
4275 bool plymouth_running(void) {
4276 return access("/run/plymouth/pid", F_OK) >= 0;
4279 void parse_syslog_priority(char **p, int *priority) {
4280 int a = 0, b = 0, c = 0;
4290 if (!strchr(*p, '>'))
4293 if ((*p)[2] == '>') {
4294 c = undecchar((*p)[1]);
4296 } else if ((*p)[3] == '>') {
4297 b = undecchar((*p)[1]);
4298 c = undecchar((*p)[2]);
4300 } else if ((*p)[4] == '>') {
4301 a = undecchar((*p)[1]);
4302 b = undecchar((*p)[2]);
4303 c = undecchar((*p)[3]);
4308 if (a < 0 || b < 0 || c < 0)
4311 *priority = a*100+b*10+c;
4315 int have_effective_cap(int value) {
4317 cap_flag_value_t fv;
4320 if (!(cap = cap_get_proc()))
4323 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4332 char* strshorten(char *s, size_t l) {
4341 static bool hostname_valid_char(char c) {
4343 (c >= 'a' && c <= 'z') ||
4344 (c >= 'A' && c <= 'Z') ||
4345 (c >= '0' && c <= '9') ||
4351 bool hostname_is_valid(const char *s) {
4357 for (p = s; *p; p++)
4358 if (!hostname_valid_char(*p))
4361 if (p-s > HOST_NAME_MAX)
4367 char* hostname_cleanup(char *s) {
4370 for (p = s, d = s; *p; p++)
4371 if ((*p >= 'a' && *p <= 'z') ||
4372 (*p >= 'A' && *p <= 'Z') ||
4373 (*p >= '0' && *p <= '9') ||
4381 strshorten(s, HOST_NAME_MAX);
4385 static const char *const ioprio_class_table[] = {
4386 [IOPRIO_CLASS_NONE] = "none",
4387 [IOPRIO_CLASS_RT] = "realtime",
4388 [IOPRIO_CLASS_BE] = "best-effort",
4389 [IOPRIO_CLASS_IDLE] = "idle"
4392 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4394 static const char *const sigchld_code_table[] = {
4395 [CLD_EXITED] = "exited",
4396 [CLD_KILLED] = "killed",
4397 [CLD_DUMPED] = "dumped",
4398 [CLD_TRAPPED] = "trapped",
4399 [CLD_STOPPED] = "stopped",
4400 [CLD_CONTINUED] = "continued",
4403 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4405 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4406 [LOG_FAC(LOG_KERN)] = "kern",
4407 [LOG_FAC(LOG_USER)] = "user",
4408 [LOG_FAC(LOG_MAIL)] = "mail",
4409 [LOG_FAC(LOG_DAEMON)] = "daemon",
4410 [LOG_FAC(LOG_AUTH)] = "auth",
4411 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4412 [LOG_FAC(LOG_LPR)] = "lpr",
4413 [LOG_FAC(LOG_NEWS)] = "news",
4414 [LOG_FAC(LOG_UUCP)] = "uucp",
4415 [LOG_FAC(LOG_CRON)] = "cron",
4416 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4417 [LOG_FAC(LOG_FTP)] = "ftp",
4418 [LOG_FAC(LOG_LOCAL0)] = "local0",
4419 [LOG_FAC(LOG_LOCAL1)] = "local1",
4420 [LOG_FAC(LOG_LOCAL2)] = "local2",
4421 [LOG_FAC(LOG_LOCAL3)] = "local3",
4422 [LOG_FAC(LOG_LOCAL4)] = "local4",
4423 [LOG_FAC(LOG_LOCAL5)] = "local5",
4424 [LOG_FAC(LOG_LOCAL6)] = "local6",
4425 [LOG_FAC(LOG_LOCAL7)] = "local7"
4428 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4430 static const char *const log_level_table[] = {
4431 [LOG_EMERG] = "emerg",
4432 [LOG_ALERT] = "alert",
4433 [LOG_CRIT] = "crit",
4435 [LOG_WARNING] = "warning",
4436 [LOG_NOTICE] = "notice",
4437 [LOG_INFO] = "info",
4438 [LOG_DEBUG] = "debug"
4441 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4443 static const char* const sched_policy_table[] = {
4444 [SCHED_OTHER] = "other",
4445 [SCHED_BATCH] = "batch",
4446 [SCHED_IDLE] = "idle",
4447 [SCHED_FIFO] = "fifo",
4451 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4453 static const char* const rlimit_table[] = {
4454 [RLIMIT_CPU] = "LimitCPU",
4455 [RLIMIT_FSIZE] = "LimitFSIZE",
4456 [RLIMIT_DATA] = "LimitDATA",
4457 [RLIMIT_STACK] = "LimitSTACK",
4458 [RLIMIT_CORE] = "LimitCORE",
4459 [RLIMIT_RSS] = "LimitRSS",
4460 [RLIMIT_NOFILE] = "LimitNOFILE",
4461 [RLIMIT_AS] = "LimitAS",
4462 [RLIMIT_NPROC] = "LimitNPROC",
4463 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4464 [RLIMIT_LOCKS] = "LimitLOCKS",
4465 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4466 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4467 [RLIMIT_NICE] = "LimitNICE",
4468 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4469 [RLIMIT_RTTIME] = "LimitRTTIME"
4472 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4474 static const char* const ip_tos_table[] = {
4475 [IPTOS_LOWDELAY] = "low-delay",
4476 [IPTOS_THROUGHPUT] = "throughput",
4477 [IPTOS_RELIABILITY] = "reliability",
4478 [IPTOS_LOWCOST] = "low-cost",
4481 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4483 static const char *const signal_table[] = {
4500 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4511 [SIGVTALRM] = "VTALRM",
4513 [SIGWINCH] = "WINCH",
4519 DEFINE_STRING_TABLE_LOOKUP(signal, int);