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"
68 char **saved_argv = NULL;
70 size_t page_size(void) {
71 static __thread size_t pgsz = 0;
77 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
84 bool streq_ptr(const char *a, const char *b) {
86 /* Like streq(), but tries to make sense of NULL pointers */
97 usec_t now(clockid_t clock_id) {
100 assert_se(clock_gettime(clock_id, &ts) == 0);
102 return timespec_load(&ts);
105 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
108 ts->realtime = now(CLOCK_REALTIME);
109 ts->monotonic = now(CLOCK_MONOTONIC);
114 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
123 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
125 ts->monotonic = now(CLOCK_MONOTONIC);
127 if ((int64_t) ts->monotonic > delta)
128 ts->monotonic -= delta;
136 usec_t timespec_load(const struct timespec *ts) {
140 (usec_t) ts->tv_sec * USEC_PER_SEC +
141 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
144 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
147 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
148 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
153 usec_t timeval_load(const struct timeval *tv) {
157 (usec_t) tv->tv_sec * USEC_PER_SEC +
158 (usec_t) tv->tv_usec;
161 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
164 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
165 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
170 bool endswith(const char *s, const char *postfix) {
177 pl = strlen(postfix);
185 return memcmp(s + sl - pl, postfix, pl) == 0;
188 bool startswith(const char *s, const char *prefix) {
203 return memcmp(s, prefix, pl) == 0;
206 bool startswith_no_case(const char *s, const char *prefix) {
222 for(i = 0; i < pl; ++i) {
223 if (tolower(s[i]) != tolower(prefix[i]))
230 bool first_word(const char *s, const char *word) {
245 if (memcmp(s, word, wl) != 0)
249 strchr(WHITESPACE, s[wl]);
252 int close_nointr(int fd) {
267 void close_nointr_nofail(int fd) {
268 int saved_errno = errno;
270 /* like close_nointr() but cannot fail, and guarantees errno
273 assert_se(close_nointr(fd) == 0);
278 void close_many(const int fds[], unsigned n_fd) {
281 for (i = 0; i < n_fd; i++)
282 close_nointr_nofail(fds[i]);
285 int parse_boolean(const char *v) {
288 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
290 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
296 int parse_pid(const char *s, pid_t* ret_pid) {
297 unsigned long ul = 0;
304 if ((r = safe_atolu(s, &ul)) < 0)
309 if ((unsigned long) pid != ul)
319 int safe_atou(const char *s, unsigned *ret_u) {
327 l = strtoul(s, &x, 0);
329 if (!x || *x || errno)
330 return errno ? -errno : -EINVAL;
332 if ((unsigned long) (unsigned) l != l)
335 *ret_u = (unsigned) l;
339 int safe_atoi(const char *s, int *ret_i) {
347 l = strtol(s, &x, 0);
349 if (!x || *x || errno)
350 return errno ? -errno : -EINVAL;
352 if ((long) (int) l != l)
359 int safe_atollu(const char *s, long long unsigned *ret_llu) {
361 unsigned long long l;
367 l = strtoull(s, &x, 0);
369 if (!x || *x || errno)
370 return errno ? -errno : -EINVAL;
376 int safe_atolli(const char *s, long long int *ret_lli) {
384 l = strtoll(s, &x, 0);
386 if (!x || *x || errno)
387 return errno ? -errno : -EINVAL;
393 /* Split a string into words. */
394 char *split(const char *c, size_t *l, const char *separator, char **state) {
397 current = *state ? *state : (char*) c;
399 if (!*current || *c == 0)
402 current += strspn(current, separator);
403 *l = strcspn(current, separator);
406 return (char*) current;
409 /* Split a string into words, but consider strings enclosed in '' and
410 * "" as words even if they include spaces. */
411 char *split_quoted(const char *c, size_t *l, char **state) {
413 bool escaped = false;
415 current = *state ? *state : (char*) c;
417 if (!*current || *c == 0)
420 current += strspn(current, WHITESPACE);
422 if (*current == '\'') {
425 for (e = current; *e; e++) {
435 *state = *e == 0 ? e : e+1;
436 } else if (*current == '\"') {
439 for (e = current; *e; e++) {
449 *state = *e == 0 ? e : e+1;
451 for (e = current; *e; e++) {
456 else if (strchr(WHITESPACE, *e))
463 return (char*) current;
466 char **split_path_and_make_absolute(const char *p) {
470 if (!(l = strv_split(p, ":")))
473 if (!strv_path_make_absolute_cwd(l)) {
481 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
484 char fn[PATH_MAX], line[LINE_MAX], *p;
490 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
493 if (!(f = fopen(fn, "r")))
496 if (!(fgets(line, sizeof(line), f))) {
504 /* Let's skip the pid and comm fields. The latter is enclosed
505 * in () but does not escape any () in its value, so let's
506 * skip over it manually */
508 if (!(p = strrchr(line, ')')))
519 if ((long unsigned) (pid_t) ppid != ppid)
522 *_ppid = (pid_t) ppid;
527 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
530 char fn[PATH_MAX], line[LINE_MAX], *p;
535 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
538 if (!(f = fopen(fn, "r")))
541 if (!(fgets(line, sizeof(line), f))) {
549 /* Let's skip the pid and comm fields. The latter is enclosed
550 * in () but does not escape any () in its value, so let's
551 * skip over it manually */
553 if (!(p = strrchr(line, ')')))
574 "%*d " /* priority */
576 "%*d " /* num_threads */
577 "%*d " /* itrealvalue */
578 "%llu " /* starttime */,
585 int write_one_line_file(const char *fn, const char *line) {
592 if (!(f = fopen(fn, "we")))
596 if (fputs(line, f) < 0) {
601 if (!endswith(line, "\n"))
619 int fchmod_umask(int fd, mode_t m) {
624 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
630 int write_one_line_file_atomic(const char *fn, const char *line) {
638 r = fopen_temporary(fn, &f, &p);
642 fchmod_umask(fileno(f), 0644);
645 if (fputs(line, f) < 0) {
650 if (!endswith(line, "\n"))
661 if (rename(p, fn) < 0)
677 int read_one_line_file(const char *fn, char **line) {
680 char t[LINE_MAX], *c;
685 if (!(f = fopen(fn, "re")))
688 if (!(fgets(t, sizeof(t), f))) {
693 if (!(c = strdup(t))) {
708 int read_full_file(const char *fn, char **contents, size_t *size) {
715 if (!(f = fopen(fn, "re")))
718 if (fstat(fileno(f), &st) < 0) {
724 if (st.st_size > 4*1024*1024) {
729 n = st.st_size > 0 ? st.st_size : LINE_MAX;
736 if (!(t = realloc(buf, n+1))) {
742 k = fread(buf + l, 1, n - l, f);
757 if (n > 4*1024*1024) {
765 else if (!(buf = calloc(1, 1))) {
787 const char *separator, ...) {
795 if ((r = read_full_file(fname, &contents, NULL)) < 0)
800 const char *key = NULL;
802 p += strspn(p, separator);
803 p += strspn(p, WHITESPACE);
808 if (!strchr(COMMENTS, *p)) {
812 va_start(ap, separator);
813 while ((key = va_arg(ap, char *))) {
817 value = va_arg(ap, char **);
820 if (strncmp(p, key, n) != 0 ||
825 n = strcspn(p, separator);
828 strchr(QUOTES, p[0]) &&
830 v = strndup(p+1, n-2);
841 /* return empty value strings as NULL */
858 p += strcspn(p, separator);
877 if (!(f = fopen(fname, "re")))
881 char l[LINE_MAX], *p, *u;
884 if (!fgets(l, sizeof(l), f)) {
897 if (strchr(COMMENTS, *p))
900 if (!(u = normalize_env_assignment(p))) {
901 log_error("Out of memory");
906 t = strv_append(m, u);
910 log_error("Out of memory");
933 int write_env_file(const char *fname, char **l) {
938 r = fopen_temporary(fname, &f, &p);
942 fchmod_umask(fileno(f), 0644);
958 if (rename(p, fname) < 0)
973 char *truncate_nl(char *s) {
976 s[strcspn(s, NEWLINE)] = 0;
980 int get_process_name(pid_t pid, char **name) {
987 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
990 r = read_one_line_file(p, name);
999 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1007 assert(max_length > 0);
1010 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1019 if (!(r = new(char, max_length))) {
1026 while ((c = getc(f)) != EOF) {
1048 size_t n = MIN(left-1, 3U);
1049 memcpy(k, "...", n);
1056 /* Kernel threads have no argv[] */
1063 if ((h = get_process_name(pid, &t)) < 0)
1066 h = asprintf(&r, "[%s]", t);
1077 char *strnappend(const char *s, const char *suffix, size_t b) {
1085 return strndup(suffix, b);
1095 if (!(r = new(char, a+b+1)))
1099 memcpy(r+a, suffix, b);
1105 char *strappend(const char *s, const char *suffix) {
1106 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1109 int readlink_malloc(const char *p, char **r) {
1119 if (!(c = new(char, l)))
1122 if ((n = readlink(p, c, l-1)) < 0) {
1128 if ((size_t) n < l-1) {
1139 int readlink_and_make_absolute(const char *p, char **r) {
1146 if ((j = readlink_malloc(p, &target)) < 0)
1149 k = file_in_same_dir(p, target);
1159 int parent_of_path(const char *path, char **_r) {
1160 const char *e, *a = NULL, *b = NULL, *p;
1170 for (e = path; *e; e++) {
1172 if (!slash && *e == '/') {
1176 } else if (slash && *e != '/')
1191 r = strndup(path, p-path);
1201 char *file_name_from_path(const char *p) {
1206 if ((r = strrchr(p, '/')))
1212 bool path_is_absolute(const char *p) {
1218 bool is_path(const char *p) {
1220 return !!strchr(p, '/');
1223 char *path_make_absolute(const char *p, const char *prefix) {
1228 /* Makes every item in the list an absolute path by prepending
1229 * the prefix, if specified and necessary */
1231 if (path_is_absolute(p) || !prefix)
1234 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1240 char *path_make_absolute_cwd(const char *p) {
1245 /* Similar to path_make_absolute(), but prefixes with the
1246 * current working directory. */
1248 if (path_is_absolute(p))
1251 if (!(cwd = get_current_dir_name()))
1254 r = path_make_absolute(p, cwd);
1260 char **strv_path_make_absolute_cwd(char **l) {
1263 /* Goes through every item in the string list and makes it
1264 * absolute. This works in place and won't rollback any
1265 * changes on failure. */
1267 STRV_FOREACH(s, l) {
1270 if (!(t = path_make_absolute_cwd(*s)))
1280 char **strv_path_canonicalize(char **l) {
1283 bool enomem = false;
1285 if (strv_isempty(l))
1288 /* Goes through every item in the string list and canonicalize
1289 * the path. This works in place and won't rollback any
1290 * changes on failure. */
1292 STRV_FOREACH(s, l) {
1295 t = path_make_absolute_cwd(*s);
1304 u = canonicalize_file_name(t);
1308 if (errno == ENOMEM || !errno)
1325 char **strv_path_remove_empty(char **l) {
1331 for (f = t = l; *f; f++) {
1333 if (dir_is_empty(*f) > 0) {
1345 int reset_all_signal_handlers(void) {
1348 for (sig = 1; sig < _NSIG; sig++) {
1349 struct sigaction sa;
1351 if (sig == SIGKILL || sig == SIGSTOP)
1355 sa.sa_handler = SIG_DFL;
1356 sa.sa_flags = SA_RESTART;
1358 /* On Linux the first two RT signals are reserved by
1359 * glibc, and sigaction() will return EINVAL for them. */
1360 if ((sigaction(sig, &sa, NULL) < 0))
1361 if (errno != EINVAL)
1368 char *strstrip(char *s) {
1371 /* Drops trailing whitespace. Modifies the string in
1372 * place. Returns pointer to first non-space character */
1374 s += strspn(s, WHITESPACE);
1376 for (e = s; *e; e++)
1377 if (!strchr(WHITESPACE, *e))
1388 char *delete_chars(char *s, const char *bad) {
1391 /* Drops all whitespace, regardless where in the string */
1393 for (f = s, t = s; *f; f++) {
1394 if (strchr(bad, *f))
1405 char *file_in_same_dir(const char *path, const char *filename) {
1412 /* This removes the last component of path and appends
1413 * filename, unless the latter is absolute anyway or the
1416 if (path_is_absolute(filename))
1417 return strdup(filename);
1419 if (!(e = strrchr(path, '/')))
1420 return strdup(filename);
1422 k = strlen(filename);
1423 if (!(r = new(char, e-path+1+k+1)))
1426 memcpy(r, path, e-path+1);
1427 memcpy(r+(e-path)+1, filename, k+1);
1432 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1435 if (label_mkdir(path, mode) >= 0)
1436 if (chmod_and_chown(path, mode, uid, gid) < 0)
1439 if (lstat(path, &st) < 0)
1442 if ((st.st_mode & 0777) != mode ||
1445 !S_ISDIR(st.st_mode)) {
1454 int mkdir_parents(const char *path, mode_t mode) {
1459 /* Creates every parent directory in the path except the last
1462 p = path + strspn(path, "/");
1467 e = p + strcspn(p, "/");
1468 p = e + strspn(e, "/");
1470 /* Is this the last component? If so, then we're
1475 if (!(t = strndup(path, e - path)))
1478 r = label_mkdir(t, mode);
1481 if (r < 0 && errno != EEXIST)
1486 int mkdir_p(const char *path, mode_t mode) {
1491 if ((r = mkdir_parents(path, mode)) < 0)
1494 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1500 int rmdir_parents(const char *path, const char *stop) {
1509 /* Skip trailing slashes */
1510 while (l > 0 && path[l-1] == '/')
1516 /* Skip last component */
1517 while (l > 0 && path[l-1] != '/')
1520 /* Skip trailing slashes */
1521 while (l > 0 && path[l-1] == '/')
1527 if (!(t = strndup(path, l)))
1530 if (path_startswith(stop, t)) {
1539 if (errno != ENOENT)
1547 char hexchar(int x) {
1548 static const char table[16] = "0123456789abcdef";
1550 return table[x & 15];
1553 int unhexchar(char c) {
1555 if (c >= '0' && c <= '9')
1558 if (c >= 'a' && c <= 'f')
1559 return c - 'a' + 10;
1561 if (c >= 'A' && c <= 'F')
1562 return c - 'A' + 10;
1567 char octchar(int x) {
1568 return '0' + (x & 7);
1571 int unoctchar(char c) {
1573 if (c >= '0' && c <= '7')
1579 char decchar(int x) {
1580 return '0' + (x % 10);
1583 int undecchar(char c) {
1585 if (c >= '0' && c <= '9')
1591 char *cescape(const char *s) {
1597 /* Does C style string escaping. */
1599 if (!(r = new(char, strlen(s)*4 + 1)))
1602 for (f = s, t = r; *f; f++)
1648 /* For special chars we prefer octal over
1649 * hexadecimal encoding, simply because glib's
1650 * g_strescape() does the same */
1651 if ((*f < ' ') || (*f >= 127)) {
1653 *(t++) = octchar((unsigned char) *f >> 6);
1654 *(t++) = octchar((unsigned char) *f >> 3);
1655 *(t++) = octchar((unsigned char) *f);
1666 char *cunescape_length(const char *s, size_t length) {
1672 /* Undoes C style string escaping */
1674 if (!(r = new(char, length+1)))
1677 for (f = s, t = r; f < s + length; f++) {
1720 /* This is an extension of the XDG syntax files */
1725 /* hexadecimal encoding */
1728 if ((a = unhexchar(f[1])) < 0 ||
1729 (b = unhexchar(f[2])) < 0) {
1730 /* Invalid escape code, let's take it literal then */
1734 *(t++) = (char) ((a << 4) | b);
1749 /* octal encoding */
1752 if ((a = unoctchar(f[0])) < 0 ||
1753 (b = unoctchar(f[1])) < 0 ||
1754 (c = unoctchar(f[2])) < 0) {
1755 /* Invalid escape code, let's take it literal then */
1759 *(t++) = (char) ((a << 6) | (b << 3) | c);
1767 /* premature end of string.*/
1772 /* Invalid escape code, let's take it literal then */
1784 char *cunescape(const char *s) {
1785 return cunescape_length(s, strlen(s));
1788 char *xescape(const char *s, const char *bad) {
1792 /* Escapes all chars in bad, in addition to \ and all special
1793 * chars, in \xFF style escaping. May be reversed with
1796 if (!(r = new(char, strlen(s)*4+1)))
1799 for (f = s, t = r; *f; f++) {
1801 if ((*f < ' ') || (*f >= 127) ||
1802 (*f == '\\') || strchr(bad, *f)) {
1805 *(t++) = hexchar(*f >> 4);
1806 *(t++) = hexchar(*f);
1816 char *bus_path_escape(const char *s) {
1822 /* Escapes all chars that D-Bus' object path cannot deal
1823 * with. Can be reverse with bus_path_unescape() */
1825 if (!(r = new(char, strlen(s)*3+1)))
1828 for (f = s, t = r; *f; f++) {
1830 if (!(*f >= 'A' && *f <= 'Z') &&
1831 !(*f >= 'a' && *f <= 'z') &&
1832 !(*f >= '0' && *f <= '9')) {
1834 *(t++) = hexchar(*f >> 4);
1835 *(t++) = hexchar(*f);
1845 char *bus_path_unescape(const char *f) {
1850 if (!(r = strdup(f)))
1853 for (t = r; *f; f++) {
1858 if ((a = unhexchar(f[1])) < 0 ||
1859 (b = unhexchar(f[2])) < 0) {
1860 /* Invalid escape code, let's take it literal then */
1863 *(t++) = (char) ((a << 4) | b);
1875 char *path_kill_slashes(char *path) {
1879 /* Removes redundant inner and trailing slashes. Modifies the
1880 * passed string in-place.
1882 * ///foo///bar/ becomes /foo/bar
1885 for (f = path, t = path; *f; f++) {
1900 /* Special rule, if we are talking of the root directory, a
1901 trailing slash is good */
1903 if (t == path && slash)
1910 bool path_startswith(const char *path, const char *prefix) {
1914 if ((path[0] == '/') != (prefix[0] == '/'))
1920 path += strspn(path, "/");
1921 prefix += strspn(prefix, "/");
1929 a = strcspn(path, "/");
1930 b = strcspn(prefix, "/");
1935 if (memcmp(path, prefix, a) != 0)
1943 bool path_equal(const char *a, const char *b) {
1947 if ((a[0] == '/') != (b[0] == '/'))
1953 a += strspn(a, "/");
1954 b += strspn(b, "/");
1956 if (*a == 0 && *b == 0)
1959 if (*a == 0 || *b == 0)
1962 j = strcspn(a, "/");
1963 k = strcspn(b, "/");
1968 if (memcmp(a, b, j) != 0)
1976 char *ascii_strlower(char *t) {
1981 for (p = t; *p; p++)
1982 if (*p >= 'A' && *p <= 'Z')
1983 *p = *p - 'A' + 'a';
1988 bool ignore_file(const char *filename) {
1992 filename[0] == '.' ||
1993 streq(filename, "lost+found") ||
1994 streq(filename, "aquota.user") ||
1995 streq(filename, "aquota.group") ||
1996 endswith(filename, "~") ||
1997 endswith(filename, ".rpmnew") ||
1998 endswith(filename, ".rpmsave") ||
1999 endswith(filename, ".rpmorig") ||
2000 endswith(filename, ".dpkg-old") ||
2001 endswith(filename, ".dpkg-new") ||
2002 endswith(filename, ".swp");
2005 int fd_nonblock(int fd, bool nonblock) {
2010 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2014 flags |= O_NONBLOCK;
2016 flags &= ~O_NONBLOCK;
2018 if (fcntl(fd, F_SETFL, flags) < 0)
2024 int fd_cloexec(int fd, bool cloexec) {
2029 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2033 flags |= FD_CLOEXEC;
2035 flags &= ~FD_CLOEXEC;
2037 if (fcntl(fd, F_SETFD, flags) < 0)
2043 int close_all_fds(const int except[], unsigned n_except) {
2048 if (!(d = opendir("/proc/self/fd")))
2051 while ((de = readdir(d))) {
2054 if (ignore_file(de->d_name))
2057 if (safe_atoi(de->d_name, &fd) < 0)
2058 /* Let's better ignore this, just in case */
2072 for (i = 0; i < n_except; i++)
2073 if (except[i] == fd) {
2082 if (close_nointr(fd) < 0) {
2083 /* Valgrind has its own FD and doesn't want to have it closed */
2084 if (errno != EBADF && r == 0)
2093 bool chars_intersect(const char *a, const char *b) {
2096 /* Returns true if any of the chars in a are in b. */
2097 for (p = a; *p; p++)
2104 char *format_timestamp(char *buf, size_t l, usec_t t) {
2114 sec = (time_t) (t / USEC_PER_SEC);
2116 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2122 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2125 n = now(CLOCK_REALTIME);
2127 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2132 if (d >= USEC_PER_YEAR)
2133 snprintf(buf, l, "%llu years and %llu months ago",
2134 (unsigned long long) (d / USEC_PER_YEAR),
2135 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2136 else if (d >= USEC_PER_MONTH)
2137 snprintf(buf, l, "%llu months and %llu days ago",
2138 (unsigned long long) (d / USEC_PER_MONTH),
2139 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2140 else if (d >= USEC_PER_WEEK)
2141 snprintf(buf, l, "%llu weeks and %llu days ago",
2142 (unsigned long long) (d / USEC_PER_WEEK),
2143 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2144 else if (d >= 2*USEC_PER_DAY)
2145 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2146 else if (d >= 25*USEC_PER_HOUR)
2147 snprintf(buf, l, "1 day and %lluh ago",
2148 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2149 else if (d >= 6*USEC_PER_HOUR)
2150 snprintf(buf, l, "%lluh ago",
2151 (unsigned long long) (d / USEC_PER_HOUR));
2152 else if (d >= USEC_PER_HOUR)
2153 snprintf(buf, l, "%lluh %llumin ago",
2154 (unsigned long long) (d / USEC_PER_HOUR),
2155 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2156 else if (d >= 5*USEC_PER_MINUTE)
2157 snprintf(buf, l, "%llumin ago",
2158 (unsigned long long) (d / USEC_PER_MINUTE));
2159 else if (d >= USEC_PER_MINUTE)
2160 snprintf(buf, l, "%llumin %llus ago",
2161 (unsigned long long) (d / USEC_PER_MINUTE),
2162 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2163 else if (d >= USEC_PER_SEC)
2164 snprintf(buf, l, "%llus ago",
2165 (unsigned long long) (d / USEC_PER_SEC));
2166 else if (d >= USEC_PER_MSEC)
2167 snprintf(buf, l, "%llums ago",
2168 (unsigned long long) (d / USEC_PER_MSEC));
2170 snprintf(buf, l, "%lluus ago",
2171 (unsigned long long) d);
2173 snprintf(buf, l, "now");
2179 char *format_timespan(char *buf, size_t l, usec_t t) {
2180 static const struct {
2184 { "w", USEC_PER_WEEK },
2185 { "d", USEC_PER_DAY },
2186 { "h", USEC_PER_HOUR },
2187 { "min", USEC_PER_MINUTE },
2188 { "s", USEC_PER_SEC },
2189 { "ms", USEC_PER_MSEC },
2199 if (t == (usec_t) -1)
2203 snprintf(p, l, "0");
2208 /* The result of this function can be parsed with parse_usec */
2210 for (i = 0; i < ELEMENTSOF(table); i++) {
2214 if (t < table[i].usec)
2220 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2221 n = MIN((size_t) k, l);
2234 bool fstype_is_network(const char *fstype) {
2235 static const char * const table[] = {
2247 for (i = 0; i < ELEMENTSOF(table); i++)
2248 if (streq(table[i], fstype))
2257 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2262 TIOCL_GETKMSGREDIRECT,
2266 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2269 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2272 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2275 close_nointr_nofail(r);
2279 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2280 struct termios old_termios, new_termios;
2282 char line[LINE_MAX];
2287 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2288 new_termios = old_termios;
2290 new_termios.c_lflag &= ~ICANON;
2291 new_termios.c_cc[VMIN] = 1;
2292 new_termios.c_cc[VTIME] = 0;
2294 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2297 k = fread(&c, 1, 1, f);
2299 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2305 *need_nl = c != '\n';
2312 if (!(fgets(line, sizeof(line), f)))
2317 if (strlen(line) != 1)
2327 int ask(char *ret, const char *replies, const char *text, ...) {
2334 on_tty = isatty(STDOUT_FILENO);
2340 bool need_nl = true;
2343 fputs("\x1B[1m", stdout);
2350 fputs("\x1B[0m", stdout);
2354 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2356 if (r == -EBADMSG) {
2357 puts("Bad input, please try again.");
2368 if (strchr(replies, c)) {
2373 puts("Read unexpected character, please try again.");
2377 int reset_terminal_fd(int fd) {
2378 struct termios termios;
2382 /* Set terminal to some sane defaults */
2386 /* We leave locked terminal attributes untouched, so that
2387 * Plymouth may set whatever it wants to set, and we don't
2388 * interfere with that. */
2390 /* Disable exclusive mode, just in case */
2391 ioctl(fd, TIOCNXCL);
2393 /* Enable console unicode mode */
2395 ioctl(fd, KDSKBMODE, &arg);
2397 if (tcgetattr(fd, &termios) < 0) {
2402 /* We only reset the stuff that matters to the software. How
2403 * hardware is set up we don't touch assuming that somebody
2404 * else will do that for us */
2406 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2407 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2408 termios.c_oflag |= ONLCR;
2409 termios.c_cflag |= CREAD;
2410 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2412 termios.c_cc[VINTR] = 03; /* ^C */
2413 termios.c_cc[VQUIT] = 034; /* ^\ */
2414 termios.c_cc[VERASE] = 0177;
2415 termios.c_cc[VKILL] = 025; /* ^X */
2416 termios.c_cc[VEOF] = 04; /* ^D */
2417 termios.c_cc[VSTART] = 021; /* ^Q */
2418 termios.c_cc[VSTOP] = 023; /* ^S */
2419 termios.c_cc[VSUSP] = 032; /* ^Z */
2420 termios.c_cc[VLNEXT] = 026; /* ^V */
2421 termios.c_cc[VWERASE] = 027; /* ^W */
2422 termios.c_cc[VREPRINT] = 022; /* ^R */
2423 termios.c_cc[VEOL] = 0;
2424 termios.c_cc[VEOL2] = 0;
2426 termios.c_cc[VTIME] = 0;
2427 termios.c_cc[VMIN] = 1;
2429 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2433 /* Just in case, flush all crap out */
2434 tcflush(fd, TCIOFLUSH);
2439 int reset_terminal(const char *name) {
2442 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2446 r = reset_terminal_fd(fd);
2447 close_nointr_nofail(fd);
2452 int open_terminal(const char *name, int mode) {
2457 * If a TTY is in the process of being closed opening it might
2458 * cause EIO. This is horribly awful, but unlikely to be
2459 * changed in the kernel. Hence we work around this problem by
2460 * retrying a couple of times.
2462 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2466 if ((fd = open(name, mode)) >= 0)
2475 usleep(50 * USEC_PER_MSEC);
2482 if ((r = isatty(fd)) < 0) {
2483 close_nointr_nofail(fd);
2488 close_nointr_nofail(fd);
2495 int flush_fd(int fd) {
2496 struct pollfd pollfd;
2500 pollfd.events = POLLIN;
2507 if ((r = poll(&pollfd, 1, 0)) < 0) {
2518 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2523 if (errno == EAGAIN)
2534 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2535 int fd = -1, notify = -1, r, wd = -1;
2539 /* We use inotify to be notified when the tty is closed. We
2540 * create the watch before checking if we can actually acquire
2541 * it, so that we don't lose any event.
2543 * Note: strictly speaking this actually watches for the
2544 * device being closed, it does *not* really watch whether a
2545 * tty loses its controlling process. However, unless some
2546 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2547 * its tty otherwise this will not become a problem. As long
2548 * as the administrator makes sure not configure any service
2549 * on the same tty as an untrusted user this should not be a
2550 * problem. (Which he probably should not do anyway.) */
2552 if (!fail && !force) {
2553 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2558 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2566 if ((r = flush_fd(notify)) < 0)
2569 /* We pass here O_NOCTTY only so that we can check the return
2570 * value TIOCSCTTY and have a reliable way to figure out if we
2571 * successfully became the controlling process of the tty */
2572 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2575 /* First, try to get the tty */
2576 r = ioctl(fd, TIOCSCTTY, force);
2578 /* Sometimes it makes sense to ignore TIOCSCTTY
2579 * returning EPERM, i.e. when very likely we already
2580 * are have this controlling terminal. */
2581 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2584 if (r < 0 && (force || fail || errno != EPERM)) {
2594 assert(notify >= 0);
2597 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2599 struct inotify_event *e;
2601 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2610 e = (struct inotify_event*) inotify_buffer;
2615 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2620 step = sizeof(struct inotify_event) + e->len;
2621 assert(step <= (size_t) l);
2623 e = (struct inotify_event*) ((uint8_t*) e + step);
2630 /* We close the tty fd here since if the old session
2631 * ended our handle will be dead. It's important that
2632 * we do this after sleeping, so that we don't enter
2633 * an endless loop. */
2634 close_nointr_nofail(fd);
2638 close_nointr_nofail(notify);
2640 if ((r = reset_terminal_fd(fd)) < 0)
2641 log_warning("Failed to reset terminal: %s", strerror(-r));
2647 close_nointr_nofail(fd);
2650 close_nointr_nofail(notify);
2655 int release_terminal(void) {
2657 struct sigaction sa_old, sa_new;
2659 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2662 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2663 * by our own TIOCNOTTY */
2666 sa_new.sa_handler = SIG_IGN;
2667 sa_new.sa_flags = SA_RESTART;
2668 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2670 if (ioctl(fd, TIOCNOTTY) < 0)
2673 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2675 close_nointr_nofail(fd);
2679 int sigaction_many(const struct sigaction *sa, ...) {
2684 while ((sig = va_arg(ap, int)) > 0)
2685 if (sigaction(sig, sa, NULL) < 0)
2692 int ignore_signals(int sig, ...) {
2693 struct sigaction sa;
2698 sa.sa_handler = SIG_IGN;
2699 sa.sa_flags = SA_RESTART;
2701 if (sigaction(sig, &sa, NULL) < 0)
2705 while ((sig = va_arg(ap, int)) > 0)
2706 if (sigaction(sig, &sa, NULL) < 0)
2713 int default_signals(int sig, ...) {
2714 struct sigaction sa;
2719 sa.sa_handler = SIG_DFL;
2720 sa.sa_flags = SA_RESTART;
2722 if (sigaction(sig, &sa, NULL) < 0)
2726 while ((sig = va_arg(ap, int)) > 0)
2727 if (sigaction(sig, &sa, NULL) < 0)
2734 int close_pipe(int p[]) {
2740 a = close_nointr(p[0]);
2745 b = close_nointr(p[1]);
2749 return a < 0 ? a : b;
2752 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2761 while (nbytes > 0) {
2764 if ((k = read(fd, p, nbytes)) <= 0) {
2766 if (k < 0 && errno == EINTR)
2769 if (k < 0 && errno == EAGAIN && do_poll) {
2770 struct pollfd pollfd;
2774 pollfd.events = POLLIN;
2776 if (poll(&pollfd, 1, -1) < 0) {
2780 return n > 0 ? n : -errno;
2783 if (pollfd.revents != POLLIN)
2784 return n > 0 ? n : -EIO;
2789 return n > 0 ? n : (k < 0 ? -errno : 0);
2800 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2809 while (nbytes > 0) {
2812 if ((k = write(fd, p, nbytes)) <= 0) {
2814 if (k < 0 && errno == EINTR)
2817 if (k < 0 && errno == EAGAIN && do_poll) {
2818 struct pollfd pollfd;
2822 pollfd.events = POLLOUT;
2824 if (poll(&pollfd, 1, -1) < 0) {
2828 return n > 0 ? n : -errno;
2831 if (pollfd.revents != POLLOUT)
2832 return n > 0 ? n : -EIO;
2837 return n > 0 ? n : (k < 0 ? -errno : 0);
2848 int path_is_mount_point(const char *t) {
2853 if (lstat(t, &a) < 0) {
2854 if (errno == ENOENT)
2860 if ((r = parent_of_path(t, &parent)) < 0)
2863 r = lstat(parent, &b);
2869 return a.st_dev != b.st_dev;
2872 int parse_usec(const char *t, usec_t *usec) {
2873 static const struct {
2877 { "sec", USEC_PER_SEC },
2878 { "s", USEC_PER_SEC },
2879 { "min", USEC_PER_MINUTE },
2880 { "hr", USEC_PER_HOUR },
2881 { "h", USEC_PER_HOUR },
2882 { "d", USEC_PER_DAY },
2883 { "w", USEC_PER_WEEK },
2884 { "msec", USEC_PER_MSEC },
2885 { "ms", USEC_PER_MSEC },
2886 { "m", USEC_PER_MINUTE },
2889 { "", USEC_PER_SEC },
2905 l = strtoll(p, &e, 10);
2916 e += strspn(e, WHITESPACE);
2918 for (i = 0; i < ELEMENTSOF(table); i++)
2919 if (startswith(e, table[i].suffix)) {
2920 r += (usec_t) l * table[i].usec;
2921 p = e + strlen(table[i].suffix);
2925 if (i >= ELEMENTSOF(table))
2935 int make_stdio(int fd) {
2940 r = dup2(fd, STDIN_FILENO);
2941 s = dup2(fd, STDOUT_FILENO);
2942 t = dup2(fd, STDERR_FILENO);
2945 close_nointr_nofail(fd);
2947 if (r < 0 || s < 0 || t < 0)
2953 int make_null_stdio(void) {
2956 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2959 return make_stdio(null_fd);
2962 bool is_device_path(const char *path) {
2964 /* Returns true on paths that refer to a device, either in
2965 * sysfs or in /dev */
2968 path_startswith(path, "/dev/") ||
2969 path_startswith(path, "/sys/");
2972 int dir_is_empty(const char *path) {
2975 struct dirent buf, *de;
2977 if (!(d = opendir(path)))
2981 if ((r = readdir_r(d, &buf, &de)) > 0) {
2991 if (!ignore_file(de->d_name)) {
3001 unsigned long long random_ull(void) {
3006 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3009 r = loop_read(fd, &ull, sizeof(ull), true);
3010 close_nointr_nofail(fd);
3012 if (r != sizeof(ull))
3018 return random() * RAND_MAX + random();
3021 void rename_process(const char name[8]) {
3024 prctl(PR_SET_NAME, name);
3026 /* This is a like a poor man's setproctitle(). The string
3027 * passed should fit in 7 chars (i.e. the length of
3030 if (program_invocation_name)
3031 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3033 if (saved_argc > 0) {
3037 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3039 for (i = 1; i < saved_argc; i++) {
3043 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3048 void sigset_add_many(sigset_t *ss, ...) {
3055 while ((sig = va_arg(ap, int)) > 0)
3056 assert_se(sigaddset(ss, sig) == 0);
3060 char* gethostname_malloc(void) {
3063 assert_se(uname(&u) >= 0);
3066 return strdup(u.nodename);
3068 return strdup(u.sysname);
3071 char* getlogname_malloc(void) {
3075 struct passwd pwbuf, *pw = NULL;
3078 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3083 /* Shortcut things to avoid NSS lookups */
3085 return strdup("root");
3087 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3090 if (!(buf = malloc(bufsize)))
3093 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3094 name = strdup(pw->pw_name);
3101 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3107 int getttyname_malloc(int fd, char **r) {
3108 char path[PATH_MAX], *c;
3113 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3118 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3125 int getttyname_harder(int fd, char **r) {
3129 if ((k = getttyname_malloc(fd, &s)) < 0)
3132 if (streq(s, "tty")) {
3134 return get_ctty(0, NULL, r);
3141 int get_ctty_devnr(pid_t pid, dev_t *d) {
3143 char line[LINE_MAX], *p, *fn;
3144 unsigned long ttynr;
3147 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3150 f = fopen(fn, "re");
3155 if (!fgets(line, sizeof(line), f)) {
3163 p = strrchr(line, ')');
3173 "%*d " /* session */
3182 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3184 char fn[PATH_MAX], *s, *b, *p;
3189 k = get_ctty_devnr(pid, &devnr);
3193 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3196 if ((k = readlink_malloc(fn, &s)) < 0) {
3201 /* This is an ugly hack */
3202 if (major(devnr) == 136) {
3203 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3213 /* Probably something like the ptys which have no
3214 * symlink in /dev/char. Let's return something
3215 * vaguely useful. */
3217 if (!(b = strdup(fn + 5)))
3227 if (startswith(s, "/dev/"))
3229 else if (startswith(s, "../"))
3247 static int rm_rf_children(int fd, bool only_dirs) {
3253 /* This returns the first error we run into, but nevertheless
3256 if (!(d = fdopendir(fd))) {
3257 close_nointr_nofail(fd);
3259 return errno == ENOENT ? 0 : -errno;
3263 struct dirent buf, *de;
3267 if ((r = readdir_r(d, &buf, &de)) != 0) {
3276 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3279 if (de->d_type == DT_UNKNOWN) {
3282 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3283 if (ret == 0 && errno != ENOENT)
3288 is_dir = S_ISDIR(st.st_mode);
3290 is_dir = de->d_type == DT_DIR;
3295 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3296 if (ret == 0 && errno != ENOENT)
3301 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3306 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3307 if (ret == 0 && errno != ENOENT)
3310 } else if (!only_dirs) {
3312 if (unlinkat(fd, de->d_name, 0) < 0) {
3313 if (ret == 0 && errno != ENOENT)
3324 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3330 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3332 if (errno != ENOTDIR)
3335 if (delete_root && !only_dirs)
3336 if (unlink(path) < 0)
3342 r = rm_rf_children(fd, only_dirs);
3345 if (rmdir(path) < 0) {
3353 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3356 /* Under the assumption that we are running privileged we
3357 * first change the access mode and only then hand out
3358 * ownership to avoid a window where access is too open. */
3360 if (chmod(path, mode) < 0)
3363 if (chown(path, uid, gid) < 0)
3369 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3373 /* Allocates the cpuset in the right size */
3376 if (!(r = CPU_ALLOC(n)))
3379 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3380 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3390 if (errno != EINVAL)
3397 void status_vprintf(const char *format, va_list ap) {
3403 /* This independent of logging, as status messages are
3404 * optional and go exclusively to the console. */
3406 if (vasprintf(&s, format, ap) < 0)
3409 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3412 write(fd, s, strlen(s));
3418 close_nointr_nofail(fd);
3421 void status_printf(const char *format, ...) {
3426 va_start(ap, format);
3427 status_vprintf(format, ap);
3431 void status_welcome(void) {
3432 char *pretty_name = NULL, *ansi_color = NULL;
3433 const char *const_pretty = NULL, *const_color = NULL;
3436 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3437 "PRETTY_NAME", &pretty_name,
3438 "ANSI_COLOR", &ansi_color,
3442 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3445 #if defined(TARGET_FEDORA)
3447 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3450 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3454 if (!ansi_color && pretty_name) {
3456 /* This tries to mimic the color magic the old Red Hat sysinit
3459 if (startswith(pretty_name, "Red Hat"))
3460 const_color = "0;31"; /* Red for RHEL */
3461 else if (startswith(pretty_name, "Fedora"))
3462 const_color = "0;34"; /* Blue for Fedora */
3465 #elif defined(TARGET_SUSE)
3468 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3471 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3476 const_color = "0;32"; /* Green for openSUSE */
3478 #elif defined(TARGET_GENTOO)
3481 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3484 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3489 const_color = "1;34"; /* Light Blue for Gentoo */
3491 #elif defined(TARGET_ALTLINUX)
3494 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3497 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3502 const_color = "0;36"; /* Cyan for ALTLinux */
3505 #elif defined(TARGET_DEBIAN)
3510 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3513 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3515 pretty_name = strappend("Debian ", version);
3519 log_warning("Failed to allocate Debian version string.");
3524 const_color = "1;31"; /* Light Red for Debian */
3526 #elif defined(TARGET_UBUNTU)
3528 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3529 "DISTRIB_DESCRIPTION", &pretty_name,
3533 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3537 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3539 #elif defined(TARGET_MANDRIVA)
3544 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3546 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3548 p = strstr(s, " release ");
3552 p[strcspn(p, " ")] = '\0';
3554 /* This corresponds to standard rc.sysinit */
3555 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3556 const_color = "1;36";
3558 log_warning("Failed to allocate Mandriva version string.");
3560 log_warning("Failed to parse /etc/mandriva-release");
3564 #elif defined(TARGET_MEEGO)
3567 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3570 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3575 const_color = "1;35"; /* Bright Magenta for MeeGo */
3578 if (!pretty_name && !const_pretty)
3579 const_pretty = "Linux";
3581 if (!ansi_color && !const_color)
3584 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3585 const_color ? const_color : ansi_color,
3586 const_pretty ? const_pretty : pretty_name);
3592 char *replace_env(const char *format, char **env) {
3599 const char *e, *word = format;
3604 for (e = format; *e; e ++) {
3615 if (!(k = strnappend(r, word, e-word-1)))
3624 } else if (*e == '$') {
3625 if (!(k = strnappend(r, word, e-word)))
3641 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3644 if (!(k = strappend(r, t)))
3657 if (!(k = strnappend(r, word, e-word)))
3668 char **replace_env_argv(char **argv, char **env) {
3670 unsigned k = 0, l = 0;
3672 l = strv_length(argv);
3674 if (!(r = new(char*, l+1)))
3677 STRV_FOREACH(i, argv) {
3679 /* If $FOO appears as single word, replace it by the split up variable */
3680 if ((*i)[0] == '$' && (*i)[1] != '{') {
3685 if ((e = strv_env_get(env, *i+1))) {
3687 if (!(m = strv_split_quoted(e))) {
3698 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3707 memcpy(r + k, m, q * sizeof(char*));
3715 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3716 if (!(r[k++] = replace_env(*i, env))) {
3727 static __thread int parsed_columns = 0;
3730 if (parsed_columns > 0)
3731 return parsed_columns;
3733 if ((e = getenv("COLUMNS")))
3734 parsed_columns = atoi(e);
3736 if (parsed_columns <= 0) {
3740 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3741 parsed_columns = ws.ws_col;
3744 if (parsed_columns <= 0)
3745 parsed_columns = 80;
3747 return parsed_columns;
3750 int running_in_chroot(void) {
3756 /* Only works as root */
3758 if (stat("/proc/1/root", &a) < 0)
3761 if (stat("/", &b) < 0)
3765 a.st_dev != b.st_dev ||
3766 a.st_ino != b.st_ino;
3769 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3774 assert(percent <= 100);
3775 assert(length >= 3);
3779 if (l <= 3 || l <= length)
3782 if (!(r = new0(char, length+1)))
3785 x = (length * percent) / 100;
3795 s + l - (length - x - 3),
3801 int touch(const char *path) {
3806 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3809 close_nointr_nofail(fd);
3813 char *unquote(const char *s, const char* quotes) {
3817 if ((l = strlen(s)) < 2)
3820 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3821 return strndup(s+1, l-2);
3826 char *normalize_env_assignment(const char *s) {
3827 char *name, *value, *p, *r;
3832 if (!(r = strdup(s)))
3838 if (!(name = strndup(s, p - s)))
3841 if (!(p = strdup(p+1))) {
3846 value = unquote(strstrip(p), QUOTES);
3854 if (asprintf(&r, "%s=%s", name, value) < 0)
3863 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3870 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3882 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3889 if ((r = wait_for_terminate(pid, &status)) < 0) {
3890 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3894 if (status.si_code == CLD_EXITED) {
3895 if (status.si_status != 0) {
3896 log_warning("%s failed with error code %i.", name, status.si_status);
3897 return status.si_status;
3900 log_debug("%s succeeded.", name);
3903 } else if (status.si_code == CLD_KILLED ||
3904 status.si_code == CLD_DUMPED) {
3906 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3910 log_warning("%s failed due to unknown reason.", name);
3917 /* Make sure nobody waits for us on a socket anymore */
3918 close_all_fds(NULL, 0);
3926 bool null_or_empty(struct stat *st) {
3929 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3932 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3938 DIR *xopendirat(int fd, const char *name, int flags) {
3942 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3945 if (!(d = fdopendir(nfd))) {
3946 close_nointr_nofail(nfd);
3953 int signal_from_string_try_harder(const char *s) {
3957 if ((signo = signal_from_string(s)) <= 0)
3958 if (startswith(s, "SIG"))
3959 return signal_from_string(s+3);
3964 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3970 if (!dual_timestamp_is_set(t))
3973 fprintf(f, "%s=%llu %llu\n",
3975 (unsigned long long) t->realtime,
3976 (unsigned long long) t->monotonic);
3979 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3980 unsigned long long a, b;
3985 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3986 log_debug("Failed to parse finish timestamp value %s", value);
3993 char *fstab_node_to_udev_node(const char *p) {
3997 /* FIXME: to follow udev's logic 100% we need to leave valid
3998 * UTF8 chars unescaped */
4000 if (startswith(p, "LABEL=")) {
4002 if (!(u = unquote(p+6, "\"\'")))
4005 t = xescape(u, "/ ");
4011 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4020 if (startswith(p, "UUID=")) {
4022 if (!(u = unquote(p+5, "\"\'")))
4025 t = xescape(u, "/ ");
4031 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4043 void filter_environ(const char *prefix) {
4050 for (i = 0, j = 0; environ[i]; i++) {
4052 if (startswith(environ[i], prefix))
4055 environ[j++] = environ[i];
4061 bool tty_is_vc(const char *tty) {
4064 if (startswith(tty, "/dev/"))
4067 return vtnr_from_tty(tty) >= 0;
4070 int vtnr_from_tty(const char *tty) {
4075 if (startswith(tty, "/dev/"))
4078 if (!startswith(tty, "tty") )
4081 if (tty[3] < '0' || tty[3] > '9')
4084 r = safe_atoi(tty+3, &i);
4088 if (i < 0 || i > 63)
4094 const char *default_term_for_tty(const char *tty) {
4095 char *active = NULL;
4100 if (startswith(tty, "/dev/"))
4103 /* Resolve where /dev/console is pointing when determining
4105 if (streq(tty, "console"))
4106 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4107 /* If multiple log outputs are configured the
4108 * last one is what /dev/console points to */
4109 if ((tty = strrchr(active, ' ')))
4115 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4121 /* Returns a short identifier for the various VM implementations */
4122 int detect_vm(const char **id) {
4124 #if defined(__i386__) || defined(__x86_64__)
4126 /* Both CPUID and DMI are x86 specific interfaces... */
4128 static const char *const dmi_vendors[] = {
4129 "/sys/class/dmi/id/sys_vendor",
4130 "/sys/class/dmi/id/board_vendor",
4131 "/sys/class/dmi/id/bios_vendor"
4134 static const char dmi_vendor_table[] =
4136 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4137 "VMware\0" "vmware\0"
4139 "Microsoft Corporation\0" "microsoft\0"
4140 "innotek GmbH\0" "oracle\0"
4142 "Bochs\0" "bochs\0";
4144 static const char cpuid_vendor_table[] =
4145 "XenVMMXenVMM\0" "xen\0"
4146 "KVMKVMKVM\0" "kvm\0"
4147 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4148 "VMwareVMware\0" "vmware\0"
4149 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4150 "Microsoft Hv\0" "microsoft\0";
4161 /* http://lwn.net/Articles/301888/ */
4164 #if defined (__i386__)
4167 #elif defined (__amd64__)
4172 /* First detect whether there is a hypervisor */
4174 __asm__ __volatile__ (
4175 /* ebx/rbx is being used for PIC! */
4176 " push %%"REG_b" \n\t"
4178 " pop %%"REG_b" \n\t"
4180 : "=a" (eax), "=c" (ecx)
4184 hypervisor = !!(ecx & 0x80000000U);
4188 /* There is a hypervisor, see what it is */
4190 __asm__ __volatile__ (
4191 /* ebx/rbx is being used for PIC! */
4192 " push %%"REG_b" \n\t"
4194 " mov %%ebx, %1 \n\t"
4195 " pop %%"REG_b" \n\t"
4197 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4201 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4202 if (streq(sig.text, j)) {
4211 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4214 const char *found = NULL;
4216 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4223 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4224 if (startswith(s, j))
4247 int detect_container(const char **id) {
4250 /* Unfortunately many of these operations require root access
4251 * in one way or another */
4256 if (running_in_chroot() > 0) {
4264 /* /proc/vz exists in container and outside of the container,
4265 * /proc/bc only outside of the container. */
4266 if (access("/proc/vz", F_OK) >= 0 &&
4267 access("/proc/bc", F_OK) < 0) {
4275 if ((f = fopen("/proc/self/cgroup", "r"))) {
4278 char line[LINE_MAX], *p;
4280 if (!fgets(line, sizeof(line), f))
4283 if (!(p = strchr(strstrip(line), ':')))
4286 if (strncmp(p, ":ns:", 4))
4289 if (!streq(p, ":ns:/")) {
4305 /* Returns a short identifier for the various VM/container implementations */
4306 int detect_virtualization(const char **id) {
4307 static __thread const char *cached_id = NULL;
4313 if (cached_id == (const char*) -1)
4322 if ((r = detect_container(&_id)) != 0)
4325 r = detect_vm(&_id);
4334 cached_id = (const char*) -1;
4339 bool dirent_is_file(struct dirent *de) {
4342 if (ignore_file(de->d_name))
4345 if (de->d_type != DT_REG &&
4346 de->d_type != DT_LNK &&
4347 de->d_type != DT_UNKNOWN)
4353 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4356 Hashmap *pids = NULL;
4360 /* Executes all binaries in a directory in parallel and waits
4361 * until all they all finished. */
4364 if (!(_d = opendir(directory))) {
4366 if (errno == ENOENT)
4369 log_error("Failed to enumerate directory %s: %m", directory);
4376 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4377 log_error("Failed to allocate set.");
4381 while ((de = readdir(d))) {
4386 if (!dirent_is_file(de))
4389 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4390 log_error("Out of memory");
4394 if ((pid = fork()) < 0) {
4395 log_error("Failed to fork: %m");
4414 log_error("Failed to execute %s: %m", path);
4415 _exit(EXIT_FAILURE);
4418 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4420 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4421 log_error("Failed to add PID to set: %s", strerror(-k));
4426 while (!hashmap_isempty(pids)) {
4431 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4436 log_error("waitid() failed: %m");
4440 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4441 if (!is_clean_exit(si.si_code, si.si_status)) {
4442 if (si.si_code == CLD_EXITED)
4443 log_error("%s exited with exit status %i.", path, si.si_status);
4445 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4447 log_debug("%s exited successfully.", path);
4458 hashmap_free_free(pids);
4461 int kill_and_sigcont(pid_t pid, int sig) {
4464 r = kill(pid, sig) < 0 ? -errno : 0;
4472 bool nulstr_contains(const char*nulstr, const char *needle) {
4478 NULSTR_FOREACH(i, nulstr)
4479 if (streq(i, needle))
4485 bool plymouth_running(void) {
4486 return access("/run/plymouth/pid", F_OK) >= 0;
4489 void parse_syslog_priority(char **p, int *priority) {
4490 int a = 0, b = 0, c = 0;
4500 if (!strchr(*p, '>'))
4503 if ((*p)[2] == '>') {
4504 c = undecchar((*p)[1]);
4506 } else if ((*p)[3] == '>') {
4507 b = undecchar((*p)[1]);
4508 c = undecchar((*p)[2]);
4510 } else if ((*p)[4] == '>') {
4511 a = undecchar((*p)[1]);
4512 b = undecchar((*p)[2]);
4513 c = undecchar((*p)[3]);
4518 if (a < 0 || b < 0 || c < 0)
4521 *priority = a*100+b*10+c;
4525 int have_effective_cap(int value) {
4527 cap_flag_value_t fv;
4530 if (!(cap = cap_get_proc()))
4533 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4542 char* strshorten(char *s, size_t l) {
4551 static bool hostname_valid_char(char c) {
4553 (c >= 'a' && c <= 'z') ||
4554 (c >= 'A' && c <= 'Z') ||
4555 (c >= '0' && c <= '9') ||
4561 bool hostname_is_valid(const char *s) {
4567 for (p = s; *p; p++)
4568 if (!hostname_valid_char(*p))
4571 if (p-s > HOST_NAME_MAX)
4577 char* hostname_cleanup(char *s) {
4580 for (p = s, d = s; *p; p++)
4581 if ((*p >= 'a' && *p <= 'z') ||
4582 (*p >= 'A' && *p <= 'Z') ||
4583 (*p >= '0' && *p <= '9') ||
4591 strshorten(s, HOST_NAME_MAX);
4595 int pipe_eof(int fd) {
4596 struct pollfd pollfd;
4601 pollfd.events = POLLIN|POLLHUP;
4603 r = poll(&pollfd, 1, 0);
4610 return pollfd.revents & POLLHUP;
4613 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4624 t = new(char, strlen(path) + 1 + 6 + 1);
4628 fn = file_name_from_path(path);
4632 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4634 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4640 f = fdopen(fd, "we");
4653 int terminal_vhangup_fd(int fd) {
4656 if (ioctl(fd, TIOCVHANGUP) < 0)
4662 int terminal_vhangup(const char *name) {
4665 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4669 r = terminal_vhangup_fd(fd);
4670 close_nointr_nofail(fd);
4675 int vt_disallocate(const char *name) {
4679 /* Deallocate the VT if possible. If not possible
4680 * (i.e. because it is the active one), at least clear it
4681 * entirely (including the scrollback buffer) */
4683 if (!startswith(name, "/dev/"))
4686 if (!tty_is_vc(name)) {
4687 /* So this is not a VT. I guess we cannot deallocate
4688 * it then. But let's at least clear the screen */
4690 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4695 "\033[r" /* clear scrolling region */
4696 "\033[H" /* move home */
4697 "\033[2J", /* clear screen */
4699 close_nointr_nofail(fd);
4704 if (!startswith(name, "/dev/tty"))
4707 r = safe_atou(name+8, &u);
4714 /* Try to deallocate */
4715 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4719 r = ioctl(fd, VT_DISALLOCATE, u);
4720 close_nointr_nofail(fd);
4728 /* Couldn't deallocate, so let's clear it fully with
4730 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4735 "\033[r" /* clear scrolling region */
4736 "\033[H" /* move home */
4737 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4739 close_nointr_nofail(fd);
4745 static int file_is_conf(const struct dirent *d, const char *suffix) {
4748 if (ignore_file(d->d_name))
4751 if (d->d_type != DT_REG &&
4752 d->d_type != DT_LNK &&
4753 d->d_type != DT_UNKNOWN)
4756 return endswith(d->d_name, suffix);
4759 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4764 dir = opendir(path);
4766 if (errno == ENOENT)
4771 for (de = readdir(dir); de; de = readdir(dir)) {
4775 if (!file_is_conf(de, suffix))
4778 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4783 f = canonicalize_file_name(p);
4785 log_error("Failed to canonicalize file name '%s': %m", p);
4791 log_debug("found: %s\n", f);
4792 base = f + strlen(path) + 1;
4793 if (hashmap_put(h, base, f) <= 0)
4802 static int base_cmp(const void *a, const void *b) {
4803 const char *s1, *s2;
4805 s1 = *(char * const *)a;
4806 s2 = *(char * const *)b;
4807 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4810 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4813 char **files = NULL;
4819 dirs = strv_new_ap(dir, ap);
4825 if (!strv_path_canonicalize(dirs)) {
4829 if (!strv_uniq(dirs)) {
4834 fh = hashmap_new(string_hash_func, string_compare_func);
4840 STRV_FOREACH(p, dirs) {
4841 if (files_add(fh, *p, suffix) < 0) {
4842 log_error("Failed to search for files.");
4848 files = hashmap_get_strv(fh);
4849 if (files == NULL) {
4850 log_error("Failed to compose list of files.");
4855 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4864 int hwclock_is_localtime(void) {
4869 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4875 f = fopen("/etc/adjtime", "re");
4877 char line[LINE_MAX];
4880 b = fgets(line, sizeof(line), f) &&
4881 fgets(line, sizeof(line), f) &&
4882 fgets(line, sizeof(line), f);
4891 local = streq(line, "LOCAL");
4893 } else if (errno != -ENOENT)
4899 int hwclock_apply_localtime_delta(void) {
4900 const struct timeval *tv_null = NULL;
4906 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4907 assert_se(tm = localtime(&ts.tv_sec));
4908 minuteswest = tm->tm_gmtoff / 60;
4910 tz.tz_minuteswest = -minuteswest;
4911 tz.tz_dsttime = 0; /* DST_NONE*/
4914 * If the hardware clock does not run in UTC, but in local time:
4915 * The very first time we set the kernel's timezone, it will warp
4916 * the clock so that it runs in UTC instead of local time.
4918 if (settimeofday(tv_null, &tz) < 0)
4924 int hwclock_reset_localtime_delta(void) {
4925 const struct timeval *tv_null = NULL;
4928 tz.tz_minuteswest = 0;
4929 tz.tz_dsttime = 0; /* DST_NONE*/
4931 if (settimeofday(tv_null, &tz) < 0)
4937 int hwclock_get_time(struct tm *tm) {
4943 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4947 /* This leaves the timezone fields of struct tm
4949 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4952 /* We don't now daylight saving, so we reset this in order not
4953 * to confused mktime(). */
4956 close_nointr_nofail(fd);
4961 int hwclock_set_time(const struct tm *tm) {
4967 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4971 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4974 close_nointr_nofail(fd);
4979 int copy_file(const char *from, const char *to) {
4985 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4989 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4991 close_nointr_nofail(fdf);
4999 n = read(fdf, buf, sizeof(buf));
5003 close_nointr_nofail(fdf);
5014 k = loop_write(fdt, buf, n, false);
5016 r = k < 0 ? k : (errno ? -errno : -EIO);
5018 close_nointr_nofail(fdf);
5026 close_nointr_nofail(fdf);
5027 r = close_nointr(fdt);
5037 int symlink_or_copy(const char *from, const char *to) {
5038 char *pf = NULL, *pt = NULL;
5045 if (parent_of_path(from, &pf) < 0 ||
5046 parent_of_path(to, &pt) < 0) {
5051 if (stat(pf, &a) < 0 ||
5057 if (a.st_dev != b.st_dev) {
5061 return copy_file(from, to);
5064 if (symlink(from, to) < 0) {
5078 int symlink_or_copy_atomic(const char *from, const char *to) {
5082 unsigned long long ull;
5089 t = new(char, strlen(to) + 1 + 16 + 1);
5093 fn = file_name_from_path(to);
5097 x = stpcpy(t+k+1, fn);
5100 for (i = 0; i < 16; i++) {
5101 *(x++) = hexchar(ull & 0xF);
5107 r = symlink_or_copy(from, t);
5114 if (rename(t, to) < 0) {
5125 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5133 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5136 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5139 r = read_one_line_file(p, &s);
5144 r = safe_atou32(s, &u);
5150 if (u == (uint32_t) -1 || u <= 0)
5157 bool display_is_local(const char *display) {
5161 display[0] == ':' &&
5162 display[1] >= '0' &&
5166 int socket_from_display(const char *display, char **path) {
5173 if (!display_is_local(display))
5176 k = strspn(display+1, "0123456789");
5178 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5182 c = stpcpy(f, "/tmp/.X11-unix/X");
5183 memcpy(c, display+1, k);
5191 static const char *const ioprio_class_table[] = {
5192 [IOPRIO_CLASS_NONE] = "none",
5193 [IOPRIO_CLASS_RT] = "realtime",
5194 [IOPRIO_CLASS_BE] = "best-effort",
5195 [IOPRIO_CLASS_IDLE] = "idle"
5198 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5200 static const char *const sigchld_code_table[] = {
5201 [CLD_EXITED] = "exited",
5202 [CLD_KILLED] = "killed",
5203 [CLD_DUMPED] = "dumped",
5204 [CLD_TRAPPED] = "trapped",
5205 [CLD_STOPPED] = "stopped",
5206 [CLD_CONTINUED] = "continued",
5209 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5211 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5212 [LOG_FAC(LOG_KERN)] = "kern",
5213 [LOG_FAC(LOG_USER)] = "user",
5214 [LOG_FAC(LOG_MAIL)] = "mail",
5215 [LOG_FAC(LOG_DAEMON)] = "daemon",
5216 [LOG_FAC(LOG_AUTH)] = "auth",
5217 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5218 [LOG_FAC(LOG_LPR)] = "lpr",
5219 [LOG_FAC(LOG_NEWS)] = "news",
5220 [LOG_FAC(LOG_UUCP)] = "uucp",
5221 [LOG_FAC(LOG_CRON)] = "cron",
5222 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5223 [LOG_FAC(LOG_FTP)] = "ftp",
5224 [LOG_FAC(LOG_LOCAL0)] = "local0",
5225 [LOG_FAC(LOG_LOCAL1)] = "local1",
5226 [LOG_FAC(LOG_LOCAL2)] = "local2",
5227 [LOG_FAC(LOG_LOCAL3)] = "local3",
5228 [LOG_FAC(LOG_LOCAL4)] = "local4",
5229 [LOG_FAC(LOG_LOCAL5)] = "local5",
5230 [LOG_FAC(LOG_LOCAL6)] = "local6",
5231 [LOG_FAC(LOG_LOCAL7)] = "local7"
5234 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5236 static const char *const log_level_table[] = {
5237 [LOG_EMERG] = "emerg",
5238 [LOG_ALERT] = "alert",
5239 [LOG_CRIT] = "crit",
5241 [LOG_WARNING] = "warning",
5242 [LOG_NOTICE] = "notice",
5243 [LOG_INFO] = "info",
5244 [LOG_DEBUG] = "debug"
5247 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5249 static const char* const sched_policy_table[] = {
5250 [SCHED_OTHER] = "other",
5251 [SCHED_BATCH] = "batch",
5252 [SCHED_IDLE] = "idle",
5253 [SCHED_FIFO] = "fifo",
5257 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5259 static const char* const rlimit_table[] = {
5260 [RLIMIT_CPU] = "LimitCPU",
5261 [RLIMIT_FSIZE] = "LimitFSIZE",
5262 [RLIMIT_DATA] = "LimitDATA",
5263 [RLIMIT_STACK] = "LimitSTACK",
5264 [RLIMIT_CORE] = "LimitCORE",
5265 [RLIMIT_RSS] = "LimitRSS",
5266 [RLIMIT_NOFILE] = "LimitNOFILE",
5267 [RLIMIT_AS] = "LimitAS",
5268 [RLIMIT_NPROC] = "LimitNPROC",
5269 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5270 [RLIMIT_LOCKS] = "LimitLOCKS",
5271 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5272 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5273 [RLIMIT_NICE] = "LimitNICE",
5274 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5275 [RLIMIT_RTTIME] = "LimitRTTIME"
5278 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5280 static const char* const ip_tos_table[] = {
5281 [IPTOS_LOWDELAY] = "low-delay",
5282 [IPTOS_THROUGHPUT] = "throughput",
5283 [IPTOS_RELIABILITY] = "reliability",
5284 [IPTOS_LOWCOST] = "low-cost",
5287 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5289 static const char *const signal_table[] = {
5306 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5317 [SIGVTALRM] = "VTALRM",
5319 [SIGWINCH] = "WINCH",
5325 DEFINE_STRING_TABLE_LOOKUP(signal, int);