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 readlink_and_canonicalize(const char *p, char **r) {
1167 j = readlink_and_make_absolute(p, &t);
1171 s = canonicalize_file_name(t);
1178 path_kill_slashes(*r);
1183 int parent_of_path(const char *path, char **_r) {
1184 const char *e, *a = NULL, *b = NULL, *p;
1194 for (e = path; *e; e++) {
1196 if (!slash && *e == '/') {
1200 } else if (slash && *e != '/')
1215 r = strndup(path, p-path);
1225 char *file_name_from_path(const char *p) {
1230 if ((r = strrchr(p, '/')))
1236 bool path_is_absolute(const char *p) {
1242 bool is_path(const char *p) {
1244 return !!strchr(p, '/');
1247 char *path_make_absolute(const char *p, const char *prefix) {
1252 /* Makes every item in the list an absolute path by prepending
1253 * the prefix, if specified and necessary */
1255 if (path_is_absolute(p) || !prefix)
1258 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1264 char *path_make_absolute_cwd(const char *p) {
1269 /* Similar to path_make_absolute(), but prefixes with the
1270 * current working directory. */
1272 if (path_is_absolute(p))
1275 if (!(cwd = get_current_dir_name()))
1278 r = path_make_absolute(p, cwd);
1284 char **strv_path_make_absolute_cwd(char **l) {
1287 /* Goes through every item in the string list and makes it
1288 * absolute. This works in place and won't rollback any
1289 * changes on failure. */
1291 STRV_FOREACH(s, l) {
1294 if (!(t = path_make_absolute_cwd(*s)))
1304 char **strv_path_canonicalize(char **l) {
1307 bool enomem = false;
1309 if (strv_isempty(l))
1312 /* Goes through every item in the string list and canonicalize
1313 * the path. This works in place and won't rollback any
1314 * changes on failure. */
1316 STRV_FOREACH(s, l) {
1319 t = path_make_absolute_cwd(*s);
1328 u = canonicalize_file_name(t);
1332 if (errno == ENOMEM || !errno)
1349 char **strv_path_remove_empty(char **l) {
1355 for (f = t = l; *f; f++) {
1357 if (dir_is_empty(*f) > 0) {
1369 int reset_all_signal_handlers(void) {
1372 for (sig = 1; sig < _NSIG; sig++) {
1373 struct sigaction sa;
1375 if (sig == SIGKILL || sig == SIGSTOP)
1379 sa.sa_handler = SIG_DFL;
1380 sa.sa_flags = SA_RESTART;
1382 /* On Linux the first two RT signals are reserved by
1383 * glibc, and sigaction() will return EINVAL for them. */
1384 if ((sigaction(sig, &sa, NULL) < 0))
1385 if (errno != EINVAL)
1392 char *strstrip(char *s) {
1395 /* Drops trailing whitespace. Modifies the string in
1396 * place. Returns pointer to first non-space character */
1398 s += strspn(s, WHITESPACE);
1400 for (e = s; *e; e++)
1401 if (!strchr(WHITESPACE, *e))
1412 char *delete_chars(char *s, const char *bad) {
1415 /* Drops all whitespace, regardless where in the string */
1417 for (f = s, t = s; *f; f++) {
1418 if (strchr(bad, *f))
1429 char *file_in_same_dir(const char *path, const char *filename) {
1436 /* This removes the last component of path and appends
1437 * filename, unless the latter is absolute anyway or the
1440 if (path_is_absolute(filename))
1441 return strdup(filename);
1443 if (!(e = strrchr(path, '/')))
1444 return strdup(filename);
1446 k = strlen(filename);
1447 if (!(r = new(char, e-path+1+k+1)))
1450 memcpy(r, path, e-path+1);
1451 memcpy(r+(e-path)+1, filename, k+1);
1456 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1459 if (label_mkdir(path, mode) >= 0)
1460 if (chmod_and_chown(path, mode, uid, gid) < 0)
1463 if (lstat(path, &st) < 0)
1466 if ((st.st_mode & 0777) != mode ||
1469 !S_ISDIR(st.st_mode)) {
1478 int mkdir_parents(const char *path, mode_t mode) {
1483 /* Creates every parent directory in the path except the last
1486 p = path + strspn(path, "/");
1491 e = p + strcspn(p, "/");
1492 p = e + strspn(e, "/");
1494 /* Is this the last component? If so, then we're
1499 if (!(t = strndup(path, e - path)))
1502 r = label_mkdir(t, mode);
1505 if (r < 0 && errno != EEXIST)
1510 int mkdir_p(const char *path, mode_t mode) {
1515 if ((r = mkdir_parents(path, mode)) < 0)
1518 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1524 int rmdir_parents(const char *path, const char *stop) {
1533 /* Skip trailing slashes */
1534 while (l > 0 && path[l-1] == '/')
1540 /* Skip last component */
1541 while (l > 0 && path[l-1] != '/')
1544 /* Skip trailing slashes */
1545 while (l > 0 && path[l-1] == '/')
1551 if (!(t = strndup(path, l)))
1554 if (path_startswith(stop, t)) {
1563 if (errno != ENOENT)
1571 char hexchar(int x) {
1572 static const char table[16] = "0123456789abcdef";
1574 return table[x & 15];
1577 int unhexchar(char c) {
1579 if (c >= '0' && c <= '9')
1582 if (c >= 'a' && c <= 'f')
1583 return c - 'a' + 10;
1585 if (c >= 'A' && c <= 'F')
1586 return c - 'A' + 10;
1591 char octchar(int x) {
1592 return '0' + (x & 7);
1595 int unoctchar(char c) {
1597 if (c >= '0' && c <= '7')
1603 char decchar(int x) {
1604 return '0' + (x % 10);
1607 int undecchar(char c) {
1609 if (c >= '0' && c <= '9')
1615 char *cescape(const char *s) {
1621 /* Does C style string escaping. */
1623 if (!(r = new(char, strlen(s)*4 + 1)))
1626 for (f = s, t = r; *f; f++)
1672 /* For special chars we prefer octal over
1673 * hexadecimal encoding, simply because glib's
1674 * g_strescape() does the same */
1675 if ((*f < ' ') || (*f >= 127)) {
1677 *(t++) = octchar((unsigned char) *f >> 6);
1678 *(t++) = octchar((unsigned char) *f >> 3);
1679 *(t++) = octchar((unsigned char) *f);
1690 char *cunescape_length(const char *s, size_t length) {
1696 /* Undoes C style string escaping */
1698 if (!(r = new(char, length+1)))
1701 for (f = s, t = r; f < s + length; f++) {
1744 /* This is an extension of the XDG syntax files */
1749 /* hexadecimal encoding */
1752 if ((a = unhexchar(f[1])) < 0 ||
1753 (b = unhexchar(f[2])) < 0) {
1754 /* Invalid escape code, let's take it literal then */
1758 *(t++) = (char) ((a << 4) | b);
1773 /* octal encoding */
1776 if ((a = unoctchar(f[0])) < 0 ||
1777 (b = unoctchar(f[1])) < 0 ||
1778 (c = unoctchar(f[2])) < 0) {
1779 /* Invalid escape code, let's take it literal then */
1783 *(t++) = (char) ((a << 6) | (b << 3) | c);
1791 /* premature end of string.*/
1796 /* Invalid escape code, let's take it literal then */
1808 char *cunescape(const char *s) {
1809 return cunescape_length(s, strlen(s));
1812 char *xescape(const char *s, const char *bad) {
1816 /* Escapes all chars in bad, in addition to \ and all special
1817 * chars, in \xFF style escaping. May be reversed with
1820 if (!(r = new(char, strlen(s)*4+1)))
1823 for (f = s, t = r; *f; f++) {
1825 if ((*f < ' ') || (*f >= 127) ||
1826 (*f == '\\') || strchr(bad, *f)) {
1829 *(t++) = hexchar(*f >> 4);
1830 *(t++) = hexchar(*f);
1840 char *bus_path_escape(const char *s) {
1846 /* Escapes all chars that D-Bus' object path cannot deal
1847 * with. Can be reverse with bus_path_unescape() */
1849 if (!(r = new(char, strlen(s)*3+1)))
1852 for (f = s, t = r; *f; f++) {
1854 if (!(*f >= 'A' && *f <= 'Z') &&
1855 !(*f >= 'a' && *f <= 'z') &&
1856 !(*f >= '0' && *f <= '9')) {
1858 *(t++) = hexchar(*f >> 4);
1859 *(t++) = hexchar(*f);
1869 char *bus_path_unescape(const char *f) {
1874 if (!(r = strdup(f)))
1877 for (t = r; *f; f++) {
1882 if ((a = unhexchar(f[1])) < 0 ||
1883 (b = unhexchar(f[2])) < 0) {
1884 /* Invalid escape code, let's take it literal then */
1887 *(t++) = (char) ((a << 4) | b);
1899 char *path_kill_slashes(char *path) {
1903 /* Removes redundant inner and trailing slashes. Modifies the
1904 * passed string in-place.
1906 * ///foo///bar/ becomes /foo/bar
1909 for (f = path, t = path; *f; f++) {
1924 /* Special rule, if we are talking of the root directory, a
1925 trailing slash is good */
1927 if (t == path && slash)
1934 bool path_startswith(const char *path, const char *prefix) {
1938 if ((path[0] == '/') != (prefix[0] == '/'))
1944 path += strspn(path, "/");
1945 prefix += strspn(prefix, "/");
1953 a = strcspn(path, "/");
1954 b = strcspn(prefix, "/");
1959 if (memcmp(path, prefix, a) != 0)
1967 bool path_equal(const char *a, const char *b) {
1971 if ((a[0] == '/') != (b[0] == '/'))
1977 a += strspn(a, "/");
1978 b += strspn(b, "/");
1980 if (*a == 0 && *b == 0)
1983 if (*a == 0 || *b == 0)
1986 j = strcspn(a, "/");
1987 k = strcspn(b, "/");
1992 if (memcmp(a, b, j) != 0)
2000 char *ascii_strlower(char *t) {
2005 for (p = t; *p; p++)
2006 if (*p >= 'A' && *p <= 'Z')
2007 *p = *p - 'A' + 'a';
2012 bool ignore_file(const char *filename) {
2016 filename[0] == '.' ||
2017 streq(filename, "lost+found") ||
2018 streq(filename, "aquota.user") ||
2019 streq(filename, "aquota.group") ||
2020 endswith(filename, "~") ||
2021 endswith(filename, ".rpmnew") ||
2022 endswith(filename, ".rpmsave") ||
2023 endswith(filename, ".rpmorig") ||
2024 endswith(filename, ".dpkg-old") ||
2025 endswith(filename, ".dpkg-new") ||
2026 endswith(filename, ".swp");
2029 int fd_nonblock(int fd, bool nonblock) {
2034 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2038 flags |= O_NONBLOCK;
2040 flags &= ~O_NONBLOCK;
2042 if (fcntl(fd, F_SETFL, flags) < 0)
2048 int fd_cloexec(int fd, bool cloexec) {
2053 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2057 flags |= FD_CLOEXEC;
2059 flags &= ~FD_CLOEXEC;
2061 if (fcntl(fd, F_SETFD, flags) < 0)
2067 int close_all_fds(const int except[], unsigned n_except) {
2072 if (!(d = opendir("/proc/self/fd")))
2075 while ((de = readdir(d))) {
2078 if (ignore_file(de->d_name))
2081 if (safe_atoi(de->d_name, &fd) < 0)
2082 /* Let's better ignore this, just in case */
2096 for (i = 0; i < n_except; i++)
2097 if (except[i] == fd) {
2106 if (close_nointr(fd) < 0) {
2107 /* Valgrind has its own FD and doesn't want to have it closed */
2108 if (errno != EBADF && r == 0)
2117 bool chars_intersect(const char *a, const char *b) {
2120 /* Returns true if any of the chars in a are in b. */
2121 for (p = a; *p; p++)
2128 char *format_timestamp(char *buf, size_t l, usec_t t) {
2138 sec = (time_t) (t / USEC_PER_SEC);
2140 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2146 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2149 n = now(CLOCK_REALTIME);
2151 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2156 if (d >= USEC_PER_YEAR)
2157 snprintf(buf, l, "%llu years and %llu months ago",
2158 (unsigned long long) (d / USEC_PER_YEAR),
2159 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2160 else if (d >= USEC_PER_MONTH)
2161 snprintf(buf, l, "%llu months and %llu days ago",
2162 (unsigned long long) (d / USEC_PER_MONTH),
2163 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2164 else if (d >= USEC_PER_WEEK)
2165 snprintf(buf, l, "%llu weeks and %llu days ago",
2166 (unsigned long long) (d / USEC_PER_WEEK),
2167 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2168 else if (d >= 2*USEC_PER_DAY)
2169 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2170 else if (d >= 25*USEC_PER_HOUR)
2171 snprintf(buf, l, "1 day and %lluh ago",
2172 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2173 else if (d >= 6*USEC_PER_HOUR)
2174 snprintf(buf, l, "%lluh ago",
2175 (unsigned long long) (d / USEC_PER_HOUR));
2176 else if (d >= USEC_PER_HOUR)
2177 snprintf(buf, l, "%lluh %llumin ago",
2178 (unsigned long long) (d / USEC_PER_HOUR),
2179 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2180 else if (d >= 5*USEC_PER_MINUTE)
2181 snprintf(buf, l, "%llumin ago",
2182 (unsigned long long) (d / USEC_PER_MINUTE));
2183 else if (d >= USEC_PER_MINUTE)
2184 snprintf(buf, l, "%llumin %llus ago",
2185 (unsigned long long) (d / USEC_PER_MINUTE),
2186 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2187 else if (d >= USEC_PER_SEC)
2188 snprintf(buf, l, "%llus ago",
2189 (unsigned long long) (d / USEC_PER_SEC));
2190 else if (d >= USEC_PER_MSEC)
2191 snprintf(buf, l, "%llums ago",
2192 (unsigned long long) (d / USEC_PER_MSEC));
2194 snprintf(buf, l, "%lluus ago",
2195 (unsigned long long) d);
2197 snprintf(buf, l, "now");
2203 char *format_timespan(char *buf, size_t l, usec_t t) {
2204 static const struct {
2208 { "w", USEC_PER_WEEK },
2209 { "d", USEC_PER_DAY },
2210 { "h", USEC_PER_HOUR },
2211 { "min", USEC_PER_MINUTE },
2212 { "s", USEC_PER_SEC },
2213 { "ms", USEC_PER_MSEC },
2223 if (t == (usec_t) -1)
2227 snprintf(p, l, "0");
2232 /* The result of this function can be parsed with parse_usec */
2234 for (i = 0; i < ELEMENTSOF(table); i++) {
2238 if (t < table[i].usec)
2244 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2245 n = MIN((size_t) k, l);
2258 bool fstype_is_network(const char *fstype) {
2259 static const char * const table[] = {
2271 for (i = 0; i < ELEMENTSOF(table); i++)
2272 if (streq(table[i], fstype))
2281 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2286 TIOCL_GETKMSGREDIRECT,
2290 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2293 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2296 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2299 close_nointr_nofail(r);
2303 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2304 struct termios old_termios, new_termios;
2306 char line[LINE_MAX];
2311 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2312 new_termios = old_termios;
2314 new_termios.c_lflag &= ~ICANON;
2315 new_termios.c_cc[VMIN] = 1;
2316 new_termios.c_cc[VTIME] = 0;
2318 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2321 k = fread(&c, 1, 1, f);
2323 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2329 *need_nl = c != '\n';
2336 if (!(fgets(line, sizeof(line), f)))
2341 if (strlen(line) != 1)
2351 int ask(char *ret, const char *replies, const char *text, ...) {
2358 on_tty = isatty(STDOUT_FILENO);
2364 bool need_nl = true;
2367 fputs("\x1B[1m", stdout);
2374 fputs("\x1B[0m", stdout);
2378 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2380 if (r == -EBADMSG) {
2381 puts("Bad input, please try again.");
2392 if (strchr(replies, c)) {
2397 puts("Read unexpected character, please try again.");
2401 int reset_terminal_fd(int fd) {
2402 struct termios termios;
2406 /* Set terminal to some sane defaults */
2410 /* We leave locked terminal attributes untouched, so that
2411 * Plymouth may set whatever it wants to set, and we don't
2412 * interfere with that. */
2414 /* Disable exclusive mode, just in case */
2415 ioctl(fd, TIOCNXCL);
2417 /* Enable console unicode mode */
2419 ioctl(fd, KDSKBMODE, &arg);
2421 if (tcgetattr(fd, &termios) < 0) {
2426 /* We only reset the stuff that matters to the software. How
2427 * hardware is set up we don't touch assuming that somebody
2428 * else will do that for us */
2430 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2431 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2432 termios.c_oflag |= ONLCR;
2433 termios.c_cflag |= CREAD;
2434 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2436 termios.c_cc[VINTR] = 03; /* ^C */
2437 termios.c_cc[VQUIT] = 034; /* ^\ */
2438 termios.c_cc[VERASE] = 0177;
2439 termios.c_cc[VKILL] = 025; /* ^X */
2440 termios.c_cc[VEOF] = 04; /* ^D */
2441 termios.c_cc[VSTART] = 021; /* ^Q */
2442 termios.c_cc[VSTOP] = 023; /* ^S */
2443 termios.c_cc[VSUSP] = 032; /* ^Z */
2444 termios.c_cc[VLNEXT] = 026; /* ^V */
2445 termios.c_cc[VWERASE] = 027; /* ^W */
2446 termios.c_cc[VREPRINT] = 022; /* ^R */
2447 termios.c_cc[VEOL] = 0;
2448 termios.c_cc[VEOL2] = 0;
2450 termios.c_cc[VTIME] = 0;
2451 termios.c_cc[VMIN] = 1;
2453 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2457 /* Just in case, flush all crap out */
2458 tcflush(fd, TCIOFLUSH);
2463 int reset_terminal(const char *name) {
2466 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2470 r = reset_terminal_fd(fd);
2471 close_nointr_nofail(fd);
2476 int open_terminal(const char *name, int mode) {
2481 * If a TTY is in the process of being closed opening it might
2482 * cause EIO. This is horribly awful, but unlikely to be
2483 * changed in the kernel. Hence we work around this problem by
2484 * retrying a couple of times.
2486 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2490 if ((fd = open(name, mode)) >= 0)
2499 usleep(50 * USEC_PER_MSEC);
2506 if ((r = isatty(fd)) < 0) {
2507 close_nointr_nofail(fd);
2512 close_nointr_nofail(fd);
2519 int flush_fd(int fd) {
2520 struct pollfd pollfd;
2524 pollfd.events = POLLIN;
2531 if ((r = poll(&pollfd, 1, 0)) < 0) {
2542 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2547 if (errno == EAGAIN)
2558 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2559 int fd = -1, notify = -1, r, wd = -1;
2563 /* We use inotify to be notified when the tty is closed. We
2564 * create the watch before checking if we can actually acquire
2565 * it, so that we don't lose any event.
2567 * Note: strictly speaking this actually watches for the
2568 * device being closed, it does *not* really watch whether a
2569 * tty loses its controlling process. However, unless some
2570 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2571 * its tty otherwise this will not become a problem. As long
2572 * as the administrator makes sure not configure any service
2573 * on the same tty as an untrusted user this should not be a
2574 * problem. (Which he probably should not do anyway.) */
2576 if (!fail && !force) {
2577 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2582 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2590 if ((r = flush_fd(notify)) < 0)
2593 /* We pass here O_NOCTTY only so that we can check the return
2594 * value TIOCSCTTY and have a reliable way to figure out if we
2595 * successfully became the controlling process of the tty */
2596 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2599 /* First, try to get the tty */
2600 r = ioctl(fd, TIOCSCTTY, force);
2602 /* Sometimes it makes sense to ignore TIOCSCTTY
2603 * returning EPERM, i.e. when very likely we already
2604 * are have this controlling terminal. */
2605 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2608 if (r < 0 && (force || fail || errno != EPERM)) {
2618 assert(notify >= 0);
2621 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2623 struct inotify_event *e;
2625 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2634 e = (struct inotify_event*) inotify_buffer;
2639 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2644 step = sizeof(struct inotify_event) + e->len;
2645 assert(step <= (size_t) l);
2647 e = (struct inotify_event*) ((uint8_t*) e + step);
2654 /* We close the tty fd here since if the old session
2655 * ended our handle will be dead. It's important that
2656 * we do this after sleeping, so that we don't enter
2657 * an endless loop. */
2658 close_nointr_nofail(fd);
2662 close_nointr_nofail(notify);
2664 if ((r = reset_terminal_fd(fd)) < 0)
2665 log_warning("Failed to reset terminal: %s", strerror(-r));
2671 close_nointr_nofail(fd);
2674 close_nointr_nofail(notify);
2679 int release_terminal(void) {
2681 struct sigaction sa_old, sa_new;
2683 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2686 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2687 * by our own TIOCNOTTY */
2690 sa_new.sa_handler = SIG_IGN;
2691 sa_new.sa_flags = SA_RESTART;
2692 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2694 if (ioctl(fd, TIOCNOTTY) < 0)
2697 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2699 close_nointr_nofail(fd);
2703 int sigaction_many(const struct sigaction *sa, ...) {
2708 while ((sig = va_arg(ap, int)) > 0)
2709 if (sigaction(sig, sa, NULL) < 0)
2716 int ignore_signals(int sig, ...) {
2717 struct sigaction sa;
2722 sa.sa_handler = SIG_IGN;
2723 sa.sa_flags = SA_RESTART;
2725 if (sigaction(sig, &sa, NULL) < 0)
2729 while ((sig = va_arg(ap, int)) > 0)
2730 if (sigaction(sig, &sa, NULL) < 0)
2737 int default_signals(int sig, ...) {
2738 struct sigaction sa;
2743 sa.sa_handler = SIG_DFL;
2744 sa.sa_flags = SA_RESTART;
2746 if (sigaction(sig, &sa, NULL) < 0)
2750 while ((sig = va_arg(ap, int)) > 0)
2751 if (sigaction(sig, &sa, NULL) < 0)
2758 int close_pipe(int p[]) {
2764 a = close_nointr(p[0]);
2769 b = close_nointr(p[1]);
2773 return a < 0 ? a : b;
2776 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2785 while (nbytes > 0) {
2788 if ((k = read(fd, p, nbytes)) <= 0) {
2790 if (k < 0 && errno == EINTR)
2793 if (k < 0 && errno == EAGAIN && do_poll) {
2794 struct pollfd pollfd;
2798 pollfd.events = POLLIN;
2800 if (poll(&pollfd, 1, -1) < 0) {
2804 return n > 0 ? n : -errno;
2807 if (pollfd.revents != POLLIN)
2808 return n > 0 ? n : -EIO;
2813 return n > 0 ? n : (k < 0 ? -errno : 0);
2824 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2833 while (nbytes > 0) {
2836 if ((k = write(fd, p, nbytes)) <= 0) {
2838 if (k < 0 && errno == EINTR)
2841 if (k < 0 && errno == EAGAIN && do_poll) {
2842 struct pollfd pollfd;
2846 pollfd.events = POLLOUT;
2848 if (poll(&pollfd, 1, -1) < 0) {
2852 return n > 0 ? n : -errno;
2855 if (pollfd.revents != POLLOUT)
2856 return n > 0 ? n : -EIO;
2861 return n > 0 ? n : (k < 0 ? -errno : 0);
2872 int path_is_mount_point(const char *t) {
2877 if (lstat(t, &a) < 0) {
2878 if (errno == ENOENT)
2884 if ((r = parent_of_path(t, &parent)) < 0)
2887 r = lstat(parent, &b);
2893 return a.st_dev != b.st_dev;
2896 int parse_usec(const char *t, usec_t *usec) {
2897 static const struct {
2901 { "sec", USEC_PER_SEC },
2902 { "s", USEC_PER_SEC },
2903 { "min", USEC_PER_MINUTE },
2904 { "hr", USEC_PER_HOUR },
2905 { "h", USEC_PER_HOUR },
2906 { "d", USEC_PER_DAY },
2907 { "w", USEC_PER_WEEK },
2908 { "msec", USEC_PER_MSEC },
2909 { "ms", USEC_PER_MSEC },
2910 { "m", USEC_PER_MINUTE },
2913 { "", USEC_PER_SEC },
2929 l = strtoll(p, &e, 10);
2940 e += strspn(e, WHITESPACE);
2942 for (i = 0; i < ELEMENTSOF(table); i++)
2943 if (startswith(e, table[i].suffix)) {
2944 r += (usec_t) l * table[i].usec;
2945 p = e + strlen(table[i].suffix);
2949 if (i >= ELEMENTSOF(table))
2959 int make_stdio(int fd) {
2964 r = dup2(fd, STDIN_FILENO);
2965 s = dup2(fd, STDOUT_FILENO);
2966 t = dup2(fd, STDERR_FILENO);
2969 close_nointr_nofail(fd);
2971 if (r < 0 || s < 0 || t < 0)
2974 fd_cloexec(STDIN_FILENO, false);
2975 fd_cloexec(STDOUT_FILENO, false);
2976 fd_cloexec(STDERR_FILENO, false);
2981 int make_null_stdio(void) {
2984 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2987 return make_stdio(null_fd);
2990 bool is_device_path(const char *path) {
2992 /* Returns true on paths that refer to a device, either in
2993 * sysfs or in /dev */
2996 path_startswith(path, "/dev/") ||
2997 path_startswith(path, "/sys/");
3000 int dir_is_empty(const char *path) {
3003 struct dirent buf, *de;
3005 if (!(d = opendir(path)))
3009 if ((r = readdir_r(d, &buf, &de)) > 0) {
3019 if (!ignore_file(de->d_name)) {
3029 unsigned long long random_ull(void) {
3034 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3037 r = loop_read(fd, &ull, sizeof(ull), true);
3038 close_nointr_nofail(fd);
3040 if (r != sizeof(ull))
3046 return random() * RAND_MAX + random();
3049 void rename_process(const char name[8]) {
3052 prctl(PR_SET_NAME, name);
3054 /* This is a like a poor man's setproctitle(). The string
3055 * passed should fit in 7 chars (i.e. the length of
3058 if (program_invocation_name)
3059 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3061 if (saved_argc > 0) {
3065 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3067 for (i = 1; i < saved_argc; i++) {
3071 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3076 void sigset_add_many(sigset_t *ss, ...) {
3083 while ((sig = va_arg(ap, int)) > 0)
3084 assert_se(sigaddset(ss, sig) == 0);
3088 char* gethostname_malloc(void) {
3091 assert_se(uname(&u) >= 0);
3094 return strdup(u.nodename);
3096 return strdup(u.sysname);
3099 char* getlogname_malloc(void) {
3103 struct passwd pwbuf, *pw = NULL;
3106 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3111 /* Shortcut things to avoid NSS lookups */
3113 return strdup("root");
3115 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3118 if (!(buf = malloc(bufsize)))
3121 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3122 name = strdup(pw->pw_name);
3129 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3135 int getttyname_malloc(int fd, char **r) {
3136 char path[PATH_MAX], *c;
3141 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3146 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3153 int getttyname_harder(int fd, char **r) {
3157 if ((k = getttyname_malloc(fd, &s)) < 0)
3160 if (streq(s, "tty")) {
3162 return get_ctty(0, NULL, r);
3169 int get_ctty_devnr(pid_t pid, dev_t *d) {
3171 char line[LINE_MAX], *p, *fn;
3172 unsigned long ttynr;
3175 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3178 f = fopen(fn, "re");
3183 if (!fgets(line, sizeof(line), f)) {
3191 p = strrchr(line, ')');
3201 "%*d " /* session */
3210 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3212 char fn[PATH_MAX], *s, *b, *p;
3217 k = get_ctty_devnr(pid, &devnr);
3221 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3224 if ((k = readlink_malloc(fn, &s)) < 0) {
3229 /* This is an ugly hack */
3230 if (major(devnr) == 136) {
3231 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3241 /* Probably something like the ptys which have no
3242 * symlink in /dev/char. Let's return something
3243 * vaguely useful. */
3245 if (!(b = strdup(fn + 5)))
3255 if (startswith(s, "/dev/"))
3257 else if (startswith(s, "../"))
3275 static int rm_rf_children(int fd, bool only_dirs) {
3281 /* This returns the first error we run into, but nevertheless
3284 if (!(d = fdopendir(fd))) {
3285 close_nointr_nofail(fd);
3287 return errno == ENOENT ? 0 : -errno;
3291 struct dirent buf, *de;
3295 if ((r = readdir_r(d, &buf, &de)) != 0) {
3304 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3307 if (de->d_type == DT_UNKNOWN) {
3310 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3311 if (ret == 0 && errno != ENOENT)
3316 is_dir = S_ISDIR(st.st_mode);
3318 is_dir = de->d_type == DT_DIR;
3323 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3324 if (ret == 0 && errno != ENOENT)
3329 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3334 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3335 if (ret == 0 && errno != ENOENT)
3338 } else if (!only_dirs) {
3340 if (unlinkat(fd, de->d_name, 0) < 0) {
3341 if (ret == 0 && errno != ENOENT)
3352 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3358 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3360 if (errno != ENOTDIR)
3363 if (delete_root && !only_dirs)
3364 if (unlink(path) < 0)
3370 r = rm_rf_children(fd, only_dirs);
3373 if (rmdir(path) < 0) {
3381 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3384 /* Under the assumption that we are running privileged we
3385 * first change the access mode and only then hand out
3386 * ownership to avoid a window where access is too open. */
3388 if (chmod(path, mode) < 0)
3391 if (chown(path, uid, gid) < 0)
3397 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3401 /* Allocates the cpuset in the right size */
3404 if (!(r = CPU_ALLOC(n)))
3407 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3408 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3418 if (errno != EINVAL)
3425 void status_vprintf(const char *format, va_list ap) {
3431 /* This independent of logging, as status messages are
3432 * optional and go exclusively to the console. */
3434 if (vasprintf(&s, format, ap) < 0)
3437 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3440 write(fd, s, strlen(s));
3446 close_nointr_nofail(fd);
3449 void status_printf(const char *format, ...) {
3454 va_start(ap, format);
3455 status_vprintf(format, ap);
3459 void status_welcome(void) {
3460 char *pretty_name = NULL, *ansi_color = NULL;
3461 const char *const_pretty = NULL, *const_color = NULL;
3464 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3465 "PRETTY_NAME", &pretty_name,
3466 "ANSI_COLOR", &ansi_color,
3470 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3473 #if defined(TARGET_FEDORA)
3475 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3478 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3482 if (!ansi_color && pretty_name) {
3484 /* This tries to mimic the color magic the old Red Hat sysinit
3487 if (startswith(pretty_name, "Red Hat"))
3488 const_color = "0;31"; /* Red for RHEL */
3489 else if (startswith(pretty_name, "Fedora"))
3490 const_color = "0;34"; /* Blue for Fedora */
3493 #elif defined(TARGET_SUSE)
3496 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3499 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3504 const_color = "0;32"; /* Green for openSUSE */
3506 #elif defined(TARGET_GENTOO)
3509 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3512 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3517 const_color = "1;34"; /* Light Blue for Gentoo */
3519 #elif defined(TARGET_ALTLINUX)
3522 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3525 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3530 const_color = "0;36"; /* Cyan for ALTLinux */
3533 #elif defined(TARGET_DEBIAN)
3538 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3541 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3543 pretty_name = strappend("Debian ", version);
3547 log_warning("Failed to allocate Debian version string.");
3552 const_color = "1;31"; /* Light Red for Debian */
3554 #elif defined(TARGET_UBUNTU)
3556 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3557 "DISTRIB_DESCRIPTION", &pretty_name,
3561 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3565 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3567 #elif defined(TARGET_MANDRIVA)
3572 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3574 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3576 p = strstr(s, " release ");
3580 p[strcspn(p, " ")] = '\0';
3582 /* This corresponds to standard rc.sysinit */
3583 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3584 const_color = "1;36";
3586 log_warning("Failed to allocate Mandriva version string.");
3588 log_warning("Failed to parse /etc/mandriva-release");
3592 #elif defined(TARGET_MEEGO)
3595 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3598 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3603 const_color = "1;35"; /* Bright Magenta for MeeGo */
3606 if (!pretty_name && !const_pretty)
3607 const_pretty = "Linux";
3609 if (!ansi_color && !const_color)
3612 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3613 const_color ? const_color : ansi_color,
3614 const_pretty ? const_pretty : pretty_name);
3620 char *replace_env(const char *format, char **env) {
3627 const char *e, *word = format;
3632 for (e = format; *e; e ++) {
3643 if (!(k = strnappend(r, word, e-word-1)))
3652 } else if (*e == '$') {
3653 if (!(k = strnappend(r, word, e-word)))
3669 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3672 if (!(k = strappend(r, t)))
3685 if (!(k = strnappend(r, word, e-word)))
3696 char **replace_env_argv(char **argv, char **env) {
3698 unsigned k = 0, l = 0;
3700 l = strv_length(argv);
3702 if (!(r = new(char*, l+1)))
3705 STRV_FOREACH(i, argv) {
3707 /* If $FOO appears as single word, replace it by the split up variable */
3708 if ((*i)[0] == '$' && (*i)[1] != '{') {
3713 if ((e = strv_env_get(env, *i+1))) {
3715 if (!(m = strv_split_quoted(e))) {
3726 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3735 memcpy(r + k, m, q * sizeof(char*));
3743 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3744 if (!(r[k++] = replace_env(*i, env))) {
3755 static __thread int parsed_columns = 0;
3758 if (parsed_columns > 0)
3759 return parsed_columns;
3761 if ((e = getenv("COLUMNS")))
3762 parsed_columns = atoi(e);
3764 if (parsed_columns <= 0) {
3768 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3769 parsed_columns = ws.ws_col;
3772 if (parsed_columns <= 0)
3773 parsed_columns = 80;
3775 return parsed_columns;
3778 int running_in_chroot(void) {
3784 /* Only works as root */
3786 if (stat("/proc/1/root", &a) < 0)
3789 if (stat("/", &b) < 0)
3793 a.st_dev != b.st_dev ||
3794 a.st_ino != b.st_ino;
3797 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3802 assert(percent <= 100);
3803 assert(length >= 3);
3807 if (l <= 3 || l <= length)
3810 if (!(r = new0(char, length+1)))
3813 x = (length * percent) / 100;
3823 s + l - (length - x - 3),
3829 int touch(const char *path) {
3834 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3837 close_nointr_nofail(fd);
3841 char *unquote(const char *s, const char* quotes) {
3845 if ((l = strlen(s)) < 2)
3848 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3849 return strndup(s+1, l-2);
3854 char *normalize_env_assignment(const char *s) {
3855 char *name, *value, *p, *r;
3860 if (!(r = strdup(s)))
3866 if (!(name = strndup(s, p - s)))
3869 if (!(p = strdup(p+1))) {
3874 value = unquote(strstrip(p), QUOTES);
3882 if (asprintf(&r, "%s=%s", name, value) < 0)
3891 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3902 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3914 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3921 if ((r = wait_for_terminate(pid, &status)) < 0) {
3922 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3926 if (status.si_code == CLD_EXITED) {
3927 if (status.si_status != 0) {
3928 log_warning("%s failed with error code %i.", name, status.si_status);
3929 return status.si_status;
3932 log_debug("%s succeeded.", name);
3935 } else if (status.si_code == CLD_KILLED ||
3936 status.si_code == CLD_DUMPED) {
3938 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3942 log_warning("%s failed due to unknown reason.", name);
3949 /* Make sure nobody waits for us on a socket anymore */
3950 close_all_fds(NULL, 0);
3958 bool null_or_empty(struct stat *st) {
3961 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3964 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3970 int null_or_empty_path(const char *fn) {
3975 if (stat(fn, &st) < 0)
3978 return null_or_empty(&st);
3981 DIR *xopendirat(int fd, const char *name, int flags) {
3985 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3988 if (!(d = fdopendir(nfd))) {
3989 close_nointr_nofail(nfd);
3996 int signal_from_string_try_harder(const char *s) {
4000 if ((signo = signal_from_string(s)) <= 0)
4001 if (startswith(s, "SIG"))
4002 return signal_from_string(s+3);
4007 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4013 if (!dual_timestamp_is_set(t))
4016 fprintf(f, "%s=%llu %llu\n",
4018 (unsigned long long) t->realtime,
4019 (unsigned long long) t->monotonic);
4022 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4023 unsigned long long a, b;
4028 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4029 log_debug("Failed to parse finish timestamp value %s", value);
4036 char *fstab_node_to_udev_node(const char *p) {
4040 /* FIXME: to follow udev's logic 100% we need to leave valid
4041 * UTF8 chars unescaped */
4043 if (startswith(p, "LABEL=")) {
4045 if (!(u = unquote(p+6, "\"\'")))
4048 t = xescape(u, "/ ");
4054 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4063 if (startswith(p, "UUID=")) {
4065 if (!(u = unquote(p+5, "\"\'")))
4068 t = xescape(u, "/ ");
4074 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4086 void filter_environ(const char *prefix) {
4093 for (i = 0, j = 0; environ[i]; i++) {
4095 if (startswith(environ[i], prefix))
4098 environ[j++] = environ[i];
4104 bool tty_is_vc(const char *tty) {
4107 if (startswith(tty, "/dev/"))
4110 return vtnr_from_tty(tty) >= 0;
4113 int vtnr_from_tty(const char *tty) {
4118 if (startswith(tty, "/dev/"))
4121 if (!startswith(tty, "tty") )
4124 if (tty[3] < '0' || tty[3] > '9')
4127 r = safe_atoi(tty+3, &i);
4131 if (i < 0 || i > 63)
4137 const char *default_term_for_tty(const char *tty) {
4138 char *active = NULL;
4143 if (startswith(tty, "/dev/"))
4146 /* Resolve where /dev/console is pointing when determining
4148 if (streq(tty, "console"))
4149 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4150 /* If multiple log outputs are configured the
4151 * last one is what /dev/console points to */
4152 if ((tty = strrchr(active, ' ')))
4158 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4164 /* Returns a short identifier for the various VM implementations */
4165 int detect_vm(const char **id) {
4167 #if defined(__i386__) || defined(__x86_64__)
4169 /* Both CPUID and DMI are x86 specific interfaces... */
4171 static const char *const dmi_vendors[] = {
4172 "/sys/class/dmi/id/sys_vendor",
4173 "/sys/class/dmi/id/board_vendor",
4174 "/sys/class/dmi/id/bios_vendor"
4177 static const char dmi_vendor_table[] =
4179 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4180 "VMware\0" "vmware\0"
4182 "Microsoft Corporation\0" "microsoft\0"
4183 "innotek GmbH\0" "oracle\0"
4185 "Bochs\0" "bochs\0";
4187 static const char cpuid_vendor_table[] =
4188 "XenVMMXenVMM\0" "xen\0"
4189 "KVMKVMKVM\0" "kvm\0"
4190 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4191 "VMwareVMware\0" "vmware\0"
4192 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4193 "Microsoft Hv\0" "microsoft\0";
4204 /* http://lwn.net/Articles/301888/ */
4207 #if defined (__i386__)
4210 #elif defined (__amd64__)
4215 /* First detect whether there is a hypervisor */
4217 __asm__ __volatile__ (
4218 /* ebx/rbx is being used for PIC! */
4219 " push %%"REG_b" \n\t"
4221 " pop %%"REG_b" \n\t"
4223 : "=a" (eax), "=c" (ecx)
4227 hypervisor = !!(ecx & 0x80000000U);
4231 /* There is a hypervisor, see what it is */
4233 __asm__ __volatile__ (
4234 /* ebx/rbx is being used for PIC! */
4235 " push %%"REG_b" \n\t"
4237 " mov %%ebx, %1 \n\t"
4238 " pop %%"REG_b" \n\t"
4240 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4244 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4245 if (streq(sig.text, j)) {
4254 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4257 const char *found = NULL;
4259 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4266 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4267 if (startswith(s, j))
4290 int detect_container(const char **id) {
4293 /* Unfortunately many of these operations require root access
4294 * in one way or another */
4299 if (running_in_chroot() > 0) {
4307 /* /proc/vz exists in container and outside of the container,
4308 * /proc/bc only outside of the container. */
4309 if (access("/proc/vz", F_OK) >= 0 &&
4310 access("/proc/bc", F_OK) < 0) {
4318 if ((f = fopen("/proc/self/cgroup", "re"))) {
4321 char line[LINE_MAX], *p;
4323 if (!fgets(line, sizeof(line), f))
4326 if (!(p = strchr(strstrip(line), ':')))
4329 if (strncmp(p, ":ns:", 4))
4332 if (!streq(p, ":ns:/")) {
4348 /* Returns a short identifier for the various VM/container implementations */
4349 int detect_virtualization(const char **id) {
4350 static __thread const char *cached_id = NULL;
4356 if (cached_id == (const char*) -1)
4365 if ((r = detect_container(&_id)) != 0)
4368 r = detect_vm(&_id);
4377 cached_id = (const char*) -1;
4382 bool dirent_is_file(struct dirent *de) {
4385 if (ignore_file(de->d_name))
4388 if (de->d_type != DT_REG &&
4389 de->d_type != DT_LNK &&
4390 de->d_type != DT_UNKNOWN)
4396 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4399 Hashmap *pids = NULL;
4403 /* Executes all binaries in a directory in parallel and waits
4404 * until all they all finished. */
4407 if (!(_d = opendir(directory))) {
4409 if (errno == ENOENT)
4412 log_error("Failed to enumerate directory %s: %m", directory);
4419 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4420 log_error("Failed to allocate set.");
4424 while ((de = readdir(d))) {
4429 if (!dirent_is_file(de))
4432 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4433 log_error("Out of memory");
4437 if ((pid = fork()) < 0) {
4438 log_error("Failed to fork: %m");
4457 log_error("Failed to execute %s: %m", path);
4458 _exit(EXIT_FAILURE);
4461 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4463 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4464 log_error("Failed to add PID to set: %s", strerror(-k));
4469 while (!hashmap_isempty(pids)) {
4474 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4479 log_error("waitid() failed: %m");
4483 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4484 if (!is_clean_exit(si.si_code, si.si_status)) {
4485 if (si.si_code == CLD_EXITED)
4486 log_error("%s exited with exit status %i.", path, si.si_status);
4488 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4490 log_debug("%s exited successfully.", path);
4501 hashmap_free_free(pids);
4504 int kill_and_sigcont(pid_t pid, int sig) {
4507 r = kill(pid, sig) < 0 ? -errno : 0;
4515 bool nulstr_contains(const char*nulstr, const char *needle) {
4521 NULSTR_FOREACH(i, nulstr)
4522 if (streq(i, needle))
4528 bool plymouth_running(void) {
4529 return access("/run/plymouth/pid", F_OK) >= 0;
4532 void parse_syslog_priority(char **p, int *priority) {
4533 int a = 0, b = 0, c = 0;
4543 if (!strchr(*p, '>'))
4546 if ((*p)[2] == '>') {
4547 c = undecchar((*p)[1]);
4549 } else if ((*p)[3] == '>') {
4550 b = undecchar((*p)[1]);
4551 c = undecchar((*p)[2]);
4553 } else if ((*p)[4] == '>') {
4554 a = undecchar((*p)[1]);
4555 b = undecchar((*p)[2]);
4556 c = undecchar((*p)[3]);
4561 if (a < 0 || b < 0 || c < 0)
4564 *priority = a*100+b*10+c;
4568 int have_effective_cap(int value) {
4570 cap_flag_value_t fv;
4573 if (!(cap = cap_get_proc()))
4576 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4585 char* strshorten(char *s, size_t l) {
4594 static bool hostname_valid_char(char c) {
4596 (c >= 'a' && c <= 'z') ||
4597 (c >= 'A' && c <= 'Z') ||
4598 (c >= '0' && c <= '9') ||
4604 bool hostname_is_valid(const char *s) {
4610 for (p = s; *p; p++)
4611 if (!hostname_valid_char(*p))
4614 if (p-s > HOST_NAME_MAX)
4620 char* hostname_cleanup(char *s) {
4623 for (p = s, d = s; *p; p++)
4624 if ((*p >= 'a' && *p <= 'z') ||
4625 (*p >= 'A' && *p <= 'Z') ||
4626 (*p >= '0' && *p <= '9') ||
4634 strshorten(s, HOST_NAME_MAX);
4638 int pipe_eof(int fd) {
4639 struct pollfd pollfd;
4644 pollfd.events = POLLIN|POLLHUP;
4646 r = poll(&pollfd, 1, 0);
4653 return pollfd.revents & POLLHUP;
4656 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4667 t = new(char, strlen(path) + 1 + 6 + 1);
4671 fn = file_name_from_path(path);
4675 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4677 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4683 f = fdopen(fd, "we");
4696 int terminal_vhangup_fd(int fd) {
4699 if (ioctl(fd, TIOCVHANGUP) < 0)
4705 int terminal_vhangup(const char *name) {
4708 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4712 r = terminal_vhangup_fd(fd);
4713 close_nointr_nofail(fd);
4718 int vt_disallocate(const char *name) {
4722 /* Deallocate the VT if possible. If not possible
4723 * (i.e. because it is the active one), at least clear it
4724 * entirely (including the scrollback buffer) */
4726 if (!startswith(name, "/dev/"))
4729 if (!tty_is_vc(name)) {
4730 /* So this is not a VT. I guess we cannot deallocate
4731 * it then. But let's at least clear the screen */
4733 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4738 "\033[r" /* clear scrolling region */
4739 "\033[H" /* move home */
4740 "\033[2J", /* clear screen */
4742 close_nointr_nofail(fd);
4747 if (!startswith(name, "/dev/tty"))
4750 r = safe_atou(name+8, &u);
4757 /* Try to deallocate */
4758 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4762 r = ioctl(fd, VT_DISALLOCATE, u);
4763 close_nointr_nofail(fd);
4771 /* Couldn't deallocate, so let's clear it fully with
4773 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4778 "\033[r" /* clear scrolling region */
4779 "\033[H" /* move home */
4780 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4782 close_nointr_nofail(fd);
4788 static int file_is_conf(const struct dirent *d, const char *suffix) {
4791 if (ignore_file(d->d_name))
4794 if (d->d_type != DT_REG &&
4795 d->d_type != DT_LNK &&
4796 d->d_type != DT_UNKNOWN)
4799 return endswith(d->d_name, suffix);
4802 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4807 dir = opendir(path);
4809 if (errno == ENOENT)
4814 for (de = readdir(dir); de; de = readdir(dir)) {
4818 if (!file_is_conf(de, suffix))
4821 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4826 f = canonicalize_file_name(p);
4828 log_error("Failed to canonicalize file name '%s': %m", p);
4834 log_debug("found: %s\n", f);
4835 base = f + strlen(path) + 1;
4836 if (hashmap_put(h, base, f) <= 0)
4845 static int base_cmp(const void *a, const void *b) {
4846 const char *s1, *s2;
4848 s1 = *(char * const *)a;
4849 s2 = *(char * const *)b;
4850 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4853 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4856 char **files = NULL;
4862 dirs = strv_new_ap(dir, ap);
4868 if (!strv_path_canonicalize(dirs)) {
4872 if (!strv_uniq(dirs)) {
4877 fh = hashmap_new(string_hash_func, string_compare_func);
4883 STRV_FOREACH(p, dirs) {
4884 if (files_add(fh, *p, suffix) < 0) {
4885 log_error("Failed to search for files.");
4891 files = hashmap_get_strv(fh);
4892 if (files == NULL) {
4893 log_error("Failed to compose list of files.");
4898 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4907 int hwclock_is_localtime(void) {
4912 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4918 f = fopen("/etc/adjtime", "re");
4920 char line[LINE_MAX];
4923 b = fgets(line, sizeof(line), f) &&
4924 fgets(line, sizeof(line), f) &&
4925 fgets(line, sizeof(line), f);
4934 local = streq(line, "LOCAL");
4936 } else if (errno != -ENOENT)
4942 int hwclock_apply_localtime_delta(int *min) {
4943 const struct timeval *tv_null = NULL;
4949 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4950 assert_se(tm = localtime(&ts.tv_sec));
4951 minuteswest = tm->tm_gmtoff / 60;
4953 tz.tz_minuteswest = -minuteswest;
4954 tz.tz_dsttime = 0; /* DST_NONE*/
4957 * If the hardware clock does not run in UTC, but in local time:
4958 * The very first time we set the kernel's timezone, it will warp
4959 * the clock so that it runs in UTC instead of local time.
4961 if (settimeofday(tv_null, &tz) < 0)
4968 int hwclock_reset_localtime_delta(void) {
4969 const struct timeval *tv_null = NULL;
4972 tz.tz_minuteswest = 0;
4973 tz.tz_dsttime = 0; /* DST_NONE*/
4975 if (settimeofday(tv_null, &tz) < 0)
4981 int hwclock_get_time(struct tm *tm) {
4987 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
4991 /* This leaves the timezone fields of struct tm
4993 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
4996 /* We don't now daylight saving, so we reset this in order not
4997 * to confused mktime(). */
5000 close_nointr_nofail(fd);
5005 int hwclock_set_time(const struct tm *tm) {
5011 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5015 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5018 close_nointr_nofail(fd);
5023 int copy_file(const char *from, const char *to) {
5029 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5033 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5035 close_nointr_nofail(fdf);
5043 n = read(fdf, buf, sizeof(buf));
5047 close_nointr_nofail(fdf);
5058 k = loop_write(fdt, buf, n, false);
5060 r = k < 0 ? k : (errno ? -errno : -EIO);
5062 close_nointr_nofail(fdf);
5070 close_nointr_nofail(fdf);
5071 r = close_nointr(fdt);
5081 int symlink_or_copy(const char *from, const char *to) {
5082 char *pf = NULL, *pt = NULL;
5089 if (parent_of_path(from, &pf) < 0 ||
5090 parent_of_path(to, &pt) < 0) {
5095 if (stat(pf, &a) < 0 ||
5101 if (a.st_dev != b.st_dev) {
5105 return copy_file(from, to);
5108 if (symlink(from, to) < 0) {
5122 int symlink_or_copy_atomic(const char *from, const char *to) {
5126 unsigned long long ull;
5133 t = new(char, strlen(to) + 1 + 16 + 1);
5137 fn = file_name_from_path(to);
5141 x = stpcpy(t+k+1, fn);
5144 for (i = 0; i < 16; i++) {
5145 *(x++) = hexchar(ull & 0xF);
5151 r = symlink_or_copy(from, t);
5158 if (rename(t, to) < 0) {
5169 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5177 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5180 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5183 r = read_one_line_file(p, &s);
5188 r = safe_atou32(s, &u);
5194 if (u == (uint32_t) -1 || u <= 0)
5201 bool display_is_local(const char *display) {
5205 display[0] == ':' &&
5206 display[1] >= '0' &&
5210 int socket_from_display(const char *display, char **path) {
5217 if (!display_is_local(display))
5220 k = strspn(display+1, "0123456789");
5222 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5226 c = stpcpy(f, "/tmp/.X11-unix/X");
5227 memcpy(c, display+1, k);
5235 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5245 /* We enforce some special rules for uid=0: in order to avoid
5246 * NSS lookups for root we hardcode its data. */
5248 if (streq(*username, "root") || streq(*username, "0")) {
5256 if (safe_atolu(*username, &lu) >= 0) {
5258 p = getpwuid((uid_t) lu);
5260 /* If there are multiple users with the same id, make
5261 * sure to leave $USER to the configured value instead
5262 * of the first occurrence in the database. However if
5263 * the uid was configured by a numeric uid, then let's
5264 * pick the real username from /etc/passwd. */
5266 *username = p->pw_name;
5269 p = getpwnam(*username);
5273 return errno != 0 ? -errno : -ESRCH;
5281 int glob_exists(const char *path) {
5289 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5291 if (k == GLOB_NOMATCH)
5293 else if (k == GLOB_NOSPACE)
5296 r = !strv_isempty(g.gl_pathv);
5298 r = errno ? -errno : -EIO;
5305 int dirent_ensure_type(DIR *d, struct dirent *de) {
5311 if (de->d_type != DT_UNKNOWN)
5314 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5318 S_ISREG(st.st_mode) ? DT_REG :
5319 S_ISDIR(st.st_mode) ? DT_DIR :
5320 S_ISLNK(st.st_mode) ? DT_LNK :
5321 S_ISFIFO(st.st_mode) ? DT_FIFO :
5322 S_ISSOCK(st.st_mode) ? DT_SOCK :
5323 S_ISCHR(st.st_mode) ? DT_CHR :
5324 S_ISBLK(st.st_mode) ? DT_BLK :
5330 int in_search_path(const char *path, char **search) {
5334 r = parent_of_path(path, &parent);
5340 STRV_FOREACH(i, search) {
5341 if (path_equal(parent, *i)) {
5352 static const char *const ioprio_class_table[] = {
5353 [IOPRIO_CLASS_NONE] = "none",
5354 [IOPRIO_CLASS_RT] = "realtime",
5355 [IOPRIO_CLASS_BE] = "best-effort",
5356 [IOPRIO_CLASS_IDLE] = "idle"
5359 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5361 static const char *const sigchld_code_table[] = {
5362 [CLD_EXITED] = "exited",
5363 [CLD_KILLED] = "killed",
5364 [CLD_DUMPED] = "dumped",
5365 [CLD_TRAPPED] = "trapped",
5366 [CLD_STOPPED] = "stopped",
5367 [CLD_CONTINUED] = "continued",
5370 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5372 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5373 [LOG_FAC(LOG_KERN)] = "kern",
5374 [LOG_FAC(LOG_USER)] = "user",
5375 [LOG_FAC(LOG_MAIL)] = "mail",
5376 [LOG_FAC(LOG_DAEMON)] = "daemon",
5377 [LOG_FAC(LOG_AUTH)] = "auth",
5378 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5379 [LOG_FAC(LOG_LPR)] = "lpr",
5380 [LOG_FAC(LOG_NEWS)] = "news",
5381 [LOG_FAC(LOG_UUCP)] = "uucp",
5382 [LOG_FAC(LOG_CRON)] = "cron",
5383 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5384 [LOG_FAC(LOG_FTP)] = "ftp",
5385 [LOG_FAC(LOG_LOCAL0)] = "local0",
5386 [LOG_FAC(LOG_LOCAL1)] = "local1",
5387 [LOG_FAC(LOG_LOCAL2)] = "local2",
5388 [LOG_FAC(LOG_LOCAL3)] = "local3",
5389 [LOG_FAC(LOG_LOCAL4)] = "local4",
5390 [LOG_FAC(LOG_LOCAL5)] = "local5",
5391 [LOG_FAC(LOG_LOCAL6)] = "local6",
5392 [LOG_FAC(LOG_LOCAL7)] = "local7"
5395 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5397 static const char *const log_level_table[] = {
5398 [LOG_EMERG] = "emerg",
5399 [LOG_ALERT] = "alert",
5400 [LOG_CRIT] = "crit",
5402 [LOG_WARNING] = "warning",
5403 [LOG_NOTICE] = "notice",
5404 [LOG_INFO] = "info",
5405 [LOG_DEBUG] = "debug"
5408 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5410 static const char* const sched_policy_table[] = {
5411 [SCHED_OTHER] = "other",
5412 [SCHED_BATCH] = "batch",
5413 [SCHED_IDLE] = "idle",
5414 [SCHED_FIFO] = "fifo",
5418 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5420 static const char* const rlimit_table[] = {
5421 [RLIMIT_CPU] = "LimitCPU",
5422 [RLIMIT_FSIZE] = "LimitFSIZE",
5423 [RLIMIT_DATA] = "LimitDATA",
5424 [RLIMIT_STACK] = "LimitSTACK",
5425 [RLIMIT_CORE] = "LimitCORE",
5426 [RLIMIT_RSS] = "LimitRSS",
5427 [RLIMIT_NOFILE] = "LimitNOFILE",
5428 [RLIMIT_AS] = "LimitAS",
5429 [RLIMIT_NPROC] = "LimitNPROC",
5430 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5431 [RLIMIT_LOCKS] = "LimitLOCKS",
5432 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5433 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5434 [RLIMIT_NICE] = "LimitNICE",
5435 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5436 [RLIMIT_RTTIME] = "LimitRTTIME"
5439 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5441 static const char* const ip_tos_table[] = {
5442 [IPTOS_LOWDELAY] = "low-delay",
5443 [IPTOS_THROUGHPUT] = "throughput",
5444 [IPTOS_RELIABILITY] = "reliability",
5445 [IPTOS_LOWCOST] = "low-cost",
5448 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5450 static const char *const signal_table[] = {
5467 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5478 [SIGVTALRM] = "VTALRM",
5480 [SIGWINCH] = "WINCH",
5486 DEFINE_STRING_TABLE_LOOKUP(signal, int);