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>
65 #include "exit-status.h"
69 char **saved_argv = NULL;
71 size_t page_size(void) {
72 static __thread size_t pgsz = 0;
78 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
85 bool streq_ptr(const char *a, const char *b) {
87 /* Like streq(), but tries to make sense of NULL pointers */
98 usec_t now(clockid_t clock_id) {
101 assert_se(clock_gettime(clock_id, &ts) == 0);
103 return timespec_load(&ts);
106 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
109 ts->realtime = now(CLOCK_REALTIME);
110 ts->monotonic = now(CLOCK_MONOTONIC);
115 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
124 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
126 ts->monotonic = now(CLOCK_MONOTONIC);
128 if ((int64_t) ts->monotonic > delta)
129 ts->monotonic -= delta;
137 usec_t timespec_load(const struct timespec *ts) {
141 (usec_t) ts->tv_sec * USEC_PER_SEC +
142 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
145 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
148 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
149 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
154 usec_t timeval_load(const struct timeval *tv) {
158 (usec_t) tv->tv_sec * USEC_PER_SEC +
159 (usec_t) tv->tv_usec;
162 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
165 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
166 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
171 bool endswith(const char *s, const char *postfix) {
178 pl = strlen(postfix);
186 return memcmp(s + sl - pl, postfix, pl) == 0;
189 bool startswith(const char *s, const char *prefix) {
204 return memcmp(s, prefix, pl) == 0;
207 bool startswith_no_case(const char *s, const char *prefix) {
223 for(i = 0; i < pl; ++i) {
224 if (tolower(s[i]) != tolower(prefix[i]))
231 bool first_word(const char *s, const char *word) {
246 if (memcmp(s, word, wl) != 0)
250 strchr(WHITESPACE, s[wl]);
253 int close_nointr(int fd) {
268 void close_nointr_nofail(int fd) {
269 int saved_errno = errno;
271 /* like close_nointr() but cannot fail, and guarantees errno
274 assert_se(close_nointr(fd) == 0);
279 void close_many(const int fds[], unsigned n_fd) {
282 for (i = 0; i < n_fd; i++)
283 close_nointr_nofail(fds[i]);
286 int parse_boolean(const char *v) {
289 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
291 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
297 int parse_pid(const char *s, pid_t* ret_pid) {
298 unsigned long ul = 0;
305 if ((r = safe_atolu(s, &ul)) < 0)
310 if ((unsigned long) pid != ul)
320 int safe_atou(const char *s, unsigned *ret_u) {
328 l = strtoul(s, &x, 0);
330 if (!x || *x || errno)
331 return errno ? -errno : -EINVAL;
333 if ((unsigned long) (unsigned) l != l)
336 *ret_u = (unsigned) l;
340 int safe_atoi(const char *s, int *ret_i) {
348 l = strtol(s, &x, 0);
350 if (!x || *x || errno)
351 return errno ? -errno : -EINVAL;
353 if ((long) (int) l != l)
360 int safe_atollu(const char *s, long long unsigned *ret_llu) {
362 unsigned long long l;
368 l = strtoull(s, &x, 0);
370 if (!x || *x || errno)
371 return errno ? -errno : -EINVAL;
377 int safe_atolli(const char *s, long long int *ret_lli) {
385 l = strtoll(s, &x, 0);
387 if (!x || *x || errno)
388 return errno ? -errno : -EINVAL;
394 /* Split a string into words. */
395 char *split(const char *c, size_t *l, const char *separator, char **state) {
398 current = *state ? *state : (char*) c;
400 if (!*current || *c == 0)
403 current += strspn(current, separator);
404 *l = strcspn(current, separator);
407 return (char*) current;
410 /* Split a string into words, but consider strings enclosed in '' and
411 * "" as words even if they include spaces. */
412 char *split_quoted(const char *c, size_t *l, char **state) {
414 bool escaped = false;
416 current = *state ? *state : (char*) c;
418 if (!*current || *c == 0)
421 current += strspn(current, WHITESPACE);
423 if (*current == '\'') {
426 for (e = current; *e; e++) {
436 *state = *e == 0 ? e : e+1;
437 } else if (*current == '\"') {
440 for (e = current; *e; e++) {
450 *state = *e == 0 ? e : e+1;
452 for (e = current; *e; e++) {
457 else if (strchr(WHITESPACE, *e))
464 return (char*) current;
467 char **split_path_and_make_absolute(const char *p) {
471 if (!(l = strv_split(p, ":")))
474 if (!strv_path_make_absolute_cwd(l)) {
482 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
485 char fn[PATH_MAX], line[LINE_MAX], *p;
491 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
494 if (!(f = fopen(fn, "re")))
497 if (!(fgets(line, sizeof(line), f))) {
505 /* Let's skip the pid and comm fields. The latter is enclosed
506 * in () but does not escape any () in its value, so let's
507 * skip over it manually */
509 if (!(p = strrchr(line, ')')))
520 if ((long unsigned) (pid_t) ppid != ppid)
523 *_ppid = (pid_t) ppid;
528 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
531 char fn[PATH_MAX], line[LINE_MAX], *p;
536 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
539 if (!(f = fopen(fn, "re")))
542 if (!(fgets(line, sizeof(line), f))) {
550 /* Let's skip the pid and comm fields. The latter is enclosed
551 * in () but does not escape any () in its value, so let's
552 * skip over it manually */
554 if (!(p = strrchr(line, ')')))
575 "%*d " /* priority */
577 "%*d " /* num_threads */
578 "%*d " /* itrealvalue */
579 "%llu " /* starttime */,
586 int write_one_line_file(const char *fn, const char *line) {
593 if (!(f = fopen(fn, "we")))
597 if (fputs(line, f) < 0) {
602 if (!endswith(line, "\n"))
620 int fchmod_umask(int fd, mode_t m) {
625 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
631 int write_one_line_file_atomic(const char *fn, const char *line) {
639 r = fopen_temporary(fn, &f, &p);
643 fchmod_umask(fileno(f), 0644);
646 if (fputs(line, f) < 0) {
651 if (!endswith(line, "\n"))
662 if (rename(p, fn) < 0)
678 int read_one_line_file(const char *fn, char **line) {
681 char t[LINE_MAX], *c;
686 if (!(f = fopen(fn, "re")))
689 if (!(fgets(t, sizeof(t), f))) {
694 if (!(c = strdup(t))) {
709 int read_full_file(const char *fn, char **contents, size_t *size) {
716 if (!(f = fopen(fn, "re")))
719 if (fstat(fileno(f), &st) < 0) {
725 if (st.st_size > 4*1024*1024) {
730 n = st.st_size > 0 ? st.st_size : LINE_MAX;
737 if (!(t = realloc(buf, n+1))) {
743 k = fread(buf + l, 1, n - l, f);
758 if (n > 4*1024*1024) {
766 else if (!(buf = calloc(1, 1))) {
788 const char *separator, ...) {
796 if ((r = read_full_file(fname, &contents, NULL)) < 0)
801 const char *key = NULL;
803 p += strspn(p, separator);
804 p += strspn(p, WHITESPACE);
809 if (!strchr(COMMENTS, *p)) {
813 va_start(ap, separator);
814 while ((key = va_arg(ap, char *))) {
818 value = va_arg(ap, char **);
821 if (strncmp(p, key, n) != 0 ||
826 n = strcspn(p, separator);
829 strchr(QUOTES, p[0]) &&
831 v = strndup(p+1, n-2);
842 /* return empty value strings as NULL */
859 p += strcspn(p, separator);
878 if (!(f = fopen(fname, "re")))
882 char l[LINE_MAX], *p, *u;
885 if (!fgets(l, sizeof(l), f)) {
898 if (strchr(COMMENTS, *p))
901 if (!(u = normalize_env_assignment(p))) {
902 log_error("Out of memory");
907 t = strv_append(m, u);
911 log_error("Out of memory");
934 int write_env_file(const char *fname, char **l) {
939 r = fopen_temporary(fname, &f, &p);
943 fchmod_umask(fileno(f), 0644);
959 if (rename(p, fname) < 0)
974 char *truncate_nl(char *s) {
977 s[strcspn(s, NEWLINE)] = 0;
981 int get_process_name(pid_t pid, char **name) {
988 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
991 r = read_one_line_file(p, name);
1000 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1008 assert(max_length > 0);
1011 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1020 if (!(r = new(char, max_length))) {
1027 while ((c = getc(f)) != EOF) {
1049 size_t n = MIN(left-1, 3U);
1050 memcpy(k, "...", n);
1057 /* Kernel threads have no argv[] */
1064 if ((h = get_process_name(pid, &t)) < 0)
1067 h = asprintf(&r, "[%s]", t);
1078 char *strnappend(const char *s, const char *suffix, size_t b) {
1086 return strndup(suffix, b);
1096 if (!(r = new(char, a+b+1)))
1100 memcpy(r+a, suffix, b);
1106 char *strappend(const char *s, const char *suffix) {
1107 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1110 int readlink_malloc(const char *p, char **r) {
1120 if (!(c = new(char, l)))
1123 if ((n = readlink(p, c, l-1)) < 0) {
1129 if ((size_t) n < l-1) {
1140 int readlink_and_make_absolute(const char *p, char **r) {
1147 if ((j = readlink_malloc(p, &target)) < 0)
1150 k = file_in_same_dir(p, target);
1160 int parent_of_path(const char *path, char **_r) {
1161 const char *e, *a = NULL, *b = NULL, *p;
1171 for (e = path; *e; e++) {
1173 if (!slash && *e == '/') {
1177 } else if (slash && *e != '/')
1192 r = strndup(path, p-path);
1202 char *file_name_from_path(const char *p) {
1207 if ((r = strrchr(p, '/')))
1213 bool path_is_absolute(const char *p) {
1219 bool is_path(const char *p) {
1221 return !!strchr(p, '/');
1224 char *path_make_absolute(const char *p, const char *prefix) {
1229 /* Makes every item in the list an absolute path by prepending
1230 * the prefix, if specified and necessary */
1232 if (path_is_absolute(p) || !prefix)
1235 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1241 char *path_make_absolute_cwd(const char *p) {
1246 /* Similar to path_make_absolute(), but prefixes with the
1247 * current working directory. */
1249 if (path_is_absolute(p))
1252 if (!(cwd = get_current_dir_name()))
1255 r = path_make_absolute(p, cwd);
1261 char **strv_path_make_absolute_cwd(char **l) {
1264 /* Goes through every item in the string list and makes it
1265 * absolute. This works in place and won't rollback any
1266 * changes on failure. */
1268 STRV_FOREACH(s, l) {
1271 if (!(t = path_make_absolute_cwd(*s)))
1281 char **strv_path_canonicalize(char **l) {
1284 bool enomem = false;
1286 if (strv_isempty(l))
1289 /* Goes through every item in the string list and canonicalize
1290 * the path. This works in place and won't rollback any
1291 * changes on failure. */
1293 STRV_FOREACH(s, l) {
1296 t = path_make_absolute_cwd(*s);
1305 u = canonicalize_file_name(t);
1309 if (errno == ENOMEM || !errno)
1326 char **strv_path_remove_empty(char **l) {
1332 for (f = t = l; *f; f++) {
1334 if (dir_is_empty(*f) > 0) {
1346 int reset_all_signal_handlers(void) {
1349 for (sig = 1; sig < _NSIG; sig++) {
1350 struct sigaction sa;
1352 if (sig == SIGKILL || sig == SIGSTOP)
1356 sa.sa_handler = SIG_DFL;
1357 sa.sa_flags = SA_RESTART;
1359 /* On Linux the first two RT signals are reserved by
1360 * glibc, and sigaction() will return EINVAL for them. */
1361 if ((sigaction(sig, &sa, NULL) < 0))
1362 if (errno != EINVAL)
1369 char *strstrip(char *s) {
1372 /* Drops trailing whitespace. Modifies the string in
1373 * place. Returns pointer to first non-space character */
1375 s += strspn(s, WHITESPACE);
1377 for (e = s; *e; e++)
1378 if (!strchr(WHITESPACE, *e))
1389 char *delete_chars(char *s, const char *bad) {
1392 /* Drops all whitespace, regardless where in the string */
1394 for (f = s, t = s; *f; f++) {
1395 if (strchr(bad, *f))
1406 char *file_in_same_dir(const char *path, const char *filename) {
1413 /* This removes the last component of path and appends
1414 * filename, unless the latter is absolute anyway or the
1417 if (path_is_absolute(filename))
1418 return strdup(filename);
1420 if (!(e = strrchr(path, '/')))
1421 return strdup(filename);
1423 k = strlen(filename);
1424 if (!(r = new(char, e-path+1+k+1)))
1427 memcpy(r, path, e-path+1);
1428 memcpy(r+(e-path)+1, filename, k+1);
1433 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1436 if (label_mkdir(path, mode) >= 0)
1437 if (chmod_and_chown(path, mode, uid, gid) < 0)
1440 if (lstat(path, &st) < 0)
1443 if ((st.st_mode & 0777) != mode ||
1446 !S_ISDIR(st.st_mode)) {
1455 int mkdir_parents(const char *path, mode_t mode) {
1460 /* Creates every parent directory in the path except the last
1463 p = path + strspn(path, "/");
1468 e = p + strcspn(p, "/");
1469 p = e + strspn(e, "/");
1471 /* Is this the last component? If so, then we're
1476 if (!(t = strndup(path, e - path)))
1479 r = label_mkdir(t, mode);
1482 if (r < 0 && errno != EEXIST)
1487 int mkdir_p(const char *path, mode_t mode) {
1492 if ((r = mkdir_parents(path, mode)) < 0)
1495 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1501 int rmdir_parents(const char *path, const char *stop) {
1510 /* Skip trailing slashes */
1511 while (l > 0 && path[l-1] == '/')
1517 /* Skip last component */
1518 while (l > 0 && path[l-1] != '/')
1521 /* Skip trailing slashes */
1522 while (l > 0 && path[l-1] == '/')
1528 if (!(t = strndup(path, l)))
1531 if (path_startswith(stop, t)) {
1540 if (errno != ENOENT)
1548 char hexchar(int x) {
1549 static const char table[16] = "0123456789abcdef";
1551 return table[x & 15];
1554 int unhexchar(char c) {
1556 if (c >= '0' && c <= '9')
1559 if (c >= 'a' && c <= 'f')
1560 return c - 'a' + 10;
1562 if (c >= 'A' && c <= 'F')
1563 return c - 'A' + 10;
1568 char octchar(int x) {
1569 return '0' + (x & 7);
1572 int unoctchar(char c) {
1574 if (c >= '0' && c <= '7')
1580 char decchar(int x) {
1581 return '0' + (x % 10);
1584 int undecchar(char c) {
1586 if (c >= '0' && c <= '9')
1592 char *cescape(const char *s) {
1598 /* Does C style string escaping. */
1600 if (!(r = new(char, strlen(s)*4 + 1)))
1603 for (f = s, t = r; *f; f++)
1649 /* For special chars we prefer octal over
1650 * hexadecimal encoding, simply because glib's
1651 * g_strescape() does the same */
1652 if ((*f < ' ') || (*f >= 127)) {
1654 *(t++) = octchar((unsigned char) *f >> 6);
1655 *(t++) = octchar((unsigned char) *f >> 3);
1656 *(t++) = octchar((unsigned char) *f);
1667 char *cunescape_length(const char *s, size_t length) {
1673 /* Undoes C style string escaping */
1675 if (!(r = new(char, length+1)))
1678 for (f = s, t = r; f < s + length; f++) {
1721 /* This is an extension of the XDG syntax files */
1726 /* hexadecimal encoding */
1729 if ((a = unhexchar(f[1])) < 0 ||
1730 (b = unhexchar(f[2])) < 0) {
1731 /* Invalid escape code, let's take it literal then */
1735 *(t++) = (char) ((a << 4) | b);
1750 /* octal encoding */
1753 if ((a = unoctchar(f[0])) < 0 ||
1754 (b = unoctchar(f[1])) < 0 ||
1755 (c = unoctchar(f[2])) < 0) {
1756 /* Invalid escape code, let's take it literal then */
1760 *(t++) = (char) ((a << 6) | (b << 3) | c);
1768 /* premature end of string.*/
1773 /* Invalid escape code, let's take it literal then */
1785 char *cunescape(const char *s) {
1786 return cunescape_length(s, strlen(s));
1789 char *xescape(const char *s, const char *bad) {
1793 /* Escapes all chars in bad, in addition to \ and all special
1794 * chars, in \xFF style escaping. May be reversed with
1797 if (!(r = new(char, strlen(s)*4+1)))
1800 for (f = s, t = r; *f; f++) {
1802 if ((*f < ' ') || (*f >= 127) ||
1803 (*f == '\\') || strchr(bad, *f)) {
1806 *(t++) = hexchar(*f >> 4);
1807 *(t++) = hexchar(*f);
1817 char *bus_path_escape(const char *s) {
1823 /* Escapes all chars that D-Bus' object path cannot deal
1824 * with. Can be reverse with bus_path_unescape() */
1826 if (!(r = new(char, strlen(s)*3+1)))
1829 for (f = s, t = r; *f; f++) {
1831 if (!(*f >= 'A' && *f <= 'Z') &&
1832 !(*f >= 'a' && *f <= 'z') &&
1833 !(*f >= '0' && *f <= '9')) {
1835 *(t++) = hexchar(*f >> 4);
1836 *(t++) = hexchar(*f);
1846 char *bus_path_unescape(const char *f) {
1851 if (!(r = strdup(f)))
1854 for (t = r; *f; f++) {
1859 if ((a = unhexchar(f[1])) < 0 ||
1860 (b = unhexchar(f[2])) < 0) {
1861 /* Invalid escape code, let's take it literal then */
1864 *(t++) = (char) ((a << 4) | b);
1876 char *path_kill_slashes(char *path) {
1880 /* Removes redundant inner and trailing slashes. Modifies the
1881 * passed string in-place.
1883 * ///foo///bar/ becomes /foo/bar
1886 for (f = path, t = path; *f; f++) {
1901 /* Special rule, if we are talking of the root directory, a
1902 trailing slash is good */
1904 if (t == path && slash)
1911 bool path_startswith(const char *path, const char *prefix) {
1915 if ((path[0] == '/') != (prefix[0] == '/'))
1921 path += strspn(path, "/");
1922 prefix += strspn(prefix, "/");
1930 a = strcspn(path, "/");
1931 b = strcspn(prefix, "/");
1936 if (memcmp(path, prefix, a) != 0)
1944 bool path_equal(const char *a, const char *b) {
1948 if ((a[0] == '/') != (b[0] == '/'))
1954 a += strspn(a, "/");
1955 b += strspn(b, "/");
1957 if (*a == 0 && *b == 0)
1960 if (*a == 0 || *b == 0)
1963 j = strcspn(a, "/");
1964 k = strcspn(b, "/");
1969 if (memcmp(a, b, j) != 0)
1977 char *ascii_strlower(char *t) {
1982 for (p = t; *p; p++)
1983 if (*p >= 'A' && *p <= 'Z')
1984 *p = *p - 'A' + 'a';
1989 bool ignore_file(const char *filename) {
1993 filename[0] == '.' ||
1994 streq(filename, "lost+found") ||
1995 streq(filename, "aquota.user") ||
1996 streq(filename, "aquota.group") ||
1997 endswith(filename, "~") ||
1998 endswith(filename, ".rpmnew") ||
1999 endswith(filename, ".rpmsave") ||
2000 endswith(filename, ".rpmorig") ||
2001 endswith(filename, ".dpkg-old") ||
2002 endswith(filename, ".dpkg-new") ||
2003 endswith(filename, ".swp");
2006 int fd_nonblock(int fd, bool nonblock) {
2011 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2015 flags |= O_NONBLOCK;
2017 flags &= ~O_NONBLOCK;
2019 if (fcntl(fd, F_SETFL, flags) < 0)
2025 int fd_cloexec(int fd, bool cloexec) {
2030 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2034 flags |= FD_CLOEXEC;
2036 flags &= ~FD_CLOEXEC;
2038 if (fcntl(fd, F_SETFD, flags) < 0)
2044 int close_all_fds(const int except[], unsigned n_except) {
2049 if (!(d = opendir("/proc/self/fd")))
2052 while ((de = readdir(d))) {
2055 if (ignore_file(de->d_name))
2058 if (safe_atoi(de->d_name, &fd) < 0)
2059 /* Let's better ignore this, just in case */
2073 for (i = 0; i < n_except; i++)
2074 if (except[i] == fd) {
2083 if (close_nointr(fd) < 0) {
2084 /* Valgrind has its own FD and doesn't want to have it closed */
2085 if (errno != EBADF && r == 0)
2094 bool chars_intersect(const char *a, const char *b) {
2097 /* Returns true if any of the chars in a are in b. */
2098 for (p = a; *p; p++)
2105 char *format_timestamp(char *buf, size_t l, usec_t t) {
2115 sec = (time_t) (t / USEC_PER_SEC);
2117 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2123 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2126 n = now(CLOCK_REALTIME);
2128 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2133 if (d >= USEC_PER_YEAR)
2134 snprintf(buf, l, "%llu years and %llu months ago",
2135 (unsigned long long) (d / USEC_PER_YEAR),
2136 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2137 else if (d >= USEC_PER_MONTH)
2138 snprintf(buf, l, "%llu months and %llu days ago",
2139 (unsigned long long) (d / USEC_PER_MONTH),
2140 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2141 else if (d >= USEC_PER_WEEK)
2142 snprintf(buf, l, "%llu weeks and %llu days ago",
2143 (unsigned long long) (d / USEC_PER_WEEK),
2144 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2145 else if (d >= 2*USEC_PER_DAY)
2146 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2147 else if (d >= 25*USEC_PER_HOUR)
2148 snprintf(buf, l, "1 day and %lluh ago",
2149 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2150 else if (d >= 6*USEC_PER_HOUR)
2151 snprintf(buf, l, "%lluh ago",
2152 (unsigned long long) (d / USEC_PER_HOUR));
2153 else if (d >= USEC_PER_HOUR)
2154 snprintf(buf, l, "%lluh %llumin ago",
2155 (unsigned long long) (d / USEC_PER_HOUR),
2156 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2157 else if (d >= 5*USEC_PER_MINUTE)
2158 snprintf(buf, l, "%llumin ago",
2159 (unsigned long long) (d / USEC_PER_MINUTE));
2160 else if (d >= USEC_PER_MINUTE)
2161 snprintf(buf, l, "%llumin %llus ago",
2162 (unsigned long long) (d / USEC_PER_MINUTE),
2163 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2164 else if (d >= USEC_PER_SEC)
2165 snprintf(buf, l, "%llus ago",
2166 (unsigned long long) (d / USEC_PER_SEC));
2167 else if (d >= USEC_PER_MSEC)
2168 snprintf(buf, l, "%llums ago",
2169 (unsigned long long) (d / USEC_PER_MSEC));
2171 snprintf(buf, l, "%lluus ago",
2172 (unsigned long long) d);
2174 snprintf(buf, l, "now");
2180 char *format_timespan(char *buf, size_t l, usec_t t) {
2181 static const struct {
2185 { "w", USEC_PER_WEEK },
2186 { "d", USEC_PER_DAY },
2187 { "h", USEC_PER_HOUR },
2188 { "min", USEC_PER_MINUTE },
2189 { "s", USEC_PER_SEC },
2190 { "ms", USEC_PER_MSEC },
2200 if (t == (usec_t) -1)
2204 snprintf(p, l, "0");
2209 /* The result of this function can be parsed with parse_usec */
2211 for (i = 0; i < ELEMENTSOF(table); i++) {
2215 if (t < table[i].usec)
2221 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2222 n = MIN((size_t) k, l);
2235 bool fstype_is_network(const char *fstype) {
2236 static const char * const table[] = {
2248 for (i = 0; i < ELEMENTSOF(table); i++)
2249 if (streq(table[i], fstype))
2258 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2263 TIOCL_GETKMSGREDIRECT,
2267 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2270 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2273 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2276 close_nointr_nofail(r);
2280 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2281 struct termios old_termios, new_termios;
2283 char line[LINE_MAX];
2288 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2289 new_termios = old_termios;
2291 new_termios.c_lflag &= ~ICANON;
2292 new_termios.c_cc[VMIN] = 1;
2293 new_termios.c_cc[VTIME] = 0;
2295 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2298 k = fread(&c, 1, 1, f);
2300 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2306 *need_nl = c != '\n';
2313 if (!(fgets(line, sizeof(line), f)))
2318 if (strlen(line) != 1)
2328 int ask(char *ret, const char *replies, const char *text, ...) {
2335 on_tty = isatty(STDOUT_FILENO);
2341 bool need_nl = true;
2344 fputs("\x1B[1m", stdout);
2351 fputs("\x1B[0m", stdout);
2355 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2357 if (r == -EBADMSG) {
2358 puts("Bad input, please try again.");
2369 if (strchr(replies, c)) {
2374 puts("Read unexpected character, please try again.");
2378 int reset_terminal_fd(int fd) {
2379 struct termios termios;
2383 /* Set terminal to some sane defaults */
2387 /* We leave locked terminal attributes untouched, so that
2388 * Plymouth may set whatever it wants to set, and we don't
2389 * interfere with that. */
2391 /* Disable exclusive mode, just in case */
2392 ioctl(fd, TIOCNXCL);
2394 /* Enable console unicode mode */
2396 ioctl(fd, KDSKBMODE, &arg);
2398 if (tcgetattr(fd, &termios) < 0) {
2403 /* We only reset the stuff that matters to the software. How
2404 * hardware is set up we don't touch assuming that somebody
2405 * else will do that for us */
2407 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2408 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2409 termios.c_oflag |= ONLCR;
2410 termios.c_cflag |= CREAD;
2411 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2413 termios.c_cc[VINTR] = 03; /* ^C */
2414 termios.c_cc[VQUIT] = 034; /* ^\ */
2415 termios.c_cc[VERASE] = 0177;
2416 termios.c_cc[VKILL] = 025; /* ^X */
2417 termios.c_cc[VEOF] = 04; /* ^D */
2418 termios.c_cc[VSTART] = 021; /* ^Q */
2419 termios.c_cc[VSTOP] = 023; /* ^S */
2420 termios.c_cc[VSUSP] = 032; /* ^Z */
2421 termios.c_cc[VLNEXT] = 026; /* ^V */
2422 termios.c_cc[VWERASE] = 027; /* ^W */
2423 termios.c_cc[VREPRINT] = 022; /* ^R */
2424 termios.c_cc[VEOL] = 0;
2425 termios.c_cc[VEOL2] = 0;
2427 termios.c_cc[VTIME] = 0;
2428 termios.c_cc[VMIN] = 1;
2430 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2434 /* Just in case, flush all crap out */
2435 tcflush(fd, TCIOFLUSH);
2440 int reset_terminal(const char *name) {
2443 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2447 r = reset_terminal_fd(fd);
2448 close_nointr_nofail(fd);
2453 int open_terminal(const char *name, int mode) {
2458 * If a TTY is in the process of being closed opening it might
2459 * cause EIO. This is horribly awful, but unlikely to be
2460 * changed in the kernel. Hence we work around this problem by
2461 * retrying a couple of times.
2463 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2467 if ((fd = open(name, mode)) >= 0)
2476 usleep(50 * USEC_PER_MSEC);
2483 if ((r = isatty(fd)) < 0) {
2484 close_nointr_nofail(fd);
2489 close_nointr_nofail(fd);
2496 int flush_fd(int fd) {
2497 struct pollfd pollfd;
2501 pollfd.events = POLLIN;
2508 if ((r = poll(&pollfd, 1, 0)) < 0) {
2519 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2524 if (errno == EAGAIN)
2535 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2536 int fd = -1, notify = -1, r, wd = -1;
2540 /* We use inotify to be notified when the tty is closed. We
2541 * create the watch before checking if we can actually acquire
2542 * it, so that we don't lose any event.
2544 * Note: strictly speaking this actually watches for the
2545 * device being closed, it does *not* really watch whether a
2546 * tty loses its controlling process. However, unless some
2547 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2548 * its tty otherwise this will not become a problem. As long
2549 * as the administrator makes sure not configure any service
2550 * on the same tty as an untrusted user this should not be a
2551 * problem. (Which he probably should not do anyway.) */
2553 if (!fail && !force) {
2554 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2559 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2567 if ((r = flush_fd(notify)) < 0)
2570 /* We pass here O_NOCTTY only so that we can check the return
2571 * value TIOCSCTTY and have a reliable way to figure out if we
2572 * successfully became the controlling process of the tty */
2573 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2576 /* First, try to get the tty */
2577 r = ioctl(fd, TIOCSCTTY, force);
2579 /* Sometimes it makes sense to ignore TIOCSCTTY
2580 * returning EPERM, i.e. when very likely we already
2581 * are have this controlling terminal. */
2582 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2585 if (r < 0 && (force || fail || errno != EPERM)) {
2595 assert(notify >= 0);
2598 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2600 struct inotify_event *e;
2602 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2611 e = (struct inotify_event*) inotify_buffer;
2616 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2621 step = sizeof(struct inotify_event) + e->len;
2622 assert(step <= (size_t) l);
2624 e = (struct inotify_event*) ((uint8_t*) e + step);
2631 /* We close the tty fd here since if the old session
2632 * ended our handle will be dead. It's important that
2633 * we do this after sleeping, so that we don't enter
2634 * an endless loop. */
2635 close_nointr_nofail(fd);
2639 close_nointr_nofail(notify);
2641 if ((r = reset_terminal_fd(fd)) < 0)
2642 log_warning("Failed to reset terminal: %s", strerror(-r));
2648 close_nointr_nofail(fd);
2651 close_nointr_nofail(notify);
2656 int release_terminal(void) {
2658 struct sigaction sa_old, sa_new;
2660 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2663 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2664 * by our own TIOCNOTTY */
2667 sa_new.sa_handler = SIG_IGN;
2668 sa_new.sa_flags = SA_RESTART;
2669 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2671 if (ioctl(fd, TIOCNOTTY) < 0)
2674 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2676 close_nointr_nofail(fd);
2680 int sigaction_many(const struct sigaction *sa, ...) {
2685 while ((sig = va_arg(ap, int)) > 0)
2686 if (sigaction(sig, sa, NULL) < 0)
2693 int ignore_signals(int sig, ...) {
2694 struct sigaction sa;
2699 sa.sa_handler = SIG_IGN;
2700 sa.sa_flags = SA_RESTART;
2702 if (sigaction(sig, &sa, NULL) < 0)
2706 while ((sig = va_arg(ap, int)) > 0)
2707 if (sigaction(sig, &sa, NULL) < 0)
2714 int default_signals(int sig, ...) {
2715 struct sigaction sa;
2720 sa.sa_handler = SIG_DFL;
2721 sa.sa_flags = SA_RESTART;
2723 if (sigaction(sig, &sa, NULL) < 0)
2727 while ((sig = va_arg(ap, int)) > 0)
2728 if (sigaction(sig, &sa, NULL) < 0)
2735 int close_pipe(int p[]) {
2741 a = close_nointr(p[0]);
2746 b = close_nointr(p[1]);
2750 return a < 0 ? a : b;
2753 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2762 while (nbytes > 0) {
2765 if ((k = read(fd, p, nbytes)) <= 0) {
2767 if (k < 0 && errno == EINTR)
2770 if (k < 0 && errno == EAGAIN && do_poll) {
2771 struct pollfd pollfd;
2775 pollfd.events = POLLIN;
2777 if (poll(&pollfd, 1, -1) < 0) {
2781 return n > 0 ? n : -errno;
2784 if (pollfd.revents != POLLIN)
2785 return n > 0 ? n : -EIO;
2790 return n > 0 ? n : (k < 0 ? -errno : 0);
2801 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2810 while (nbytes > 0) {
2813 if ((k = write(fd, p, nbytes)) <= 0) {
2815 if (k < 0 && errno == EINTR)
2818 if (k < 0 && errno == EAGAIN && do_poll) {
2819 struct pollfd pollfd;
2823 pollfd.events = POLLOUT;
2825 if (poll(&pollfd, 1, -1) < 0) {
2829 return n > 0 ? n : -errno;
2832 if (pollfd.revents != POLLOUT)
2833 return n > 0 ? n : -EIO;
2838 return n > 0 ? n : (k < 0 ? -errno : 0);
2849 int path_is_mount_point(const char *t) {
2854 if (lstat(t, &a) < 0) {
2855 if (errno == ENOENT)
2861 if ((r = parent_of_path(t, &parent)) < 0)
2864 r = lstat(parent, &b);
2870 return a.st_dev != b.st_dev;
2873 int parse_usec(const char *t, usec_t *usec) {
2874 static const struct {
2878 { "sec", USEC_PER_SEC },
2879 { "s", USEC_PER_SEC },
2880 { "min", USEC_PER_MINUTE },
2881 { "hr", USEC_PER_HOUR },
2882 { "h", USEC_PER_HOUR },
2883 { "d", USEC_PER_DAY },
2884 { "w", USEC_PER_WEEK },
2885 { "msec", USEC_PER_MSEC },
2886 { "ms", USEC_PER_MSEC },
2887 { "m", USEC_PER_MINUTE },
2890 { "", USEC_PER_SEC },
2906 l = strtoll(p, &e, 10);
2917 e += strspn(e, WHITESPACE);
2919 for (i = 0; i < ELEMENTSOF(table); i++)
2920 if (startswith(e, table[i].suffix)) {
2921 r += (usec_t) l * table[i].usec;
2922 p = e + strlen(table[i].suffix);
2926 if (i >= ELEMENTSOF(table))
2936 int make_stdio(int fd) {
2941 r = dup2(fd, STDIN_FILENO);
2942 s = dup2(fd, STDOUT_FILENO);
2943 t = dup2(fd, STDERR_FILENO);
2946 close_nointr_nofail(fd);
2948 if (r < 0 || s < 0 || t < 0)
2951 fd_cloexec(STDIN_FILENO, false);
2952 fd_cloexec(STDOUT_FILENO, false);
2953 fd_cloexec(STDERR_FILENO, false);
2958 int make_null_stdio(void) {
2961 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2964 return make_stdio(null_fd);
2967 bool is_device_path(const char *path) {
2969 /* Returns true on paths that refer to a device, either in
2970 * sysfs or in /dev */
2973 path_startswith(path, "/dev/") ||
2974 path_startswith(path, "/sys/");
2977 int dir_is_empty(const char *path) {
2980 struct dirent buf, *de;
2982 if (!(d = opendir(path)))
2986 if ((r = readdir_r(d, &buf, &de)) > 0) {
2996 if (!ignore_file(de->d_name)) {
3006 unsigned long long random_ull(void) {
3011 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3014 r = loop_read(fd, &ull, sizeof(ull), true);
3015 close_nointr_nofail(fd);
3017 if (r != sizeof(ull))
3023 return random() * RAND_MAX + random();
3026 void rename_process(const char name[8]) {
3029 prctl(PR_SET_NAME, name);
3031 /* This is a like a poor man's setproctitle(). The string
3032 * passed should fit in 7 chars (i.e. the length of
3035 if (program_invocation_name)
3036 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3038 if (saved_argc > 0) {
3042 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3044 for (i = 1; i < saved_argc; i++) {
3048 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3053 void sigset_add_many(sigset_t *ss, ...) {
3060 while ((sig = va_arg(ap, int)) > 0)
3061 assert_se(sigaddset(ss, sig) == 0);
3065 char* gethostname_malloc(void) {
3068 assert_se(uname(&u) >= 0);
3071 return strdup(u.nodename);
3073 return strdup(u.sysname);
3076 char* getlogname_malloc(void) {
3080 struct passwd pwbuf, *pw = NULL;
3083 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3088 /* Shortcut things to avoid NSS lookups */
3090 return strdup("root");
3092 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3095 if (!(buf = malloc(bufsize)))
3098 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3099 name = strdup(pw->pw_name);
3106 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3112 int getttyname_malloc(int fd, char **r) {
3113 char path[PATH_MAX], *c;
3118 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3123 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3130 int getttyname_harder(int fd, char **r) {
3134 if ((k = getttyname_malloc(fd, &s)) < 0)
3137 if (streq(s, "tty")) {
3139 return get_ctty(0, NULL, r);
3146 int get_ctty_devnr(pid_t pid, dev_t *d) {
3148 char line[LINE_MAX], *p, *fn;
3149 unsigned long ttynr;
3152 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3155 f = fopen(fn, "re");
3160 if (!fgets(line, sizeof(line), f)) {
3168 p = strrchr(line, ')');
3178 "%*d " /* session */
3187 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3189 char fn[PATH_MAX], *s, *b, *p;
3194 k = get_ctty_devnr(pid, &devnr);
3198 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3201 if ((k = readlink_malloc(fn, &s)) < 0) {
3206 /* This is an ugly hack */
3207 if (major(devnr) == 136) {
3208 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3218 /* Probably something like the ptys which have no
3219 * symlink in /dev/char. Let's return something
3220 * vaguely useful. */
3222 if (!(b = strdup(fn + 5)))
3232 if (startswith(s, "/dev/"))
3234 else if (startswith(s, "../"))
3252 static int rm_rf_children(int fd, bool only_dirs) {
3258 /* This returns the first error we run into, but nevertheless
3261 if (!(d = fdopendir(fd))) {
3262 close_nointr_nofail(fd);
3264 return errno == ENOENT ? 0 : -errno;
3268 struct dirent buf, *de;
3272 if ((r = readdir_r(d, &buf, &de)) != 0) {
3281 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3284 if (de->d_type == DT_UNKNOWN) {
3287 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3288 if (ret == 0 && errno != ENOENT)
3293 is_dir = S_ISDIR(st.st_mode);
3295 is_dir = de->d_type == DT_DIR;
3300 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3301 if (ret == 0 && errno != ENOENT)
3306 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3311 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3312 if (ret == 0 && errno != ENOENT)
3315 } else if (!only_dirs) {
3317 if (unlinkat(fd, de->d_name, 0) < 0) {
3318 if (ret == 0 && errno != ENOENT)
3329 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3335 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3337 if (errno != ENOTDIR)
3340 if (delete_root && !only_dirs)
3341 if (unlink(path) < 0)
3347 r = rm_rf_children(fd, only_dirs);
3350 if (rmdir(path) < 0) {
3358 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3361 /* Under the assumption that we are running privileged we
3362 * first change the access mode and only then hand out
3363 * ownership to avoid a window where access is too open. */
3365 if (chmod(path, mode) < 0)
3368 if (chown(path, uid, gid) < 0)
3374 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3378 /* Allocates the cpuset in the right size */
3381 if (!(r = CPU_ALLOC(n)))
3384 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3385 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3395 if (errno != EINVAL)
3402 void status_vprintf(const char *format, va_list ap) {
3408 /* This independent of logging, as status messages are
3409 * optional and go exclusively to the console. */
3411 if (vasprintf(&s, format, ap) < 0)
3414 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3417 write(fd, s, strlen(s));
3423 close_nointr_nofail(fd);
3426 void status_printf(const char *format, ...) {
3431 va_start(ap, format);
3432 status_vprintf(format, ap);
3436 void status_welcome(void) {
3437 char *pretty_name = NULL, *ansi_color = NULL;
3438 const char *const_pretty = NULL, *const_color = NULL;
3441 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3442 "PRETTY_NAME", &pretty_name,
3443 "ANSI_COLOR", &ansi_color,
3447 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3450 #if defined(TARGET_FEDORA)
3452 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3455 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3459 if (!ansi_color && pretty_name) {
3461 /* This tries to mimic the color magic the old Red Hat sysinit
3464 if (startswith(pretty_name, "Red Hat"))
3465 const_color = "0;31"; /* Red for RHEL */
3466 else if (startswith(pretty_name, "Fedora"))
3467 const_color = "0;34"; /* Blue for Fedora */
3470 #elif defined(TARGET_SUSE)
3473 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3476 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3481 const_color = "0;32"; /* Green for openSUSE */
3483 #elif defined(TARGET_GENTOO)
3486 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3489 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3494 const_color = "1;34"; /* Light Blue for Gentoo */
3496 #elif defined(TARGET_ALTLINUX)
3499 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3502 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3507 const_color = "0;36"; /* Cyan for ALTLinux */
3510 #elif defined(TARGET_DEBIAN)
3515 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3518 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3520 pretty_name = strappend("Debian ", version);
3524 log_warning("Failed to allocate Debian version string.");
3529 const_color = "1;31"; /* Light Red for Debian */
3531 #elif defined(TARGET_UBUNTU)
3533 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3534 "DISTRIB_DESCRIPTION", &pretty_name,
3538 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3542 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3544 #elif defined(TARGET_MANDRIVA)
3549 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3551 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3553 p = strstr(s, " release ");
3557 p[strcspn(p, " ")] = '\0';
3559 /* This corresponds to standard rc.sysinit */
3560 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3561 const_color = "1;36";
3563 log_warning("Failed to allocate Mandriva version string.");
3565 log_warning("Failed to parse /etc/mandriva-release");
3569 #elif defined(TARGET_MEEGO)
3572 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3575 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3580 const_color = "1;35"; /* Bright Magenta for MeeGo */
3583 if (!pretty_name && !const_pretty)
3584 const_pretty = "Linux";
3586 if (!ansi_color && !const_color)
3589 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3590 const_color ? const_color : ansi_color,
3591 const_pretty ? const_pretty : pretty_name);
3597 char *replace_env(const char *format, char **env) {
3604 const char *e, *word = format;
3609 for (e = format; *e; e ++) {
3620 if (!(k = strnappend(r, word, e-word-1)))
3629 } else if (*e == '$') {
3630 if (!(k = strnappend(r, word, e-word)))
3646 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3649 if (!(k = strappend(r, t)))
3662 if (!(k = strnappend(r, word, e-word)))
3673 char **replace_env_argv(char **argv, char **env) {
3675 unsigned k = 0, l = 0;
3677 l = strv_length(argv);
3679 if (!(r = new(char*, l+1)))
3682 STRV_FOREACH(i, argv) {
3684 /* If $FOO appears as single word, replace it by the split up variable */
3685 if ((*i)[0] == '$' && (*i)[1] != '{') {
3690 if ((e = strv_env_get(env, *i+1))) {
3692 if (!(m = strv_split_quoted(e))) {
3703 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3712 memcpy(r + k, m, q * sizeof(char*));
3720 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3721 if (!(r[k++] = replace_env(*i, env))) {
3732 static __thread int parsed_columns = 0;
3735 if (parsed_columns > 0)
3736 return parsed_columns;
3738 if ((e = getenv("COLUMNS")))
3739 parsed_columns = atoi(e);
3741 if (parsed_columns <= 0) {
3745 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3746 parsed_columns = ws.ws_col;
3749 if (parsed_columns <= 0)
3750 parsed_columns = 80;
3752 return parsed_columns;
3755 int running_in_chroot(void) {
3761 /* Only works as root */
3763 if (stat("/proc/1/root", &a) < 0)
3766 if (stat("/", &b) < 0)
3770 a.st_dev != b.st_dev ||
3771 a.st_ino != b.st_ino;
3774 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3779 assert(percent <= 100);
3780 assert(length >= 3);
3784 if (l <= 3 || l <= length)
3787 if (!(r = new0(char, length+1)))
3790 x = (length * percent) / 100;
3800 s + l - (length - x - 3),
3806 int touch(const char *path) {
3811 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3814 close_nointr_nofail(fd);
3818 char *unquote(const char *s, const char* quotes) {
3822 if ((l = strlen(s)) < 2)
3825 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3826 return strndup(s+1, l-2);
3831 char *normalize_env_assignment(const char *s) {
3832 char *name, *value, *p, *r;
3837 if (!(r = strdup(s)))
3843 if (!(name = strndup(s, p - s)))
3846 if (!(p = strdup(p+1))) {
3851 value = unquote(strstrip(p), QUOTES);
3859 if (asprintf(&r, "%s=%s", name, value) < 0)
3868 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3879 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3891 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3898 if ((r = wait_for_terminate(pid, &status)) < 0) {
3899 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3903 if (status.si_code == CLD_EXITED) {
3904 if (status.si_status != 0) {
3905 log_warning("%s failed with error code %i.", name, status.si_status);
3906 return status.si_status;
3909 log_debug("%s succeeded.", name);
3912 } else if (status.si_code == CLD_KILLED ||
3913 status.si_code == CLD_DUMPED) {
3915 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3919 log_warning("%s failed due to unknown reason.", name);
3926 /* Make sure nobody waits for us on a socket anymore */
3927 close_all_fds(NULL, 0);
3935 bool null_or_empty(struct stat *st) {
3938 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3941 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3947 DIR *xopendirat(int fd, const char *name, int flags) {
3951 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3954 if (!(d = fdopendir(nfd))) {
3955 close_nointr_nofail(nfd);
3962 int signal_from_string_try_harder(const char *s) {
3966 if ((signo = signal_from_string(s)) <= 0)
3967 if (startswith(s, "SIG"))
3968 return signal_from_string(s+3);
3973 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3979 if (!dual_timestamp_is_set(t))
3982 fprintf(f, "%s=%llu %llu\n",
3984 (unsigned long long) t->realtime,
3985 (unsigned long long) t->monotonic);
3988 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3989 unsigned long long a, b;
3994 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3995 log_debug("Failed to parse finish timestamp value %s", value);
4002 char *fstab_node_to_udev_node(const char *p) {
4006 /* FIXME: to follow udev's logic 100% we need to leave valid
4007 * UTF8 chars unescaped */
4009 if (startswith(p, "LABEL=")) {
4011 if (!(u = unquote(p+6, "\"\'")))
4014 t = xescape(u, "/ ");
4020 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4029 if (startswith(p, "UUID=")) {
4031 if (!(u = unquote(p+5, "\"\'")))
4034 t = xescape(u, "/ ");
4040 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4052 void filter_environ(const char *prefix) {
4059 for (i = 0, j = 0; environ[i]; i++) {
4061 if (startswith(environ[i], prefix))
4064 environ[j++] = environ[i];
4070 bool tty_is_vc(const char *tty) {
4073 if (startswith(tty, "/dev/"))
4076 return vtnr_from_tty(tty) >= 0;
4079 int vtnr_from_tty(const char *tty) {
4084 if (startswith(tty, "/dev/"))
4087 if (!startswith(tty, "tty") )
4090 if (tty[3] < '0' || tty[3] > '9')
4093 r = safe_atoi(tty+3, &i);
4097 if (i < 0 || i > 63)
4103 const char *default_term_for_tty(const char *tty) {
4104 char *active = NULL;
4109 if (startswith(tty, "/dev/"))
4112 /* Resolve where /dev/console is pointing when determining
4114 if (streq(tty, "console"))
4115 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4116 /* If multiple log outputs are configured the
4117 * last one is what /dev/console points to */
4118 if ((tty = strrchr(active, ' ')))
4124 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4130 /* Returns a short identifier for the various VM implementations */
4131 int detect_vm(const char **id) {
4133 #if defined(__i386__) || defined(__x86_64__)
4135 /* Both CPUID and DMI are x86 specific interfaces... */
4137 static const char *const dmi_vendors[] = {
4138 "/sys/class/dmi/id/sys_vendor",
4139 "/sys/class/dmi/id/board_vendor",
4140 "/sys/class/dmi/id/bios_vendor"
4143 static const char dmi_vendor_table[] =
4145 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4146 "VMware\0" "vmware\0"
4148 "Microsoft Corporation\0" "microsoft\0"
4149 "innotek GmbH\0" "oracle\0"
4151 "Bochs\0" "bochs\0";
4153 static const char cpuid_vendor_table[] =
4154 "XenVMMXenVMM\0" "xen\0"
4155 "KVMKVMKVM\0" "kvm\0"
4156 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4157 "VMwareVMware\0" "vmware\0"
4158 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4159 "Microsoft Hv\0" "microsoft\0";
4170 /* http://lwn.net/Articles/301888/ */
4173 #if defined (__i386__)
4176 #elif defined (__amd64__)
4181 /* First detect whether there is a hypervisor */
4183 __asm__ __volatile__ (
4184 /* ebx/rbx is being used for PIC! */
4185 " push %%"REG_b" \n\t"
4187 " pop %%"REG_b" \n\t"
4189 : "=a" (eax), "=c" (ecx)
4193 hypervisor = !!(ecx & 0x80000000U);
4197 /* There is a hypervisor, see what it is */
4199 __asm__ __volatile__ (
4200 /* ebx/rbx is being used for PIC! */
4201 " push %%"REG_b" \n\t"
4203 " mov %%ebx, %1 \n\t"
4204 " pop %%"REG_b" \n\t"
4206 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4210 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4211 if (streq(sig.text, j)) {
4220 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4223 const char *found = NULL;
4225 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4232 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4233 if (startswith(s, j))
4256 int detect_container(const char **id) {
4259 /* Unfortunately many of these operations require root access
4260 * in one way or another */
4265 if (running_in_chroot() > 0) {
4273 /* /proc/vz exists in container and outside of the container,
4274 * /proc/bc only outside of the container. */
4275 if (access("/proc/vz", F_OK) >= 0 &&
4276 access("/proc/bc", F_OK) < 0) {
4284 if ((f = fopen("/proc/self/cgroup", "re"))) {
4287 char line[LINE_MAX], *p;
4289 if (!fgets(line, sizeof(line), f))
4292 if (!(p = strchr(strstrip(line), ':')))
4295 if (strncmp(p, ":ns:", 4))
4298 if (!streq(p, ":ns:/")) {
4314 /* Returns a short identifier for the various VM/container implementations */
4315 int detect_virtualization(const char **id) {
4316 static __thread const char *cached_id = NULL;
4322 if (cached_id == (const char*) -1)
4331 if ((r = detect_container(&_id)) != 0)
4334 r = detect_vm(&_id);
4343 cached_id = (const char*) -1;
4348 bool dirent_is_file(struct dirent *de) {
4351 if (ignore_file(de->d_name))
4354 if (de->d_type != DT_REG &&
4355 de->d_type != DT_LNK &&
4356 de->d_type != DT_UNKNOWN)
4362 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4365 Hashmap *pids = NULL;
4369 /* Executes all binaries in a directory in parallel and waits
4370 * until all they all finished. */
4373 if (!(_d = opendir(directory))) {
4375 if (errno == ENOENT)
4378 log_error("Failed to enumerate directory %s: %m", directory);
4385 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4386 log_error("Failed to allocate set.");
4390 while ((de = readdir(d))) {
4395 if (!dirent_is_file(de))
4398 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4399 log_error("Out of memory");
4403 if ((pid = fork()) < 0) {
4404 log_error("Failed to fork: %m");
4423 log_error("Failed to execute %s: %m", path);
4424 _exit(EXIT_FAILURE);
4427 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4429 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4430 log_error("Failed to add PID to set: %s", strerror(-k));
4435 while (!hashmap_isempty(pids)) {
4440 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4445 log_error("waitid() failed: %m");
4449 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4450 if (!is_clean_exit(si.si_code, si.si_status)) {
4451 if (si.si_code == CLD_EXITED)
4452 log_error("%s exited with exit status %i.", path, si.si_status);
4454 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4456 log_debug("%s exited successfully.", path);
4467 hashmap_free_free(pids);
4470 int kill_and_sigcont(pid_t pid, int sig) {
4473 r = kill(pid, sig) < 0 ? -errno : 0;
4481 bool nulstr_contains(const char*nulstr, const char *needle) {
4487 NULSTR_FOREACH(i, nulstr)
4488 if (streq(i, needle))
4494 bool plymouth_running(void) {
4495 return access("/run/plymouth/pid", F_OK) >= 0;
4498 void parse_syslog_priority(char **p, int *priority) {
4499 int a = 0, b = 0, c = 0;
4509 if (!strchr(*p, '>'))
4512 if ((*p)[2] == '>') {
4513 c = undecchar((*p)[1]);
4515 } else if ((*p)[3] == '>') {
4516 b = undecchar((*p)[1]);
4517 c = undecchar((*p)[2]);
4519 } else if ((*p)[4] == '>') {
4520 a = undecchar((*p)[1]);
4521 b = undecchar((*p)[2]);
4522 c = undecchar((*p)[3]);
4527 if (a < 0 || b < 0 || c < 0)
4530 *priority = a*100+b*10+c;
4534 int have_effective_cap(int value) {
4536 cap_flag_value_t fv;
4539 if (!(cap = cap_get_proc()))
4542 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4551 char* strshorten(char *s, size_t l) {
4560 static bool hostname_valid_char(char c) {
4562 (c >= 'a' && c <= 'z') ||
4563 (c >= 'A' && c <= 'Z') ||
4564 (c >= '0' && c <= '9') ||
4570 bool hostname_is_valid(const char *s) {
4576 for (p = s; *p; p++)
4577 if (!hostname_valid_char(*p))
4580 if (p-s > HOST_NAME_MAX)
4586 char* hostname_cleanup(char *s) {
4589 for (p = s, d = s; *p; p++)
4590 if ((*p >= 'a' && *p <= 'z') ||
4591 (*p >= 'A' && *p <= 'Z') ||
4592 (*p >= '0' && *p <= '9') ||
4600 strshorten(s, HOST_NAME_MAX);
4604 int pipe_eof(int fd) {
4605 struct pollfd pollfd;
4610 pollfd.events = POLLIN|POLLHUP;
4612 r = poll(&pollfd, 1, 0);
4619 return pollfd.revents & POLLHUP;
4622 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4633 t = new(char, strlen(path) + 1 + 6 + 1);
4637 fn = file_name_from_path(path);
4641 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4643 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4649 f = fdopen(fd, "we");
4662 int terminal_vhangup_fd(int fd) {
4665 if (ioctl(fd, TIOCVHANGUP) < 0)
4671 int terminal_vhangup(const char *name) {
4674 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4678 r = terminal_vhangup_fd(fd);
4679 close_nointr_nofail(fd);
4684 int vt_disallocate(const char *name) {
4688 /* Deallocate the VT if possible. If not possible
4689 * (i.e. because it is the active one), at least clear it
4690 * entirely (including the scrollback buffer) */
4692 if (!startswith(name, "/dev/"))
4695 if (!tty_is_vc(name)) {
4696 /* So this is not a VT. I guess we cannot deallocate
4697 * it then. But let's at least clear the screen */
4699 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4704 "\033[r" /* clear scrolling region */
4705 "\033[H" /* move home */
4706 "\033[2J", /* clear screen */
4708 close_nointr_nofail(fd);
4713 if (!startswith(name, "/dev/tty"))
4716 r = safe_atou(name+8, &u);
4723 /* Try to deallocate */
4724 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4728 r = ioctl(fd, VT_DISALLOCATE, u);
4729 close_nointr_nofail(fd);
4737 /* Couldn't deallocate, so let's clear it fully with
4739 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4744 "\033[r" /* clear scrolling region */
4745 "\033[H" /* move home */
4746 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4748 close_nointr_nofail(fd);
4754 static int file_is_conf(const struct dirent *d, const char *suffix) {
4757 if (ignore_file(d->d_name))
4760 if (d->d_type != DT_REG &&
4761 d->d_type != DT_LNK &&
4762 d->d_type != DT_UNKNOWN)
4765 return endswith(d->d_name, suffix);
4768 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4773 dir = opendir(path);
4775 if (errno == ENOENT)
4780 for (de = readdir(dir); de; de = readdir(dir)) {
4784 if (!file_is_conf(de, suffix))
4787 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4792 f = canonicalize_file_name(p);
4794 log_error("Failed to canonicalize file name '%s': %m", p);
4800 log_debug("found: %s\n", f);
4801 base = f + strlen(path) + 1;
4802 if (hashmap_put(h, base, f) <= 0)
4811 static int base_cmp(const void *a, const void *b) {
4812 const char *s1, *s2;
4814 s1 = *(char * const *)a;
4815 s2 = *(char * const *)b;
4816 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4819 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4822 char **files = NULL;
4828 dirs = strv_new_ap(dir, ap);
4834 if (!strv_path_canonicalize(dirs)) {
4838 if (!strv_uniq(dirs)) {
4843 fh = hashmap_new(string_hash_func, string_compare_func);
4849 STRV_FOREACH(p, dirs) {
4850 if (files_add(fh, *p, suffix) < 0) {
4851 log_error("Failed to search for files.");
4857 files = hashmap_get_strv(fh);
4858 if (files == NULL) {
4859 log_error("Failed to compose list of files.");
4864 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4873 int hwclock_is_localtime(void) {
4878 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4884 f = fopen("/etc/adjtime", "re");
4886 char line[LINE_MAX];
4889 b = fgets(line, sizeof(line), f) &&
4890 fgets(line, sizeof(line), f) &&
4891 fgets(line, sizeof(line), f);
4900 local = streq(line, "LOCAL");
4902 } else if (errno != -ENOENT)
4908 int hwclock_apply_localtime_delta(void) {
4909 const struct timeval *tv_null = NULL;
4915 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4916 assert_se(tm = localtime(&ts.tv_sec));
4917 minuteswest = tm->tm_gmtoff / 60;
4919 tz.tz_minuteswest = -minuteswest;
4920 tz.tz_dsttime = 0; /* DST_NONE*/
4923 * If the hardware clock does not run in UTC, but in local time:
4924 * The very first time we set the kernel's timezone, it will warp
4925 * the clock so that it runs in UTC instead of local time.
4927 if (settimeofday(tv_null, &tz) < 0)
4933 int hwclock_reset_localtime_delta(void) {
4934 const struct timeval *tv_null = NULL;
4937 tz.tz_minuteswest = 0;
4938 tz.tz_dsttime = 0; /* DST_NONE*/
4940 if (settimeofday(tv_null, &tz) < 0)
4946 int hwclock_get_time(struct tm *tm) {
4952 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4956 /* This leaves the timezone fields of struct tm
4958 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4961 /* We don't now daylight saving, so we reset this in order not
4962 * to confused mktime(). */
4965 close_nointr_nofail(fd);
4970 int hwclock_set_time(const struct tm *tm) {
4976 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4980 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
4983 close_nointr_nofail(fd);
4988 int copy_file(const char *from, const char *to) {
4994 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4998 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5000 close_nointr_nofail(fdf);
5008 n = read(fdf, buf, sizeof(buf));
5012 close_nointr_nofail(fdf);
5023 k = loop_write(fdt, buf, n, false);
5025 r = k < 0 ? k : (errno ? -errno : -EIO);
5027 close_nointr_nofail(fdf);
5035 close_nointr_nofail(fdf);
5036 r = close_nointr(fdt);
5046 int symlink_or_copy(const char *from, const char *to) {
5047 char *pf = NULL, *pt = NULL;
5054 if (parent_of_path(from, &pf) < 0 ||
5055 parent_of_path(to, &pt) < 0) {
5060 if (stat(pf, &a) < 0 ||
5066 if (a.st_dev != b.st_dev) {
5070 return copy_file(from, to);
5073 if (symlink(from, to) < 0) {
5087 int symlink_or_copy_atomic(const char *from, const char *to) {
5091 unsigned long long ull;
5098 t = new(char, strlen(to) + 1 + 16 + 1);
5102 fn = file_name_from_path(to);
5106 x = stpcpy(t+k+1, fn);
5109 for (i = 0; i < 16; i++) {
5110 *(x++) = hexchar(ull & 0xF);
5116 r = symlink_or_copy(from, t);
5123 if (rename(t, to) < 0) {
5134 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5142 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5145 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5148 r = read_one_line_file(p, &s);
5153 r = safe_atou32(s, &u);
5159 if (u == (uint32_t) -1 || u <= 0)
5166 bool display_is_local(const char *display) {
5170 display[0] == ':' &&
5171 display[1] >= '0' &&
5175 int socket_from_display(const char *display, char **path) {
5182 if (!display_is_local(display))
5185 k = strspn(display+1, "0123456789");
5187 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5191 c = stpcpy(f, "/tmp/.X11-unix/X");
5192 memcpy(c, display+1, k);
5200 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5210 /* We enforce some special rules for uid=0: in order to avoid
5211 * NSS lookups for root we hardcode its data. */
5213 if (streq(*username, "root") || streq(*username, "0")) {
5221 if (safe_atolu(*username, &lu) >= 0) {
5223 p = getpwuid((uid_t) lu);
5225 /* If there are multiple users with the same id, make
5226 * sure to leave $USER to the configured value instead
5227 * of the first occurrence in the database. However if
5228 * the uid was configured by a numeric uid, then let's
5229 * pick the real username from /etc/passwd. */
5231 *username = p->pw_name;
5234 p = getpwnam(*username);
5238 return errno != 0 ? -errno : -ESRCH;
5246 int glob_exists(const char *path) {
5254 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5256 if (k == GLOB_NOMATCH)
5258 else if (k == GLOB_NOSPACE)
5261 r = !strv_isempty(g.gl_pathv);
5263 r = errno ? -errno : -EIO;
5270 static const char *const ioprio_class_table[] = {
5271 [IOPRIO_CLASS_NONE] = "none",
5272 [IOPRIO_CLASS_RT] = "realtime",
5273 [IOPRIO_CLASS_BE] = "best-effort",
5274 [IOPRIO_CLASS_IDLE] = "idle"
5277 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5279 static const char *const sigchld_code_table[] = {
5280 [CLD_EXITED] = "exited",
5281 [CLD_KILLED] = "killed",
5282 [CLD_DUMPED] = "dumped",
5283 [CLD_TRAPPED] = "trapped",
5284 [CLD_STOPPED] = "stopped",
5285 [CLD_CONTINUED] = "continued",
5288 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5290 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5291 [LOG_FAC(LOG_KERN)] = "kern",
5292 [LOG_FAC(LOG_USER)] = "user",
5293 [LOG_FAC(LOG_MAIL)] = "mail",
5294 [LOG_FAC(LOG_DAEMON)] = "daemon",
5295 [LOG_FAC(LOG_AUTH)] = "auth",
5296 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5297 [LOG_FAC(LOG_LPR)] = "lpr",
5298 [LOG_FAC(LOG_NEWS)] = "news",
5299 [LOG_FAC(LOG_UUCP)] = "uucp",
5300 [LOG_FAC(LOG_CRON)] = "cron",
5301 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5302 [LOG_FAC(LOG_FTP)] = "ftp",
5303 [LOG_FAC(LOG_LOCAL0)] = "local0",
5304 [LOG_FAC(LOG_LOCAL1)] = "local1",
5305 [LOG_FAC(LOG_LOCAL2)] = "local2",
5306 [LOG_FAC(LOG_LOCAL3)] = "local3",
5307 [LOG_FAC(LOG_LOCAL4)] = "local4",
5308 [LOG_FAC(LOG_LOCAL5)] = "local5",
5309 [LOG_FAC(LOG_LOCAL6)] = "local6",
5310 [LOG_FAC(LOG_LOCAL7)] = "local7"
5313 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5315 static const char *const log_level_table[] = {
5316 [LOG_EMERG] = "emerg",
5317 [LOG_ALERT] = "alert",
5318 [LOG_CRIT] = "crit",
5320 [LOG_WARNING] = "warning",
5321 [LOG_NOTICE] = "notice",
5322 [LOG_INFO] = "info",
5323 [LOG_DEBUG] = "debug"
5326 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5328 static const char* const sched_policy_table[] = {
5329 [SCHED_OTHER] = "other",
5330 [SCHED_BATCH] = "batch",
5331 [SCHED_IDLE] = "idle",
5332 [SCHED_FIFO] = "fifo",
5336 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5338 static const char* const rlimit_table[] = {
5339 [RLIMIT_CPU] = "LimitCPU",
5340 [RLIMIT_FSIZE] = "LimitFSIZE",
5341 [RLIMIT_DATA] = "LimitDATA",
5342 [RLIMIT_STACK] = "LimitSTACK",
5343 [RLIMIT_CORE] = "LimitCORE",
5344 [RLIMIT_RSS] = "LimitRSS",
5345 [RLIMIT_NOFILE] = "LimitNOFILE",
5346 [RLIMIT_AS] = "LimitAS",
5347 [RLIMIT_NPROC] = "LimitNPROC",
5348 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5349 [RLIMIT_LOCKS] = "LimitLOCKS",
5350 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5351 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5352 [RLIMIT_NICE] = "LimitNICE",
5353 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5354 [RLIMIT_RTTIME] = "LimitRTTIME"
5357 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5359 static const char* const ip_tos_table[] = {
5360 [IPTOS_LOWDELAY] = "low-delay",
5361 [IPTOS_THROUGHPUT] = "throughput",
5362 [IPTOS_RELIABILITY] = "reliability",
5363 [IPTOS_LOWCOST] = "low-cost",
5366 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5368 static const char *const signal_table[] = {
5385 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5396 [SIGVTALRM] = "VTALRM",
5398 [SIGWINCH] = "WINCH",
5404 DEFINE_STRING_TABLE_LOOKUP(signal, int);