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>
55 #include <linux/rtc.h>
64 #include "exit-status.h"
67 size_t page_size(void) {
68 static __thread size_t pgsz = 0;
74 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
81 bool streq_ptr(const char *a, const char *b) {
83 /* Like streq(), but tries to make sense of NULL pointers */
94 usec_t now(clockid_t clock_id) {
97 assert_se(clock_gettime(clock_id, &ts) == 0);
99 return timespec_load(&ts);
102 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
105 ts->realtime = now(CLOCK_REALTIME);
106 ts->monotonic = now(CLOCK_MONOTONIC);
111 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
120 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
122 ts->monotonic = now(CLOCK_MONOTONIC);
124 if ((int64_t) ts->monotonic > delta)
125 ts->monotonic -= delta;
133 usec_t timespec_load(const struct timespec *ts) {
137 (usec_t) ts->tv_sec * USEC_PER_SEC +
138 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
141 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
144 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
145 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
150 usec_t timeval_load(const struct timeval *tv) {
154 (usec_t) tv->tv_sec * USEC_PER_SEC +
155 (usec_t) tv->tv_usec;
158 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
161 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
162 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
167 bool endswith(const char *s, const char *postfix) {
174 pl = strlen(postfix);
182 return memcmp(s + sl - pl, postfix, pl) == 0;
185 bool startswith(const char *s, const char *prefix) {
200 return memcmp(s, prefix, pl) == 0;
203 bool startswith_no_case(const char *s, const char *prefix) {
219 for(i = 0; i < pl; ++i) {
220 if (tolower(s[i]) != tolower(prefix[i]))
227 bool first_word(const char *s, const char *word) {
242 if (memcmp(s, word, wl) != 0)
246 strchr(WHITESPACE, s[wl]);
249 int close_nointr(int fd) {
264 void close_nointr_nofail(int fd) {
265 int saved_errno = errno;
267 /* like close_nointr() but cannot fail, and guarantees errno
270 assert_se(close_nointr(fd) == 0);
275 void close_many(const int fds[], unsigned n_fd) {
278 for (i = 0; i < n_fd; i++)
279 close_nointr_nofail(fds[i]);
282 int parse_boolean(const char *v) {
285 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
287 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
293 int parse_pid(const char *s, pid_t* ret_pid) {
294 unsigned long ul = 0;
301 if ((r = safe_atolu(s, &ul)) < 0)
306 if ((unsigned long) pid != ul)
316 int safe_atou(const char *s, unsigned *ret_u) {
324 l = strtoul(s, &x, 0);
326 if (!x || *x || errno)
327 return errno ? -errno : -EINVAL;
329 if ((unsigned long) (unsigned) l != l)
332 *ret_u = (unsigned) l;
336 int safe_atoi(const char *s, int *ret_i) {
344 l = strtol(s, &x, 0);
346 if (!x || *x || errno)
347 return errno ? -errno : -EINVAL;
349 if ((long) (int) l != l)
356 int safe_atollu(const char *s, long long unsigned *ret_llu) {
358 unsigned long long l;
364 l = strtoull(s, &x, 0);
366 if (!x || *x || errno)
367 return errno ? -errno : -EINVAL;
373 int safe_atolli(const char *s, long long int *ret_lli) {
381 l = strtoll(s, &x, 0);
383 if (!x || *x || errno)
384 return errno ? -errno : -EINVAL;
390 /* Split a string into words. */
391 char *split(const char *c, size_t *l, const char *separator, char **state) {
394 current = *state ? *state : (char*) c;
396 if (!*current || *c == 0)
399 current += strspn(current, separator);
400 *l = strcspn(current, separator);
403 return (char*) current;
406 /* Split a string into words, but consider strings enclosed in '' and
407 * "" as words even if they include spaces. */
408 char *split_quoted(const char *c, size_t *l, char **state) {
410 bool escaped = false;
412 current = *state ? *state : (char*) c;
414 if (!*current || *c == 0)
417 current += strspn(current, WHITESPACE);
419 if (*current == '\'') {
422 for (e = current; *e; e++) {
432 *state = *e == 0 ? e : e+1;
433 } else if (*current == '\"') {
436 for (e = current; *e; e++) {
446 *state = *e == 0 ? e : e+1;
448 for (e = current; *e; e++) {
453 else if (strchr(WHITESPACE, *e))
460 return (char*) current;
463 char **split_path_and_make_absolute(const char *p) {
467 if (!(l = strv_split(p, ":")))
470 if (!strv_path_make_absolute_cwd(l)) {
478 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
481 char fn[PATH_MAX], line[LINE_MAX], *p;
487 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
490 if (!(f = fopen(fn, "r")))
493 if (!(fgets(line, sizeof(line), f))) {
501 /* Let's skip the pid and comm fields. The latter is enclosed
502 * in () but does not escape any () in its value, so let's
503 * skip over it manually */
505 if (!(p = strrchr(line, ')')))
516 if ((long unsigned) (pid_t) ppid != ppid)
519 *_ppid = (pid_t) ppid;
524 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
527 char fn[PATH_MAX], line[LINE_MAX], *p;
532 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
535 if (!(f = fopen(fn, "r")))
538 if (!(fgets(line, sizeof(line), f))) {
546 /* Let's skip the pid and comm fields. The latter is enclosed
547 * in () but does not escape any () in its value, so let's
548 * skip over it manually */
550 if (!(p = strrchr(line, ')')))
571 "%*d " /* priority */
573 "%*d " /* num_threads */
574 "%*d " /* itrealvalue */
575 "%llu " /* starttime */,
582 int write_one_line_file(const char *fn, const char *line) {
589 if (!(f = fopen(fn, "we")))
593 if (fputs(line, f) < 0) {
598 if (!endswith(line, "\n"))
616 int fchmod_umask(int fd, mode_t m) {
621 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
627 int write_one_line_file_atomic(const char *fn, const char *line) {
635 r = fopen_temporary(fn, &f, &p);
639 fchmod_umask(fileno(f), 0644);
642 if (fputs(line, f) < 0) {
647 if (!endswith(line, "\n"))
658 if (rename(p, fn) < 0)
674 int read_one_line_file(const char *fn, char **line) {
677 char t[LINE_MAX], *c;
682 if (!(f = fopen(fn, "re")))
685 if (!(fgets(t, sizeof(t), f))) {
690 if (!(c = strdup(t))) {
705 int read_full_file(const char *fn, char **contents, size_t *size) {
712 if (!(f = fopen(fn, "re")))
715 if (fstat(fileno(f), &st) < 0) {
721 if (st.st_size > 4*1024*1024) {
726 n = st.st_size > 0 ? st.st_size : LINE_MAX;
733 if (!(t = realloc(buf, n+1))) {
739 k = fread(buf + l, 1, n - l, f);
754 if (n > 4*1024*1024) {
762 else if (!(buf = calloc(1, 1))) {
784 const char *separator, ...) {
792 if ((r = read_full_file(fname, &contents, NULL)) < 0)
797 const char *key = NULL;
799 p += strspn(p, separator);
800 p += strspn(p, WHITESPACE);
805 if (!strchr(COMMENTS, *p)) {
809 va_start(ap, separator);
810 while ((key = va_arg(ap, char *))) {
814 value = va_arg(ap, char **);
817 if (strncmp(p, key, n) != 0 ||
822 n = strcspn(p, separator);
825 strchr(QUOTES, p[0]) &&
827 v = strndup(p+1, n-2);
838 /* return empty value strings as NULL */
855 p += strcspn(p, separator);
874 if (!(f = fopen(fname, "re")))
878 char l[LINE_MAX], *p, *u;
881 if (!fgets(l, sizeof(l), f)) {
894 if (strchr(COMMENTS, *p))
897 if (!(u = normalize_env_assignment(p))) {
898 log_error("Out of memory");
903 t = strv_append(m, u);
907 log_error("Out of memory");
930 int write_env_file(const char *fname, char **l) {
935 r = fopen_temporary(fname, &f, &p);
939 fchmod_umask(fileno(f), 0644);
955 if (rename(p, fname) < 0)
970 char *truncate_nl(char *s) {
973 s[strcspn(s, NEWLINE)] = 0;
977 int get_process_name(pid_t pid, char **name) {
984 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
987 r = read_one_line_file(p, name);
996 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1004 assert(max_length > 0);
1007 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1016 if (!(r = new(char, max_length))) {
1023 while ((c = getc(f)) != EOF) {
1045 size_t n = MIN(left-1, 3U);
1046 memcpy(k, "...", n);
1053 /* Kernel threads have no argv[] */
1060 if ((h = get_process_name(pid, &t)) < 0)
1063 h = asprintf(&r, "[%s]", t);
1074 char *strnappend(const char *s, const char *suffix, size_t b) {
1082 return strndup(suffix, b);
1092 if (!(r = new(char, a+b+1)))
1096 memcpy(r+a, suffix, b);
1102 char *strappend(const char *s, const char *suffix) {
1103 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1106 int readlink_malloc(const char *p, char **r) {
1116 if (!(c = new(char, l)))
1119 if ((n = readlink(p, c, l-1)) < 0) {
1125 if ((size_t) n < l-1) {
1136 int readlink_and_make_absolute(const char *p, char **r) {
1143 if ((j = readlink_malloc(p, &target)) < 0)
1146 k = file_in_same_dir(p, target);
1156 int parent_of_path(const char *path, char **_r) {
1157 const char *e, *a = NULL, *b = NULL, *p;
1167 for (e = path; *e; e++) {
1169 if (!slash && *e == '/') {
1173 } else if (slash && *e != '/')
1188 r = strndup(path, p-path);
1198 char *file_name_from_path(const char *p) {
1203 if ((r = strrchr(p, '/')))
1209 bool path_is_absolute(const char *p) {
1215 bool is_path(const char *p) {
1217 return !!strchr(p, '/');
1220 char *path_make_absolute(const char *p, const char *prefix) {
1225 /* Makes every item in the list an absolute path by prepending
1226 * the prefix, if specified and necessary */
1228 if (path_is_absolute(p) || !prefix)
1231 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1237 char *path_make_absolute_cwd(const char *p) {
1242 /* Similar to path_make_absolute(), but prefixes with the
1243 * current working directory. */
1245 if (path_is_absolute(p))
1248 if (!(cwd = get_current_dir_name()))
1251 r = path_make_absolute(p, cwd);
1257 char **strv_path_make_absolute_cwd(char **l) {
1260 /* Goes through every item in the string list and makes it
1261 * absolute. This works in place and won't rollback any
1262 * changes on failure. */
1264 STRV_FOREACH(s, l) {
1267 if (!(t = path_make_absolute_cwd(*s)))
1277 char **strv_path_canonicalize(char **l) {
1280 bool enomem = false;
1282 if (strv_isempty(l))
1285 /* Goes through every item in the string list and canonicalize
1286 * the path. This works in place and won't rollback any
1287 * changes on failure. */
1289 STRV_FOREACH(s, l) {
1292 t = path_make_absolute_cwd(*s);
1301 u = canonicalize_file_name(t);
1305 if (errno == ENOMEM || !errno)
1322 char **strv_path_remove_empty(char **l) {
1328 for (f = t = l; *f; f++) {
1330 if (dir_is_empty(*f) > 0) {
1342 int reset_all_signal_handlers(void) {
1345 for (sig = 1; sig < _NSIG; sig++) {
1346 struct sigaction sa;
1348 if (sig == SIGKILL || sig == SIGSTOP)
1352 sa.sa_handler = SIG_DFL;
1353 sa.sa_flags = SA_RESTART;
1355 /* On Linux the first two RT signals are reserved by
1356 * glibc, and sigaction() will return EINVAL for them. */
1357 if ((sigaction(sig, &sa, NULL) < 0))
1358 if (errno != EINVAL)
1365 char *strstrip(char *s) {
1368 /* Drops trailing whitespace. Modifies the string in
1369 * place. Returns pointer to first non-space character */
1371 s += strspn(s, WHITESPACE);
1373 for (e = s; *e; e++)
1374 if (!strchr(WHITESPACE, *e))
1385 char *delete_chars(char *s, const char *bad) {
1388 /* Drops all whitespace, regardless where in the string */
1390 for (f = s, t = s; *f; f++) {
1391 if (strchr(bad, *f))
1402 char *file_in_same_dir(const char *path, const char *filename) {
1409 /* This removes the last component of path and appends
1410 * filename, unless the latter is absolute anyway or the
1413 if (path_is_absolute(filename))
1414 return strdup(filename);
1416 if (!(e = strrchr(path, '/')))
1417 return strdup(filename);
1419 k = strlen(filename);
1420 if (!(r = new(char, e-path+1+k+1)))
1423 memcpy(r, path, e-path+1);
1424 memcpy(r+(e-path)+1, filename, k+1);
1429 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1432 if (label_mkdir(path, mode) >= 0)
1433 if (chmod_and_chown(path, mode, uid, gid) < 0)
1436 if (lstat(path, &st) < 0)
1439 if ((st.st_mode & 0777) != mode ||
1442 !S_ISDIR(st.st_mode)) {
1451 int mkdir_parents(const char *path, mode_t mode) {
1456 /* Creates every parent directory in the path except the last
1459 p = path + strspn(path, "/");
1464 e = p + strcspn(p, "/");
1465 p = e + strspn(e, "/");
1467 /* Is this the last component? If so, then we're
1472 if (!(t = strndup(path, e - path)))
1475 r = label_mkdir(t, mode);
1478 if (r < 0 && errno != EEXIST)
1483 int mkdir_p(const char *path, mode_t mode) {
1488 if ((r = mkdir_parents(path, mode)) < 0)
1491 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1497 int rmdir_parents(const char *path, const char *stop) {
1506 /* Skip trailing slashes */
1507 while (l > 0 && path[l-1] == '/')
1513 /* Skip last component */
1514 while (l > 0 && path[l-1] != '/')
1517 /* Skip trailing slashes */
1518 while (l > 0 && path[l-1] == '/')
1524 if (!(t = strndup(path, l)))
1527 if (path_startswith(stop, t)) {
1536 if (errno != ENOENT)
1544 char hexchar(int x) {
1545 static const char table[16] = "0123456789abcdef";
1547 return table[x & 15];
1550 int unhexchar(char c) {
1552 if (c >= '0' && c <= '9')
1555 if (c >= 'a' && c <= 'f')
1556 return c - 'a' + 10;
1558 if (c >= 'A' && c <= 'F')
1559 return c - 'A' + 10;
1564 char octchar(int x) {
1565 return '0' + (x & 7);
1568 int unoctchar(char c) {
1570 if (c >= '0' && c <= '7')
1576 char decchar(int x) {
1577 return '0' + (x % 10);
1580 int undecchar(char c) {
1582 if (c >= '0' && c <= '9')
1588 char *cescape(const char *s) {
1594 /* Does C style string escaping. */
1596 if (!(r = new(char, strlen(s)*4 + 1)))
1599 for (f = s, t = r; *f; f++)
1645 /* For special chars we prefer octal over
1646 * hexadecimal encoding, simply because glib's
1647 * g_strescape() does the same */
1648 if ((*f < ' ') || (*f >= 127)) {
1650 *(t++) = octchar((unsigned char) *f >> 6);
1651 *(t++) = octchar((unsigned char) *f >> 3);
1652 *(t++) = octchar((unsigned char) *f);
1663 char *cunescape_length(const char *s, size_t length) {
1669 /* Undoes C style string escaping */
1671 if (!(r = new(char, length+1)))
1674 for (f = s, t = r; f < s + length; f++) {
1717 /* This is an extension of the XDG syntax files */
1722 /* hexadecimal encoding */
1725 if ((a = unhexchar(f[1])) < 0 ||
1726 (b = unhexchar(f[2])) < 0) {
1727 /* Invalid escape code, let's take it literal then */
1731 *(t++) = (char) ((a << 4) | b);
1746 /* octal encoding */
1749 if ((a = unoctchar(f[0])) < 0 ||
1750 (b = unoctchar(f[1])) < 0 ||
1751 (c = unoctchar(f[2])) < 0) {
1752 /* Invalid escape code, let's take it literal then */
1756 *(t++) = (char) ((a << 6) | (b << 3) | c);
1764 /* premature end of string.*/
1769 /* Invalid escape code, let's take it literal then */
1781 char *cunescape(const char *s) {
1782 return cunescape_length(s, strlen(s));
1785 char *xescape(const char *s, const char *bad) {
1789 /* Escapes all chars in bad, in addition to \ and all special
1790 * chars, in \xFF style escaping. May be reversed with
1793 if (!(r = new(char, strlen(s)*4+1)))
1796 for (f = s, t = r; *f; f++) {
1798 if ((*f < ' ') || (*f >= 127) ||
1799 (*f == '\\') || strchr(bad, *f)) {
1802 *(t++) = hexchar(*f >> 4);
1803 *(t++) = hexchar(*f);
1813 char *bus_path_escape(const char *s) {
1819 /* Escapes all chars that D-Bus' object path cannot deal
1820 * with. Can be reverse with bus_path_unescape() */
1822 if (!(r = new(char, strlen(s)*3+1)))
1825 for (f = s, t = r; *f; f++) {
1827 if (!(*f >= 'A' && *f <= 'Z') &&
1828 !(*f >= 'a' && *f <= 'z') &&
1829 !(*f >= '0' && *f <= '9')) {
1831 *(t++) = hexchar(*f >> 4);
1832 *(t++) = hexchar(*f);
1842 char *bus_path_unescape(const char *f) {
1847 if (!(r = strdup(f)))
1850 for (t = r; *f; f++) {
1855 if ((a = unhexchar(f[1])) < 0 ||
1856 (b = unhexchar(f[2])) < 0) {
1857 /* Invalid escape code, let's take it literal then */
1860 *(t++) = (char) ((a << 4) | b);
1872 char *path_kill_slashes(char *path) {
1876 /* Removes redundant inner and trailing slashes. Modifies the
1877 * passed string in-place.
1879 * ///foo///bar/ becomes /foo/bar
1882 for (f = path, t = path; *f; f++) {
1897 /* Special rule, if we are talking of the root directory, a
1898 trailing slash is good */
1900 if (t == path && slash)
1907 bool path_startswith(const char *path, const char *prefix) {
1911 if ((path[0] == '/') != (prefix[0] == '/'))
1917 path += strspn(path, "/");
1918 prefix += strspn(prefix, "/");
1926 a = strcspn(path, "/");
1927 b = strcspn(prefix, "/");
1932 if (memcmp(path, prefix, a) != 0)
1940 bool path_equal(const char *a, const char *b) {
1944 if ((a[0] == '/') != (b[0] == '/'))
1950 a += strspn(a, "/");
1951 b += strspn(b, "/");
1953 if (*a == 0 && *b == 0)
1956 if (*a == 0 || *b == 0)
1959 j = strcspn(a, "/");
1960 k = strcspn(b, "/");
1965 if (memcmp(a, b, j) != 0)
1973 char *ascii_strlower(char *t) {
1978 for (p = t; *p; p++)
1979 if (*p >= 'A' && *p <= 'Z')
1980 *p = *p - 'A' + 'a';
1985 bool ignore_file(const char *filename) {
1989 filename[0] == '.' ||
1990 streq(filename, "lost+found") ||
1991 streq(filename, "aquota.user") ||
1992 streq(filename, "aquota.group") ||
1993 endswith(filename, "~") ||
1994 endswith(filename, ".rpmnew") ||
1995 endswith(filename, ".rpmsave") ||
1996 endswith(filename, ".rpmorig") ||
1997 endswith(filename, ".dpkg-old") ||
1998 endswith(filename, ".dpkg-new") ||
1999 endswith(filename, ".swp");
2002 int fd_nonblock(int fd, bool nonblock) {
2007 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2011 flags |= O_NONBLOCK;
2013 flags &= ~O_NONBLOCK;
2015 if (fcntl(fd, F_SETFL, flags) < 0)
2021 int fd_cloexec(int fd, bool cloexec) {
2026 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2030 flags |= FD_CLOEXEC;
2032 flags &= ~FD_CLOEXEC;
2034 if (fcntl(fd, F_SETFD, flags) < 0)
2040 int close_all_fds(const int except[], unsigned n_except) {
2045 if (!(d = opendir("/proc/self/fd")))
2048 while ((de = readdir(d))) {
2051 if (ignore_file(de->d_name))
2054 if (safe_atoi(de->d_name, &fd) < 0)
2055 /* Let's better ignore this, just in case */
2069 for (i = 0; i < n_except; i++)
2070 if (except[i] == fd) {
2079 if (close_nointr(fd) < 0) {
2080 /* Valgrind has its own FD and doesn't want to have it closed */
2081 if (errno != EBADF && r == 0)
2090 bool chars_intersect(const char *a, const char *b) {
2093 /* Returns true if any of the chars in a are in b. */
2094 for (p = a; *p; p++)
2101 char *format_timestamp(char *buf, size_t l, usec_t t) {
2111 sec = (time_t) (t / USEC_PER_SEC);
2113 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2119 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2122 n = now(CLOCK_REALTIME);
2124 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2129 if (d >= USEC_PER_YEAR)
2130 snprintf(buf, l, "%llu years and %llu months ago",
2131 (unsigned long long) (d / USEC_PER_YEAR),
2132 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2133 else if (d >= USEC_PER_MONTH)
2134 snprintf(buf, l, "%llu months and %llu days ago",
2135 (unsigned long long) (d / USEC_PER_MONTH),
2136 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2137 else if (d >= USEC_PER_WEEK)
2138 snprintf(buf, l, "%llu weeks and %llu days ago",
2139 (unsigned long long) (d / USEC_PER_WEEK),
2140 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2141 else if (d >= 2*USEC_PER_DAY)
2142 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2143 else if (d >= 25*USEC_PER_HOUR)
2144 snprintf(buf, l, "1 day and %lluh ago",
2145 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2146 else if (d >= 6*USEC_PER_HOUR)
2147 snprintf(buf, l, "%lluh ago",
2148 (unsigned long long) (d / USEC_PER_HOUR));
2149 else if (d >= USEC_PER_HOUR)
2150 snprintf(buf, l, "%lluh %llumin ago",
2151 (unsigned long long) (d / USEC_PER_HOUR),
2152 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2153 else if (d >= 5*USEC_PER_MINUTE)
2154 snprintf(buf, l, "%llumin ago",
2155 (unsigned long long) (d / USEC_PER_MINUTE));
2156 else if (d >= USEC_PER_MINUTE)
2157 snprintf(buf, l, "%llumin %llus ago",
2158 (unsigned long long) (d / USEC_PER_MINUTE),
2159 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2160 else if (d >= USEC_PER_SEC)
2161 snprintf(buf, l, "%llus ago",
2162 (unsigned long long) (d / USEC_PER_SEC));
2163 else if (d >= USEC_PER_MSEC)
2164 snprintf(buf, l, "%llums ago",
2165 (unsigned long long) (d / USEC_PER_MSEC));
2167 snprintf(buf, l, "%lluus ago",
2168 (unsigned long long) d);
2170 snprintf(buf, l, "now");
2176 char *format_timespan(char *buf, size_t l, usec_t t) {
2177 static const struct {
2181 { "w", USEC_PER_WEEK },
2182 { "d", USEC_PER_DAY },
2183 { "h", USEC_PER_HOUR },
2184 { "min", USEC_PER_MINUTE },
2185 { "s", USEC_PER_SEC },
2186 { "ms", USEC_PER_MSEC },
2196 if (t == (usec_t) -1)
2200 snprintf(p, l, "0");
2205 /* The result of this function can be parsed with parse_usec */
2207 for (i = 0; i < ELEMENTSOF(table); i++) {
2211 if (t < table[i].usec)
2217 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2218 n = MIN((size_t) k, l);
2231 bool fstype_is_network(const char *fstype) {
2232 static const char * const table[] = {
2244 for (i = 0; i < ELEMENTSOF(table); i++)
2245 if (streq(table[i], fstype))
2254 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2259 TIOCL_GETKMSGREDIRECT,
2263 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2266 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2269 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2272 close_nointr_nofail(r);
2276 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2277 struct termios old_termios, new_termios;
2279 char line[LINE_MAX];
2284 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2285 new_termios = old_termios;
2287 new_termios.c_lflag &= ~ICANON;
2288 new_termios.c_cc[VMIN] = 1;
2289 new_termios.c_cc[VTIME] = 0;
2291 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2294 k = fread(&c, 1, 1, f);
2296 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2302 *need_nl = c != '\n';
2309 if (!(fgets(line, sizeof(line), f)))
2314 if (strlen(line) != 1)
2324 int ask(char *ret, const char *replies, const char *text, ...) {
2331 on_tty = isatty(STDOUT_FILENO);
2337 bool need_nl = true;
2340 fputs("\x1B[1m", stdout);
2347 fputs("\x1B[0m", stdout);
2351 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2353 if (r == -EBADMSG) {
2354 puts("Bad input, please try again.");
2365 if (strchr(replies, c)) {
2370 puts("Read unexpected character, please try again.");
2374 int reset_terminal_fd(int fd) {
2375 struct termios termios;
2379 /* Set terminal to some sane defaults */
2383 /* We leave locked terminal attributes untouched, so that
2384 * Plymouth may set whatever it wants to set, and we don't
2385 * interfere with that. */
2387 /* Disable exclusive mode, just in case */
2388 ioctl(fd, TIOCNXCL);
2390 /* Enable console unicode mode */
2392 ioctl(fd, KDSKBMODE, &arg);
2394 if (tcgetattr(fd, &termios) < 0) {
2399 /* We only reset the stuff that matters to the software. How
2400 * hardware is set up we don't touch assuming that somebody
2401 * else will do that for us */
2403 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2404 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2405 termios.c_oflag |= ONLCR;
2406 termios.c_cflag |= CREAD;
2407 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2409 termios.c_cc[VINTR] = 03; /* ^C */
2410 termios.c_cc[VQUIT] = 034; /* ^\ */
2411 termios.c_cc[VERASE] = 0177;
2412 termios.c_cc[VKILL] = 025; /* ^X */
2413 termios.c_cc[VEOF] = 04; /* ^D */
2414 termios.c_cc[VSTART] = 021; /* ^Q */
2415 termios.c_cc[VSTOP] = 023; /* ^S */
2416 termios.c_cc[VSUSP] = 032; /* ^Z */
2417 termios.c_cc[VLNEXT] = 026; /* ^V */
2418 termios.c_cc[VWERASE] = 027; /* ^W */
2419 termios.c_cc[VREPRINT] = 022; /* ^R */
2420 termios.c_cc[VEOL] = 0;
2421 termios.c_cc[VEOL2] = 0;
2423 termios.c_cc[VTIME] = 0;
2424 termios.c_cc[VMIN] = 1;
2426 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2430 /* Just in case, flush all crap out */
2431 tcflush(fd, TCIOFLUSH);
2436 int reset_terminal(const char *name) {
2439 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2443 r = reset_terminal_fd(fd);
2444 close_nointr_nofail(fd);
2449 int open_terminal(const char *name, int mode) {
2454 * If a TTY is in the process of being closed opening it might
2455 * cause EIO. This is horribly awful, but unlikely to be
2456 * changed in the kernel. Hence we work around this problem by
2457 * retrying a couple of times.
2459 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2463 if ((fd = open(name, mode)) >= 0)
2472 usleep(50 * USEC_PER_MSEC);
2479 if ((r = isatty(fd)) < 0) {
2480 close_nointr_nofail(fd);
2485 close_nointr_nofail(fd);
2492 int flush_fd(int fd) {
2493 struct pollfd pollfd;
2497 pollfd.events = POLLIN;
2504 if ((r = poll(&pollfd, 1, 0)) < 0) {
2515 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2520 if (errno == EAGAIN)
2531 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2532 int fd = -1, notify = -1, r, wd = -1;
2536 /* We use inotify to be notified when the tty is closed. We
2537 * create the watch before checking if we can actually acquire
2538 * it, so that we don't lose any event.
2540 * Note: strictly speaking this actually watches for the
2541 * device being closed, it does *not* really watch whether a
2542 * tty loses its controlling process. However, unless some
2543 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2544 * its tty otherwise this will not become a problem. As long
2545 * as the administrator makes sure not configure any service
2546 * on the same tty as an untrusted user this should not be a
2547 * problem. (Which he probably should not do anyway.) */
2549 if (!fail && !force) {
2550 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2555 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2563 if ((r = flush_fd(notify)) < 0)
2566 /* We pass here O_NOCTTY only so that we can check the return
2567 * value TIOCSCTTY and have a reliable way to figure out if we
2568 * successfully became the controlling process of the tty */
2569 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2572 /* First, try to get the tty */
2573 r = ioctl(fd, TIOCSCTTY, force);
2575 /* Sometimes it makes sense to ignore TIOCSCTTY
2576 * returning EPERM, i.e. when very likely we already
2577 * are have this controlling terminal. */
2578 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2581 if (r < 0 && (force || fail || errno != EPERM)) {
2591 assert(notify >= 0);
2594 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2596 struct inotify_event *e;
2598 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2607 e = (struct inotify_event*) inotify_buffer;
2612 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2617 step = sizeof(struct inotify_event) + e->len;
2618 assert(step <= (size_t) l);
2620 e = (struct inotify_event*) ((uint8_t*) e + step);
2627 /* We close the tty fd here since if the old session
2628 * ended our handle will be dead. It's important that
2629 * we do this after sleeping, so that we don't enter
2630 * an endless loop. */
2631 close_nointr_nofail(fd);
2635 close_nointr_nofail(notify);
2637 if ((r = reset_terminal_fd(fd)) < 0)
2638 log_warning("Failed to reset terminal: %s", strerror(-r));
2644 close_nointr_nofail(fd);
2647 close_nointr_nofail(notify);
2652 int release_terminal(void) {
2654 struct sigaction sa_old, sa_new;
2656 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2659 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2660 * by our own TIOCNOTTY */
2663 sa_new.sa_handler = SIG_IGN;
2664 sa_new.sa_flags = SA_RESTART;
2665 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2667 if (ioctl(fd, TIOCNOTTY) < 0)
2670 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2672 close_nointr_nofail(fd);
2676 int sigaction_many(const struct sigaction *sa, ...) {
2681 while ((sig = va_arg(ap, int)) > 0)
2682 if (sigaction(sig, sa, NULL) < 0)
2689 int ignore_signals(int sig, ...) {
2690 struct sigaction sa;
2695 sa.sa_handler = SIG_IGN;
2696 sa.sa_flags = SA_RESTART;
2698 if (sigaction(sig, &sa, NULL) < 0)
2702 while ((sig = va_arg(ap, int)) > 0)
2703 if (sigaction(sig, &sa, NULL) < 0)
2710 int default_signals(int sig, ...) {
2711 struct sigaction sa;
2716 sa.sa_handler = SIG_DFL;
2717 sa.sa_flags = SA_RESTART;
2719 if (sigaction(sig, &sa, NULL) < 0)
2723 while ((sig = va_arg(ap, int)) > 0)
2724 if (sigaction(sig, &sa, NULL) < 0)
2731 int close_pipe(int p[]) {
2737 a = close_nointr(p[0]);
2742 b = close_nointr(p[1]);
2746 return a < 0 ? a : b;
2749 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2758 while (nbytes > 0) {
2761 if ((k = read(fd, p, nbytes)) <= 0) {
2763 if (k < 0 && errno == EINTR)
2766 if (k < 0 && errno == EAGAIN && do_poll) {
2767 struct pollfd pollfd;
2771 pollfd.events = POLLIN;
2773 if (poll(&pollfd, 1, -1) < 0) {
2777 return n > 0 ? n : -errno;
2780 if (pollfd.revents != POLLIN)
2781 return n > 0 ? n : -EIO;
2786 return n > 0 ? n : (k < 0 ? -errno : 0);
2797 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2806 while (nbytes > 0) {
2809 if ((k = write(fd, p, nbytes)) <= 0) {
2811 if (k < 0 && errno == EINTR)
2814 if (k < 0 && errno == EAGAIN && do_poll) {
2815 struct pollfd pollfd;
2819 pollfd.events = POLLOUT;
2821 if (poll(&pollfd, 1, -1) < 0) {
2825 return n > 0 ? n : -errno;
2828 if (pollfd.revents != POLLOUT)
2829 return n > 0 ? n : -EIO;
2834 return n > 0 ? n : (k < 0 ? -errno : 0);
2845 int path_is_mount_point(const char *t) {
2850 if (lstat(t, &a) < 0) {
2851 if (errno == ENOENT)
2857 if ((r = parent_of_path(t, &parent)) < 0)
2860 r = lstat(parent, &b);
2866 return a.st_dev != b.st_dev;
2869 int parse_usec(const char *t, usec_t *usec) {
2870 static const struct {
2874 { "sec", USEC_PER_SEC },
2875 { "s", USEC_PER_SEC },
2876 { "min", USEC_PER_MINUTE },
2877 { "hr", USEC_PER_HOUR },
2878 { "h", USEC_PER_HOUR },
2879 { "d", USEC_PER_DAY },
2880 { "w", USEC_PER_WEEK },
2881 { "msec", USEC_PER_MSEC },
2882 { "ms", USEC_PER_MSEC },
2883 { "m", USEC_PER_MINUTE },
2886 { "", USEC_PER_SEC },
2902 l = strtoll(p, &e, 10);
2913 e += strspn(e, WHITESPACE);
2915 for (i = 0; i < ELEMENTSOF(table); i++)
2916 if (startswith(e, table[i].suffix)) {
2917 r += (usec_t) l * table[i].usec;
2918 p = e + strlen(table[i].suffix);
2922 if (i >= ELEMENTSOF(table))
2932 int make_stdio(int fd) {
2937 r = dup2(fd, STDIN_FILENO);
2938 s = dup2(fd, STDOUT_FILENO);
2939 t = dup2(fd, STDERR_FILENO);
2942 close_nointr_nofail(fd);
2944 if (r < 0 || s < 0 || t < 0)
2950 int make_null_stdio(void) {
2953 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2956 return make_stdio(null_fd);
2959 bool is_device_path(const char *path) {
2961 /* Returns true on paths that refer to a device, either in
2962 * sysfs or in /dev */
2965 path_startswith(path, "/dev/") ||
2966 path_startswith(path, "/sys/");
2969 int dir_is_empty(const char *path) {
2972 struct dirent buf, *de;
2974 if (!(d = opendir(path)))
2978 if ((r = readdir_r(d, &buf, &de)) > 0) {
2988 if (!ignore_file(de->d_name)) {
2998 unsigned long long random_ull(void) {
3003 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3006 r = loop_read(fd, &ull, sizeof(ull), true);
3007 close_nointr_nofail(fd);
3009 if (r != sizeof(ull))
3015 return random() * RAND_MAX + random();
3018 void rename_process(const char name[8]) {
3021 prctl(PR_SET_NAME, name);
3023 /* This is a like a poor man's setproctitle(). The string
3024 * passed should fit in 7 chars (i.e. the length of
3027 if (program_invocation_name)
3028 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3031 void sigset_add_many(sigset_t *ss, ...) {
3038 while ((sig = va_arg(ap, int)) > 0)
3039 assert_se(sigaddset(ss, sig) == 0);
3043 char* gethostname_malloc(void) {
3046 assert_se(uname(&u) >= 0);
3049 return strdup(u.nodename);
3051 return strdup(u.sysname);
3054 char* getlogname_malloc(void) {
3058 struct passwd pwbuf, *pw = NULL;
3061 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3066 /* Shortcut things to avoid NSS lookups */
3068 return strdup("root");
3070 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3073 if (!(buf = malloc(bufsize)))
3076 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3077 name = strdup(pw->pw_name);
3084 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3090 int getttyname_malloc(int fd, char **r) {
3091 char path[PATH_MAX], *c;
3096 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3101 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3108 int getttyname_harder(int fd, char **r) {
3112 if ((k = getttyname_malloc(fd, &s)) < 0)
3115 if (streq(s, "tty")) {
3117 return get_ctty(0, NULL, r);
3124 int get_ctty_devnr(pid_t pid, dev_t *d) {
3126 char line[LINE_MAX], *p, *fn;
3127 unsigned long ttynr;
3130 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3133 f = fopen(fn, "re");
3138 if (!fgets(line, sizeof(line), f)) {
3146 p = strrchr(line, ')');
3156 "%*d " /* session */
3165 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3167 char fn[PATH_MAX], *s, *b, *p;
3172 k = get_ctty_devnr(pid, &devnr);
3176 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3179 if ((k = readlink_malloc(fn, &s)) < 0) {
3184 /* This is an ugly hack */
3185 if (major(devnr) == 136) {
3186 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3196 /* Probably something like the ptys which have no
3197 * symlink in /dev/char. Let's return something
3198 * vaguely useful. */
3200 if (!(b = strdup(fn + 5)))
3210 if (startswith(s, "/dev/"))
3212 else if (startswith(s, "../"))
3230 static int rm_rf_children(int fd, bool only_dirs) {
3236 /* This returns the first error we run into, but nevertheless
3239 if (!(d = fdopendir(fd))) {
3240 close_nointr_nofail(fd);
3242 return errno == ENOENT ? 0 : -errno;
3246 struct dirent buf, *de;
3250 if ((r = readdir_r(d, &buf, &de)) != 0) {
3259 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3262 if (de->d_type == DT_UNKNOWN) {
3265 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3266 if (ret == 0 && errno != ENOENT)
3271 is_dir = S_ISDIR(st.st_mode);
3273 is_dir = de->d_type == DT_DIR;
3278 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3279 if (ret == 0 && errno != ENOENT)
3284 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3289 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3290 if (ret == 0 && errno != ENOENT)
3293 } else if (!only_dirs) {
3295 if (unlinkat(fd, de->d_name, 0) < 0) {
3296 if (ret == 0 && errno != ENOENT)
3307 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3313 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3315 if (errno != ENOTDIR)
3318 if (delete_root && !only_dirs)
3319 if (unlink(path) < 0)
3325 r = rm_rf_children(fd, only_dirs);
3328 if (rmdir(path) < 0) {
3336 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3339 /* Under the assumption that we are running privileged we
3340 * first change the access mode and only then hand out
3341 * ownership to avoid a window where access is too open. */
3343 if (chmod(path, mode) < 0)
3346 if (chown(path, uid, gid) < 0)
3352 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3356 /* Allocates the cpuset in the right size */
3359 if (!(r = CPU_ALLOC(n)))
3362 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3363 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3373 if (errno != EINVAL)
3380 void status_vprintf(const char *format, va_list ap) {
3386 /* This independent of logging, as status messages are
3387 * optional and go exclusively to the console. */
3389 if (vasprintf(&s, format, ap) < 0)
3392 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3395 write(fd, s, strlen(s));
3401 close_nointr_nofail(fd);
3404 void status_printf(const char *format, ...) {
3409 va_start(ap, format);
3410 status_vprintf(format, ap);
3414 void status_welcome(void) {
3415 char *pretty_name = NULL, *ansi_color = NULL;
3416 const char *const_pretty = NULL, *const_color = NULL;
3419 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3420 "PRETTY_NAME", &pretty_name,
3421 "ANSI_COLOR", &ansi_color,
3425 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3428 #if defined(TARGET_FEDORA)
3430 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3433 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3437 if (!ansi_color && pretty_name) {
3439 /* This tries to mimic the color magic the old Red Hat sysinit
3442 if (startswith(pretty_name, "Red Hat"))
3443 const_color = "0;31"; /* Red for RHEL */
3444 else if (startswith(pretty_name, "Fedora"))
3445 const_color = "0;34"; /* Blue for Fedora */
3448 #elif defined(TARGET_SUSE)
3451 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3454 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3459 const_color = "0;32"; /* Green for openSUSE */
3461 #elif defined(TARGET_GENTOO)
3464 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3467 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3472 const_color = "1;34"; /* Light Blue for Gentoo */
3474 #elif defined(TARGET_ALTLINUX)
3477 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3480 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3485 const_color = "0;36"; /* Cyan for ALTLinux */
3488 #elif defined(TARGET_DEBIAN)
3493 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3496 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3498 pretty_name = strappend("Debian ", version);
3502 log_warning("Failed to allocate Debian version string.");
3507 const_color = "1;31"; /* Light Red for Debian */
3509 #elif defined(TARGET_UBUNTU)
3511 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3512 "DISTRIB_DESCRIPTION", &pretty_name,
3516 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3520 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3522 #elif defined(TARGET_MANDRIVA)
3527 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3529 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3531 p = strstr(s, " release ");
3535 p[strcspn(p, " ")] = '\0';
3537 /* This corresponds to standard rc.sysinit */
3538 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3539 const_color = "1;36";
3541 log_warning("Failed to allocate Mandriva version string.");
3543 log_warning("Failed to parse /etc/mandriva-release");
3547 #elif defined(TARGET_MEEGO)
3550 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3553 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3558 const_color = "1;35"; /* Bright Magenta for MeeGo */
3561 if (!pretty_name && !const_pretty)
3562 const_pretty = "Linux";
3564 if (!ansi_color && !const_color)
3567 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3568 const_color ? const_color : ansi_color,
3569 const_pretty ? const_pretty : pretty_name);
3575 char *replace_env(const char *format, char **env) {
3582 const char *e, *word = format;
3587 for (e = format; *e; e ++) {
3598 if (!(k = strnappend(r, word, e-word-1)))
3607 } else if (*e == '$') {
3608 if (!(k = strnappend(r, word, e-word)))
3624 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3627 if (!(k = strappend(r, t)))
3640 if (!(k = strnappend(r, word, e-word)))
3651 char **replace_env_argv(char **argv, char **env) {
3653 unsigned k = 0, l = 0;
3655 l = strv_length(argv);
3657 if (!(r = new(char*, l+1)))
3660 STRV_FOREACH(i, argv) {
3662 /* If $FOO appears as single word, replace it by the split up variable */
3663 if ((*i)[0] == '$' && (*i)[1] != '{') {
3668 if ((e = strv_env_get(env, *i+1))) {
3670 if (!(m = strv_split_quoted(e))) {
3681 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3690 memcpy(r + k, m, q * sizeof(char*));
3698 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3699 if (!(r[k++] = replace_env(*i, env))) {
3710 static __thread int parsed_columns = 0;
3713 if (parsed_columns > 0)
3714 return parsed_columns;
3716 if ((e = getenv("COLUMNS")))
3717 parsed_columns = atoi(e);
3719 if (parsed_columns <= 0) {
3723 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3724 parsed_columns = ws.ws_col;
3727 if (parsed_columns <= 0)
3728 parsed_columns = 80;
3730 return parsed_columns;
3733 int running_in_chroot(void) {
3739 /* Only works as root */
3741 if (stat("/proc/1/root", &a) < 0)
3744 if (stat("/", &b) < 0)
3748 a.st_dev != b.st_dev ||
3749 a.st_ino != b.st_ino;
3752 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3757 assert(percent <= 100);
3758 assert(length >= 3);
3762 if (l <= 3 || l <= length)
3765 if (!(r = new0(char, length+1)))
3768 x = (length * percent) / 100;
3778 s + l - (length - x - 3),
3784 int touch(const char *path) {
3789 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3792 close_nointr_nofail(fd);
3796 char *unquote(const char *s, const char* quotes) {
3800 if ((l = strlen(s)) < 2)
3803 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3804 return strndup(s+1, l-2);
3809 char *normalize_env_assignment(const char *s) {
3810 char *name, *value, *p, *r;
3815 if (!(r = strdup(s)))
3821 if (!(name = strndup(s, p - s)))
3824 if (!(p = strdup(p+1))) {
3829 value = unquote(strstrip(p), QUOTES);
3837 if (asprintf(&r, "%s=%s", name, value) < 0)
3846 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3853 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3865 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3872 if ((r = wait_for_terminate(pid, &status)) < 0) {
3873 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3877 if (status.si_code == CLD_EXITED) {
3878 if (status.si_status != 0) {
3879 log_warning("%s failed with error code %i.", name, status.si_status);
3880 return status.si_status;
3883 log_debug("%s succeeded.", name);
3886 } else if (status.si_code == CLD_KILLED ||
3887 status.si_code == CLD_DUMPED) {
3889 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3893 log_warning("%s failed due to unknown reason.", name);
3900 /* Make sure nobody waits for us on a socket anymore */
3901 close_all_fds(NULL, 0);
3909 bool null_or_empty(struct stat *st) {
3912 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3915 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3921 DIR *xopendirat(int fd, const char *name, int flags) {
3925 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3928 if (!(d = fdopendir(nfd))) {
3929 close_nointr_nofail(nfd);
3936 int signal_from_string_try_harder(const char *s) {
3940 if ((signo = signal_from_string(s)) <= 0)
3941 if (startswith(s, "SIG"))
3942 return signal_from_string(s+3);
3947 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3953 if (!dual_timestamp_is_set(t))
3956 fprintf(f, "%s=%llu %llu\n",
3958 (unsigned long long) t->realtime,
3959 (unsigned long long) t->monotonic);
3962 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3963 unsigned long long a, b;
3968 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3969 log_debug("Failed to parse finish timestamp value %s", value);
3976 char *fstab_node_to_udev_node(const char *p) {
3980 /* FIXME: to follow udev's logic 100% we need to leave valid
3981 * UTF8 chars unescaped */
3983 if (startswith(p, "LABEL=")) {
3985 if (!(u = unquote(p+6, "\"\'")))
3988 t = xescape(u, "/ ");
3994 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4003 if (startswith(p, "UUID=")) {
4005 if (!(u = unquote(p+5, "\"\'")))
4008 t = xescape(u, "/ ");
4014 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4026 void filter_environ(const char *prefix) {
4033 for (i = 0, j = 0; environ[i]; i++) {
4035 if (startswith(environ[i], prefix))
4038 environ[j++] = environ[i];
4044 bool tty_is_vc(const char *tty) {
4047 if (startswith(tty, "/dev/"))
4050 return vtnr_from_tty(tty) >= 0;
4053 int vtnr_from_tty(const char *tty) {
4058 if (startswith(tty, "/dev/"))
4061 if (!startswith(tty, "tty") )
4064 if (tty[3] < '0' || tty[3] > '9')
4067 r = safe_atoi(tty+3, &i);
4071 if (i < 0 || i > 63)
4077 const char *default_term_for_tty(const char *tty) {
4078 char *active = NULL;
4083 if (startswith(tty, "/dev/"))
4086 /* Resolve where /dev/console is pointing when determining
4088 if (streq(tty, "console"))
4089 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4090 /* If multiple log outputs are configured the
4091 * last one is what /dev/console points to */
4092 if ((tty = strrchr(active, ' ')))
4098 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4104 /* Returns a short identifier for the various VM implementations */
4105 int detect_vm(const char **id) {
4107 #if defined(__i386__) || defined(__x86_64__)
4109 /* Both CPUID and DMI are x86 specific interfaces... */
4111 static const char *const dmi_vendors[] = {
4112 "/sys/class/dmi/id/sys_vendor",
4113 "/sys/class/dmi/id/board_vendor",
4114 "/sys/class/dmi/id/bios_vendor"
4117 static const char dmi_vendor_table[] =
4119 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4120 "VMware\0" "vmware\0"
4122 "Microsoft Corporation\0" "microsoft\0"
4123 "innotek GmbH\0" "oracle\0"
4125 "Bochs\0" "bochs\0";
4127 static const char cpuid_vendor_table[] =
4128 "XenVMMXenVMM\0" "xen\0"
4129 "KVMKVMKVM\0" "kvm\0"
4130 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4131 "VMwareVMware\0" "vmware\0"
4132 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4133 "Microsoft Hv\0" "microsoft\0";
4144 /* http://lwn.net/Articles/301888/ */
4147 #if defined (__i386__)
4150 #elif defined (__amd64__)
4155 /* First detect whether there is a hypervisor */
4157 __asm__ __volatile__ (
4158 /* ebx/rbx is being used for PIC! */
4159 " push %%"REG_b" \n\t"
4161 " pop %%"REG_b" \n\t"
4163 : "=a" (eax), "=c" (ecx)
4167 hypervisor = !!(ecx & 0x80000000U);
4171 /* There is a hypervisor, see what it is */
4173 __asm__ __volatile__ (
4174 /* ebx/rbx is being used for PIC! */
4175 " push %%"REG_b" \n\t"
4177 " mov %%ebx, %1 \n\t"
4178 " pop %%"REG_b" \n\t"
4180 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4184 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4185 if (streq(sig.text, j)) {
4194 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4197 const char *found = NULL;
4199 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4206 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4207 if (startswith(s, j))
4230 int detect_container(const char **id) {
4233 /* Unfortunately many of these operations require root access
4234 * in one way or another */
4239 if (running_in_chroot() > 0) {
4247 /* /proc/vz exists in container and outside of the container,
4248 * /proc/bc only outside of the container. */
4249 if (access("/proc/vz", F_OK) >= 0 &&
4250 access("/proc/bc", F_OK) < 0) {
4258 if ((f = fopen("/proc/self/cgroup", "r"))) {
4261 char line[LINE_MAX], *p;
4263 if (!fgets(line, sizeof(line), f))
4266 if (!(p = strchr(strstrip(line), ':')))
4269 if (strncmp(p, ":ns:", 4))
4272 if (!streq(p, ":ns:/")) {
4288 /* Returns a short identifier for the various VM/container implementations */
4289 int detect_virtualization(const char **id) {
4290 static __thread const char *cached_id = NULL;
4296 if (cached_id == (const char*) -1)
4305 if ((r = detect_container(&_id)) != 0)
4308 r = detect_vm(&_id);
4317 cached_id = (const char*) -1;
4322 bool dirent_is_file(struct dirent *de) {
4325 if (ignore_file(de->d_name))
4328 if (de->d_type != DT_REG &&
4329 de->d_type != DT_LNK &&
4330 de->d_type != DT_UNKNOWN)
4336 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4339 Hashmap *pids = NULL;
4343 /* Executes all binaries in a directory in parallel and waits
4344 * until all they all finished. */
4347 if (!(_d = opendir(directory))) {
4349 if (errno == ENOENT)
4352 log_error("Failed to enumerate directory %s: %m", directory);
4359 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4360 log_error("Failed to allocate set.");
4364 while ((de = readdir(d))) {
4369 if (!dirent_is_file(de))
4372 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4373 log_error("Out of memory");
4377 if ((pid = fork()) < 0) {
4378 log_error("Failed to fork: %m");
4397 log_error("Failed to execute %s: %m", path);
4398 _exit(EXIT_FAILURE);
4401 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4403 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4404 log_error("Failed to add PID to set: %s", strerror(-k));
4409 while (!hashmap_isempty(pids)) {
4414 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4419 log_error("waitid() failed: %m");
4423 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4424 if (!is_clean_exit(si.si_code, si.si_status)) {
4425 if (si.si_code == CLD_EXITED)
4426 log_error("%s exited with exit status %i.", path, si.si_status);
4428 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4430 log_debug("%s exited successfully.", path);
4441 hashmap_free_free(pids);
4444 int kill_and_sigcont(pid_t pid, int sig) {
4447 r = kill(pid, sig) < 0 ? -errno : 0;
4455 bool nulstr_contains(const char*nulstr, const char *needle) {
4461 NULSTR_FOREACH(i, nulstr)
4462 if (streq(i, needle))
4468 bool plymouth_running(void) {
4469 return access("/run/plymouth/pid", F_OK) >= 0;
4472 void parse_syslog_priority(char **p, int *priority) {
4473 int a = 0, b = 0, c = 0;
4483 if (!strchr(*p, '>'))
4486 if ((*p)[2] == '>') {
4487 c = undecchar((*p)[1]);
4489 } else if ((*p)[3] == '>') {
4490 b = undecchar((*p)[1]);
4491 c = undecchar((*p)[2]);
4493 } else if ((*p)[4] == '>') {
4494 a = undecchar((*p)[1]);
4495 b = undecchar((*p)[2]);
4496 c = undecchar((*p)[3]);
4501 if (a < 0 || b < 0 || c < 0)
4504 *priority = a*100+b*10+c;
4508 int have_effective_cap(int value) {
4510 cap_flag_value_t fv;
4513 if (!(cap = cap_get_proc()))
4516 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4525 char* strshorten(char *s, size_t l) {
4534 static bool hostname_valid_char(char c) {
4536 (c >= 'a' && c <= 'z') ||
4537 (c >= 'A' && c <= 'Z') ||
4538 (c >= '0' && c <= '9') ||
4544 bool hostname_is_valid(const char *s) {
4550 for (p = s; *p; p++)
4551 if (!hostname_valid_char(*p))
4554 if (p-s > HOST_NAME_MAX)
4560 char* hostname_cleanup(char *s) {
4563 for (p = s, d = s; *p; p++)
4564 if ((*p >= 'a' && *p <= 'z') ||
4565 (*p >= 'A' && *p <= 'Z') ||
4566 (*p >= '0' && *p <= '9') ||
4574 strshorten(s, HOST_NAME_MAX);
4578 int pipe_eof(int fd) {
4579 struct pollfd pollfd;
4584 pollfd.events = POLLIN|POLLHUP;
4586 r = poll(&pollfd, 1, 0);
4593 return pollfd.revents & POLLHUP;
4596 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4607 t = new(char, strlen(path) + 1 + 6 + 1);
4611 fn = file_name_from_path(path);
4615 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4617 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4623 f = fdopen(fd, "we");
4636 int terminal_vhangup_fd(int fd) {
4639 if (ioctl(fd, TIOCVHANGUP) < 0)
4645 int terminal_vhangup(const char *name) {
4648 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4652 r = terminal_vhangup_fd(fd);
4653 close_nointr_nofail(fd);
4658 int vt_disallocate(const char *name) {
4662 /* Deallocate the VT if possible. If not possible
4663 * (i.e. because it is the active one), at least clear it
4664 * entirely (including the scrollback buffer) */
4666 if (!startswith(name, "/dev/"))
4669 if (!tty_is_vc(name)) {
4670 /* So this is not a VT. I guess we cannot deallocate
4671 * it then. But let's at least clear the screen */
4673 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4677 loop_write(fd, "\033[H\033[2J", 7, false); /* clear screen */
4678 close_nointr_nofail(fd);
4683 if (!startswith(name, "/dev/tty"))
4686 r = safe_atou(name+8, &u);
4693 /* Try to deallocate */
4694 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4698 r = ioctl(fd, VT_DISALLOCATE, u);
4699 close_nointr_nofail(fd);
4707 /* Couldn't deallocate, so let's clear it fully with
4709 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4713 /* Requires Linux 2.6.40 */
4714 loop_write(fd, "\033[H\033[3J", 7, false); /* clear screen including scrollback */
4715 close_nointr_nofail(fd);
4721 static int file_is_conf(const struct dirent *d, const char *suffix) {
4724 if (ignore_file(d->d_name))
4727 if (d->d_type != DT_REG &&
4728 d->d_type != DT_LNK &&
4729 d->d_type != DT_UNKNOWN)
4732 return endswith(d->d_name, suffix);
4735 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4740 dir = opendir(path);
4742 if (errno == ENOENT)
4747 for (de = readdir(dir); de; de = readdir(dir)) {
4751 if (!file_is_conf(de, suffix))
4754 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4759 f = canonicalize_file_name(p);
4761 log_error("Failed to canonicalize file name '%s': %m", p);
4767 log_debug("found: %s\n", f);
4768 base = f + strlen(path) + 1;
4769 if (hashmap_put(h, base, f) <= 0)
4778 static int base_cmp(const void *a, const void *b) {
4779 const char *s1, *s2;
4781 s1 = *(char * const *)a;
4782 s2 = *(char * const *)b;
4783 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4786 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4789 char **files = NULL;
4795 dirs = strv_new_ap(dir, ap);
4801 if (!strv_path_canonicalize(dirs)) {
4805 if (!strv_uniq(dirs)) {
4810 fh = hashmap_new(string_hash_func, string_compare_func);
4816 STRV_FOREACH(p, dirs) {
4817 if (files_add(fh, *p, suffix) < 0) {
4818 log_error("Failed to search for files.");
4824 files = hashmap_get_strv(fh);
4825 if (files == NULL) {
4826 log_error("Failed to compose list of files.");
4831 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4840 int hwclock_is_localtime(void) {
4845 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4851 f = fopen("/etc/adjtime", "re");
4853 char line[LINE_MAX];
4856 b = fgets(line, sizeof(line), f) &&
4857 fgets(line, sizeof(line), f) &&
4858 fgets(line, sizeof(line), f);
4867 local = streq(line, "LOCAL");
4869 } else if (errno != -ENOENT)
4875 int hwclock_apply_localtime_delta(void) {
4876 const struct timeval *tv_null = NULL;
4882 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4883 assert_se(tm = localtime(&ts.tv_sec));
4884 minuteswest = tm->tm_gmtoff / 60;
4886 tz.tz_minuteswest = -minuteswest;
4887 tz.tz_dsttime = 0; /* DST_NONE*/
4890 * If the hardware clock does not run in UTC, but in local time:
4891 * The very first time we set the kernel's timezone, it will warp
4892 * the clock so that it runs in UTC instead of local time.
4894 if (settimeofday(tv_null, &tz) < 0)
4900 int hwclock_reset_localtime_delta(void) {
4901 const struct timeval *tv_null = NULL;
4904 tz.tz_minuteswest = 0;
4905 tz.tz_dsttime = 0; /* DST_NONE*/
4907 if (settimeofday(tv_null, &tz) < 0)
4913 int hwclock_get_time(struct tm *tm) {
4919 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4923 /* This leaves the timezone fields of struct tm
4925 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4928 /* We don't now daylight saving, so we reset this in order not
4929 * to confused mktime(). */
4932 close_nointr_nofail(fd);
4937 int hwclock_set_time(const struct tm *tm) {
4943 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4947 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4950 close_nointr_nofail(fd);
4955 int copy_file(const char *from, const char *to) {
4961 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4965 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4967 close_nointr_nofail(fdf);
4975 n = read(fdf, buf, sizeof(buf));
4979 close_nointr_nofail(fdf);
4990 k = loop_write(fdt, buf, n, false);
4992 r = k < 0 ? k : (errno ? -errno : -EIO);
4994 close_nointr_nofail(fdf);
5002 close_nointr_nofail(fdf);
5003 r = close_nointr(fdt);
5013 int symlink_or_copy(const char *from, const char *to) {
5014 char *pf = NULL, *pt = NULL;
5021 if (parent_of_path(from, &pf) < 0 ||
5022 parent_of_path(to, &pt) < 0) {
5027 if (stat(pf, &a) < 0 ||
5033 if (a.st_dev != b.st_dev) {
5037 return copy_file(from, to);
5040 if (symlink(from, to) < 0) {
5054 int symlink_or_copy_atomic(const char *from, const char *to) {
5058 unsigned long long ull;
5065 t = new(char, strlen(to) + 1 + 16 + 1);
5069 fn = file_name_from_path(to);
5073 x = stpcpy(t+k+1, fn);
5076 for (i = 0; i < 16; i++) {
5077 *(x++) = hexchar(ull & 0xF);
5083 r = symlink_or_copy(from, t);
5090 if (rename(t, to) < 0) {
5101 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5109 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5112 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5115 r = read_one_line_file(p, &s);
5120 r = safe_atou32(s, &u);
5126 if (u == (uint32_t) -1 || u <= 0)
5133 bool display_is_local(const char *display) {
5137 display[0] == ':' &&
5138 display[1] >= '0' &&
5142 int socket_from_display(const char *display, char **path) {
5149 if (!display_is_local(display))
5152 k = strspn(display+1, "0123456789");
5154 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5158 c = stpcpy(f, "/tmp/.X11-unix/X");
5159 memcpy(c, display+1, k);
5167 static const char *const ioprio_class_table[] = {
5168 [IOPRIO_CLASS_NONE] = "none",
5169 [IOPRIO_CLASS_RT] = "realtime",
5170 [IOPRIO_CLASS_BE] = "best-effort",
5171 [IOPRIO_CLASS_IDLE] = "idle"
5174 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5176 static const char *const sigchld_code_table[] = {
5177 [CLD_EXITED] = "exited",
5178 [CLD_KILLED] = "killed",
5179 [CLD_DUMPED] = "dumped",
5180 [CLD_TRAPPED] = "trapped",
5181 [CLD_STOPPED] = "stopped",
5182 [CLD_CONTINUED] = "continued",
5185 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5187 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5188 [LOG_FAC(LOG_KERN)] = "kern",
5189 [LOG_FAC(LOG_USER)] = "user",
5190 [LOG_FAC(LOG_MAIL)] = "mail",
5191 [LOG_FAC(LOG_DAEMON)] = "daemon",
5192 [LOG_FAC(LOG_AUTH)] = "auth",
5193 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5194 [LOG_FAC(LOG_LPR)] = "lpr",
5195 [LOG_FAC(LOG_NEWS)] = "news",
5196 [LOG_FAC(LOG_UUCP)] = "uucp",
5197 [LOG_FAC(LOG_CRON)] = "cron",
5198 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5199 [LOG_FAC(LOG_FTP)] = "ftp",
5200 [LOG_FAC(LOG_LOCAL0)] = "local0",
5201 [LOG_FAC(LOG_LOCAL1)] = "local1",
5202 [LOG_FAC(LOG_LOCAL2)] = "local2",
5203 [LOG_FAC(LOG_LOCAL3)] = "local3",
5204 [LOG_FAC(LOG_LOCAL4)] = "local4",
5205 [LOG_FAC(LOG_LOCAL5)] = "local5",
5206 [LOG_FAC(LOG_LOCAL6)] = "local6",
5207 [LOG_FAC(LOG_LOCAL7)] = "local7"
5210 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5212 static const char *const log_level_table[] = {
5213 [LOG_EMERG] = "emerg",
5214 [LOG_ALERT] = "alert",
5215 [LOG_CRIT] = "crit",
5217 [LOG_WARNING] = "warning",
5218 [LOG_NOTICE] = "notice",
5219 [LOG_INFO] = "info",
5220 [LOG_DEBUG] = "debug"
5223 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5225 static const char* const sched_policy_table[] = {
5226 [SCHED_OTHER] = "other",
5227 [SCHED_BATCH] = "batch",
5228 [SCHED_IDLE] = "idle",
5229 [SCHED_FIFO] = "fifo",
5233 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5235 static const char* const rlimit_table[] = {
5236 [RLIMIT_CPU] = "LimitCPU",
5237 [RLIMIT_FSIZE] = "LimitFSIZE",
5238 [RLIMIT_DATA] = "LimitDATA",
5239 [RLIMIT_STACK] = "LimitSTACK",
5240 [RLIMIT_CORE] = "LimitCORE",
5241 [RLIMIT_RSS] = "LimitRSS",
5242 [RLIMIT_NOFILE] = "LimitNOFILE",
5243 [RLIMIT_AS] = "LimitAS",
5244 [RLIMIT_NPROC] = "LimitNPROC",
5245 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5246 [RLIMIT_LOCKS] = "LimitLOCKS",
5247 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5248 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5249 [RLIMIT_NICE] = "LimitNICE",
5250 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5251 [RLIMIT_RTTIME] = "LimitRTTIME"
5254 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5256 static const char* const ip_tos_table[] = {
5257 [IPTOS_LOWDELAY] = "low-delay",
5258 [IPTOS_THROUGHPUT] = "throughput",
5259 [IPTOS_RELIABILITY] = "reliability",
5260 [IPTOS_LOWCOST] = "low-cost",
5263 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5265 static const char *const signal_table[] = {
5282 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5293 [SIGVTALRM] = "VTALRM",
5295 [SIGWINCH] = "WINCH",
5301 DEFINE_STRING_TABLE_LOOKUP(signal, int);