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 usec_t timespec_load(const struct timespec *ts) {
115 (usec_t) ts->tv_sec * USEC_PER_SEC +
116 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
119 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
122 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
123 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
128 usec_t timeval_load(const struct timeval *tv) {
132 (usec_t) tv->tv_sec * USEC_PER_SEC +
133 (usec_t) tv->tv_usec;
136 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
139 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
140 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
145 bool endswith(const char *s, const char *postfix) {
152 pl = strlen(postfix);
160 return memcmp(s + sl - pl, postfix, pl) == 0;
163 bool startswith(const char *s, const char *prefix) {
178 return memcmp(s, prefix, pl) == 0;
181 bool startswith_no_case(const char *s, const char *prefix) {
197 for(i = 0; i < pl; ++i) {
198 if (tolower(s[i]) != tolower(prefix[i]))
205 bool first_word(const char *s, const char *word) {
220 if (memcmp(s, word, wl) != 0)
224 strchr(WHITESPACE, s[wl]);
227 int close_nointr(int fd) {
242 void close_nointr_nofail(int fd) {
243 int saved_errno = errno;
245 /* like close_nointr() but cannot fail, and guarantees errno
248 assert_se(close_nointr(fd) == 0);
253 void close_many(const int fds[], unsigned n_fd) {
256 for (i = 0; i < n_fd; i++)
257 close_nointr_nofail(fds[i]);
260 int parse_boolean(const char *v) {
263 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
265 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
271 int parse_pid(const char *s, pid_t* ret_pid) {
272 unsigned long ul = 0;
279 if ((r = safe_atolu(s, &ul)) < 0)
284 if ((unsigned long) pid != ul)
294 int safe_atou(const char *s, unsigned *ret_u) {
302 l = strtoul(s, &x, 0);
304 if (!x || *x || errno)
305 return errno ? -errno : -EINVAL;
307 if ((unsigned long) (unsigned) l != l)
310 *ret_u = (unsigned) l;
314 int safe_atoi(const char *s, int *ret_i) {
322 l = strtol(s, &x, 0);
324 if (!x || *x || errno)
325 return errno ? -errno : -EINVAL;
327 if ((long) (int) l != l)
334 int safe_atollu(const char *s, long long unsigned *ret_llu) {
336 unsigned long long l;
342 l = strtoull(s, &x, 0);
344 if (!x || *x || errno)
345 return errno ? -errno : -EINVAL;
351 int safe_atolli(const char *s, long long int *ret_lli) {
359 l = strtoll(s, &x, 0);
361 if (!x || *x || errno)
362 return errno ? -errno : -EINVAL;
368 /* Split a string into words. */
369 char *split(const char *c, size_t *l, const char *separator, char **state) {
372 current = *state ? *state : (char*) c;
374 if (!*current || *c == 0)
377 current += strspn(current, separator);
378 *l = strcspn(current, separator);
381 return (char*) current;
384 /* Split a string into words, but consider strings enclosed in '' and
385 * "" as words even if they include spaces. */
386 char *split_quoted(const char *c, size_t *l, char **state) {
388 bool escaped = false;
390 current = *state ? *state : (char*) c;
392 if (!*current || *c == 0)
395 current += strspn(current, WHITESPACE);
397 if (*current == '\'') {
400 for (e = current; *e; e++) {
410 *state = *e == 0 ? e : e+1;
411 } else if (*current == '\"') {
414 for (e = current; *e; e++) {
424 *state = *e == 0 ? e : e+1;
426 for (e = current; *e; e++) {
431 else if (strchr(WHITESPACE, *e))
438 return (char*) current;
441 char **split_path_and_make_absolute(const char *p) {
445 if (!(l = strv_split(p, ":")))
448 if (!strv_path_make_absolute_cwd(l)) {
456 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
459 char fn[PATH_MAX], line[LINE_MAX], *p;
465 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
468 if (!(f = fopen(fn, "r")))
471 if (!(fgets(line, sizeof(line), f))) {
479 /* Let's skip the pid and comm fields. The latter is enclosed
480 * in () but does not escape any () in its value, so let's
481 * skip over it manually */
483 if (!(p = strrchr(line, ')')))
494 if ((long unsigned) (pid_t) ppid != ppid)
497 *_ppid = (pid_t) ppid;
502 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
505 char fn[PATH_MAX], line[LINE_MAX], *p;
510 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
513 if (!(f = fopen(fn, "r")))
516 if (!(fgets(line, sizeof(line), f))) {
524 /* Let's skip the pid and comm fields. The latter is enclosed
525 * in () but does not escape any () in its value, so let's
526 * skip over it manually */
528 if (!(p = strrchr(line, ')')))
549 "%*d " /* priority */
551 "%*d " /* num_threads */
552 "%*d " /* itrealvalue */
553 "%llu " /* starttime */,
560 int write_one_line_file(const char *fn, const char *line) {
567 if (!(f = fopen(fn, "we")))
571 if (fputs(line, f) < 0) {
576 if (!endswith(line, "\n"))
594 int fchmod_umask(int fd, mode_t m) {
599 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
605 int write_one_line_file_atomic(const char *fn, const char *line) {
613 r = fopen_temporary(fn, &f, &p);
617 fchmod_umask(fileno(f), 0644);
620 if (fputs(line, f) < 0) {
625 if (!endswith(line, "\n"))
636 if (rename(p, fn) < 0)
652 int read_one_line_file(const char *fn, char **line) {
655 char t[LINE_MAX], *c;
660 if (!(f = fopen(fn, "re")))
663 if (!(fgets(t, sizeof(t), f))) {
668 if (!(c = strdup(t))) {
683 int read_full_file(const char *fn, char **contents, size_t *size) {
690 if (!(f = fopen(fn, "re")))
693 if (fstat(fileno(f), &st) < 0) {
699 if (st.st_size > 4*1024*1024) {
704 n = st.st_size > 0 ? st.st_size : LINE_MAX;
711 if (!(t = realloc(buf, n+1))) {
717 k = fread(buf + l, 1, n - l, f);
732 if (n > 4*1024*1024) {
740 else if (!(buf = calloc(1, 1))) {
762 const char *separator, ...) {
770 if ((r = read_full_file(fname, &contents, NULL)) < 0)
775 const char *key = NULL;
777 p += strspn(p, separator);
778 p += strspn(p, WHITESPACE);
783 if (!strchr(COMMENTS, *p)) {
787 va_start(ap, separator);
788 while ((key = va_arg(ap, char *))) {
792 value = va_arg(ap, char **);
795 if (strncmp(p, key, n) != 0 ||
800 n = strcspn(p, separator);
803 strchr(QUOTES, p[0]) &&
805 v = strndup(p+1, n-2);
816 /* return empty value strings as NULL */
833 p += strcspn(p, separator);
852 if (!(f = fopen(fname, "re")))
856 char l[LINE_MAX], *p, *u;
859 if (!fgets(l, sizeof(l), f)) {
872 if (strchr(COMMENTS, *p))
875 if (!(u = normalize_env_assignment(p))) {
876 log_error("Out of memory");
881 t = strv_append(m, u);
885 log_error("Out of memory");
908 int write_env_file(const char *fname, char **l) {
913 r = fopen_temporary(fname, &f, &p);
917 fchmod_umask(fileno(f), 0644);
933 if (rename(p, fname) < 0)
948 char *truncate_nl(char *s) {
951 s[strcspn(s, NEWLINE)] = 0;
955 int get_process_name(pid_t pid, char **name) {
962 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
965 r = read_one_line_file(p, name);
974 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
982 assert(max_length > 0);
985 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
994 if (!(r = new(char, max_length))) {
1001 while ((c = getc(f)) != EOF) {
1023 size_t n = MIN(left-1, 3U);
1024 memcpy(k, "...", n);
1031 /* Kernel threads have no argv[] */
1038 if ((h = get_process_name(pid, &t)) < 0)
1041 h = asprintf(&r, "[%s]", t);
1052 char *strnappend(const char *s, const char *suffix, size_t b) {
1060 return strndup(suffix, b);
1070 if (!(r = new(char, a+b+1)))
1074 memcpy(r+a, suffix, b);
1080 char *strappend(const char *s, const char *suffix) {
1081 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1084 int readlink_malloc(const char *p, char **r) {
1094 if (!(c = new(char, l)))
1097 if ((n = readlink(p, c, l-1)) < 0) {
1103 if ((size_t) n < l-1) {
1114 int readlink_and_make_absolute(const char *p, char **r) {
1121 if ((j = readlink_malloc(p, &target)) < 0)
1124 k = file_in_same_dir(p, target);
1134 int parent_of_path(const char *path, char **_r) {
1135 const char *e, *a = NULL, *b = NULL, *p;
1145 for (e = path; *e; e++) {
1147 if (!slash && *e == '/') {
1151 } else if (slash && *e != '/')
1166 r = strndup(path, p-path);
1176 char *file_name_from_path(const char *p) {
1181 if ((r = strrchr(p, '/')))
1187 bool path_is_absolute(const char *p) {
1193 bool is_path(const char *p) {
1195 return !!strchr(p, '/');
1198 char *path_make_absolute(const char *p, const char *prefix) {
1203 /* Makes every item in the list an absolute path by prepending
1204 * the prefix, if specified and necessary */
1206 if (path_is_absolute(p) || !prefix)
1209 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1215 char *path_make_absolute_cwd(const char *p) {
1220 /* Similar to path_make_absolute(), but prefixes with the
1221 * current working directory. */
1223 if (path_is_absolute(p))
1226 if (!(cwd = get_current_dir_name()))
1229 r = path_make_absolute(p, cwd);
1235 char **strv_path_make_absolute_cwd(char **l) {
1238 /* Goes through every item in the string list and makes it
1239 * absolute. This works in place and won't rollback any
1240 * changes on failure. */
1242 STRV_FOREACH(s, l) {
1245 if (!(t = path_make_absolute_cwd(*s)))
1255 char **strv_path_canonicalize(char **l) {
1258 bool enomem = false;
1260 if (strv_isempty(l))
1263 /* Goes through every item in the string list and canonicalize
1264 * the path. This works in place and won't rollback any
1265 * changes on failure. */
1267 STRV_FOREACH(s, l) {
1270 t = path_make_absolute_cwd(*s);
1279 u = canonicalize_file_name(t);
1283 if (errno == ENOMEM || !errno)
1300 char **strv_path_remove_empty(char **l) {
1306 for (f = t = l; *f; f++) {
1308 if (dir_is_empty(*f) > 0) {
1320 int reset_all_signal_handlers(void) {
1323 for (sig = 1; sig < _NSIG; sig++) {
1324 struct sigaction sa;
1326 if (sig == SIGKILL || sig == SIGSTOP)
1330 sa.sa_handler = SIG_DFL;
1331 sa.sa_flags = SA_RESTART;
1333 /* On Linux the first two RT signals are reserved by
1334 * glibc, and sigaction() will return EINVAL for them. */
1335 if ((sigaction(sig, &sa, NULL) < 0))
1336 if (errno != EINVAL)
1343 char *strstrip(char *s) {
1346 /* Drops trailing whitespace. Modifies the string in
1347 * place. Returns pointer to first non-space character */
1349 s += strspn(s, WHITESPACE);
1351 for (e = s; *e; e++)
1352 if (!strchr(WHITESPACE, *e))
1363 char *delete_chars(char *s, const char *bad) {
1366 /* Drops all whitespace, regardless where in the string */
1368 for (f = s, t = s; *f; f++) {
1369 if (strchr(bad, *f))
1380 char *file_in_same_dir(const char *path, const char *filename) {
1387 /* This removes the last component of path and appends
1388 * filename, unless the latter is absolute anyway or the
1391 if (path_is_absolute(filename))
1392 return strdup(filename);
1394 if (!(e = strrchr(path, '/')))
1395 return strdup(filename);
1397 k = strlen(filename);
1398 if (!(r = new(char, e-path+1+k+1)))
1401 memcpy(r, path, e-path+1);
1402 memcpy(r+(e-path)+1, filename, k+1);
1407 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1410 if (label_mkdir(path, mode) >= 0)
1411 if (chmod_and_chown(path, mode, uid, gid) < 0)
1414 if (lstat(path, &st) < 0)
1417 if ((st.st_mode & 0777) != mode ||
1420 !S_ISDIR(st.st_mode)) {
1429 int mkdir_parents(const char *path, mode_t mode) {
1434 /* Creates every parent directory in the path except the last
1437 p = path + strspn(path, "/");
1442 e = p + strcspn(p, "/");
1443 p = e + strspn(e, "/");
1445 /* Is this the last component? If so, then we're
1450 if (!(t = strndup(path, e - path)))
1453 r = label_mkdir(t, mode);
1456 if (r < 0 && errno != EEXIST)
1461 int mkdir_p(const char *path, mode_t mode) {
1466 if ((r = mkdir_parents(path, mode)) < 0)
1469 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1475 int rmdir_parents(const char *path, const char *stop) {
1484 /* Skip trailing slashes */
1485 while (l > 0 && path[l-1] == '/')
1491 /* Skip last component */
1492 while (l > 0 && path[l-1] != '/')
1495 /* Skip trailing slashes */
1496 while (l > 0 && path[l-1] == '/')
1502 if (!(t = strndup(path, l)))
1505 if (path_startswith(stop, t)) {
1514 if (errno != ENOENT)
1522 char hexchar(int x) {
1523 static const char table[16] = "0123456789abcdef";
1525 return table[x & 15];
1528 int unhexchar(char c) {
1530 if (c >= '0' && c <= '9')
1533 if (c >= 'a' && c <= 'f')
1534 return c - 'a' + 10;
1536 if (c >= 'A' && c <= 'F')
1537 return c - 'A' + 10;
1542 char octchar(int x) {
1543 return '0' + (x & 7);
1546 int unoctchar(char c) {
1548 if (c >= '0' && c <= '7')
1554 char decchar(int x) {
1555 return '0' + (x % 10);
1558 int undecchar(char c) {
1560 if (c >= '0' && c <= '9')
1566 char *cescape(const char *s) {
1572 /* Does C style string escaping. */
1574 if (!(r = new(char, strlen(s)*4 + 1)))
1577 for (f = s, t = r; *f; f++)
1623 /* For special chars we prefer octal over
1624 * hexadecimal encoding, simply because glib's
1625 * g_strescape() does the same */
1626 if ((*f < ' ') || (*f >= 127)) {
1628 *(t++) = octchar((unsigned char) *f >> 6);
1629 *(t++) = octchar((unsigned char) *f >> 3);
1630 *(t++) = octchar((unsigned char) *f);
1641 char *cunescape_length(const char *s, size_t length) {
1647 /* Undoes C style string escaping */
1649 if (!(r = new(char, length+1)))
1652 for (f = s, t = r; f < s + length; f++) {
1695 /* This is an extension of the XDG syntax files */
1700 /* hexadecimal encoding */
1703 if ((a = unhexchar(f[1])) < 0 ||
1704 (b = unhexchar(f[2])) < 0) {
1705 /* Invalid escape code, let's take it literal then */
1709 *(t++) = (char) ((a << 4) | b);
1724 /* octal encoding */
1727 if ((a = unoctchar(f[0])) < 0 ||
1728 (b = unoctchar(f[1])) < 0 ||
1729 (c = unoctchar(f[2])) < 0) {
1730 /* Invalid escape code, let's take it literal then */
1734 *(t++) = (char) ((a << 6) | (b << 3) | c);
1742 /* premature end of string.*/
1747 /* Invalid escape code, let's take it literal then */
1759 char *cunescape(const char *s) {
1760 return cunescape_length(s, strlen(s));
1763 char *xescape(const char *s, const char *bad) {
1767 /* Escapes all chars in bad, in addition to \ and all special
1768 * chars, in \xFF style escaping. May be reversed with
1771 if (!(r = new(char, strlen(s)*4+1)))
1774 for (f = s, t = r; *f; f++) {
1776 if ((*f < ' ') || (*f >= 127) ||
1777 (*f == '\\') || strchr(bad, *f)) {
1780 *(t++) = hexchar(*f >> 4);
1781 *(t++) = hexchar(*f);
1791 char *bus_path_escape(const char *s) {
1797 /* Escapes all chars that D-Bus' object path cannot deal
1798 * with. Can be reverse with bus_path_unescape() */
1800 if (!(r = new(char, strlen(s)*3+1)))
1803 for (f = s, t = r; *f; f++) {
1805 if (!(*f >= 'A' && *f <= 'Z') &&
1806 !(*f >= 'a' && *f <= 'z') &&
1807 !(*f >= '0' && *f <= '9')) {
1809 *(t++) = hexchar(*f >> 4);
1810 *(t++) = hexchar(*f);
1820 char *bus_path_unescape(const char *f) {
1825 if (!(r = strdup(f)))
1828 for (t = r; *f; f++) {
1833 if ((a = unhexchar(f[1])) < 0 ||
1834 (b = unhexchar(f[2])) < 0) {
1835 /* Invalid escape code, let's take it literal then */
1838 *(t++) = (char) ((a << 4) | b);
1850 char *path_kill_slashes(char *path) {
1854 /* Removes redundant inner and trailing slashes. Modifies the
1855 * passed string in-place.
1857 * ///foo///bar/ becomes /foo/bar
1860 for (f = path, t = path; *f; f++) {
1875 /* Special rule, if we are talking of the root directory, a
1876 trailing slash is good */
1878 if (t == path && slash)
1885 bool path_startswith(const char *path, const char *prefix) {
1889 if ((path[0] == '/') != (prefix[0] == '/'))
1895 path += strspn(path, "/");
1896 prefix += strspn(prefix, "/");
1904 a = strcspn(path, "/");
1905 b = strcspn(prefix, "/");
1910 if (memcmp(path, prefix, a) != 0)
1918 bool path_equal(const char *a, const char *b) {
1922 if ((a[0] == '/') != (b[0] == '/'))
1928 a += strspn(a, "/");
1929 b += strspn(b, "/");
1931 if (*a == 0 && *b == 0)
1934 if (*a == 0 || *b == 0)
1937 j = strcspn(a, "/");
1938 k = strcspn(b, "/");
1943 if (memcmp(a, b, j) != 0)
1951 char *ascii_strlower(char *t) {
1956 for (p = t; *p; p++)
1957 if (*p >= 'A' && *p <= 'Z')
1958 *p = *p - 'A' + 'a';
1963 bool ignore_file(const char *filename) {
1967 filename[0] == '.' ||
1968 streq(filename, "lost+found") ||
1969 streq(filename, "aquota.user") ||
1970 streq(filename, "aquota.group") ||
1971 endswith(filename, "~") ||
1972 endswith(filename, ".rpmnew") ||
1973 endswith(filename, ".rpmsave") ||
1974 endswith(filename, ".rpmorig") ||
1975 endswith(filename, ".dpkg-old") ||
1976 endswith(filename, ".dpkg-new") ||
1977 endswith(filename, ".swp");
1980 int fd_nonblock(int fd, bool nonblock) {
1985 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1989 flags |= O_NONBLOCK;
1991 flags &= ~O_NONBLOCK;
1993 if (fcntl(fd, F_SETFL, flags) < 0)
1999 int fd_cloexec(int fd, bool cloexec) {
2004 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2008 flags |= FD_CLOEXEC;
2010 flags &= ~FD_CLOEXEC;
2012 if (fcntl(fd, F_SETFD, flags) < 0)
2018 int close_all_fds(const int except[], unsigned n_except) {
2023 if (!(d = opendir("/proc/self/fd")))
2026 while ((de = readdir(d))) {
2029 if (ignore_file(de->d_name))
2032 if (safe_atoi(de->d_name, &fd) < 0)
2033 /* Let's better ignore this, just in case */
2047 for (i = 0; i < n_except; i++)
2048 if (except[i] == fd) {
2057 if (close_nointr(fd) < 0) {
2058 /* Valgrind has its own FD and doesn't want to have it closed */
2059 if (errno != EBADF && r == 0)
2068 bool chars_intersect(const char *a, const char *b) {
2071 /* Returns true if any of the chars in a are in b. */
2072 for (p = a; *p; p++)
2079 char *format_timestamp(char *buf, size_t l, usec_t t) {
2089 sec = (time_t) (t / USEC_PER_SEC);
2091 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2097 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2100 n = now(CLOCK_REALTIME);
2102 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2107 if (d >= USEC_PER_YEAR)
2108 snprintf(buf, l, "%llu years and %llu months ago",
2109 (unsigned long long) (d / USEC_PER_YEAR),
2110 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2111 else if (d >= USEC_PER_MONTH)
2112 snprintf(buf, l, "%llu months and %llu days ago",
2113 (unsigned long long) (d / USEC_PER_MONTH),
2114 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2115 else if (d >= USEC_PER_WEEK)
2116 snprintf(buf, l, "%llu weeks and %llu days ago",
2117 (unsigned long long) (d / USEC_PER_WEEK),
2118 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2119 else if (d >= 2*USEC_PER_DAY)
2120 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2121 else if (d >= 25*USEC_PER_HOUR)
2122 snprintf(buf, l, "1 day and %lluh ago",
2123 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2124 else if (d >= 6*USEC_PER_HOUR)
2125 snprintf(buf, l, "%lluh ago",
2126 (unsigned long long) (d / USEC_PER_HOUR));
2127 else if (d >= USEC_PER_HOUR)
2128 snprintf(buf, l, "%lluh %llumin ago",
2129 (unsigned long long) (d / USEC_PER_HOUR),
2130 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2131 else if (d >= 5*USEC_PER_MINUTE)
2132 snprintf(buf, l, "%llumin ago",
2133 (unsigned long long) (d / USEC_PER_MINUTE));
2134 else if (d >= USEC_PER_MINUTE)
2135 snprintf(buf, l, "%llumin %llus ago",
2136 (unsigned long long) (d / USEC_PER_MINUTE),
2137 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2138 else if (d >= USEC_PER_SEC)
2139 snprintf(buf, l, "%llus ago",
2140 (unsigned long long) (d / USEC_PER_SEC));
2141 else if (d >= USEC_PER_MSEC)
2142 snprintf(buf, l, "%llums ago",
2143 (unsigned long long) (d / USEC_PER_MSEC));
2145 snprintf(buf, l, "%lluus ago",
2146 (unsigned long long) d);
2148 snprintf(buf, l, "now");
2154 char *format_timespan(char *buf, size_t l, usec_t t) {
2155 static const struct {
2159 { "w", USEC_PER_WEEK },
2160 { "d", USEC_PER_DAY },
2161 { "h", USEC_PER_HOUR },
2162 { "min", USEC_PER_MINUTE },
2163 { "s", USEC_PER_SEC },
2164 { "ms", USEC_PER_MSEC },
2174 if (t == (usec_t) -1)
2178 snprintf(p, l, "0");
2183 /* The result of this function can be parsed with parse_usec */
2185 for (i = 0; i < ELEMENTSOF(table); i++) {
2189 if (t < table[i].usec)
2195 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2196 n = MIN((size_t) k, l);
2209 bool fstype_is_network(const char *fstype) {
2210 static const char * const table[] = {
2222 for (i = 0; i < ELEMENTSOF(table); i++)
2223 if (streq(table[i], fstype))
2232 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2237 TIOCL_GETKMSGREDIRECT,
2241 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2244 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2247 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2250 close_nointr_nofail(r);
2254 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2255 struct termios old_termios, new_termios;
2257 char line[LINE_MAX];
2262 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2263 new_termios = old_termios;
2265 new_termios.c_lflag &= ~ICANON;
2266 new_termios.c_cc[VMIN] = 1;
2267 new_termios.c_cc[VTIME] = 0;
2269 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2272 k = fread(&c, 1, 1, f);
2274 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2280 *need_nl = c != '\n';
2287 if (!(fgets(line, sizeof(line), f)))
2292 if (strlen(line) != 1)
2302 int ask(char *ret, const char *replies, const char *text, ...) {
2309 on_tty = isatty(STDOUT_FILENO);
2315 bool need_nl = true;
2318 fputs("\x1B[1m", stdout);
2325 fputs("\x1B[0m", stdout);
2329 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2331 if (r == -EBADMSG) {
2332 puts("Bad input, please try again.");
2343 if (strchr(replies, c)) {
2348 puts("Read unexpected character, please try again.");
2352 int reset_terminal_fd(int fd) {
2353 struct termios termios;
2357 /* Set terminal to some sane defaults */
2361 /* We leave locked terminal attributes untouched, so that
2362 * Plymouth may set whatever it wants to set, and we don't
2363 * interfere with that. */
2365 /* Disable exclusive mode, just in case */
2366 ioctl(fd, TIOCNXCL);
2368 /* Enable console unicode mode */
2370 ioctl(fd, KDSKBMODE, &arg);
2372 if (tcgetattr(fd, &termios) < 0) {
2377 /* We only reset the stuff that matters to the software. How
2378 * hardware is set up we don't touch assuming that somebody
2379 * else will do that for us */
2381 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2382 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2383 termios.c_oflag |= ONLCR;
2384 termios.c_cflag |= CREAD;
2385 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2387 termios.c_cc[VINTR] = 03; /* ^C */
2388 termios.c_cc[VQUIT] = 034; /* ^\ */
2389 termios.c_cc[VERASE] = 0177;
2390 termios.c_cc[VKILL] = 025; /* ^X */
2391 termios.c_cc[VEOF] = 04; /* ^D */
2392 termios.c_cc[VSTART] = 021; /* ^Q */
2393 termios.c_cc[VSTOP] = 023; /* ^S */
2394 termios.c_cc[VSUSP] = 032; /* ^Z */
2395 termios.c_cc[VLNEXT] = 026; /* ^V */
2396 termios.c_cc[VWERASE] = 027; /* ^W */
2397 termios.c_cc[VREPRINT] = 022; /* ^R */
2398 termios.c_cc[VEOL] = 0;
2399 termios.c_cc[VEOL2] = 0;
2401 termios.c_cc[VTIME] = 0;
2402 termios.c_cc[VMIN] = 1;
2404 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2408 /* Just in case, flush all crap out */
2409 tcflush(fd, TCIOFLUSH);
2414 int reset_terminal(const char *name) {
2417 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2421 r = reset_terminal_fd(fd);
2422 close_nointr_nofail(fd);
2427 int open_terminal(const char *name, int mode) {
2432 * If a TTY is in the process of being closed opening it might
2433 * cause EIO. This is horribly awful, but unlikely to be
2434 * changed in the kernel. Hence we work around this problem by
2435 * retrying a couple of times.
2437 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2441 if ((fd = open(name, mode)) >= 0)
2450 usleep(50 * USEC_PER_MSEC);
2457 if ((r = isatty(fd)) < 0) {
2458 close_nointr_nofail(fd);
2463 close_nointr_nofail(fd);
2470 int flush_fd(int fd) {
2471 struct pollfd pollfd;
2475 pollfd.events = POLLIN;
2482 if ((r = poll(&pollfd, 1, 0)) < 0) {
2493 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2498 if (errno == EAGAIN)
2509 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2510 int fd = -1, notify = -1, r, wd = -1;
2514 /* We use inotify to be notified when the tty is closed. We
2515 * create the watch before checking if we can actually acquire
2516 * it, so that we don't lose any event.
2518 * Note: strictly speaking this actually watches for the
2519 * device being closed, it does *not* really watch whether a
2520 * tty loses its controlling process. However, unless some
2521 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2522 * its tty otherwise this will not become a problem. As long
2523 * as the administrator makes sure not configure any service
2524 * on the same tty as an untrusted user this should not be a
2525 * problem. (Which he probably should not do anyway.) */
2527 if (!fail && !force) {
2528 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2533 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2541 if ((r = flush_fd(notify)) < 0)
2544 /* We pass here O_NOCTTY only so that we can check the return
2545 * value TIOCSCTTY and have a reliable way to figure out if we
2546 * successfully became the controlling process of the tty */
2547 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2550 /* First, try to get the tty */
2551 r = ioctl(fd, TIOCSCTTY, force);
2553 /* Sometimes it makes sense to ignore TIOCSCTTY
2554 * returning EPERM, i.e. when very likely we already
2555 * are have this controlling terminal. */
2556 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2559 if (r < 0 && (force || fail || errno != EPERM)) {
2569 assert(notify >= 0);
2572 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2574 struct inotify_event *e;
2576 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2585 e = (struct inotify_event*) inotify_buffer;
2590 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2595 step = sizeof(struct inotify_event) + e->len;
2596 assert(step <= (size_t) l);
2598 e = (struct inotify_event*) ((uint8_t*) e + step);
2605 /* We close the tty fd here since if the old session
2606 * ended our handle will be dead. It's important that
2607 * we do this after sleeping, so that we don't enter
2608 * an endless loop. */
2609 close_nointr_nofail(fd);
2613 close_nointr_nofail(notify);
2615 if ((r = reset_terminal_fd(fd)) < 0)
2616 log_warning("Failed to reset terminal: %s", strerror(-r));
2622 close_nointr_nofail(fd);
2625 close_nointr_nofail(notify);
2630 int release_terminal(void) {
2632 struct sigaction sa_old, sa_new;
2634 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2637 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2638 * by our own TIOCNOTTY */
2641 sa_new.sa_handler = SIG_IGN;
2642 sa_new.sa_flags = SA_RESTART;
2643 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2645 if (ioctl(fd, TIOCNOTTY) < 0)
2648 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2650 close_nointr_nofail(fd);
2654 int sigaction_many(const struct sigaction *sa, ...) {
2659 while ((sig = va_arg(ap, int)) > 0)
2660 if (sigaction(sig, sa, NULL) < 0)
2667 int ignore_signals(int sig, ...) {
2668 struct sigaction sa;
2673 sa.sa_handler = SIG_IGN;
2674 sa.sa_flags = SA_RESTART;
2676 if (sigaction(sig, &sa, NULL) < 0)
2680 while ((sig = va_arg(ap, int)) > 0)
2681 if (sigaction(sig, &sa, NULL) < 0)
2688 int default_signals(int sig, ...) {
2689 struct sigaction sa;
2694 sa.sa_handler = SIG_DFL;
2695 sa.sa_flags = SA_RESTART;
2697 if (sigaction(sig, &sa, NULL) < 0)
2701 while ((sig = va_arg(ap, int)) > 0)
2702 if (sigaction(sig, &sa, NULL) < 0)
2709 int close_pipe(int p[]) {
2715 a = close_nointr(p[0]);
2720 b = close_nointr(p[1]);
2724 return a < 0 ? a : b;
2727 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2736 while (nbytes > 0) {
2739 if ((k = read(fd, p, nbytes)) <= 0) {
2741 if (k < 0 && errno == EINTR)
2744 if (k < 0 && errno == EAGAIN && do_poll) {
2745 struct pollfd pollfd;
2749 pollfd.events = POLLIN;
2751 if (poll(&pollfd, 1, -1) < 0) {
2755 return n > 0 ? n : -errno;
2758 if (pollfd.revents != POLLIN)
2759 return n > 0 ? n : -EIO;
2764 return n > 0 ? n : (k < 0 ? -errno : 0);
2775 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2784 while (nbytes > 0) {
2787 if ((k = write(fd, p, nbytes)) <= 0) {
2789 if (k < 0 && errno == EINTR)
2792 if (k < 0 && errno == EAGAIN && do_poll) {
2793 struct pollfd pollfd;
2797 pollfd.events = POLLOUT;
2799 if (poll(&pollfd, 1, -1) < 0) {
2803 return n > 0 ? n : -errno;
2806 if (pollfd.revents != POLLOUT)
2807 return n > 0 ? n : -EIO;
2812 return n > 0 ? n : (k < 0 ? -errno : 0);
2823 int path_is_mount_point(const char *t) {
2828 if (lstat(t, &a) < 0) {
2829 if (errno == ENOENT)
2835 if ((r = parent_of_path(t, &parent)) < 0)
2838 r = lstat(parent, &b);
2844 return a.st_dev != b.st_dev;
2847 int parse_usec(const char *t, usec_t *usec) {
2848 static const struct {
2852 { "sec", USEC_PER_SEC },
2853 { "s", USEC_PER_SEC },
2854 { "min", USEC_PER_MINUTE },
2855 { "hr", USEC_PER_HOUR },
2856 { "h", USEC_PER_HOUR },
2857 { "d", USEC_PER_DAY },
2858 { "w", USEC_PER_WEEK },
2859 { "msec", USEC_PER_MSEC },
2860 { "ms", USEC_PER_MSEC },
2861 { "m", USEC_PER_MINUTE },
2864 { "", USEC_PER_SEC },
2880 l = strtoll(p, &e, 10);
2891 e += strspn(e, WHITESPACE);
2893 for (i = 0; i < ELEMENTSOF(table); i++)
2894 if (startswith(e, table[i].suffix)) {
2895 r += (usec_t) l * table[i].usec;
2896 p = e + strlen(table[i].suffix);
2900 if (i >= ELEMENTSOF(table))
2910 int make_stdio(int fd) {
2915 r = dup2(fd, STDIN_FILENO);
2916 s = dup2(fd, STDOUT_FILENO);
2917 t = dup2(fd, STDERR_FILENO);
2920 close_nointr_nofail(fd);
2922 if (r < 0 || s < 0 || t < 0)
2928 int make_null_stdio(void) {
2931 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2934 return make_stdio(null_fd);
2937 bool is_device_path(const char *path) {
2939 /* Returns true on paths that refer to a device, either in
2940 * sysfs or in /dev */
2943 path_startswith(path, "/dev/") ||
2944 path_startswith(path, "/sys/");
2947 int dir_is_empty(const char *path) {
2950 struct dirent buf, *de;
2952 if (!(d = opendir(path)))
2956 if ((r = readdir_r(d, &buf, &de)) > 0) {
2966 if (!ignore_file(de->d_name)) {
2976 unsigned long long random_ull(void) {
2981 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2984 r = loop_read(fd, &ull, sizeof(ull), true);
2985 close_nointr_nofail(fd);
2987 if (r != sizeof(ull))
2993 return random() * RAND_MAX + random();
2996 void rename_process(const char name[8]) {
2999 prctl(PR_SET_NAME, name);
3001 /* This is a like a poor man's setproctitle(). The string
3002 * passed should fit in 7 chars (i.e. the length of
3005 if (program_invocation_name)
3006 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3009 void sigset_add_many(sigset_t *ss, ...) {
3016 while ((sig = va_arg(ap, int)) > 0)
3017 assert_se(sigaddset(ss, sig) == 0);
3021 char* gethostname_malloc(void) {
3024 assert_se(uname(&u) >= 0);
3027 return strdup(u.nodename);
3029 return strdup(u.sysname);
3032 char* getlogname_malloc(void) {
3036 struct passwd pwbuf, *pw = NULL;
3039 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3044 /* Shortcut things to avoid NSS lookups */
3046 return strdup("root");
3048 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3051 if (!(buf = malloc(bufsize)))
3054 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3055 name = strdup(pw->pw_name);
3062 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3068 int getttyname_malloc(int fd, char **r) {
3069 char path[PATH_MAX], *c;
3074 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3079 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3086 int getttyname_harder(int fd, char **r) {
3090 if ((k = getttyname_malloc(fd, &s)) < 0)
3093 if (streq(s, "tty")) {
3095 return get_ctty(r, NULL);
3102 int get_ctty_devnr(dev_t *d) {
3104 char line[LINE_MAX], *p;
3105 unsigned long ttynr;
3108 if (!(f = fopen("/proc/self/stat", "r")))
3111 if (!(fgets(line, sizeof(line), f))) {
3119 if (!(p = strrchr(line, ')')))
3128 "%*d " /* session */
3137 int get_ctty(char **r, dev_t *_devnr) {
3139 char fn[PATH_MAX], *s, *b, *p;
3144 if ((k = get_ctty_devnr(&devnr)) < 0)
3147 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3150 if ((k = readlink_malloc(fn, &s)) < 0) {
3155 /* This is an ugly hack */
3156 if (major(devnr) == 136) {
3157 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3167 /* Probably something like the ptys which have no
3168 * symlink in /dev/char. Let's return something
3169 * vaguely useful. */
3171 if (!(b = strdup(fn + 5)))
3181 if (startswith(s, "/dev/"))
3183 else if (startswith(s, "../"))
3201 static int rm_rf_children(int fd, bool only_dirs) {
3207 /* This returns the first error we run into, but nevertheless
3210 if (!(d = fdopendir(fd))) {
3211 close_nointr_nofail(fd);
3213 return errno == ENOENT ? 0 : -errno;
3217 struct dirent buf, *de;
3221 if ((r = readdir_r(d, &buf, &de)) != 0) {
3230 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3233 if (de->d_type == DT_UNKNOWN) {
3236 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3237 if (ret == 0 && errno != ENOENT)
3242 is_dir = S_ISDIR(st.st_mode);
3244 is_dir = de->d_type == DT_DIR;
3249 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3250 if (ret == 0 && errno != ENOENT)
3255 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3260 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3261 if (ret == 0 && errno != ENOENT)
3264 } else if (!only_dirs) {
3266 if (unlinkat(fd, de->d_name, 0) < 0) {
3267 if (ret == 0 && errno != ENOENT)
3278 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3284 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3286 if (errno != ENOTDIR)
3289 if (delete_root && !only_dirs)
3290 if (unlink(path) < 0)
3296 r = rm_rf_children(fd, only_dirs);
3299 if (rmdir(path) < 0) {
3307 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3310 /* Under the assumption that we are running privileged we
3311 * first change the access mode and only then hand out
3312 * ownership to avoid a window where access is too open. */
3314 if (chmod(path, mode) < 0)
3317 if (chown(path, uid, gid) < 0)
3323 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3327 /* Allocates the cpuset in the right size */
3330 if (!(r = CPU_ALLOC(n)))
3333 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3334 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3344 if (errno != EINVAL)
3351 void status_vprintf(const char *format, va_list ap) {
3357 /* This independent of logging, as status messages are
3358 * optional and go exclusively to the console. */
3360 if (vasprintf(&s, format, ap) < 0)
3363 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3366 write(fd, s, strlen(s));
3372 close_nointr_nofail(fd);
3375 void status_printf(const char *format, ...) {
3380 va_start(ap, format);
3381 status_vprintf(format, ap);
3385 void status_welcome(void) {
3386 char *pretty_name = NULL, *ansi_color = NULL;
3387 const char *const_pretty = NULL, *const_color = NULL;
3390 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3391 "PRETTY_NAME", &pretty_name,
3392 "ANSI_COLOR", &ansi_color,
3396 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3399 #if defined(TARGET_FEDORA)
3401 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3404 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3408 if (!ansi_color && pretty_name) {
3410 /* This tries to mimic the color magic the old Red Hat sysinit
3413 if (startswith(pretty_name, "Red Hat"))
3414 const_color = "0;31"; /* Red for RHEL */
3415 else if (startswith(pretty_name, "Fedora"))
3416 const_color = "0;34"; /* Blue for Fedora */
3419 #elif defined(TARGET_SUSE)
3422 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3425 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3430 const_color = "0;32"; /* Green for openSUSE */
3432 #elif defined(TARGET_GENTOO)
3435 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3438 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3443 const_color = "1;34"; /* Light Blue for Gentoo */
3445 #elif defined(TARGET_ALTLINUX)
3448 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3451 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3456 const_color = "0;36"; /* Cyan for ALTLinux */
3459 #elif defined(TARGET_DEBIAN)
3464 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3467 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3469 pretty_name = strappend("Debian ", version);
3473 log_warning("Failed to allocate Debian version string.");
3478 const_color = "1;31"; /* Light Red for Debian */
3480 #elif defined(TARGET_UBUNTU)
3482 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3483 "DISTRIB_DESCRIPTION", &pretty_name,
3487 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3491 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3493 #elif defined(TARGET_MANDRIVA)
3498 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3500 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3502 p = strstr(s, " release ");
3506 p[strcspn(p, " ")] = '\0';
3508 /* This corresponds to standard rc.sysinit */
3509 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3510 const_color = "1;36";
3512 log_warning("Failed to allocate Mandriva version string.");
3514 log_warning("Failed to parse /etc/mandriva-release");
3518 #elif defined(TARGET_MEEGO)
3521 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3524 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3529 const_color = "1;35"; /* Bright Magenta for MeeGo */
3532 if (!pretty_name && !const_pretty)
3533 const_pretty = "Linux";
3535 if (!ansi_color && !const_color)
3538 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3539 const_color ? const_color : ansi_color,
3540 const_pretty ? const_pretty : pretty_name);
3546 char *replace_env(const char *format, char **env) {
3553 const char *e, *word = format;
3558 for (e = format; *e; e ++) {
3569 if (!(k = strnappend(r, word, e-word-1)))
3578 } else if (*e == '$') {
3579 if (!(k = strnappend(r, word, e-word)))
3595 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3598 if (!(k = strappend(r, t)))
3611 if (!(k = strnappend(r, word, e-word)))
3622 char **replace_env_argv(char **argv, char **env) {
3624 unsigned k = 0, l = 0;
3626 l = strv_length(argv);
3628 if (!(r = new(char*, l+1)))
3631 STRV_FOREACH(i, argv) {
3633 /* If $FOO appears as single word, replace it by the split up variable */
3634 if ((*i)[0] == '$' && (*i)[1] != '{') {
3639 if ((e = strv_env_get(env, *i+1))) {
3641 if (!(m = strv_split_quoted(e))) {
3652 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3661 memcpy(r + k, m, q * sizeof(char*));
3669 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3670 if (!(r[k++] = replace_env(*i, env))) {
3681 static __thread int parsed_columns = 0;
3684 if (parsed_columns > 0)
3685 return parsed_columns;
3687 if ((e = getenv("COLUMNS")))
3688 parsed_columns = atoi(e);
3690 if (parsed_columns <= 0) {
3694 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3695 parsed_columns = ws.ws_col;
3698 if (parsed_columns <= 0)
3699 parsed_columns = 80;
3701 return parsed_columns;
3704 int running_in_chroot(void) {
3710 /* Only works as root */
3712 if (stat("/proc/1/root", &a) < 0)
3715 if (stat("/", &b) < 0)
3719 a.st_dev != b.st_dev ||
3720 a.st_ino != b.st_ino;
3723 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3728 assert(percent <= 100);
3729 assert(length >= 3);
3733 if (l <= 3 || l <= length)
3736 if (!(r = new0(char, length+1)))
3739 x = (length * percent) / 100;
3749 s + l - (length - x - 3),
3755 int touch(const char *path) {
3760 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3763 close_nointr_nofail(fd);
3767 char *unquote(const char *s, const char* quotes) {
3771 if ((l = strlen(s)) < 2)
3774 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3775 return strndup(s+1, l-2);
3780 char *normalize_env_assignment(const char *s) {
3781 char *name, *value, *p, *r;
3786 if (!(r = strdup(s)))
3792 if (!(name = strndup(s, p - s)))
3795 if (!(p = strdup(p+1))) {
3800 value = unquote(strstrip(p), QUOTES);
3808 if (asprintf(&r, "%s=%s", name, value) < 0)
3817 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3824 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3836 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3843 if ((r = wait_for_terminate(pid, &status)) < 0) {
3844 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3848 if (status.si_code == CLD_EXITED) {
3849 if (status.si_status != 0) {
3850 log_warning("%s failed with error code %i.", name, status.si_status);
3851 return status.si_status;
3854 log_debug("%s succeeded.", name);
3857 } else if (status.si_code == CLD_KILLED ||
3858 status.si_code == CLD_DUMPED) {
3860 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3864 log_warning("%s failed due to unknown reason.", name);
3871 /* Make sure nobody waits for us on a socket anymore */
3872 close_all_fds(NULL, 0);
3880 bool null_or_empty(struct stat *st) {
3883 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3886 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3892 DIR *xopendirat(int fd, const char *name, int flags) {
3896 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3899 if (!(d = fdopendir(nfd))) {
3900 close_nointr_nofail(nfd);
3907 int signal_from_string_try_harder(const char *s) {
3911 if ((signo = signal_from_string(s)) <= 0)
3912 if (startswith(s, "SIG"))
3913 return signal_from_string(s+3);
3918 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3924 if (!dual_timestamp_is_set(t))
3927 fprintf(f, "%s=%llu %llu\n",
3929 (unsigned long long) t->realtime,
3930 (unsigned long long) t->monotonic);
3933 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3934 unsigned long long a, b;
3939 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3940 log_debug("Failed to parse finish timestamp value %s", value);
3947 char *fstab_node_to_udev_node(const char *p) {
3951 /* FIXME: to follow udev's logic 100% we need to leave valid
3952 * UTF8 chars unescaped */
3954 if (startswith(p, "LABEL=")) {
3956 if (!(u = unquote(p+6, "\"\'")))
3959 t = xescape(u, "/ ");
3965 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3974 if (startswith(p, "UUID=")) {
3976 if (!(u = unquote(p+5, "\"\'")))
3979 t = xescape(u, "/ ");
3985 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3997 void filter_environ(const char *prefix) {
4004 for (i = 0, j = 0; environ[i]; i++) {
4006 if (startswith(environ[i], prefix))
4009 environ[j++] = environ[i];
4015 bool tty_is_vc(const char *tty) {
4018 if (startswith(tty, "/dev/"))
4021 return startswith(tty, "tty") &&
4022 tty[3] >= '0' && tty[3] <= '9';
4025 const char *default_term_for_tty(const char *tty) {
4026 char *active = NULL;
4031 if (startswith(tty, "/dev/"))
4034 /* Resolve where /dev/console is pointing when determining
4036 if (streq(tty, "console"))
4037 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4038 /* If multiple log outputs are configured the
4039 * last one is what /dev/console points to */
4040 if ((tty = strrchr(active, ' ')))
4046 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4052 /* Returns a short identifier for the various VM implementations */
4053 int detect_vm(const char **id) {
4055 #if defined(__i386__) || defined(__x86_64__)
4057 /* Both CPUID and DMI are x86 specific interfaces... */
4059 static const char *const dmi_vendors[] = {
4060 "/sys/class/dmi/id/sys_vendor",
4061 "/sys/class/dmi/id/board_vendor",
4062 "/sys/class/dmi/id/bios_vendor"
4065 static const char dmi_vendor_table[] =
4067 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4068 "VMware\0" "vmware\0"
4070 "Microsoft Corporation\0" "microsoft\0"
4071 "innotek GmbH\0" "oracle\0"
4073 "Bochs\0" "bochs\0";
4075 static const char cpuid_vendor_table[] =
4076 "XenVMMXenVMM\0" "xen\0"
4077 "KVMKVMKVM\0" "kvm\0"
4078 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4079 "VMwareVMware\0" "vmware\0"
4080 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4081 "Microsoft Hv\0" "microsoft\0";
4092 /* http://lwn.net/Articles/301888/ */
4095 #if defined (__i386__)
4098 #elif defined (__amd64__)
4103 /* First detect whether there is a hypervisor */
4105 __asm__ __volatile__ (
4106 /* ebx/rbx is being used for PIC! */
4107 " push %%"REG_b" \n\t"
4109 " pop %%"REG_b" \n\t"
4111 : "=a" (eax), "=c" (ecx)
4115 hypervisor = !!(ecx & 0x80000000U);
4119 /* There is a hypervisor, see what it is */
4121 __asm__ __volatile__ (
4122 /* ebx/rbx is being used for PIC! */
4123 " push %%"REG_b" \n\t"
4125 " mov %%ebx, %1 \n\t"
4126 " pop %%"REG_b" \n\t"
4128 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4132 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4133 if (streq(sig.text, j)) {
4142 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4145 const char *found = NULL;
4147 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4154 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4155 if (startswith(s, j))
4178 int detect_container(const char **id) {
4181 /* Unfortunately many of these operations require root access
4182 * in one way or another */
4187 if (running_in_chroot() > 0) {
4195 /* /proc/vz exists in container and outside of the container,
4196 * /proc/bc only outside of the container. */
4197 if (access("/proc/vz", F_OK) >= 0 &&
4198 access("/proc/bc", F_OK) < 0) {
4206 if ((f = fopen("/proc/self/cgroup", "r"))) {
4209 char line[LINE_MAX], *p;
4211 if (!fgets(line, sizeof(line), f))
4214 if (!(p = strchr(strstrip(line), ':')))
4217 if (strncmp(p, ":ns:", 4))
4220 if (!streq(p, ":ns:/")) {
4236 /* Returns a short identifier for the various VM/container implementations */
4237 int detect_virtualization(const char **id) {
4238 static __thread const char *cached_id = NULL;
4244 if (cached_id == (const char*) -1)
4253 if ((r = detect_container(&_id)) != 0)
4256 r = detect_vm(&_id);
4265 cached_id = (const char*) -1;
4270 bool dirent_is_file(struct dirent *de) {
4273 if (ignore_file(de->d_name))
4276 if (de->d_type != DT_REG &&
4277 de->d_type != DT_LNK &&
4278 de->d_type != DT_UNKNOWN)
4284 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4287 Hashmap *pids = NULL;
4291 /* Executes all binaries in a directory in parallel and waits
4292 * until all they all finished. */
4295 if (!(_d = opendir(directory))) {
4297 if (errno == ENOENT)
4300 log_error("Failed to enumerate directory %s: %m", directory);
4307 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4308 log_error("Failed to allocate set.");
4312 while ((de = readdir(d))) {
4317 if (!dirent_is_file(de))
4320 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4321 log_error("Out of memory");
4325 if ((pid = fork()) < 0) {
4326 log_error("Failed to fork: %m");
4345 log_error("Failed to execute %s: %m", path);
4346 _exit(EXIT_FAILURE);
4349 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4351 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4352 log_error("Failed to add PID to set: %s", strerror(-k));
4357 while (!hashmap_isempty(pids)) {
4362 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4367 log_error("waitid() failed: %m");
4371 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4372 if (!is_clean_exit(si.si_code, si.si_status)) {
4373 if (si.si_code == CLD_EXITED)
4374 log_error("%s exited with exit status %i.", path, si.si_status);
4376 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4378 log_debug("%s exited successfully.", path);
4389 hashmap_free_free(pids);
4392 int kill_and_sigcont(pid_t pid, int sig) {
4395 r = kill(pid, sig) < 0 ? -errno : 0;
4403 bool nulstr_contains(const char*nulstr, const char *needle) {
4409 NULSTR_FOREACH(i, nulstr)
4410 if (streq(i, needle))
4416 bool plymouth_running(void) {
4417 return access("/run/plymouth/pid", F_OK) >= 0;
4420 void parse_syslog_priority(char **p, int *priority) {
4421 int a = 0, b = 0, c = 0;
4431 if (!strchr(*p, '>'))
4434 if ((*p)[2] == '>') {
4435 c = undecchar((*p)[1]);
4437 } else if ((*p)[3] == '>') {
4438 b = undecchar((*p)[1]);
4439 c = undecchar((*p)[2]);
4441 } else if ((*p)[4] == '>') {
4442 a = undecchar((*p)[1]);
4443 b = undecchar((*p)[2]);
4444 c = undecchar((*p)[3]);
4449 if (a < 0 || b < 0 || c < 0)
4452 *priority = a*100+b*10+c;
4456 int have_effective_cap(int value) {
4458 cap_flag_value_t fv;
4461 if (!(cap = cap_get_proc()))
4464 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4473 char* strshorten(char *s, size_t l) {
4482 static bool hostname_valid_char(char c) {
4484 (c >= 'a' && c <= 'z') ||
4485 (c >= 'A' && c <= 'Z') ||
4486 (c >= '0' && c <= '9') ||
4492 bool hostname_is_valid(const char *s) {
4498 for (p = s; *p; p++)
4499 if (!hostname_valid_char(*p))
4502 if (p-s > HOST_NAME_MAX)
4508 char* hostname_cleanup(char *s) {
4511 for (p = s, d = s; *p; p++)
4512 if ((*p >= 'a' && *p <= 'z') ||
4513 (*p >= 'A' && *p <= 'Z') ||
4514 (*p >= '0' && *p <= '9') ||
4522 strshorten(s, HOST_NAME_MAX);
4526 int pipe_eof(int fd) {
4527 struct pollfd pollfd;
4532 pollfd.events = POLLIN|POLLHUP;
4534 r = poll(&pollfd, 1, 0);
4541 return pollfd.revents & POLLHUP;
4544 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4555 t = new(char, strlen(path) + 1 + 6 + 1);
4559 fn = file_name_from_path(path);
4563 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4565 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4571 f = fdopen(fd, "we");
4584 int terminal_vhangup_fd(int fd) {
4587 if (ioctl(fd, TIOCVHANGUP) < 0)
4593 int terminal_vhangup(const char *name) {
4596 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4600 r = terminal_vhangup_fd(fd);
4601 close_nointr_nofail(fd);
4606 int vt_disallocate(const char *name) {
4610 /* Deallocate the VT if possible. If not possible
4611 * (i.e. because it is the active one), at least clear it
4612 * entirely (including the scrollback buffer) */
4614 if (!startswith(name, "/dev/"))
4617 if (!tty_is_vc(name)) {
4618 /* So this is not a VT. I guess we cannot deallocate
4619 * it then. But let's at least clear the screen */
4621 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4625 loop_write(fd, "\033[H\033[2J", 7, false); /* clear screen */
4626 close_nointr_nofail(fd);
4631 if (!startswith(name, "/dev/tty"))
4634 r = safe_atou(name+8, &u);
4641 /* Try to deallocate */
4642 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4646 r = ioctl(fd, VT_DISALLOCATE, u);
4647 close_nointr_nofail(fd);
4655 /* Couldn't deallocate, so let's clear it fully with
4657 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4661 /* Requires Linux 2.6.40 */
4662 loop_write(fd, "\033[H\033[3J", 7, false); /* clear screen including scrollback */
4663 close_nointr_nofail(fd);
4669 static int file_is_conf(const struct dirent *d, const char *suffix) {
4672 if (ignore_file(d->d_name))
4675 if (d->d_type != DT_REG &&
4676 d->d_type != DT_LNK &&
4677 d->d_type != DT_UNKNOWN)
4680 return endswith(d->d_name, suffix);
4683 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4688 dir = opendir(path);
4690 if (errno == ENOENT)
4695 for (de = readdir(dir); de; de = readdir(dir)) {
4699 if (!file_is_conf(de, suffix))
4702 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4707 f = canonicalize_file_name(p);
4709 log_error("Failed to canonicalize file name '%s': %m", p);
4715 log_debug("found: %s\n", f);
4716 base = f + strlen(path) + 1;
4717 if (hashmap_put(h, base, f) <= 0)
4726 static int base_cmp(const void *a, const void *b) {
4727 const char *s1, *s2;
4729 s1 = *(char * const *)a;
4730 s2 = *(char * const *)b;
4731 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4734 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4737 char **files = NULL;
4743 dirs = strv_new_ap(dir, ap);
4749 if (!strv_path_canonicalize(dirs)) {
4753 if (!strv_uniq(dirs)) {
4758 fh = hashmap_new(string_hash_func, string_compare_func);
4764 STRV_FOREACH(p, dirs) {
4765 if (files_add(fh, *p, suffix) < 0) {
4766 log_error("Failed to search for files.");
4772 files = hashmap_get_strv(fh);
4773 if (files == NULL) {
4774 log_error("Failed to compose list of files.");
4779 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4788 bool hwclock_is_localtime(void) {
4790 char line[LINE_MAX];
4794 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4800 f = fopen("/etc/adjtime", "re");
4802 if (fgets(line, sizeof(line), f) &&
4803 fgets(line, sizeof(line), f) &&
4804 fgets(line, sizeof(line), f) ) {
4805 if (!strcmp(line, "LOCAL\n"))
4813 int hwclock_apply_localtime_delta(void) {
4814 const struct timeval *tv_null = NULL;
4820 gettimeofday(&tv, NULL);
4821 tm = localtime(&tv.tv_sec);
4822 minuteswest = tm->tm_gmtoff / 60;
4824 tz.tz_minuteswest = -minuteswest;
4825 tz.tz_dsttime = 0; /* DST_NONE*/
4828 * If the hardware clock does not run in UTC, but in local time:
4829 * The very first time we set the kernel's timezone, it will warp
4830 * the clock so that it runs in UTC instead of local time.
4832 if (settimeofday(tv_null, &tz) < 0)
4838 int hwclock_get_time(struct tm *tm) {
4842 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4845 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4852 int hwclock_set_time(const struct tm *tm) {
4856 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4859 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4866 int copy_file(const char *from, const char *to) {
4872 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4876 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4878 close_nointr_nofail(fdf);
4886 n = read(fdf, buf, sizeof(buf));
4890 close_nointr_nofail(fdf);
4901 k = loop_write(fdt, buf, n, false);
4903 r = k < 0 ? k : (errno ? -errno : -EIO);
4905 close_nointr_nofail(fdf);
4913 close_nointr_nofail(fdf);
4914 r = close_nointr(fdt);
4924 int symlink_or_copy(const char *from, const char *to) {
4925 char *pf = NULL, *pt = NULL;
4932 if (parent_of_path(from, &pf) < 0 ||
4933 parent_of_path(to, &pt) < 0) {
4938 if (stat(pf, &a) < 0 ||
4944 if (a.st_dev != b.st_dev) {
4948 return copy_file(from, to);
4951 if (symlink(from, to) < 0) {
4965 int symlink_or_copy_atomic(const char *from, const char *to) {
4969 unsigned long long ull;
4976 t = new(char, strlen(to) + 1 + 16 + 1);
4980 fn = file_name_from_path(to);
4984 x = stpcpy(t+k+1, fn);
4987 for (i = 0; i < 16; i++) {
4988 *(x++) = hexchar(ull & 0xF);
4994 r = symlink_or_copy(from, t);
5001 if (rename(t, to) < 0) {
5012 static const char *const ioprio_class_table[] = {
5013 [IOPRIO_CLASS_NONE] = "none",
5014 [IOPRIO_CLASS_RT] = "realtime",
5015 [IOPRIO_CLASS_BE] = "best-effort",
5016 [IOPRIO_CLASS_IDLE] = "idle"
5019 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5021 static const char *const sigchld_code_table[] = {
5022 [CLD_EXITED] = "exited",
5023 [CLD_KILLED] = "killed",
5024 [CLD_DUMPED] = "dumped",
5025 [CLD_TRAPPED] = "trapped",
5026 [CLD_STOPPED] = "stopped",
5027 [CLD_CONTINUED] = "continued",
5030 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5032 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5033 [LOG_FAC(LOG_KERN)] = "kern",
5034 [LOG_FAC(LOG_USER)] = "user",
5035 [LOG_FAC(LOG_MAIL)] = "mail",
5036 [LOG_FAC(LOG_DAEMON)] = "daemon",
5037 [LOG_FAC(LOG_AUTH)] = "auth",
5038 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5039 [LOG_FAC(LOG_LPR)] = "lpr",
5040 [LOG_FAC(LOG_NEWS)] = "news",
5041 [LOG_FAC(LOG_UUCP)] = "uucp",
5042 [LOG_FAC(LOG_CRON)] = "cron",
5043 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5044 [LOG_FAC(LOG_FTP)] = "ftp",
5045 [LOG_FAC(LOG_LOCAL0)] = "local0",
5046 [LOG_FAC(LOG_LOCAL1)] = "local1",
5047 [LOG_FAC(LOG_LOCAL2)] = "local2",
5048 [LOG_FAC(LOG_LOCAL3)] = "local3",
5049 [LOG_FAC(LOG_LOCAL4)] = "local4",
5050 [LOG_FAC(LOG_LOCAL5)] = "local5",
5051 [LOG_FAC(LOG_LOCAL6)] = "local6",
5052 [LOG_FAC(LOG_LOCAL7)] = "local7"
5055 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5057 static const char *const log_level_table[] = {
5058 [LOG_EMERG] = "emerg",
5059 [LOG_ALERT] = "alert",
5060 [LOG_CRIT] = "crit",
5062 [LOG_WARNING] = "warning",
5063 [LOG_NOTICE] = "notice",
5064 [LOG_INFO] = "info",
5065 [LOG_DEBUG] = "debug"
5068 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5070 static const char* const sched_policy_table[] = {
5071 [SCHED_OTHER] = "other",
5072 [SCHED_BATCH] = "batch",
5073 [SCHED_IDLE] = "idle",
5074 [SCHED_FIFO] = "fifo",
5078 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5080 static const char* const rlimit_table[] = {
5081 [RLIMIT_CPU] = "LimitCPU",
5082 [RLIMIT_FSIZE] = "LimitFSIZE",
5083 [RLIMIT_DATA] = "LimitDATA",
5084 [RLIMIT_STACK] = "LimitSTACK",
5085 [RLIMIT_CORE] = "LimitCORE",
5086 [RLIMIT_RSS] = "LimitRSS",
5087 [RLIMIT_NOFILE] = "LimitNOFILE",
5088 [RLIMIT_AS] = "LimitAS",
5089 [RLIMIT_NPROC] = "LimitNPROC",
5090 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5091 [RLIMIT_LOCKS] = "LimitLOCKS",
5092 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5093 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5094 [RLIMIT_NICE] = "LimitNICE",
5095 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5096 [RLIMIT_RTTIME] = "LimitRTTIME"
5099 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5101 static const char* const ip_tos_table[] = {
5102 [IPTOS_LOWDELAY] = "low-delay",
5103 [IPTOS_THROUGHPUT] = "throughput",
5104 [IPTOS_RELIABILITY] = "reliability",
5105 [IPTOS_LOWCOST] = "low-cost",
5108 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5110 static const char *const signal_table[] = {
5127 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5138 [SIGVTALRM] = "VTALRM",
5140 [SIGWINCH] = "WINCH",
5146 DEFINE_STRING_TABLE_LOOKUP(signal, int);