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")))
570 if (fputs(line, f) < 0) {
575 if (!endswith(line, "\n"))
593 int read_one_line_file(const char *fn, char **line) {
596 char t[LINE_MAX], *c;
601 if (!(f = fopen(fn, "re")))
604 if (!(fgets(t, sizeof(t), f))) {
609 if (!(c = strdup(t))) {
624 int read_full_file(const char *fn, char **contents) {
631 if (!(f = fopen(fn, "re")))
634 if (fstat(fileno(f), &st) < 0) {
639 n = st.st_size > 0 ? st.st_size : LINE_MAX;
646 if (!(t = realloc(buf, n+1))) {
652 k = fread(buf + l, 1, n - l, f);
667 if (n > 4*1024*1024) {
675 else if (!(buf = calloc(1, 1))) {
694 const char *separator, ...) {
702 if ((r = read_full_file(fname, &contents)) < 0)
707 const char *key = NULL;
709 p += strspn(p, separator);
710 p += strspn(p, WHITESPACE);
715 if (!strchr(COMMENTS, *p)) {
719 va_start(ap, separator);
720 while ((key = va_arg(ap, char *))) {
724 value = va_arg(ap, char **);
727 if (strncmp(p, key, n) != 0 ||
732 n = strcspn(p, separator);
735 strchr(QUOTES, p[0]) &&
737 v = strndup(p+1, n-2);
748 /* return empty value strings as NULL */
765 p += strcspn(p, separator);
784 if (!(f = fopen(fname, "re")))
788 char l[LINE_MAX], *p, *u;
791 if (!fgets(l, sizeof(l), f)) {
804 if (strchr(COMMENTS, *p))
807 if (!(u = normalize_env_assignment(p))) {
808 log_error("Out of memory");
813 t = strv_append(m, u);
817 log_error("Out of memory");
840 int write_env_file(const char *fname, char **l) {
846 f = fopen(fname, "we");
857 r = ferror(f) ? -errno : 0;
863 char *truncate_nl(char *s) {
866 s[strcspn(s, NEWLINE)] = 0;
870 int get_process_name(pid_t pid, char **name) {
877 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
880 r = read_one_line_file(p, name);
889 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
897 assert(max_length > 0);
900 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
909 if (!(r = new(char, max_length))) {
916 while ((c = getc(f)) != EOF) {
938 size_t n = MIN(left-1, 3U);
946 /* Kernel threads have no argv[] */
953 if ((h = get_process_name(pid, &t)) < 0)
956 h = asprintf(&r, "[%s]", t);
967 char *strnappend(const char *s, const char *suffix, size_t b) {
975 return strndup(suffix, b);
985 if (!(r = new(char, a+b+1)))
989 memcpy(r+a, suffix, b);
995 char *strappend(const char *s, const char *suffix) {
996 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
999 int readlink_malloc(const char *p, char **r) {
1009 if (!(c = new(char, l)))
1012 if ((n = readlink(p, c, l-1)) < 0) {
1018 if ((size_t) n < l-1) {
1029 int readlink_and_make_absolute(const char *p, char **r) {
1036 if ((j = readlink_malloc(p, &target)) < 0)
1039 k = file_in_same_dir(p, target);
1049 int parent_of_path(const char *path, char **_r) {
1050 const char *e, *a = NULL, *b = NULL, *p;
1060 for (e = path; *e; e++) {
1062 if (!slash && *e == '/') {
1066 } else if (slash && *e != '/')
1081 r = strndup(path, p-path);
1091 char *file_name_from_path(const char *p) {
1096 if ((r = strrchr(p, '/')))
1102 bool path_is_absolute(const char *p) {
1108 bool is_path(const char *p) {
1110 return !!strchr(p, '/');
1113 char *path_make_absolute(const char *p, const char *prefix) {
1118 /* Makes every item in the list an absolute path by prepending
1119 * the prefix, if specified and necessary */
1121 if (path_is_absolute(p) || !prefix)
1124 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1130 char *path_make_absolute_cwd(const char *p) {
1135 /* Similar to path_make_absolute(), but prefixes with the
1136 * current working directory. */
1138 if (path_is_absolute(p))
1141 if (!(cwd = get_current_dir_name()))
1144 r = path_make_absolute(p, cwd);
1150 char **strv_path_make_absolute_cwd(char **l) {
1153 /* Goes through every item in the string list and makes it
1154 * absolute. This works in place and won't rollback any
1155 * changes on failure. */
1157 STRV_FOREACH(s, l) {
1160 if (!(t = path_make_absolute_cwd(*s)))
1170 char **strv_path_canonicalize(char **l) {
1173 bool enomem = false;
1175 if (strv_isempty(l))
1178 /* Goes through every item in the string list and canonicalize
1179 * the path. This works in place and won't rollback any
1180 * changes on failure. */
1182 STRV_FOREACH(s, l) {
1185 t = path_make_absolute_cwd(*s);
1194 u = canonicalize_file_name(t);
1198 if (errno == ENOMEM || !errno)
1215 char **strv_path_remove_empty(char **l) {
1221 for (f = t = l; *f; f++) {
1223 if (dir_is_empty(*f) > 0) {
1235 int reset_all_signal_handlers(void) {
1238 for (sig = 1; sig < _NSIG; sig++) {
1239 struct sigaction sa;
1241 if (sig == SIGKILL || sig == SIGSTOP)
1245 sa.sa_handler = SIG_DFL;
1246 sa.sa_flags = SA_RESTART;
1248 /* On Linux the first two RT signals are reserved by
1249 * glibc, and sigaction() will return EINVAL for them. */
1250 if ((sigaction(sig, &sa, NULL) < 0))
1251 if (errno != EINVAL)
1258 char *strstrip(char *s) {
1261 /* Drops trailing whitespace. Modifies the string in
1262 * place. Returns pointer to first non-space character */
1264 s += strspn(s, WHITESPACE);
1266 for (e = s; *e; e++)
1267 if (!strchr(WHITESPACE, *e))
1278 char *delete_chars(char *s, const char *bad) {
1281 /* Drops all whitespace, regardless where in the string */
1283 for (f = s, t = s; *f; f++) {
1284 if (strchr(bad, *f))
1295 char *file_in_same_dir(const char *path, const char *filename) {
1302 /* This removes the last component of path and appends
1303 * filename, unless the latter is absolute anyway or the
1306 if (path_is_absolute(filename))
1307 return strdup(filename);
1309 if (!(e = strrchr(path, '/')))
1310 return strdup(filename);
1312 k = strlen(filename);
1313 if (!(r = new(char, e-path+1+k+1)))
1316 memcpy(r, path, e-path+1);
1317 memcpy(r+(e-path)+1, filename, k+1);
1322 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1325 if (label_mkdir(path, mode) >= 0)
1326 if (chmod_and_chown(path, mode, uid, gid) < 0)
1329 if (lstat(path, &st) < 0)
1332 if ((st.st_mode & 0777) != mode ||
1335 !S_ISDIR(st.st_mode)) {
1344 int mkdir_parents(const char *path, mode_t mode) {
1349 /* Creates every parent directory in the path except the last
1352 p = path + strspn(path, "/");
1357 e = p + strcspn(p, "/");
1358 p = e + strspn(e, "/");
1360 /* Is this the last component? If so, then we're
1365 if (!(t = strndup(path, e - path)))
1368 r = label_mkdir(t, mode);
1371 if (r < 0 && errno != EEXIST)
1376 int mkdir_p(const char *path, mode_t mode) {
1381 if ((r = mkdir_parents(path, mode)) < 0)
1384 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1390 int rmdir_parents(const char *path, const char *stop) {
1399 /* Skip trailing slashes */
1400 while (l > 0 && path[l-1] == '/')
1406 /* Skip last component */
1407 while (l > 0 && path[l-1] != '/')
1410 /* Skip trailing slashes */
1411 while (l > 0 && path[l-1] == '/')
1417 if (!(t = strndup(path, l)))
1420 if (path_startswith(stop, t)) {
1429 if (errno != ENOENT)
1437 char hexchar(int x) {
1438 static const char table[16] = "0123456789abcdef";
1440 return table[x & 15];
1443 int unhexchar(char c) {
1445 if (c >= '0' && c <= '9')
1448 if (c >= 'a' && c <= 'f')
1449 return c - 'a' + 10;
1451 if (c >= 'A' && c <= 'F')
1452 return c - 'A' + 10;
1457 char octchar(int x) {
1458 return '0' + (x & 7);
1461 int unoctchar(char c) {
1463 if (c >= '0' && c <= '7')
1469 char decchar(int x) {
1470 return '0' + (x % 10);
1473 int undecchar(char c) {
1475 if (c >= '0' && c <= '9')
1481 char *cescape(const char *s) {
1487 /* Does C style string escaping. */
1489 if (!(r = new(char, strlen(s)*4 + 1)))
1492 for (f = s, t = r; *f; f++)
1538 /* For special chars we prefer octal over
1539 * hexadecimal encoding, simply because glib's
1540 * g_strescape() does the same */
1541 if ((*f < ' ') || (*f >= 127)) {
1543 *(t++) = octchar((unsigned char) *f >> 6);
1544 *(t++) = octchar((unsigned char) *f >> 3);
1545 *(t++) = octchar((unsigned char) *f);
1556 char *cunescape_length(const char *s, size_t length) {
1562 /* Undoes C style string escaping */
1564 if (!(r = new(char, length+1)))
1567 for (f = s, t = r; f < s + length; f++) {
1610 /* This is an extension of the XDG syntax files */
1615 /* hexadecimal encoding */
1618 if ((a = unhexchar(f[1])) < 0 ||
1619 (b = unhexchar(f[2])) < 0) {
1620 /* Invalid escape code, let's take it literal then */
1624 *(t++) = (char) ((a << 4) | b);
1639 /* octal encoding */
1642 if ((a = unoctchar(f[0])) < 0 ||
1643 (b = unoctchar(f[1])) < 0 ||
1644 (c = unoctchar(f[2])) < 0) {
1645 /* Invalid escape code, let's take it literal then */
1649 *(t++) = (char) ((a << 6) | (b << 3) | c);
1657 /* premature end of string.*/
1662 /* Invalid escape code, let's take it literal then */
1674 char *cunescape(const char *s) {
1675 return cunescape_length(s, strlen(s));
1678 char *xescape(const char *s, const char *bad) {
1682 /* Escapes all chars in bad, in addition to \ and all special
1683 * chars, in \xFF style escaping. May be reversed with
1686 if (!(r = new(char, strlen(s)*4+1)))
1689 for (f = s, t = r; *f; f++) {
1691 if ((*f < ' ') || (*f >= 127) ||
1692 (*f == '\\') || strchr(bad, *f)) {
1695 *(t++) = hexchar(*f >> 4);
1696 *(t++) = hexchar(*f);
1706 char *bus_path_escape(const char *s) {
1712 /* Escapes all chars that D-Bus' object path cannot deal
1713 * with. Can be reverse with bus_path_unescape() */
1715 if (!(r = new(char, strlen(s)*3+1)))
1718 for (f = s, t = r; *f; f++) {
1720 if (!(*f >= 'A' && *f <= 'Z') &&
1721 !(*f >= 'a' && *f <= 'z') &&
1722 !(*f >= '0' && *f <= '9')) {
1724 *(t++) = hexchar(*f >> 4);
1725 *(t++) = hexchar(*f);
1735 char *bus_path_unescape(const char *f) {
1740 if (!(r = strdup(f)))
1743 for (t = r; *f; f++) {
1748 if ((a = unhexchar(f[1])) < 0 ||
1749 (b = unhexchar(f[2])) < 0) {
1750 /* Invalid escape code, let's take it literal then */
1753 *(t++) = (char) ((a << 4) | b);
1765 char *path_kill_slashes(char *path) {
1769 /* Removes redundant inner and trailing slashes. Modifies the
1770 * passed string in-place.
1772 * ///foo///bar/ becomes /foo/bar
1775 for (f = path, t = path; *f; f++) {
1790 /* Special rule, if we are talking of the root directory, a
1791 trailing slash is good */
1793 if (t == path && slash)
1800 bool path_startswith(const char *path, const char *prefix) {
1804 if ((path[0] == '/') != (prefix[0] == '/'))
1810 path += strspn(path, "/");
1811 prefix += strspn(prefix, "/");
1819 a = strcspn(path, "/");
1820 b = strcspn(prefix, "/");
1825 if (memcmp(path, prefix, a) != 0)
1833 bool path_equal(const char *a, const char *b) {
1837 if ((a[0] == '/') != (b[0] == '/'))
1843 a += strspn(a, "/");
1844 b += strspn(b, "/");
1846 if (*a == 0 && *b == 0)
1849 if (*a == 0 || *b == 0)
1852 j = strcspn(a, "/");
1853 k = strcspn(b, "/");
1858 if (memcmp(a, b, j) != 0)
1866 char *ascii_strlower(char *t) {
1871 for (p = t; *p; p++)
1872 if (*p >= 'A' && *p <= 'Z')
1873 *p = *p - 'A' + 'a';
1878 bool ignore_file(const char *filename) {
1882 filename[0] == '.' ||
1883 streq(filename, "lost+found") ||
1884 streq(filename, "aquota.user") ||
1885 streq(filename, "aquota.group") ||
1886 endswith(filename, "~") ||
1887 endswith(filename, ".rpmnew") ||
1888 endswith(filename, ".rpmsave") ||
1889 endswith(filename, ".rpmorig") ||
1890 endswith(filename, ".dpkg-old") ||
1891 endswith(filename, ".dpkg-new") ||
1892 endswith(filename, ".swp");
1895 int fd_nonblock(int fd, bool nonblock) {
1900 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1904 flags |= O_NONBLOCK;
1906 flags &= ~O_NONBLOCK;
1908 if (fcntl(fd, F_SETFL, flags) < 0)
1914 int fd_cloexec(int fd, bool cloexec) {
1919 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1923 flags |= FD_CLOEXEC;
1925 flags &= ~FD_CLOEXEC;
1927 if (fcntl(fd, F_SETFD, flags) < 0)
1933 int close_all_fds(const int except[], unsigned n_except) {
1938 if (!(d = opendir("/proc/self/fd")))
1941 while ((de = readdir(d))) {
1944 if (ignore_file(de->d_name))
1947 if (safe_atoi(de->d_name, &fd) < 0)
1948 /* Let's better ignore this, just in case */
1962 for (i = 0; i < n_except; i++)
1963 if (except[i] == fd) {
1972 if (close_nointr(fd) < 0) {
1973 /* Valgrind has its own FD and doesn't want to have it closed */
1974 if (errno != EBADF && r == 0)
1983 bool chars_intersect(const char *a, const char *b) {
1986 /* Returns true if any of the chars in a are in b. */
1987 for (p = a; *p; p++)
1994 char *format_timestamp(char *buf, size_t l, usec_t t) {
2004 sec = (time_t) (t / USEC_PER_SEC);
2006 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2012 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2015 n = now(CLOCK_REALTIME);
2017 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2022 if (d >= USEC_PER_YEAR)
2023 snprintf(buf, l, "%llu years and %llu months ago",
2024 (unsigned long long) (d / USEC_PER_YEAR),
2025 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2026 else if (d >= USEC_PER_MONTH)
2027 snprintf(buf, l, "%llu months and %llu days ago",
2028 (unsigned long long) (d / USEC_PER_MONTH),
2029 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2030 else if (d >= USEC_PER_WEEK)
2031 snprintf(buf, l, "%llu weeks and %llu days ago",
2032 (unsigned long long) (d / USEC_PER_WEEK),
2033 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2034 else if (d >= 2*USEC_PER_DAY)
2035 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2036 else if (d >= 25*USEC_PER_HOUR)
2037 snprintf(buf, l, "1 day and %lluh ago",
2038 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2039 else if (d >= 6*USEC_PER_HOUR)
2040 snprintf(buf, l, "%lluh ago",
2041 (unsigned long long) (d / USEC_PER_HOUR));
2042 else if (d >= USEC_PER_HOUR)
2043 snprintf(buf, l, "%lluh %llumin ago",
2044 (unsigned long long) (d / USEC_PER_HOUR),
2045 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2046 else if (d >= 5*USEC_PER_MINUTE)
2047 snprintf(buf, l, "%llumin ago",
2048 (unsigned long long) (d / USEC_PER_MINUTE));
2049 else if (d >= USEC_PER_MINUTE)
2050 snprintf(buf, l, "%llumin %llus ago",
2051 (unsigned long long) (d / USEC_PER_MINUTE),
2052 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2053 else if (d >= USEC_PER_SEC)
2054 snprintf(buf, l, "%llus ago",
2055 (unsigned long long) (d / USEC_PER_SEC));
2056 else if (d >= USEC_PER_MSEC)
2057 snprintf(buf, l, "%llums ago",
2058 (unsigned long long) (d / USEC_PER_MSEC));
2060 snprintf(buf, l, "%lluus ago",
2061 (unsigned long long) d);
2063 snprintf(buf, l, "now");
2069 char *format_timespan(char *buf, size_t l, usec_t t) {
2070 static const struct {
2074 { "w", USEC_PER_WEEK },
2075 { "d", USEC_PER_DAY },
2076 { "h", USEC_PER_HOUR },
2077 { "min", USEC_PER_MINUTE },
2078 { "s", USEC_PER_SEC },
2079 { "ms", USEC_PER_MSEC },
2089 if (t == (usec_t) -1)
2093 snprintf(p, l, "0");
2098 /* The result of this function can be parsed with parse_usec */
2100 for (i = 0; i < ELEMENTSOF(table); i++) {
2104 if (t < table[i].usec)
2110 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2111 n = MIN((size_t) k, l);
2124 bool fstype_is_network(const char *fstype) {
2125 static const char * const table[] = {
2137 for (i = 0; i < ELEMENTSOF(table); i++)
2138 if (streq(table[i], fstype))
2147 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2152 TIOCL_GETKMSGREDIRECT,
2156 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2159 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2162 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2165 close_nointr_nofail(r);
2169 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2170 struct termios old_termios, new_termios;
2172 char line[LINE_MAX];
2177 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2178 new_termios = old_termios;
2180 new_termios.c_lflag &= ~ICANON;
2181 new_termios.c_cc[VMIN] = 1;
2182 new_termios.c_cc[VTIME] = 0;
2184 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2187 k = fread(&c, 1, 1, f);
2189 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2195 *need_nl = c != '\n';
2202 if (!(fgets(line, sizeof(line), f)))
2207 if (strlen(line) != 1)
2217 int ask(char *ret, const char *replies, const char *text, ...) {
2224 on_tty = isatty(STDOUT_FILENO);
2230 bool need_nl = true;
2233 fputs("\x1B[1m", stdout);
2240 fputs("\x1B[0m", stdout);
2244 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2246 if (r == -EBADMSG) {
2247 puts("Bad input, please try again.");
2258 if (strchr(replies, c)) {
2263 puts("Read unexpected character, please try again.");
2267 int reset_terminal_fd(int fd) {
2268 struct termios termios;
2272 /* Set terminal to some sane defaults */
2276 /* We leave locked terminal attributes untouched, so that
2277 * Plymouth may set whatever it wants to set, and we don't
2278 * interfere with that. */
2280 /* Disable exclusive mode, just in case */
2281 ioctl(fd, TIOCNXCL);
2283 /* Enable console unicode mode */
2285 ioctl(fd, KDSKBMODE, &arg);
2287 if (tcgetattr(fd, &termios) < 0) {
2292 /* We only reset the stuff that matters to the software. How
2293 * hardware is set up we don't touch assuming that somebody
2294 * else will do that for us */
2296 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2297 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2298 termios.c_oflag |= ONLCR;
2299 termios.c_cflag |= CREAD;
2300 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2302 termios.c_cc[VINTR] = 03; /* ^C */
2303 termios.c_cc[VQUIT] = 034; /* ^\ */
2304 termios.c_cc[VERASE] = 0177;
2305 termios.c_cc[VKILL] = 025; /* ^X */
2306 termios.c_cc[VEOF] = 04; /* ^D */
2307 termios.c_cc[VSTART] = 021; /* ^Q */
2308 termios.c_cc[VSTOP] = 023; /* ^S */
2309 termios.c_cc[VSUSP] = 032; /* ^Z */
2310 termios.c_cc[VLNEXT] = 026; /* ^V */
2311 termios.c_cc[VWERASE] = 027; /* ^W */
2312 termios.c_cc[VREPRINT] = 022; /* ^R */
2313 termios.c_cc[VEOL] = 0;
2314 termios.c_cc[VEOL2] = 0;
2316 termios.c_cc[VTIME] = 0;
2317 termios.c_cc[VMIN] = 1;
2319 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2323 /* Just in case, flush all crap out */
2324 tcflush(fd, TCIOFLUSH);
2329 int reset_terminal(const char *name) {
2332 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2336 r = reset_terminal_fd(fd);
2337 close_nointr_nofail(fd);
2342 int open_terminal(const char *name, int mode) {
2347 * If a TTY is in the process of being closed opening it might
2348 * cause EIO. This is horribly awful, but unlikely to be
2349 * changed in the kernel. Hence we work around this problem by
2350 * retrying a couple of times.
2352 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2356 if ((fd = open(name, mode)) >= 0)
2365 usleep(50 * USEC_PER_MSEC);
2372 if ((r = isatty(fd)) < 0) {
2373 close_nointr_nofail(fd);
2378 close_nointr_nofail(fd);
2385 int flush_fd(int fd) {
2386 struct pollfd pollfd;
2390 pollfd.events = POLLIN;
2397 if ((r = poll(&pollfd, 1, 0)) < 0) {
2408 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2413 if (errno == EAGAIN)
2424 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2425 int fd = -1, notify = -1, r, wd = -1;
2429 /* We use inotify to be notified when the tty is closed. We
2430 * create the watch before checking if we can actually acquire
2431 * it, so that we don't lose any event.
2433 * Note: strictly speaking this actually watches for the
2434 * device being closed, it does *not* really watch whether a
2435 * tty loses its controlling process. However, unless some
2436 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2437 * its tty otherwise this will not become a problem. As long
2438 * as the administrator makes sure not configure any service
2439 * on the same tty as an untrusted user this should not be a
2440 * problem. (Which he probably should not do anyway.) */
2442 if (!fail && !force) {
2443 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2448 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2456 if ((r = flush_fd(notify)) < 0)
2459 /* We pass here O_NOCTTY only so that we can check the return
2460 * value TIOCSCTTY and have a reliable way to figure out if we
2461 * successfully became the controlling process of the tty */
2462 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2465 /* First, try to get the tty */
2466 r = ioctl(fd, TIOCSCTTY, force);
2468 /* Sometimes it makes sense to ignore TIOCSCTTY
2469 * returning EPERM, i.e. when very likely we already
2470 * are have this controlling terminal. */
2471 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2474 if (r < 0 && (force || fail || errno != EPERM)) {
2484 assert(notify >= 0);
2487 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2489 struct inotify_event *e;
2491 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2500 e = (struct inotify_event*) inotify_buffer;
2505 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2510 step = sizeof(struct inotify_event) + e->len;
2511 assert(step <= (size_t) l);
2513 e = (struct inotify_event*) ((uint8_t*) e + step);
2520 /* We close the tty fd here since if the old session
2521 * ended our handle will be dead. It's important that
2522 * we do this after sleeping, so that we don't enter
2523 * an endless loop. */
2524 close_nointr_nofail(fd);
2528 close_nointr_nofail(notify);
2530 if ((r = reset_terminal_fd(fd)) < 0)
2531 log_warning("Failed to reset terminal: %s", strerror(-r));
2537 close_nointr_nofail(fd);
2540 close_nointr_nofail(notify);
2545 int release_terminal(void) {
2547 struct sigaction sa_old, sa_new;
2549 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2552 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2553 * by our own TIOCNOTTY */
2556 sa_new.sa_handler = SIG_IGN;
2557 sa_new.sa_flags = SA_RESTART;
2558 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2560 if (ioctl(fd, TIOCNOTTY) < 0)
2563 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2565 close_nointr_nofail(fd);
2569 int sigaction_many(const struct sigaction *sa, ...) {
2574 while ((sig = va_arg(ap, int)) > 0)
2575 if (sigaction(sig, sa, NULL) < 0)
2582 int ignore_signals(int sig, ...) {
2583 struct sigaction sa;
2588 sa.sa_handler = SIG_IGN;
2589 sa.sa_flags = SA_RESTART;
2591 if (sigaction(sig, &sa, NULL) < 0)
2595 while ((sig = va_arg(ap, int)) > 0)
2596 if (sigaction(sig, &sa, NULL) < 0)
2603 int default_signals(int sig, ...) {
2604 struct sigaction sa;
2609 sa.sa_handler = SIG_DFL;
2610 sa.sa_flags = SA_RESTART;
2612 if (sigaction(sig, &sa, NULL) < 0)
2616 while ((sig = va_arg(ap, int)) > 0)
2617 if (sigaction(sig, &sa, NULL) < 0)
2624 int close_pipe(int p[]) {
2630 a = close_nointr(p[0]);
2635 b = close_nointr(p[1]);
2639 return a < 0 ? a : b;
2642 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2651 while (nbytes > 0) {
2654 if ((k = read(fd, p, nbytes)) <= 0) {
2656 if (k < 0 && errno == EINTR)
2659 if (k < 0 && errno == EAGAIN && do_poll) {
2660 struct pollfd pollfd;
2664 pollfd.events = POLLIN;
2666 if (poll(&pollfd, 1, -1) < 0) {
2670 return n > 0 ? n : -errno;
2673 if (pollfd.revents != POLLIN)
2674 return n > 0 ? n : -EIO;
2679 return n > 0 ? n : (k < 0 ? -errno : 0);
2690 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2699 while (nbytes > 0) {
2702 if ((k = write(fd, p, nbytes)) <= 0) {
2704 if (k < 0 && errno == EINTR)
2707 if (k < 0 && errno == EAGAIN && do_poll) {
2708 struct pollfd pollfd;
2712 pollfd.events = POLLOUT;
2714 if (poll(&pollfd, 1, -1) < 0) {
2718 return n > 0 ? n : -errno;
2721 if (pollfd.revents != POLLOUT)
2722 return n > 0 ? n : -EIO;
2727 return n > 0 ? n : (k < 0 ? -errno : 0);
2738 int path_is_mount_point(const char *t) {
2743 if (lstat(t, &a) < 0) {
2744 if (errno == ENOENT)
2750 if ((r = parent_of_path(t, &parent)) < 0)
2753 r = lstat(parent, &b);
2759 return a.st_dev != b.st_dev;
2762 int parse_usec(const char *t, usec_t *usec) {
2763 static const struct {
2767 { "sec", USEC_PER_SEC },
2768 { "s", USEC_PER_SEC },
2769 { "min", USEC_PER_MINUTE },
2770 { "hr", USEC_PER_HOUR },
2771 { "h", USEC_PER_HOUR },
2772 { "d", USEC_PER_DAY },
2773 { "w", USEC_PER_WEEK },
2774 { "msec", USEC_PER_MSEC },
2775 { "ms", USEC_PER_MSEC },
2776 { "m", USEC_PER_MINUTE },
2779 { "", USEC_PER_SEC },
2795 l = strtoll(p, &e, 10);
2806 e += strspn(e, WHITESPACE);
2808 for (i = 0; i < ELEMENTSOF(table); i++)
2809 if (startswith(e, table[i].suffix)) {
2810 r += (usec_t) l * table[i].usec;
2811 p = e + strlen(table[i].suffix);
2815 if (i >= ELEMENTSOF(table))
2825 int make_stdio(int fd) {
2830 r = dup2(fd, STDIN_FILENO);
2831 s = dup2(fd, STDOUT_FILENO);
2832 t = dup2(fd, STDERR_FILENO);
2835 close_nointr_nofail(fd);
2837 if (r < 0 || s < 0 || t < 0)
2843 int make_null_stdio(void) {
2846 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2849 return make_stdio(null_fd);
2852 bool is_device_path(const char *path) {
2854 /* Returns true on paths that refer to a device, either in
2855 * sysfs or in /dev */
2858 path_startswith(path, "/dev/") ||
2859 path_startswith(path, "/sys/");
2862 int dir_is_empty(const char *path) {
2865 struct dirent buf, *de;
2867 if (!(d = opendir(path)))
2871 if ((r = readdir_r(d, &buf, &de)) > 0) {
2881 if (!ignore_file(de->d_name)) {
2891 unsigned long long random_ull(void) {
2896 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2899 r = loop_read(fd, &ull, sizeof(ull), true);
2900 close_nointr_nofail(fd);
2902 if (r != sizeof(ull))
2908 return random() * RAND_MAX + random();
2911 void rename_process(const char name[8]) {
2914 prctl(PR_SET_NAME, name);
2916 /* This is a like a poor man's setproctitle(). The string
2917 * passed should fit in 7 chars (i.e. the length of
2920 if (program_invocation_name)
2921 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2924 void sigset_add_many(sigset_t *ss, ...) {
2931 while ((sig = va_arg(ap, int)) > 0)
2932 assert_se(sigaddset(ss, sig) == 0);
2936 char* gethostname_malloc(void) {
2939 assert_se(uname(&u) >= 0);
2942 return strdup(u.nodename);
2944 return strdup(u.sysname);
2947 char* getlogname_malloc(void) {
2951 struct passwd pwbuf, *pw = NULL;
2954 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2959 /* Shortcut things to avoid NSS lookups */
2961 return strdup("root");
2963 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2966 if (!(buf = malloc(bufsize)))
2969 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2970 name = strdup(pw->pw_name);
2977 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2983 int getttyname_malloc(int fd, char **r) {
2984 char path[PATH_MAX], *c;
2989 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
2994 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3001 int getttyname_harder(int fd, char **r) {
3005 if ((k = getttyname_malloc(fd, &s)) < 0)
3008 if (streq(s, "tty")) {
3010 return get_ctty(r, NULL);
3017 int get_ctty_devnr(dev_t *d) {
3019 char line[LINE_MAX], *p;
3020 unsigned long ttynr;
3023 if (!(f = fopen("/proc/self/stat", "r")))
3026 if (!(fgets(line, sizeof(line), f))) {
3034 if (!(p = strrchr(line, ')')))
3043 "%*d " /* session */
3052 int get_ctty(char **r, dev_t *_devnr) {
3054 char fn[PATH_MAX], *s, *b, *p;
3059 if ((k = get_ctty_devnr(&devnr)) < 0)
3062 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3065 if ((k = readlink_malloc(fn, &s)) < 0) {
3070 /* This is an ugly hack */
3071 if (major(devnr) == 136) {
3072 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3082 /* Probably something like the ptys which have no
3083 * symlink in /dev/char. Let's return something
3084 * vaguely useful. */
3086 if (!(b = strdup(fn + 5)))
3096 if (startswith(s, "/dev/"))
3098 else if (startswith(s, "../"))
3116 static int rm_rf_children(int fd, bool only_dirs) {
3122 /* This returns the first error we run into, but nevertheless
3125 if (!(d = fdopendir(fd))) {
3126 close_nointr_nofail(fd);
3128 return errno == ENOENT ? 0 : -errno;
3132 struct dirent buf, *de;
3136 if ((r = readdir_r(d, &buf, &de)) != 0) {
3145 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3148 if (de->d_type == DT_UNKNOWN) {
3151 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3152 if (ret == 0 && errno != ENOENT)
3157 is_dir = S_ISDIR(st.st_mode);
3159 is_dir = de->d_type == DT_DIR;
3164 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3165 if (ret == 0 && errno != ENOENT)
3170 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3175 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3176 if (ret == 0 && errno != ENOENT)
3179 } else if (!only_dirs) {
3181 if (unlinkat(fd, de->d_name, 0) < 0) {
3182 if (ret == 0 && errno != ENOENT)
3193 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3199 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3201 if (errno != ENOTDIR)
3204 if (delete_root && !only_dirs)
3205 if (unlink(path) < 0)
3211 r = rm_rf_children(fd, only_dirs);
3214 if (rmdir(path) < 0) {
3222 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3225 /* Under the assumption that we are running privileged we
3226 * first change the access mode and only then hand out
3227 * ownership to avoid a window where access is too open. */
3229 if (chmod(path, mode) < 0)
3232 if (chown(path, uid, gid) < 0)
3238 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3242 /* Allocates the cpuset in the right size */
3245 if (!(r = CPU_ALLOC(n)))
3248 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3249 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3259 if (errno != EINVAL)
3266 void status_vprintf(const char *format, va_list ap) {
3272 /* This independent of logging, as status messages are
3273 * optional and go exclusively to the console. */
3275 if (vasprintf(&s, format, ap) < 0)
3278 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3281 write(fd, s, strlen(s));
3287 close_nointr_nofail(fd);
3290 void status_printf(const char *format, ...) {
3295 va_start(ap, format);
3296 status_vprintf(format, ap);
3300 void status_welcome(void) {
3301 char *pretty_name = NULL, *ansi_color = NULL;
3302 const char *const_pretty = NULL, *const_color = NULL;
3305 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3306 "PRETTY_NAME", &pretty_name,
3307 "ANSI_COLOR", &ansi_color,
3311 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3314 #if defined(TARGET_FEDORA)
3316 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3319 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3323 if (!ansi_color && pretty_name) {
3325 /* This tries to mimic the color magic the old Red Hat sysinit
3328 if (startswith(pretty_name, "Red Hat"))
3329 const_color = "0;31"; /* Red for RHEL */
3330 else if (startswith(pretty_name, "Fedora"))
3331 const_color = "0;34"; /* Blue for Fedora */
3334 #elif defined(TARGET_SUSE)
3337 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3340 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3345 const_color = "0;32"; /* Green for openSUSE */
3347 #elif defined(TARGET_GENTOO)
3350 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3353 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3358 const_color = "1;34"; /* Light Blue for Gentoo */
3360 #elif defined(TARGET_ALTLINUX)
3363 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3366 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3371 const_color = "0;36"; /* Cyan for ALTLinux */
3374 #elif defined(TARGET_DEBIAN)
3379 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3382 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3384 pretty_name = strappend("Debian ", version);
3388 log_warning("Failed to allocate Debian version string.");
3393 const_color = "1;31"; /* Light Red for Debian */
3395 #elif defined(TARGET_UBUNTU)
3397 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3398 "DISTRIB_DESCRIPTION", &pretty_name,
3402 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3406 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3408 #elif defined(TARGET_MANDRIVA)
3413 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3415 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3417 p = strstr(s, " release ");
3421 p[strcspn(p, " ")] = '\0';
3423 /* This corresponds to standard rc.sysinit */
3424 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3425 const_color = "1;36";
3427 log_warning("Failed to allocate Mandriva version string.");
3429 log_warning("Failed to parse /etc/mandriva-release");
3433 #elif defined(TARGET_MEEGO)
3436 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3439 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3444 const_color = "1;35"; /* Bright Magenta for MeeGo */
3447 if (!pretty_name && !const_pretty)
3448 const_pretty = "Linux";
3450 if (!ansi_color && !const_color)
3453 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3454 const_color ? const_color : ansi_color,
3455 const_pretty ? const_pretty : pretty_name);
3461 char *replace_env(const char *format, char **env) {
3468 const char *e, *word = format;
3473 for (e = format; *e; e ++) {
3484 if (!(k = strnappend(r, word, e-word-1)))
3493 } else if (*e == '$') {
3494 if (!(k = strnappend(r, word, e-word)))
3510 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3513 if (!(k = strappend(r, t)))
3526 if (!(k = strnappend(r, word, e-word)))
3537 char **replace_env_argv(char **argv, char **env) {
3539 unsigned k = 0, l = 0;
3541 l = strv_length(argv);
3543 if (!(r = new(char*, l+1)))
3546 STRV_FOREACH(i, argv) {
3548 /* If $FOO appears as single word, replace it by the split up variable */
3549 if ((*i)[0] == '$' && (*i)[1] != '{') {
3554 if ((e = strv_env_get(env, *i+1))) {
3556 if (!(m = strv_split_quoted(e))) {
3567 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3576 memcpy(r + k, m, q * sizeof(char*));
3584 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3585 if (!(r[k++] = replace_env(*i, env))) {
3596 static __thread int parsed_columns = 0;
3599 if (parsed_columns > 0)
3600 return parsed_columns;
3602 if ((e = getenv("COLUMNS")))
3603 parsed_columns = atoi(e);
3605 if (parsed_columns <= 0) {
3609 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3610 parsed_columns = ws.ws_col;
3613 if (parsed_columns <= 0)
3614 parsed_columns = 80;
3616 return parsed_columns;
3619 int running_in_chroot(void) {
3625 /* Only works as root */
3627 if (stat("/proc/1/root", &a) < 0)
3630 if (stat("/", &b) < 0)
3634 a.st_dev != b.st_dev ||
3635 a.st_ino != b.st_ino;
3638 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3643 assert(percent <= 100);
3644 assert(length >= 3);
3648 if (l <= 3 || l <= length)
3651 if (!(r = new0(char, length+1)))
3654 x = (length * percent) / 100;
3664 s + l - (length - x - 3),
3670 int touch(const char *path) {
3675 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3678 close_nointr_nofail(fd);
3682 char *unquote(const char *s, const char* quotes) {
3686 if ((l = strlen(s)) < 2)
3689 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3690 return strndup(s+1, l-2);
3695 char *normalize_env_assignment(const char *s) {
3696 char *name, *value, *p, *r;
3701 if (!(r = strdup(s)))
3707 if (!(name = strndup(s, p - s)))
3710 if (!(p = strdup(p+1))) {
3715 value = unquote(strstrip(p), QUOTES);
3723 if (asprintf(&r, "%s=%s", name, value) < 0)
3732 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3739 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3751 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3758 if ((r = wait_for_terminate(pid, &status)) < 0) {
3759 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3763 if (status.si_code == CLD_EXITED) {
3764 if (status.si_status != 0) {
3765 log_warning("%s failed with error code %i.", name, status.si_status);
3766 return status.si_status;
3769 log_debug("%s succeeded.", name);
3772 } else if (status.si_code == CLD_KILLED ||
3773 status.si_code == CLD_DUMPED) {
3775 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3779 log_warning("%s failed due to unknown reason.", name);
3786 /* Make sure nobody waits for us on a socket anymore */
3787 close_all_fds(NULL, 0);
3795 bool null_or_empty(struct stat *st) {
3798 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3801 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3807 DIR *xopendirat(int fd, const char *name, int flags) {
3811 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3814 if (!(d = fdopendir(nfd))) {
3815 close_nointr_nofail(nfd);
3822 int signal_from_string_try_harder(const char *s) {
3826 if ((signo = signal_from_string(s)) <= 0)
3827 if (startswith(s, "SIG"))
3828 return signal_from_string(s+3);
3833 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3839 if (!dual_timestamp_is_set(t))
3842 fprintf(f, "%s=%llu %llu\n",
3844 (unsigned long long) t->realtime,
3845 (unsigned long long) t->monotonic);
3848 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3849 unsigned long long a, b;
3854 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3855 log_debug("Failed to parse finish timestamp value %s", value);
3862 char *fstab_node_to_udev_node(const char *p) {
3866 /* FIXME: to follow udev's logic 100% we need to leave valid
3867 * UTF8 chars unescaped */
3869 if (startswith(p, "LABEL=")) {
3871 if (!(u = unquote(p+6, "\"\'")))
3874 t = xescape(u, "/ ");
3880 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3889 if (startswith(p, "UUID=")) {
3891 if (!(u = unquote(p+5, "\"\'")))
3894 t = xescape(u, "/ ");
3900 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
3912 void filter_environ(const char *prefix) {
3919 for (i = 0, j = 0; environ[i]; i++) {
3921 if (startswith(environ[i], prefix))
3924 environ[j++] = environ[i];
3930 bool tty_is_vc(const char *tty) {
3933 if (startswith(tty, "/dev/"))
3936 return startswith(tty, "tty") &&
3937 tty[3] >= '0' && tty[3] <= '9';
3940 const char *default_term_for_tty(const char *tty) {
3941 char *active = NULL;
3946 if (startswith(tty, "/dev/"))
3949 /* Resolve where /dev/console is pointing when determining
3951 if (streq(tty, "console"))
3952 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3953 /* If multiple log outputs are configured the
3954 * last one is what /dev/console points to */
3955 if ((tty = strrchr(active, ' ')))
3961 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3967 /* Returns a short identifier for the various VM implementations */
3968 int detect_vm(const char **id) {
3970 #if defined(__i386__) || defined(__x86_64__)
3972 /* Both CPUID and DMI are x86 specific interfaces... */
3974 static const char *const dmi_vendors[] = {
3975 "/sys/class/dmi/id/sys_vendor",
3976 "/sys/class/dmi/id/board_vendor",
3977 "/sys/class/dmi/id/bios_vendor"
3980 static const char dmi_vendor_table[] =
3982 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3983 "VMware\0" "vmware\0"
3985 "Microsoft Corporation\0" "microsoft\0"
3986 "innotek GmbH\0" "oracle\0"
3988 "Bochs\0" "bochs\0";
3990 static const char cpuid_vendor_table[] =
3991 "XenVMMXenVMM\0" "xen\0"
3992 "KVMKVMKVM\0" "kvm\0"
3993 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3994 "VMwareVMware\0" "vmware\0"
3995 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3996 "Microsoft Hv\0" "microsoft\0";
4007 /* http://lwn.net/Articles/301888/ */
4010 #if defined (__i386__)
4013 #elif defined (__amd64__)
4018 /* First detect whether there is a hypervisor */
4020 __asm__ __volatile__ (
4021 /* ebx/rbx is being used for PIC! */
4022 " push %%"REG_b" \n\t"
4024 " pop %%"REG_b" \n\t"
4026 : "=a" (eax), "=c" (ecx)
4030 hypervisor = !!(ecx & 0x80000000U);
4034 /* There is a hypervisor, see what it is */
4036 __asm__ __volatile__ (
4037 /* ebx/rbx is being used for PIC! */
4038 " push %%"REG_b" \n\t"
4040 " mov %%ebx, %1 \n\t"
4041 " pop %%"REG_b" \n\t"
4043 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4047 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4048 if (streq(sig.text, j)) {
4057 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4060 const char *found = NULL;
4062 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4069 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4070 if (startswith(s, j))
4093 int detect_container(const char **id) {
4096 /* Unfortunately many of these operations require root access
4097 * in one way or another */
4102 if (running_in_chroot() > 0) {
4110 /* /proc/vz exists in container and outside of the container,
4111 * /proc/bc only outside of the container. */
4112 if (access("/proc/vz", F_OK) >= 0 &&
4113 access("/proc/bc", F_OK) < 0) {
4121 if ((f = fopen("/proc/self/cgroup", "r"))) {
4124 char line[LINE_MAX], *p;
4126 if (!fgets(line, sizeof(line), f))
4129 if (!(p = strchr(strstrip(line), ':')))
4132 if (strncmp(p, ":ns:", 4))
4135 if (!streq(p, ":ns:/")) {
4151 /* Returns a short identifier for the various VM/container implementations */
4152 int detect_virtualization(const char **id) {
4153 static __thread const char *cached_id = NULL;
4159 if (cached_id == (const char*) -1)
4168 if ((r = detect_container(&_id)) != 0)
4171 r = detect_vm(&_id);
4180 cached_id = (const char*) -1;
4185 bool dirent_is_file(struct dirent *de) {
4188 if (ignore_file(de->d_name))
4191 if (de->d_type != DT_REG &&
4192 de->d_type != DT_LNK &&
4193 de->d_type != DT_UNKNOWN)
4199 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4202 Hashmap *pids = NULL;
4206 /* Executes all binaries in a directory in parallel and waits
4207 * until all they all finished. */
4210 if (!(_d = opendir(directory))) {
4212 if (errno == ENOENT)
4215 log_error("Failed to enumerate directory %s: %m", directory);
4222 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4223 log_error("Failed to allocate set.");
4227 while ((de = readdir(d))) {
4232 if (!dirent_is_file(de))
4235 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4236 log_error("Out of memory");
4240 if ((pid = fork()) < 0) {
4241 log_error("Failed to fork: %m");
4260 log_error("Failed to execute %s: %m", path);
4261 _exit(EXIT_FAILURE);
4264 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4266 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4267 log_error("Failed to add PID to set: %s", strerror(-k));
4272 while (!hashmap_isempty(pids)) {
4277 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4282 log_error("waitid() failed: %m");
4286 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4287 if (!is_clean_exit(si.si_code, si.si_status)) {
4288 if (si.si_code == CLD_EXITED)
4289 log_error("%s exited with exit status %i.", path, si.si_status);
4291 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4293 log_debug("%s exited successfully.", path);
4304 hashmap_free_free(pids);
4307 int kill_and_sigcont(pid_t pid, int sig) {
4310 r = kill(pid, sig) < 0 ? -errno : 0;
4318 bool nulstr_contains(const char*nulstr, const char *needle) {
4324 NULSTR_FOREACH(i, nulstr)
4325 if (streq(i, needle))
4331 bool plymouth_running(void) {
4332 return access("/run/plymouth/pid", F_OK) >= 0;
4335 void parse_syslog_priority(char **p, int *priority) {
4336 int a = 0, b = 0, c = 0;
4346 if (!strchr(*p, '>'))
4349 if ((*p)[2] == '>') {
4350 c = undecchar((*p)[1]);
4352 } else if ((*p)[3] == '>') {
4353 b = undecchar((*p)[1]);
4354 c = undecchar((*p)[2]);
4356 } else if ((*p)[4] == '>') {
4357 a = undecchar((*p)[1]);
4358 b = undecchar((*p)[2]);
4359 c = undecchar((*p)[3]);
4364 if (a < 0 || b < 0 || c < 0)
4367 *priority = a*100+b*10+c;
4371 int have_effective_cap(int value) {
4373 cap_flag_value_t fv;
4376 if (!(cap = cap_get_proc()))
4379 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4388 char* strshorten(char *s, size_t l) {
4397 static bool hostname_valid_char(char c) {
4399 (c >= 'a' && c <= 'z') ||
4400 (c >= 'A' && c <= 'Z') ||
4401 (c >= '0' && c <= '9') ||
4407 bool hostname_is_valid(const char *s) {
4413 for (p = s; *p; p++)
4414 if (!hostname_valid_char(*p))
4417 if (p-s > HOST_NAME_MAX)
4423 char* hostname_cleanup(char *s) {
4426 for (p = s, d = s; *p; p++)
4427 if ((*p >= 'a' && *p <= 'z') ||
4428 (*p >= 'A' && *p <= 'Z') ||
4429 (*p >= '0' && *p <= '9') ||
4437 strshorten(s, HOST_NAME_MAX);
4441 int pipe_eof(int fd) {
4442 struct pollfd pollfd;
4447 pollfd.events = POLLIN|POLLHUP;
4449 r = poll(&pollfd, 1, 0);
4456 return pollfd.revents & POLLHUP;
4459 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4470 t = new(char, strlen(path) + 1 + 6 + 1);
4474 fn = file_name_from_path(path);
4478 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4480 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4486 f = fdopen(fd, "we");
4499 int terminal_vhangup_fd(int fd) {
4502 if (ioctl(fd, TIOCVHANGUP) < 0)
4508 int terminal_vhangup(const char *name) {
4511 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4515 r = terminal_vhangup_fd(fd);
4516 close_nointr_nofail(fd);
4521 int vt_disallocate(const char *name) {
4525 /* Deallocate the VT if possible. If not possible
4526 * (i.e. because it is the active one), at least clear it
4527 * entirely (including the scrollback buffer) */
4529 if (!startswith(name, "/dev/"))
4532 if (!tty_is_vc(name)) {
4533 /* So this is not a VT. I guess we cannot deallocate
4534 * it then. But let's at least clear the screen */
4536 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4540 loop_write(fd, "\033[H\033[2J", 7, false); /* clear screen */
4541 close_nointr_nofail(fd);
4546 if (!startswith(name, "/dev/tty"))
4549 r = safe_atou(name+8, &u);
4556 /* Try to deallocate */
4557 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4561 r = ioctl(fd, VT_DISALLOCATE, u);
4562 close_nointr_nofail(fd);
4570 /* Couldn't deallocate, so let's clear it fully with
4572 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4576 /* Requires Linux 2.6.40 */
4577 loop_write(fd, "\033[H\033[3J", 7, false); /* clear screen including scrollback */
4578 close_nointr_nofail(fd);
4584 static int file_is_conf(const struct dirent *d, const char *suffix) {
4587 if (ignore_file(d->d_name))
4590 if (d->d_type != DT_REG &&
4591 d->d_type != DT_LNK &&
4592 d->d_type != DT_UNKNOWN)
4595 return endswith(d->d_name, suffix);
4598 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4603 dir = opendir(path);
4605 if (errno == ENOENT)
4610 for (de = readdir(dir); de; de = readdir(dir)) {
4614 if (!file_is_conf(de, suffix))
4617 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4622 f = canonicalize_file_name(p);
4624 log_error("Failed to canonicalize file name '%s': %m", p);
4630 log_debug("found: %s\n", f);
4631 base = f + strlen(path) + 1;
4632 if (hashmap_put(h, base, f) <= 0)
4641 static int base_cmp(const void *a, const void *b) {
4642 const char *s1, *s2;
4644 s1 = *(char * const *)a;
4645 s2 = *(char * const *)b;
4646 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4649 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4652 char **files = NULL;
4658 dirs = strv_new_ap(dir, ap);
4664 if (!strv_path_canonicalize(dirs)) {
4668 if (!strv_uniq(dirs)) {
4673 fh = hashmap_new(string_hash_func, string_compare_func);
4679 STRV_FOREACH(p, dirs) {
4680 if (files_add(fh, *p, suffix) < 0) {
4681 log_error("Failed to search for files.");
4687 files = hashmap_get_strv(fh);
4688 if (files == NULL) {
4689 log_error("Failed to compose list of files.");
4694 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4703 bool hwclock_is_localtime(void) {
4705 char line[LINE_MAX];
4709 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4715 f = fopen("/etc/adjtime", "re");
4717 if (fgets(line, sizeof(line), f) &&
4718 fgets(line, sizeof(line), f) &&
4719 fgets(line, sizeof(line), f) ) {
4720 if (!strcmp(line, "LOCAL\n"))
4728 int hwclock_apply_localtime_delta(void) {
4729 const struct timeval *tv_null = NULL;
4735 gettimeofday(&tv, NULL);
4736 tm = localtime(&tv.tv_sec);
4737 minuteswest = tm->tm_gmtoff / 60;
4739 tz.tz_minuteswest = -minuteswest;
4740 tz.tz_dsttime = 0; /* DST_NONE*/
4743 * If the hardware clock does not run in UTC, but in local time:
4744 * The very first time we set the kernel's timezone, it will warp
4745 * the clock so that it runs in UTC instead of local time.
4747 if (settimeofday(tv_null, &tz) < 0)
4753 int hwclock_get_time(struct tm *tm) {
4757 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4760 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4767 int hwclock_set_time(const struct tm *tm) {
4771 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4774 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4781 static const char *const ioprio_class_table[] = {
4782 [IOPRIO_CLASS_NONE] = "none",
4783 [IOPRIO_CLASS_RT] = "realtime",
4784 [IOPRIO_CLASS_BE] = "best-effort",
4785 [IOPRIO_CLASS_IDLE] = "idle"
4788 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
4790 static const char *const sigchld_code_table[] = {
4791 [CLD_EXITED] = "exited",
4792 [CLD_KILLED] = "killed",
4793 [CLD_DUMPED] = "dumped",
4794 [CLD_TRAPPED] = "trapped",
4795 [CLD_STOPPED] = "stopped",
4796 [CLD_CONTINUED] = "continued",
4799 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4801 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4802 [LOG_FAC(LOG_KERN)] = "kern",
4803 [LOG_FAC(LOG_USER)] = "user",
4804 [LOG_FAC(LOG_MAIL)] = "mail",
4805 [LOG_FAC(LOG_DAEMON)] = "daemon",
4806 [LOG_FAC(LOG_AUTH)] = "auth",
4807 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4808 [LOG_FAC(LOG_LPR)] = "lpr",
4809 [LOG_FAC(LOG_NEWS)] = "news",
4810 [LOG_FAC(LOG_UUCP)] = "uucp",
4811 [LOG_FAC(LOG_CRON)] = "cron",
4812 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4813 [LOG_FAC(LOG_FTP)] = "ftp",
4814 [LOG_FAC(LOG_LOCAL0)] = "local0",
4815 [LOG_FAC(LOG_LOCAL1)] = "local1",
4816 [LOG_FAC(LOG_LOCAL2)] = "local2",
4817 [LOG_FAC(LOG_LOCAL3)] = "local3",
4818 [LOG_FAC(LOG_LOCAL4)] = "local4",
4819 [LOG_FAC(LOG_LOCAL5)] = "local5",
4820 [LOG_FAC(LOG_LOCAL6)] = "local6",
4821 [LOG_FAC(LOG_LOCAL7)] = "local7"
4824 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
4826 static const char *const log_level_table[] = {
4827 [LOG_EMERG] = "emerg",
4828 [LOG_ALERT] = "alert",
4829 [LOG_CRIT] = "crit",
4831 [LOG_WARNING] = "warning",
4832 [LOG_NOTICE] = "notice",
4833 [LOG_INFO] = "info",
4834 [LOG_DEBUG] = "debug"
4837 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4839 static const char* const sched_policy_table[] = {
4840 [SCHED_OTHER] = "other",
4841 [SCHED_BATCH] = "batch",
4842 [SCHED_IDLE] = "idle",
4843 [SCHED_FIFO] = "fifo",
4847 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4849 static const char* const rlimit_table[] = {
4850 [RLIMIT_CPU] = "LimitCPU",
4851 [RLIMIT_FSIZE] = "LimitFSIZE",
4852 [RLIMIT_DATA] = "LimitDATA",
4853 [RLIMIT_STACK] = "LimitSTACK",
4854 [RLIMIT_CORE] = "LimitCORE",
4855 [RLIMIT_RSS] = "LimitRSS",
4856 [RLIMIT_NOFILE] = "LimitNOFILE",
4857 [RLIMIT_AS] = "LimitAS",
4858 [RLIMIT_NPROC] = "LimitNPROC",
4859 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4860 [RLIMIT_LOCKS] = "LimitLOCKS",
4861 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4862 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4863 [RLIMIT_NICE] = "LimitNICE",
4864 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4865 [RLIMIT_RTTIME] = "LimitRTTIME"
4868 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4870 static const char* const ip_tos_table[] = {
4871 [IPTOS_LOWDELAY] = "low-delay",
4872 [IPTOS_THROUGHPUT] = "throughput",
4873 [IPTOS_RELIABILITY] = "reliability",
4874 [IPTOS_LOWCOST] = "low-cost",
4877 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
4879 static const char *const signal_table[] = {
4896 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4907 [SIGVTALRM] = "VTALRM",
4909 [SIGWINCH] = "WINCH",
4915 DEFINE_STRING_TABLE_LOOKUP(signal, int);