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>
66 #include "exit-status.h"
70 char **saved_argv = NULL;
72 size_t page_size(void) {
73 static __thread size_t pgsz = 0;
79 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
86 bool streq_ptr(const char *a, const char *b) {
88 /* Like streq(), but tries to make sense of NULL pointers */
99 usec_t now(clockid_t clock_id) {
102 assert_se(clock_gettime(clock_id, &ts) == 0);
104 return timespec_load(&ts);
107 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
110 ts->realtime = now(CLOCK_REALTIME);
111 ts->monotonic = now(CLOCK_MONOTONIC);
116 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
125 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
127 ts->monotonic = now(CLOCK_MONOTONIC);
129 if ((int64_t) ts->monotonic > delta)
130 ts->monotonic -= delta;
138 usec_t timespec_load(const struct timespec *ts) {
142 (usec_t) ts->tv_sec * USEC_PER_SEC +
143 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
146 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
149 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
150 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
155 usec_t timeval_load(const struct timeval *tv) {
159 (usec_t) tv->tv_sec * USEC_PER_SEC +
160 (usec_t) tv->tv_usec;
163 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
166 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
167 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
172 bool endswith(const char *s, const char *postfix) {
179 pl = strlen(postfix);
187 return memcmp(s + sl - pl, postfix, pl) == 0;
190 bool startswith(const char *s, const char *prefix) {
205 return memcmp(s, prefix, pl) == 0;
208 bool startswith_no_case(const char *s, const char *prefix) {
224 for(i = 0; i < pl; ++i) {
225 if (tolower(s[i]) != tolower(prefix[i]))
232 bool first_word(const char *s, const char *word) {
247 if (memcmp(s, word, wl) != 0)
251 strchr(WHITESPACE, s[wl]);
254 int close_nointr(int fd) {
269 void close_nointr_nofail(int fd) {
270 int saved_errno = errno;
272 /* like close_nointr() but cannot fail, and guarantees errno
275 assert_se(close_nointr(fd) == 0);
280 void close_many(const int fds[], unsigned n_fd) {
283 for (i = 0; i < n_fd; i++)
284 close_nointr_nofail(fds[i]);
287 int parse_boolean(const char *v) {
290 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
292 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
298 int parse_pid(const char *s, pid_t* ret_pid) {
299 unsigned long ul = 0;
306 if ((r = safe_atolu(s, &ul)) < 0)
311 if ((unsigned long) pid != ul)
321 int parse_uid(const char *s, uid_t* ret_uid) {
322 unsigned long ul = 0;
329 if ((r = safe_atolu(s, &ul)) < 0)
334 if ((unsigned long) uid != ul)
341 int safe_atou(const char *s, unsigned *ret_u) {
349 l = strtoul(s, &x, 0);
351 if (!x || *x || errno)
352 return errno ? -errno : -EINVAL;
354 if ((unsigned long) (unsigned) l != l)
357 *ret_u = (unsigned) l;
361 int safe_atoi(const char *s, int *ret_i) {
369 l = strtol(s, &x, 0);
371 if (!x || *x || errno)
372 return errno ? -errno : -EINVAL;
374 if ((long) (int) l != l)
381 int safe_atollu(const char *s, long long unsigned *ret_llu) {
383 unsigned long long l;
389 l = strtoull(s, &x, 0);
391 if (!x || *x || errno)
392 return errno ? -errno : -EINVAL;
398 int safe_atolli(const char *s, long long int *ret_lli) {
406 l = strtoll(s, &x, 0);
408 if (!x || *x || errno)
409 return errno ? -errno : -EINVAL;
415 /* Split a string into words. */
416 char *split(const char *c, size_t *l, const char *separator, char **state) {
419 current = *state ? *state : (char*) c;
421 if (!*current || *c == 0)
424 current += strspn(current, separator);
425 *l = strcspn(current, separator);
428 return (char*) current;
431 /* Split a string into words, but consider strings enclosed in '' and
432 * "" as words even if they include spaces. */
433 char *split_quoted(const char *c, size_t *l, char **state) {
435 bool escaped = false;
437 current = *state ? *state : (char*) c;
439 if (!*current || *c == 0)
442 current += strspn(current, WHITESPACE);
444 if (*current == '\'') {
447 for (e = current; *e; e++) {
457 *state = *e == 0 ? e : e+1;
458 } else if (*current == '\"') {
461 for (e = current; *e; e++) {
471 *state = *e == 0 ? e : e+1;
473 for (e = current; *e; e++) {
478 else if (strchr(WHITESPACE, *e))
485 return (char*) current;
488 char **split_path_and_make_absolute(const char *p) {
492 if (!(l = strv_split(p, ":")))
495 if (!strv_path_make_absolute_cwd(l)) {
503 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
506 char fn[PATH_MAX], line[LINE_MAX], *p;
512 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
515 if (!(f = fopen(fn, "re")))
518 if (!(fgets(line, sizeof(line), f))) {
526 /* Let's skip the pid and comm fields. The latter is enclosed
527 * in () but does not escape any () in its value, so let's
528 * skip over it manually */
530 if (!(p = strrchr(line, ')')))
541 if ((long unsigned) (pid_t) ppid != ppid)
544 *_ppid = (pid_t) ppid;
549 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
552 char fn[PATH_MAX], line[LINE_MAX], *p;
557 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
560 if (!(f = fopen(fn, "re")))
563 if (!(fgets(line, sizeof(line), f))) {
571 /* Let's skip the pid and comm fields. The latter is enclosed
572 * in () but does not escape any () in its value, so let's
573 * skip over it manually */
575 if (!(p = strrchr(line, ')')))
596 "%*d " /* priority */
598 "%*d " /* num_threads */
599 "%*d " /* itrealvalue */
600 "%llu " /* starttime */,
607 int write_one_line_file(const char *fn, const char *line) {
614 if (!(f = fopen(fn, "we")))
618 if (fputs(line, f) < 0) {
623 if (!endswith(line, "\n"))
641 int fchmod_umask(int fd, mode_t m) {
646 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
652 int write_one_line_file_atomic(const char *fn, const char *line) {
660 r = fopen_temporary(fn, &f, &p);
664 fchmod_umask(fileno(f), 0644);
667 if (fputs(line, f) < 0) {
672 if (!endswith(line, "\n"))
683 if (rename(p, fn) < 0)
699 int read_one_line_file(const char *fn, char **line) {
702 char t[LINE_MAX], *c;
707 if (!(f = fopen(fn, "re")))
710 if (!(fgets(t, sizeof(t), f))) {
715 if (!(c = strdup(t))) {
730 int read_full_file(const char *fn, char **contents, size_t *size) {
737 if (!(f = fopen(fn, "re")))
740 if (fstat(fileno(f), &st) < 0) {
746 if (st.st_size > 4*1024*1024) {
751 n = st.st_size > 0 ? st.st_size : LINE_MAX;
758 if (!(t = realloc(buf, n+1))) {
764 k = fread(buf + l, 1, n - l, f);
779 if (n > 4*1024*1024) {
787 else if (!(buf = calloc(1, 1))) {
809 const char *separator, ...) {
817 if ((r = read_full_file(fname, &contents, NULL)) < 0)
822 const char *key = NULL;
824 p += strspn(p, separator);
825 p += strspn(p, WHITESPACE);
830 if (!strchr(COMMENTS, *p)) {
834 va_start(ap, separator);
835 while ((key = va_arg(ap, char *))) {
839 value = va_arg(ap, char **);
842 if (strncmp(p, key, n) != 0 ||
847 n = strcspn(p, separator);
850 strchr(QUOTES, p[0]) &&
852 v = strndup(p+1, n-2);
863 /* return empty value strings as NULL */
880 p += strcspn(p, separator);
899 if (!(f = fopen(fname, "re")))
903 char l[LINE_MAX], *p, *u;
906 if (!fgets(l, sizeof(l), f)) {
919 if (strchr(COMMENTS, *p))
922 if (!(u = normalize_env_assignment(p))) {
923 log_error("Out of memory");
928 t = strv_append(m, u);
932 log_error("Out of memory");
955 int write_env_file(const char *fname, char **l) {
960 r = fopen_temporary(fname, &f, &p);
964 fchmod_umask(fileno(f), 0644);
980 if (rename(p, fname) < 0)
995 char *truncate_nl(char *s) {
998 s[strcspn(s, NEWLINE)] = 0;
1002 int get_process_name(pid_t pid, char **name) {
1009 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1012 r = read_one_line_file(p, name);
1021 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1029 assert(max_length > 0);
1032 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1041 if (!(r = new(char, max_length))) {
1048 while ((c = getc(f)) != EOF) {
1070 size_t n = MIN(left-1, 3U);
1071 memcpy(k, "...", n);
1078 /* Kernel threads have no argv[] */
1085 if ((h = get_process_name(pid, &t)) < 0)
1088 h = asprintf(&r, "[%s]", t);
1099 char *strnappend(const char *s, const char *suffix, size_t b) {
1107 return strndup(suffix, b);
1117 if (!(r = new(char, a+b+1)))
1121 memcpy(r+a, suffix, b);
1127 char *strappend(const char *s, const char *suffix) {
1128 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1131 int readlink_malloc(const char *p, char **r) {
1141 if (!(c = new(char, l)))
1144 if ((n = readlink(p, c, l-1)) < 0) {
1150 if ((size_t) n < l-1) {
1161 int readlink_and_make_absolute(const char *p, char **r) {
1168 if ((j = readlink_malloc(p, &target)) < 0)
1171 k = file_in_same_dir(p, target);
1181 int readlink_and_canonicalize(const char *p, char **r) {
1188 j = readlink_and_make_absolute(p, &t);
1192 s = canonicalize_file_name(t);
1199 path_kill_slashes(*r);
1204 int parent_of_path(const char *path, char **_r) {
1205 const char *e, *a = NULL, *b = NULL, *p;
1215 for (e = path; *e; e++) {
1217 if (!slash && *e == '/') {
1221 } else if (slash && *e != '/')
1236 r = strndup(path, p-path);
1246 char *file_name_from_path(const char *p) {
1251 if ((r = strrchr(p, '/')))
1257 bool path_is_absolute(const char *p) {
1263 bool is_path(const char *p) {
1265 return !!strchr(p, '/');
1268 char *path_make_absolute(const char *p, const char *prefix) {
1273 /* Makes every item in the list an absolute path by prepending
1274 * the prefix, if specified and necessary */
1276 if (path_is_absolute(p) || !prefix)
1279 if (asprintf(&r, "%s/%s", prefix, p) < 0)
1285 char *path_make_absolute_cwd(const char *p) {
1290 /* Similar to path_make_absolute(), but prefixes with the
1291 * current working directory. */
1293 if (path_is_absolute(p))
1296 if (!(cwd = get_current_dir_name()))
1299 r = path_make_absolute(p, cwd);
1305 char **strv_path_make_absolute_cwd(char **l) {
1308 /* Goes through every item in the string list and makes it
1309 * absolute. This works in place and won't rollback any
1310 * changes on failure. */
1312 STRV_FOREACH(s, l) {
1315 if (!(t = path_make_absolute_cwd(*s)))
1325 char **strv_path_canonicalize(char **l) {
1328 bool enomem = false;
1330 if (strv_isempty(l))
1333 /* Goes through every item in the string list and canonicalize
1334 * the path. This works in place and won't rollback any
1335 * changes on failure. */
1337 STRV_FOREACH(s, l) {
1340 t = path_make_absolute_cwd(*s);
1349 u = canonicalize_file_name(t);
1353 if (errno == ENOMEM || !errno)
1370 char **strv_path_remove_empty(char **l) {
1376 for (f = t = l; *f; f++) {
1378 if (dir_is_empty(*f) > 0) {
1390 int reset_all_signal_handlers(void) {
1393 for (sig = 1; sig < _NSIG; sig++) {
1394 struct sigaction sa;
1396 if (sig == SIGKILL || sig == SIGSTOP)
1400 sa.sa_handler = SIG_DFL;
1401 sa.sa_flags = SA_RESTART;
1403 /* On Linux the first two RT signals are reserved by
1404 * glibc, and sigaction() will return EINVAL for them. */
1405 if ((sigaction(sig, &sa, NULL) < 0))
1406 if (errno != EINVAL)
1413 char *strstrip(char *s) {
1416 /* Drops trailing whitespace. Modifies the string in
1417 * place. Returns pointer to first non-space character */
1419 s += strspn(s, WHITESPACE);
1421 for (e = s; *e; e++)
1422 if (!strchr(WHITESPACE, *e))
1433 char *delete_chars(char *s, const char *bad) {
1436 /* Drops all whitespace, regardless where in the string */
1438 for (f = s, t = s; *f; f++) {
1439 if (strchr(bad, *f))
1450 char *file_in_same_dir(const char *path, const char *filename) {
1457 /* This removes the last component of path and appends
1458 * filename, unless the latter is absolute anyway or the
1461 if (path_is_absolute(filename))
1462 return strdup(filename);
1464 if (!(e = strrchr(path, '/')))
1465 return strdup(filename);
1467 k = strlen(filename);
1468 if (!(r = new(char, e-path+1+k+1)))
1471 memcpy(r, path, e-path+1);
1472 memcpy(r+(e-path)+1, filename, k+1);
1477 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1480 if (label_mkdir(path, mode) >= 0)
1481 if (chmod_and_chown(path, mode, uid, gid) < 0)
1484 if (lstat(path, &st) < 0)
1487 if ((st.st_mode & 0777) != mode ||
1490 !S_ISDIR(st.st_mode)) {
1499 int mkdir_parents(const char *path, mode_t mode) {
1504 /* Creates every parent directory in the path except the last
1507 p = path + strspn(path, "/");
1512 e = p + strcspn(p, "/");
1513 p = e + strspn(e, "/");
1515 /* Is this the last component? If so, then we're
1520 if (!(t = strndup(path, e - path)))
1523 r = label_mkdir(t, mode);
1526 if (r < 0 && errno != EEXIST)
1531 int mkdir_p(const char *path, mode_t mode) {
1536 if ((r = mkdir_parents(path, mode)) < 0)
1539 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1545 int rmdir_parents(const char *path, const char *stop) {
1554 /* Skip trailing slashes */
1555 while (l > 0 && path[l-1] == '/')
1561 /* Skip last component */
1562 while (l > 0 && path[l-1] != '/')
1565 /* Skip trailing slashes */
1566 while (l > 0 && path[l-1] == '/')
1572 if (!(t = strndup(path, l)))
1575 if (path_startswith(stop, t)) {
1584 if (errno != ENOENT)
1592 char hexchar(int x) {
1593 static const char table[16] = "0123456789abcdef";
1595 return table[x & 15];
1598 int unhexchar(char c) {
1600 if (c >= '0' && c <= '9')
1603 if (c >= 'a' && c <= 'f')
1604 return c - 'a' + 10;
1606 if (c >= 'A' && c <= 'F')
1607 return c - 'A' + 10;
1612 char octchar(int x) {
1613 return '0' + (x & 7);
1616 int unoctchar(char c) {
1618 if (c >= '0' && c <= '7')
1624 char decchar(int x) {
1625 return '0' + (x % 10);
1628 int undecchar(char c) {
1630 if (c >= '0' && c <= '9')
1636 char *cescape(const char *s) {
1642 /* Does C style string escaping. */
1644 if (!(r = new(char, strlen(s)*4 + 1)))
1647 for (f = s, t = r; *f; f++)
1693 /* For special chars we prefer octal over
1694 * hexadecimal encoding, simply because glib's
1695 * g_strescape() does the same */
1696 if ((*f < ' ') || (*f >= 127)) {
1698 *(t++) = octchar((unsigned char) *f >> 6);
1699 *(t++) = octchar((unsigned char) *f >> 3);
1700 *(t++) = octchar((unsigned char) *f);
1711 char *cunescape_length(const char *s, size_t length) {
1717 /* Undoes C style string escaping */
1719 if (!(r = new(char, length+1)))
1722 for (f = s, t = r; f < s + length; f++) {
1765 /* This is an extension of the XDG syntax files */
1770 /* hexadecimal encoding */
1773 if ((a = unhexchar(f[1])) < 0 ||
1774 (b = unhexchar(f[2])) < 0) {
1775 /* Invalid escape code, let's take it literal then */
1779 *(t++) = (char) ((a << 4) | b);
1794 /* octal encoding */
1797 if ((a = unoctchar(f[0])) < 0 ||
1798 (b = unoctchar(f[1])) < 0 ||
1799 (c = unoctchar(f[2])) < 0) {
1800 /* Invalid escape code, let's take it literal then */
1804 *(t++) = (char) ((a << 6) | (b << 3) | c);
1812 /* premature end of string.*/
1817 /* Invalid escape code, let's take it literal then */
1829 char *cunescape(const char *s) {
1830 return cunescape_length(s, strlen(s));
1833 char *xescape(const char *s, const char *bad) {
1837 /* Escapes all chars in bad, in addition to \ and all special
1838 * chars, in \xFF style escaping. May be reversed with
1841 if (!(r = new(char, strlen(s)*4+1)))
1844 for (f = s, t = r; *f; f++) {
1846 if ((*f < ' ') || (*f >= 127) ||
1847 (*f == '\\') || strchr(bad, *f)) {
1850 *(t++) = hexchar(*f >> 4);
1851 *(t++) = hexchar(*f);
1861 char *bus_path_escape(const char *s) {
1867 /* Escapes all chars that D-Bus' object path cannot deal
1868 * with. Can be reverse with bus_path_unescape() */
1870 if (!(r = new(char, strlen(s)*3+1)))
1873 for (f = s, t = r; *f; f++) {
1875 if (!(*f >= 'A' && *f <= 'Z') &&
1876 !(*f >= 'a' && *f <= 'z') &&
1877 !(*f >= '0' && *f <= '9')) {
1879 *(t++) = hexchar(*f >> 4);
1880 *(t++) = hexchar(*f);
1890 char *bus_path_unescape(const char *f) {
1895 if (!(r = strdup(f)))
1898 for (t = r; *f; f++) {
1903 if ((a = unhexchar(f[1])) < 0 ||
1904 (b = unhexchar(f[2])) < 0) {
1905 /* Invalid escape code, let's take it literal then */
1908 *(t++) = (char) ((a << 4) | b);
1920 char *path_kill_slashes(char *path) {
1924 /* Removes redundant inner and trailing slashes. Modifies the
1925 * passed string in-place.
1927 * ///foo///bar/ becomes /foo/bar
1930 for (f = path, t = path; *f; f++) {
1945 /* Special rule, if we are talking of the root directory, a
1946 trailing slash is good */
1948 if (t == path && slash)
1955 bool path_startswith(const char *path, const char *prefix) {
1959 if ((path[0] == '/') != (prefix[0] == '/'))
1965 path += strspn(path, "/");
1966 prefix += strspn(prefix, "/");
1974 a = strcspn(path, "/");
1975 b = strcspn(prefix, "/");
1980 if (memcmp(path, prefix, a) != 0)
1988 bool path_equal(const char *a, const char *b) {
1992 if ((a[0] == '/') != (b[0] == '/'))
1998 a += strspn(a, "/");
1999 b += strspn(b, "/");
2001 if (*a == 0 && *b == 0)
2004 if (*a == 0 || *b == 0)
2007 j = strcspn(a, "/");
2008 k = strcspn(b, "/");
2013 if (memcmp(a, b, j) != 0)
2021 char *ascii_strlower(char *t) {
2026 for (p = t; *p; p++)
2027 if (*p >= 'A' && *p <= 'Z')
2028 *p = *p - 'A' + 'a';
2033 bool ignore_file(const char *filename) {
2037 filename[0] == '.' ||
2038 streq(filename, "lost+found") ||
2039 streq(filename, "aquota.user") ||
2040 streq(filename, "aquota.group") ||
2041 endswith(filename, "~") ||
2042 endswith(filename, ".rpmnew") ||
2043 endswith(filename, ".rpmsave") ||
2044 endswith(filename, ".rpmorig") ||
2045 endswith(filename, ".dpkg-old") ||
2046 endswith(filename, ".dpkg-new") ||
2047 endswith(filename, ".swp");
2050 int fd_nonblock(int fd, bool nonblock) {
2055 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2059 flags |= O_NONBLOCK;
2061 flags &= ~O_NONBLOCK;
2063 if (fcntl(fd, F_SETFL, flags) < 0)
2069 int fd_cloexec(int fd, bool cloexec) {
2074 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2078 flags |= FD_CLOEXEC;
2080 flags &= ~FD_CLOEXEC;
2082 if (fcntl(fd, F_SETFD, flags) < 0)
2088 int close_all_fds(const int except[], unsigned n_except) {
2093 if (!(d = opendir("/proc/self/fd")))
2096 while ((de = readdir(d))) {
2099 if (ignore_file(de->d_name))
2102 if (safe_atoi(de->d_name, &fd) < 0)
2103 /* Let's better ignore this, just in case */
2117 for (i = 0; i < n_except; i++)
2118 if (except[i] == fd) {
2127 if (close_nointr(fd) < 0) {
2128 /* Valgrind has its own FD and doesn't want to have it closed */
2129 if (errno != EBADF && r == 0)
2138 bool chars_intersect(const char *a, const char *b) {
2141 /* Returns true if any of the chars in a are in b. */
2142 for (p = a; *p; p++)
2149 char *format_timestamp(char *buf, size_t l, usec_t t) {
2159 sec = (time_t) (t / USEC_PER_SEC);
2161 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2167 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2170 n = now(CLOCK_REALTIME);
2172 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2177 if (d >= USEC_PER_YEAR)
2178 snprintf(buf, l, "%llu years and %llu months ago",
2179 (unsigned long long) (d / USEC_PER_YEAR),
2180 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2181 else if (d >= USEC_PER_MONTH)
2182 snprintf(buf, l, "%llu months and %llu days ago",
2183 (unsigned long long) (d / USEC_PER_MONTH),
2184 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2185 else if (d >= USEC_PER_WEEK)
2186 snprintf(buf, l, "%llu weeks and %llu days ago",
2187 (unsigned long long) (d / USEC_PER_WEEK),
2188 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2189 else if (d >= 2*USEC_PER_DAY)
2190 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2191 else if (d >= 25*USEC_PER_HOUR)
2192 snprintf(buf, l, "1 day and %lluh ago",
2193 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2194 else if (d >= 6*USEC_PER_HOUR)
2195 snprintf(buf, l, "%lluh ago",
2196 (unsigned long long) (d / USEC_PER_HOUR));
2197 else if (d >= USEC_PER_HOUR)
2198 snprintf(buf, l, "%lluh %llumin ago",
2199 (unsigned long long) (d / USEC_PER_HOUR),
2200 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2201 else if (d >= 5*USEC_PER_MINUTE)
2202 snprintf(buf, l, "%llumin ago",
2203 (unsigned long long) (d / USEC_PER_MINUTE));
2204 else if (d >= USEC_PER_MINUTE)
2205 snprintf(buf, l, "%llumin %llus ago",
2206 (unsigned long long) (d / USEC_PER_MINUTE),
2207 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2208 else if (d >= USEC_PER_SEC)
2209 snprintf(buf, l, "%llus ago",
2210 (unsigned long long) (d / USEC_PER_SEC));
2211 else if (d >= USEC_PER_MSEC)
2212 snprintf(buf, l, "%llums ago",
2213 (unsigned long long) (d / USEC_PER_MSEC));
2215 snprintf(buf, l, "%lluus ago",
2216 (unsigned long long) d);
2218 snprintf(buf, l, "now");
2224 char *format_timespan(char *buf, size_t l, usec_t t) {
2225 static const struct {
2229 { "w", USEC_PER_WEEK },
2230 { "d", USEC_PER_DAY },
2231 { "h", USEC_PER_HOUR },
2232 { "min", USEC_PER_MINUTE },
2233 { "s", USEC_PER_SEC },
2234 { "ms", USEC_PER_MSEC },
2244 if (t == (usec_t) -1)
2248 snprintf(p, l, "0");
2253 /* The result of this function can be parsed with parse_usec */
2255 for (i = 0; i < ELEMENTSOF(table); i++) {
2259 if (t < table[i].usec)
2265 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2266 n = MIN((size_t) k, l);
2279 bool fstype_is_network(const char *fstype) {
2280 static const char * const table[] = {
2292 for (i = 0; i < ELEMENTSOF(table); i++)
2293 if (streq(table[i], fstype))
2302 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2307 TIOCL_GETKMSGREDIRECT,
2311 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2314 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2317 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2320 close_nointr_nofail(r);
2324 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2325 struct termios old_termios, new_termios;
2327 char line[LINE_MAX];
2332 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2333 new_termios = old_termios;
2335 new_termios.c_lflag &= ~ICANON;
2336 new_termios.c_cc[VMIN] = 1;
2337 new_termios.c_cc[VTIME] = 0;
2339 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2342 k = fread(&c, 1, 1, f);
2344 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2350 *need_nl = c != '\n';
2357 if (!(fgets(line, sizeof(line), f)))
2362 if (strlen(line) != 1)
2372 int ask(char *ret, const char *replies, const char *text, ...) {
2379 on_tty = isatty(STDOUT_FILENO);
2385 bool need_nl = true;
2388 fputs("\x1B[1m", stdout);
2395 fputs("\x1B[0m", stdout);
2399 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2401 if (r == -EBADMSG) {
2402 puts("Bad input, please try again.");
2413 if (strchr(replies, c)) {
2418 puts("Read unexpected character, please try again.");
2422 int reset_terminal_fd(int fd) {
2423 struct termios termios;
2427 /* Set terminal to some sane defaults */
2431 /* We leave locked terminal attributes untouched, so that
2432 * Plymouth may set whatever it wants to set, and we don't
2433 * interfere with that. */
2435 /* Disable exclusive mode, just in case */
2436 ioctl(fd, TIOCNXCL);
2438 /* Enable console unicode mode */
2440 ioctl(fd, KDSKBMODE, &arg);
2442 if (tcgetattr(fd, &termios) < 0) {
2447 /* We only reset the stuff that matters to the software. How
2448 * hardware is set up we don't touch assuming that somebody
2449 * else will do that for us */
2451 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2452 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2453 termios.c_oflag |= ONLCR;
2454 termios.c_cflag |= CREAD;
2455 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2457 termios.c_cc[VINTR] = 03; /* ^C */
2458 termios.c_cc[VQUIT] = 034; /* ^\ */
2459 termios.c_cc[VERASE] = 0177;
2460 termios.c_cc[VKILL] = 025; /* ^X */
2461 termios.c_cc[VEOF] = 04; /* ^D */
2462 termios.c_cc[VSTART] = 021; /* ^Q */
2463 termios.c_cc[VSTOP] = 023; /* ^S */
2464 termios.c_cc[VSUSP] = 032; /* ^Z */
2465 termios.c_cc[VLNEXT] = 026; /* ^V */
2466 termios.c_cc[VWERASE] = 027; /* ^W */
2467 termios.c_cc[VREPRINT] = 022; /* ^R */
2468 termios.c_cc[VEOL] = 0;
2469 termios.c_cc[VEOL2] = 0;
2471 termios.c_cc[VTIME] = 0;
2472 termios.c_cc[VMIN] = 1;
2474 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2478 /* Just in case, flush all crap out */
2479 tcflush(fd, TCIOFLUSH);
2484 int reset_terminal(const char *name) {
2487 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2491 r = reset_terminal_fd(fd);
2492 close_nointr_nofail(fd);
2497 int open_terminal(const char *name, int mode) {
2502 * If a TTY is in the process of being closed opening it might
2503 * cause EIO. This is horribly awful, but unlikely to be
2504 * changed in the kernel. Hence we work around this problem by
2505 * retrying a couple of times.
2507 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2511 if ((fd = open(name, mode)) >= 0)
2520 usleep(50 * USEC_PER_MSEC);
2527 if ((r = isatty(fd)) < 0) {
2528 close_nointr_nofail(fd);
2533 close_nointr_nofail(fd);
2540 int flush_fd(int fd) {
2541 struct pollfd pollfd;
2545 pollfd.events = POLLIN;
2552 if ((r = poll(&pollfd, 1, 0)) < 0) {
2563 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2568 if (errno == EAGAIN)
2579 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2580 int fd = -1, notify = -1, r, wd = -1;
2584 /* We use inotify to be notified when the tty is closed. We
2585 * create the watch before checking if we can actually acquire
2586 * it, so that we don't lose any event.
2588 * Note: strictly speaking this actually watches for the
2589 * device being closed, it does *not* really watch whether a
2590 * tty loses its controlling process. However, unless some
2591 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2592 * its tty otherwise this will not become a problem. As long
2593 * as the administrator makes sure not configure any service
2594 * on the same tty as an untrusted user this should not be a
2595 * problem. (Which he probably should not do anyway.) */
2597 if (!fail && !force) {
2598 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2603 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2611 if ((r = flush_fd(notify)) < 0)
2614 /* We pass here O_NOCTTY only so that we can check the return
2615 * value TIOCSCTTY and have a reliable way to figure out if we
2616 * successfully became the controlling process of the tty */
2617 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2620 /* First, try to get the tty */
2621 r = ioctl(fd, TIOCSCTTY, force);
2623 /* Sometimes it makes sense to ignore TIOCSCTTY
2624 * returning EPERM, i.e. when very likely we already
2625 * are have this controlling terminal. */
2626 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2629 if (r < 0 && (force || fail || errno != EPERM)) {
2639 assert(notify >= 0);
2642 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2644 struct inotify_event *e;
2646 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2655 e = (struct inotify_event*) inotify_buffer;
2660 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2665 step = sizeof(struct inotify_event) + e->len;
2666 assert(step <= (size_t) l);
2668 e = (struct inotify_event*) ((uint8_t*) e + step);
2675 /* We close the tty fd here since if the old session
2676 * ended our handle will be dead. It's important that
2677 * we do this after sleeping, so that we don't enter
2678 * an endless loop. */
2679 close_nointr_nofail(fd);
2683 close_nointr_nofail(notify);
2685 if ((r = reset_terminal_fd(fd)) < 0)
2686 log_warning("Failed to reset terminal: %s", strerror(-r));
2692 close_nointr_nofail(fd);
2695 close_nointr_nofail(notify);
2700 int release_terminal(void) {
2702 struct sigaction sa_old, sa_new;
2704 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2707 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2708 * by our own TIOCNOTTY */
2711 sa_new.sa_handler = SIG_IGN;
2712 sa_new.sa_flags = SA_RESTART;
2713 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2715 if (ioctl(fd, TIOCNOTTY) < 0)
2718 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2720 close_nointr_nofail(fd);
2724 int sigaction_many(const struct sigaction *sa, ...) {
2729 while ((sig = va_arg(ap, int)) > 0)
2730 if (sigaction(sig, sa, NULL) < 0)
2737 int ignore_signals(int sig, ...) {
2738 struct sigaction sa;
2743 sa.sa_handler = SIG_IGN;
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 default_signals(int sig, ...) {
2759 struct sigaction sa;
2764 sa.sa_handler = SIG_DFL;
2765 sa.sa_flags = SA_RESTART;
2767 if (sigaction(sig, &sa, NULL) < 0)
2771 while ((sig = va_arg(ap, int)) > 0)
2772 if (sigaction(sig, &sa, NULL) < 0)
2779 int close_pipe(int p[]) {
2785 a = close_nointr(p[0]);
2790 b = close_nointr(p[1]);
2794 return a < 0 ? a : b;
2797 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2806 while (nbytes > 0) {
2809 if ((k = read(fd, p, nbytes)) <= 0) {
2811 if (k < 0 && errno == EINTR)
2814 if (k < 0 && errno == EAGAIN && do_poll) {
2815 struct pollfd pollfd;
2819 pollfd.events = POLLIN;
2821 if (poll(&pollfd, 1, -1) < 0) {
2825 return n > 0 ? n : -errno;
2828 if (pollfd.revents != POLLIN)
2829 return n > 0 ? n : -EIO;
2834 return n > 0 ? n : (k < 0 ? -errno : 0);
2845 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2854 while (nbytes > 0) {
2857 if ((k = write(fd, p, nbytes)) <= 0) {
2859 if (k < 0 && errno == EINTR)
2862 if (k < 0 && errno == EAGAIN && do_poll) {
2863 struct pollfd pollfd;
2867 pollfd.events = POLLOUT;
2869 if (poll(&pollfd, 1, -1) < 0) {
2873 return n > 0 ? n : -errno;
2876 if (pollfd.revents != POLLOUT)
2877 return n > 0 ? n : -EIO;
2882 return n > 0 ? n : (k < 0 ? -errno : 0);
2893 int path_is_mount_point(const char *t) {
2898 if (lstat(t, &a) < 0) {
2899 if (errno == ENOENT)
2905 if ((r = parent_of_path(t, &parent)) < 0)
2908 r = lstat(parent, &b);
2914 return a.st_dev != b.st_dev;
2917 int parse_usec(const char *t, usec_t *usec) {
2918 static const struct {
2922 { "sec", USEC_PER_SEC },
2923 { "s", USEC_PER_SEC },
2924 { "min", USEC_PER_MINUTE },
2925 { "hr", USEC_PER_HOUR },
2926 { "h", USEC_PER_HOUR },
2927 { "d", USEC_PER_DAY },
2928 { "w", USEC_PER_WEEK },
2929 { "msec", USEC_PER_MSEC },
2930 { "ms", USEC_PER_MSEC },
2931 { "m", USEC_PER_MINUTE },
2934 { "", USEC_PER_SEC },
2950 l = strtoll(p, &e, 10);
2961 e += strspn(e, WHITESPACE);
2963 for (i = 0; i < ELEMENTSOF(table); i++)
2964 if (startswith(e, table[i].suffix)) {
2965 r += (usec_t) l * table[i].usec;
2966 p = e + strlen(table[i].suffix);
2970 if (i >= ELEMENTSOF(table))
2980 int make_stdio(int fd) {
2985 r = dup2(fd, STDIN_FILENO);
2986 s = dup2(fd, STDOUT_FILENO);
2987 t = dup2(fd, STDERR_FILENO);
2990 close_nointr_nofail(fd);
2992 if (r < 0 || s < 0 || t < 0)
2995 fd_cloexec(STDIN_FILENO, false);
2996 fd_cloexec(STDOUT_FILENO, false);
2997 fd_cloexec(STDERR_FILENO, false);
3002 int make_null_stdio(void) {
3005 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3008 return make_stdio(null_fd);
3011 bool is_device_path(const char *path) {
3013 /* Returns true on paths that refer to a device, either in
3014 * sysfs or in /dev */
3017 path_startswith(path, "/dev/") ||
3018 path_startswith(path, "/sys/");
3021 int dir_is_empty(const char *path) {
3024 struct dirent buf, *de;
3026 if (!(d = opendir(path)))
3030 if ((r = readdir_r(d, &buf, &de)) > 0) {
3040 if (!ignore_file(de->d_name)) {
3050 unsigned long long random_ull(void) {
3055 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3058 r = loop_read(fd, &ull, sizeof(ull), true);
3059 close_nointr_nofail(fd);
3061 if (r != sizeof(ull))
3067 return random() * RAND_MAX + random();
3070 void rename_process(const char name[8]) {
3073 prctl(PR_SET_NAME, name);
3075 /* This is a like a poor man's setproctitle(). The string
3076 * passed should fit in 7 chars (i.e. the length of
3079 if (program_invocation_name)
3080 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3082 if (saved_argc > 0) {
3086 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3088 for (i = 1; i < saved_argc; i++) {
3092 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3097 void sigset_add_many(sigset_t *ss, ...) {
3104 while ((sig = va_arg(ap, int)) > 0)
3105 assert_se(sigaddset(ss, sig) == 0);
3109 char* gethostname_malloc(void) {
3112 assert_se(uname(&u) >= 0);
3115 return strdup(u.nodename);
3117 return strdup(u.sysname);
3120 char* getlogname_malloc(void) {
3124 struct passwd pwbuf, *pw = NULL;
3127 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3132 /* Shortcut things to avoid NSS lookups */
3134 return strdup("root");
3136 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3139 if (!(buf = malloc(bufsize)))
3142 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3143 name = strdup(pw->pw_name);
3150 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3156 int getttyname_malloc(int fd, char **r) {
3157 char path[PATH_MAX], *c;
3162 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3167 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3174 int getttyname_harder(int fd, char **r) {
3178 if ((k = getttyname_malloc(fd, &s)) < 0)
3181 if (streq(s, "tty")) {
3183 return get_ctty(0, NULL, r);
3190 int get_ctty_devnr(pid_t pid, dev_t *d) {
3192 char line[LINE_MAX], *p, *fn;
3193 unsigned long ttynr;
3196 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3199 f = fopen(fn, "re");
3204 if (!fgets(line, sizeof(line), f)) {
3212 p = strrchr(line, ')');
3222 "%*d " /* session */
3231 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3233 char fn[PATH_MAX], *s, *b, *p;
3238 k = get_ctty_devnr(pid, &devnr);
3242 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3245 if ((k = readlink_malloc(fn, &s)) < 0) {
3250 /* This is an ugly hack */
3251 if (major(devnr) == 136) {
3252 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3262 /* Probably something like the ptys which have no
3263 * symlink in /dev/char. Let's return something
3264 * vaguely useful. */
3266 if (!(b = strdup(fn + 5)))
3276 if (startswith(s, "/dev/"))
3278 else if (startswith(s, "../"))
3296 static int rm_rf_children(int fd, bool only_dirs) {
3302 /* This returns the first error we run into, but nevertheless
3305 if (!(d = fdopendir(fd))) {
3306 close_nointr_nofail(fd);
3308 return errno == ENOENT ? 0 : -errno;
3312 struct dirent buf, *de;
3316 if ((r = readdir_r(d, &buf, &de)) != 0) {
3325 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3328 if (de->d_type == DT_UNKNOWN) {
3331 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3332 if (ret == 0 && errno != ENOENT)
3337 is_dir = S_ISDIR(st.st_mode);
3339 is_dir = de->d_type == DT_DIR;
3344 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3345 if (ret == 0 && errno != ENOENT)
3350 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
3355 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3356 if (ret == 0 && errno != ENOENT)
3359 } else if (!only_dirs) {
3361 if (unlinkat(fd, de->d_name, 0) < 0) {
3362 if (ret == 0 && errno != ENOENT)
3373 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
3379 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3381 if (errno != ENOTDIR)
3384 if (delete_root && !only_dirs)
3385 if (unlink(path) < 0)
3391 r = rm_rf_children(fd, only_dirs);
3394 if (rmdir(path) < 0) {
3402 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3405 /* Under the assumption that we are running privileged we
3406 * first change the access mode and only then hand out
3407 * ownership to avoid a window where access is too open. */
3409 if (chmod(path, mode) < 0)
3412 if (chown(path, uid, gid) < 0)
3418 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3422 /* Allocates the cpuset in the right size */
3425 if (!(r = CPU_ALLOC(n)))
3428 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3429 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3439 if (errno != EINVAL)
3446 void status_vprintf(const char *format, va_list ap) {
3452 /* This independent of logging, as status messages are
3453 * optional and go exclusively to the console. */
3455 if (vasprintf(&s, format, ap) < 0)
3458 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3461 write(fd, s, strlen(s));
3467 close_nointr_nofail(fd);
3470 void status_printf(const char *format, ...) {
3475 va_start(ap, format);
3476 status_vprintf(format, ap);
3480 void status_welcome(void) {
3481 char *pretty_name = NULL, *ansi_color = NULL;
3482 const char *const_pretty = NULL, *const_color = NULL;
3485 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3486 "PRETTY_NAME", &pretty_name,
3487 "ANSI_COLOR", &ansi_color,
3491 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3494 #if defined(TARGET_FEDORA)
3496 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3499 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3503 if (!ansi_color && pretty_name) {
3505 /* This tries to mimic the color magic the old Red Hat sysinit
3508 if (startswith(pretty_name, "Red Hat"))
3509 const_color = "0;31"; /* Red for RHEL */
3510 else if (startswith(pretty_name, "Fedora"))
3511 const_color = "0;34"; /* Blue for Fedora */
3514 #elif defined(TARGET_SUSE)
3517 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3520 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3525 const_color = "0;32"; /* Green for openSUSE */
3527 #elif defined(TARGET_GENTOO)
3530 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3533 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3538 const_color = "1;34"; /* Light Blue for Gentoo */
3540 #elif defined(TARGET_ALTLINUX)
3543 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3546 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3551 const_color = "0;36"; /* Cyan for ALTLinux */
3554 #elif defined(TARGET_DEBIAN)
3559 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3562 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3564 pretty_name = strappend("Debian ", version);
3568 log_warning("Failed to allocate Debian version string.");
3573 const_color = "1;31"; /* Light Red for Debian */
3575 #elif defined(TARGET_UBUNTU)
3577 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3578 "DISTRIB_DESCRIPTION", &pretty_name,
3582 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3586 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3588 #elif defined(TARGET_MANDRIVA)
3593 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3595 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3597 p = strstr(s, " release ");
3601 p[strcspn(p, " ")] = '\0';
3603 /* This corresponds to standard rc.sysinit */
3604 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3605 const_color = "1;36";
3607 log_warning("Failed to allocate Mandriva version string.");
3609 log_warning("Failed to parse /etc/mandriva-release");
3613 #elif defined(TARGET_MEEGO)
3616 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3619 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3624 const_color = "1;35"; /* Bright Magenta for MeeGo */
3627 if (!pretty_name && !const_pretty)
3628 const_pretty = "Linux";
3630 if (!ansi_color && !const_color)
3633 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
3634 const_color ? const_color : ansi_color,
3635 const_pretty ? const_pretty : pretty_name);
3641 char *replace_env(const char *format, char **env) {
3648 const char *e, *word = format;
3653 for (e = format; *e; e ++) {
3664 if (!(k = strnappend(r, word, e-word-1)))
3673 } else if (*e == '$') {
3674 if (!(k = strnappend(r, word, e-word)))
3690 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3693 if (!(k = strappend(r, t)))
3706 if (!(k = strnappend(r, word, e-word)))
3717 char **replace_env_argv(char **argv, char **env) {
3719 unsigned k = 0, l = 0;
3721 l = strv_length(argv);
3723 if (!(r = new(char*, l+1)))
3726 STRV_FOREACH(i, argv) {
3728 /* If $FOO appears as single word, replace it by the split up variable */
3729 if ((*i)[0] == '$' && (*i)[1] != '{') {
3734 if ((e = strv_env_get(env, *i+1))) {
3736 if (!(m = strv_split_quoted(e))) {
3747 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3756 memcpy(r + k, m, q * sizeof(char*));
3764 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3765 if (!(r[k++] = replace_env(*i, env))) {
3776 static __thread int parsed_columns = 0;
3779 if (parsed_columns > 0)
3780 return parsed_columns;
3782 if ((e = getenv("COLUMNS")))
3783 parsed_columns = atoi(e);
3785 if (parsed_columns <= 0) {
3789 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3790 parsed_columns = ws.ws_col;
3793 if (parsed_columns <= 0)
3794 parsed_columns = 80;
3796 return parsed_columns;
3799 int running_in_chroot(void) {
3805 /* Only works as root */
3807 if (stat("/proc/1/root", &a) < 0)
3810 if (stat("/", &b) < 0)
3814 a.st_dev != b.st_dev ||
3815 a.st_ino != b.st_ino;
3818 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3823 assert(percent <= 100);
3824 assert(length >= 3);
3828 if (l <= 3 || l <= length)
3831 if (!(r = new0(char, length+1)))
3834 x = (length * percent) / 100;
3844 s + l - (length - x - 3),
3850 int touch(const char *path) {
3855 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3858 close_nointr_nofail(fd);
3862 char *unquote(const char *s, const char* quotes) {
3866 if ((l = strlen(s)) < 2)
3869 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3870 return strndup(s+1, l-2);
3875 char *normalize_env_assignment(const char *s) {
3876 char *name, *value, *p, *r;
3881 if (!(r = strdup(s)))
3887 if (!(name = strndup(s, p - s)))
3890 if (!(p = strdup(p+1))) {
3895 value = unquote(strstrip(p), QUOTES);
3903 if (asprintf(&r, "%s=%s", name, value) < 0)
3912 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3923 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3935 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3942 if ((r = wait_for_terminate(pid, &status)) < 0) {
3943 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3947 if (status.si_code == CLD_EXITED) {
3948 if (status.si_status != 0) {
3949 log_warning("%s failed with error code %i.", name, status.si_status);
3950 return status.si_status;
3953 log_debug("%s succeeded.", name);
3956 } else if (status.si_code == CLD_KILLED ||
3957 status.si_code == CLD_DUMPED) {
3959 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3963 log_warning("%s failed due to unknown reason.", name);
3970 /* Make sure nobody waits for us on a socket anymore */
3971 close_all_fds(NULL, 0);
3979 bool null_or_empty(struct stat *st) {
3982 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3985 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3991 int null_or_empty_path(const char *fn) {
3996 if (stat(fn, &st) < 0)
3999 return null_or_empty(&st);
4002 DIR *xopendirat(int fd, const char *name, int flags) {
4006 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4009 if (!(d = fdopendir(nfd))) {
4010 close_nointr_nofail(nfd);
4017 int signal_from_string_try_harder(const char *s) {
4021 if ((signo = signal_from_string(s)) <= 0)
4022 if (startswith(s, "SIG"))
4023 return signal_from_string(s+3);
4028 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4034 if (!dual_timestamp_is_set(t))
4037 fprintf(f, "%s=%llu %llu\n",
4039 (unsigned long long) t->realtime,
4040 (unsigned long long) t->monotonic);
4043 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4044 unsigned long long a, b;
4049 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4050 log_debug("Failed to parse finish timestamp value %s", value);
4057 char *fstab_node_to_udev_node(const char *p) {
4061 /* FIXME: to follow udev's logic 100% we need to leave valid
4062 * UTF8 chars unescaped */
4064 if (startswith(p, "LABEL=")) {
4066 if (!(u = unquote(p+6, "\"\'")))
4069 t = xescape(u, "/ ");
4075 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4084 if (startswith(p, "UUID=")) {
4086 if (!(u = unquote(p+5, "\"\'")))
4089 t = xescape(u, "/ ");
4095 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4107 void filter_environ(const char *prefix) {
4114 for (i = 0, j = 0; environ[i]; i++) {
4116 if (startswith(environ[i], prefix))
4119 environ[j++] = environ[i];
4125 bool tty_is_vc(const char *tty) {
4128 if (startswith(tty, "/dev/"))
4131 return vtnr_from_tty(tty) >= 0;
4134 int vtnr_from_tty(const char *tty) {
4139 if (startswith(tty, "/dev/"))
4142 if (!startswith(tty, "tty") )
4145 if (tty[3] < '0' || tty[3] > '9')
4148 r = safe_atoi(tty+3, &i);
4152 if (i < 0 || i > 63)
4158 const char *default_term_for_tty(const char *tty) {
4159 char *active = NULL;
4164 if (startswith(tty, "/dev/"))
4167 /* Resolve where /dev/console is pointing when determining
4169 if (streq(tty, "console"))
4170 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4171 /* If multiple log outputs are configured the
4172 * last one is what /dev/console points to */
4173 if ((tty = strrchr(active, ' ')))
4179 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4185 /* Returns a short identifier for the various VM implementations */
4186 int detect_vm(const char **id) {
4188 #if defined(__i386__) || defined(__x86_64__)
4190 /* Both CPUID and DMI are x86 specific interfaces... */
4192 static const char *const dmi_vendors[] = {
4193 "/sys/class/dmi/id/sys_vendor",
4194 "/sys/class/dmi/id/board_vendor",
4195 "/sys/class/dmi/id/bios_vendor"
4198 static const char dmi_vendor_table[] =
4200 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4201 "VMware\0" "vmware\0"
4203 "Microsoft Corporation\0" "microsoft\0"
4204 "innotek GmbH\0" "oracle\0"
4206 "Bochs\0" "bochs\0";
4208 static const char cpuid_vendor_table[] =
4209 "XenVMMXenVMM\0" "xen\0"
4210 "KVMKVMKVM\0" "kvm\0"
4211 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4212 "VMwareVMware\0" "vmware\0"
4213 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
4214 "Microsoft Hv\0" "microsoft\0";
4225 /* http://lwn.net/Articles/301888/ */
4228 #if defined (__i386__)
4231 #elif defined (__amd64__)
4236 /* First detect whether there is a hypervisor */
4238 __asm__ __volatile__ (
4239 /* ebx/rbx is being used for PIC! */
4240 " push %%"REG_b" \n\t"
4242 " pop %%"REG_b" \n\t"
4244 : "=a" (eax), "=c" (ecx)
4248 hypervisor = !!(ecx & 0x80000000U);
4252 /* There is a hypervisor, see what it is */
4254 __asm__ __volatile__ (
4255 /* ebx/rbx is being used for PIC! */
4256 " push %%"REG_b" \n\t"
4258 " mov %%ebx, %1 \n\t"
4259 " pop %%"REG_b" \n\t"
4261 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4265 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4266 if (streq(sig.text, j)) {
4275 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4278 const char *found = NULL;
4280 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4287 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4288 if (startswith(s, j))
4311 int detect_container(const char **id) {
4314 /* Unfortunately many of these operations require root access
4315 * in one way or another */
4320 if (running_in_chroot() > 0) {
4328 /* /proc/vz exists in container and outside of the container,
4329 * /proc/bc only outside of the container. */
4330 if (access("/proc/vz", F_OK) >= 0 &&
4331 access("/proc/bc", F_OK) < 0) {
4339 if ((f = fopen("/proc/self/cgroup", "re"))) {
4342 char line[LINE_MAX], *p;
4344 if (!fgets(line, sizeof(line), f))
4347 if (!(p = strchr(strstrip(line), ':')))
4350 if (strncmp(p, ":ns:", 4))
4353 if (!streq(p, ":ns:/")) {
4369 /* Returns a short identifier for the various VM/container implementations */
4370 int detect_virtualization(const char **id) {
4371 static __thread const char *cached_id = NULL;
4377 if (cached_id == (const char*) -1)
4386 if ((r = detect_container(&_id)) != 0)
4389 r = detect_vm(&_id);
4398 cached_id = (const char*) -1;
4403 bool dirent_is_file(struct dirent *de) {
4406 if (ignore_file(de->d_name))
4409 if (de->d_type != DT_REG &&
4410 de->d_type != DT_LNK &&
4411 de->d_type != DT_UNKNOWN)
4417 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4420 Hashmap *pids = NULL;
4424 /* Executes all binaries in a directory in parallel and waits
4425 * until all they all finished. */
4428 if (!(_d = opendir(directory))) {
4430 if (errno == ENOENT)
4433 log_error("Failed to enumerate directory %s: %m", directory);
4440 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4441 log_error("Failed to allocate set.");
4445 while ((de = readdir(d))) {
4450 if (!dirent_is_file(de))
4453 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4454 log_error("Out of memory");
4458 if ((pid = fork()) < 0) {
4459 log_error("Failed to fork: %m");
4478 log_error("Failed to execute %s: %m", path);
4479 _exit(EXIT_FAILURE);
4482 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4484 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4485 log_error("Failed to add PID to set: %s", strerror(-k));
4490 while (!hashmap_isempty(pids)) {
4495 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4500 log_error("waitid() failed: %m");
4504 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4505 if (!is_clean_exit(si.si_code, si.si_status)) {
4506 if (si.si_code == CLD_EXITED)
4507 log_error("%s exited with exit status %i.", path, si.si_status);
4509 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4511 log_debug("%s exited successfully.", path);
4522 hashmap_free_free(pids);
4525 int kill_and_sigcont(pid_t pid, int sig) {
4528 r = kill(pid, sig) < 0 ? -errno : 0;
4536 bool nulstr_contains(const char*nulstr, const char *needle) {
4542 NULSTR_FOREACH(i, nulstr)
4543 if (streq(i, needle))
4549 bool plymouth_running(void) {
4550 return access("/run/plymouth/pid", F_OK) >= 0;
4553 void parse_syslog_priority(char **p, int *priority) {
4554 int a = 0, b = 0, c = 0;
4564 if (!strchr(*p, '>'))
4567 if ((*p)[2] == '>') {
4568 c = undecchar((*p)[1]);
4570 } else if ((*p)[3] == '>') {
4571 b = undecchar((*p)[1]);
4572 c = undecchar((*p)[2]);
4574 } else if ((*p)[4] == '>') {
4575 a = undecchar((*p)[1]);
4576 b = undecchar((*p)[2]);
4577 c = undecchar((*p)[3]);
4582 if (a < 0 || b < 0 || c < 0)
4585 *priority = a*100+b*10+c;
4589 int have_effective_cap(int value) {
4591 cap_flag_value_t fv;
4594 if (!(cap = cap_get_proc()))
4597 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4606 char* strshorten(char *s, size_t l) {
4615 static bool hostname_valid_char(char c) {
4617 (c >= 'a' && c <= 'z') ||
4618 (c >= 'A' && c <= 'Z') ||
4619 (c >= '0' && c <= '9') ||
4625 bool hostname_is_valid(const char *s) {
4631 for (p = s; *p; p++)
4632 if (!hostname_valid_char(*p))
4635 if (p-s > HOST_NAME_MAX)
4641 char* hostname_cleanup(char *s) {
4644 for (p = s, d = s; *p; p++)
4645 if ((*p >= 'a' && *p <= 'z') ||
4646 (*p >= 'A' && *p <= 'Z') ||
4647 (*p >= '0' && *p <= '9') ||
4655 strshorten(s, HOST_NAME_MAX);
4659 int pipe_eof(int fd) {
4660 struct pollfd pollfd;
4665 pollfd.events = POLLIN|POLLHUP;
4667 r = poll(&pollfd, 1, 0);
4674 return pollfd.revents & POLLHUP;
4677 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4688 t = new(char, strlen(path) + 1 + 6 + 1);
4692 fn = file_name_from_path(path);
4696 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4698 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4704 f = fdopen(fd, "we");
4717 int terminal_vhangup_fd(int fd) {
4720 if (ioctl(fd, TIOCVHANGUP) < 0)
4726 int terminal_vhangup(const char *name) {
4729 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4733 r = terminal_vhangup_fd(fd);
4734 close_nointr_nofail(fd);
4739 int vt_disallocate(const char *name) {
4743 /* Deallocate the VT if possible. If not possible
4744 * (i.e. because it is the active one), at least clear it
4745 * entirely (including the scrollback buffer) */
4747 if (!startswith(name, "/dev/"))
4750 if (!tty_is_vc(name)) {
4751 /* So this is not a VT. I guess we cannot deallocate
4752 * it then. But let's at least clear the screen */
4754 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4759 "\033[r" /* clear scrolling region */
4760 "\033[H" /* move home */
4761 "\033[2J", /* clear screen */
4763 close_nointr_nofail(fd);
4768 if (!startswith(name, "/dev/tty"))
4771 r = safe_atou(name+8, &u);
4778 /* Try to deallocate */
4779 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4783 r = ioctl(fd, VT_DISALLOCATE, u);
4784 close_nointr_nofail(fd);
4792 /* Couldn't deallocate, so let's clear it fully with
4794 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4799 "\033[r" /* clear scrolling region */
4800 "\033[H" /* move home */
4801 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4803 close_nointr_nofail(fd);
4809 static int file_is_conf(const struct dirent *d, const char *suffix) {
4812 if (ignore_file(d->d_name))
4815 if (d->d_type != DT_REG &&
4816 d->d_type != DT_LNK &&
4817 d->d_type != DT_UNKNOWN)
4820 return endswith(d->d_name, suffix);
4823 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4825 struct dirent buffer, *de;
4828 dir = opendir(path);
4830 if (errno == ENOENT)
4839 k = readdir_r(dir, &buffer, &de);
4848 if (!file_is_conf(de, suffix))
4851 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4856 f = canonicalize_file_name(p);
4858 log_error("Failed to canonicalize file name '%s': %m", p);
4864 log_debug("found: %s\n", f);
4865 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4874 static int base_cmp(const void *a, const void *b) {
4875 const char *s1, *s2;
4877 s1 = *(char * const *)a;
4878 s2 = *(char * const *)b;
4879 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4882 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4885 char **files = NULL;
4891 dirs = strv_new_ap(dir, ap);
4897 if (!strv_path_canonicalize(dirs)) {
4901 if (!strv_uniq(dirs)) {
4906 fh = hashmap_new(string_hash_func, string_compare_func);
4912 STRV_FOREACH(p, dirs) {
4913 if (files_add(fh, *p, suffix) < 0) {
4914 log_error("Failed to search for files.");
4920 files = hashmap_get_strv(fh);
4921 if (files == NULL) {
4922 log_error("Failed to compose list of files.");
4927 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
4936 int hwclock_is_localtime(void) {
4941 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
4947 f = fopen("/etc/adjtime", "re");
4949 char line[LINE_MAX];
4952 b = fgets(line, sizeof(line), f) &&
4953 fgets(line, sizeof(line), f) &&
4954 fgets(line, sizeof(line), f);
4963 local = streq(line, "LOCAL");
4965 } else if (errno != -ENOENT)
4971 int hwclock_apply_localtime_delta(int *min) {
4972 const struct timeval *tv_null = NULL;
4978 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
4979 assert_se(tm = localtime(&ts.tv_sec));
4980 minuteswest = tm->tm_gmtoff / 60;
4982 tz.tz_minuteswest = -minuteswest;
4983 tz.tz_dsttime = 0; /* DST_NONE*/
4986 * If the hardware clock does not run in UTC, but in local time:
4987 * The very first time we set the kernel's timezone, it will warp
4988 * the clock so that it runs in UTC instead of local time.
4990 if (settimeofday(tv_null, &tz) < 0)
4997 int hwclock_reset_localtime_delta(void) {
4998 const struct timeval *tv_null = NULL;
5001 tz.tz_minuteswest = 0;
5002 tz.tz_dsttime = 0; /* DST_NONE*/
5004 if (settimeofday(tv_null, &tz) < 0)
5010 int hwclock_get_time(struct tm *tm) {
5016 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5020 /* This leaves the timezone fields of struct tm
5022 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5025 /* We don't now daylight saving, so we reset this in order not
5026 * to confused mktime(). */
5029 close_nointr_nofail(fd);
5034 int hwclock_set_time(const struct tm *tm) {
5040 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5044 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5047 close_nointr_nofail(fd);
5052 int copy_file(const char *from, const char *to) {
5058 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5062 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5064 close_nointr_nofail(fdf);
5072 n = read(fdf, buf, sizeof(buf));
5076 close_nointr_nofail(fdf);
5087 k = loop_write(fdt, buf, n, false);
5089 r = k < 0 ? k : (errno ? -errno : -EIO);
5091 close_nointr_nofail(fdf);
5099 close_nointr_nofail(fdf);
5100 r = close_nointr(fdt);
5110 int symlink_or_copy(const char *from, const char *to) {
5111 char *pf = NULL, *pt = NULL;
5118 if (parent_of_path(from, &pf) < 0 ||
5119 parent_of_path(to, &pt) < 0) {
5124 if (stat(pf, &a) < 0 ||
5130 if (a.st_dev != b.st_dev) {
5134 return copy_file(from, to);
5137 if (symlink(from, to) < 0) {
5151 int symlink_or_copy_atomic(const char *from, const char *to) {
5155 unsigned long long ull;
5162 t = new(char, strlen(to) + 1 + 16 + 1);
5166 fn = file_name_from_path(to);
5170 x = stpcpy(t+k+1, fn);
5173 for (i = 0; i < 16; i++) {
5174 *(x++) = hexchar(ull & 0xF);
5180 r = symlink_or_copy(from, t);
5187 if (rename(t, to) < 0) {
5198 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5206 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5209 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5212 r = read_one_line_file(p, &s);
5217 r = safe_atou32(s, &u);
5223 if (u == (uint32_t) -1 || u <= 0)
5230 bool display_is_local(const char *display) {
5234 display[0] == ':' &&
5235 display[1] >= '0' &&
5239 int socket_from_display(const char *display, char **path) {
5246 if (!display_is_local(display))
5249 k = strspn(display+1, "0123456789");
5251 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5255 c = stpcpy(f, "/tmp/.X11-unix/X");
5256 memcpy(c, display+1, k);
5264 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5271 /* We enforce some special rules for uid=0: in order to avoid
5272 * NSS lookups for root we hardcode its data. */
5274 if (streq(*username, "root") || streq(*username, "0")) {
5288 if (parse_uid(*username, &u) >= 0) {
5292 /* If there are multiple users with the same id, make
5293 * sure to leave $USER to the configured value instead
5294 * of the first occurrence in the database. However if
5295 * the uid was configured by a numeric uid, then let's
5296 * pick the real username from /etc/passwd. */
5298 *username = p->pw_name;
5301 p = getpwnam(*username);
5305 return errno != 0 ? -errno : -ESRCH;
5319 int get_group_creds(const char **groupname, gid_t *gid) {
5325 /* We enforce some special rules for gid=0: in order to avoid
5326 * NSS lookups for root we hardcode its data. */
5328 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5329 *groupname = "root";
5337 if (parse_gid(*groupname, &id) >= 0) {
5342 *groupname = g->gr_name;
5345 g = getgrnam(*groupname);
5349 return errno != 0 ? -errno : -ESRCH;
5357 int glob_exists(const char *path) {
5365 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5367 if (k == GLOB_NOMATCH)
5369 else if (k == GLOB_NOSPACE)
5372 r = !strv_isempty(g.gl_pathv);
5374 r = errno ? -errno : -EIO;
5381 int dirent_ensure_type(DIR *d, struct dirent *de) {
5387 if (de->d_type != DT_UNKNOWN)
5390 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5394 S_ISREG(st.st_mode) ? DT_REG :
5395 S_ISDIR(st.st_mode) ? DT_DIR :
5396 S_ISLNK(st.st_mode) ? DT_LNK :
5397 S_ISFIFO(st.st_mode) ? DT_FIFO :
5398 S_ISSOCK(st.st_mode) ? DT_SOCK :
5399 S_ISCHR(st.st_mode) ? DT_CHR :
5400 S_ISBLK(st.st_mode) ? DT_BLK :
5406 int in_search_path(const char *path, char **search) {
5410 r = parent_of_path(path, &parent);
5416 STRV_FOREACH(i, search) {
5417 if (path_equal(parent, *i)) {
5428 int get_files_in_directory(const char *path, char ***list) {
5436 /* Returns all files in a directory in *list, and the number
5437 * of files as return value. If list is NULL returns only the
5442 struct dirent buffer, *de;
5445 k = readdir_r(d, &buffer, &de);
5454 dirent_ensure_type(d, de);
5456 if (!dirent_is_file(de))
5460 if ((unsigned) r >= n) {
5464 t = realloc(l, sizeof(char*) * n);
5473 assert((unsigned) r < n);
5475 l[r] = strdup(de->d_name);
5499 static const char *const ioprio_class_table[] = {
5500 [IOPRIO_CLASS_NONE] = "none",
5501 [IOPRIO_CLASS_RT] = "realtime",
5502 [IOPRIO_CLASS_BE] = "best-effort",
5503 [IOPRIO_CLASS_IDLE] = "idle"
5506 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5508 static const char *const sigchld_code_table[] = {
5509 [CLD_EXITED] = "exited",
5510 [CLD_KILLED] = "killed",
5511 [CLD_DUMPED] = "dumped",
5512 [CLD_TRAPPED] = "trapped",
5513 [CLD_STOPPED] = "stopped",
5514 [CLD_CONTINUED] = "continued",
5517 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5519 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5520 [LOG_FAC(LOG_KERN)] = "kern",
5521 [LOG_FAC(LOG_USER)] = "user",
5522 [LOG_FAC(LOG_MAIL)] = "mail",
5523 [LOG_FAC(LOG_DAEMON)] = "daemon",
5524 [LOG_FAC(LOG_AUTH)] = "auth",
5525 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5526 [LOG_FAC(LOG_LPR)] = "lpr",
5527 [LOG_FAC(LOG_NEWS)] = "news",
5528 [LOG_FAC(LOG_UUCP)] = "uucp",
5529 [LOG_FAC(LOG_CRON)] = "cron",
5530 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5531 [LOG_FAC(LOG_FTP)] = "ftp",
5532 [LOG_FAC(LOG_LOCAL0)] = "local0",
5533 [LOG_FAC(LOG_LOCAL1)] = "local1",
5534 [LOG_FAC(LOG_LOCAL2)] = "local2",
5535 [LOG_FAC(LOG_LOCAL3)] = "local3",
5536 [LOG_FAC(LOG_LOCAL4)] = "local4",
5537 [LOG_FAC(LOG_LOCAL5)] = "local5",
5538 [LOG_FAC(LOG_LOCAL6)] = "local6",
5539 [LOG_FAC(LOG_LOCAL7)] = "local7"
5542 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5544 static const char *const log_level_table[] = {
5545 [LOG_EMERG] = "emerg",
5546 [LOG_ALERT] = "alert",
5547 [LOG_CRIT] = "crit",
5549 [LOG_WARNING] = "warning",
5550 [LOG_NOTICE] = "notice",
5551 [LOG_INFO] = "info",
5552 [LOG_DEBUG] = "debug"
5555 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5557 static const char* const sched_policy_table[] = {
5558 [SCHED_OTHER] = "other",
5559 [SCHED_BATCH] = "batch",
5560 [SCHED_IDLE] = "idle",
5561 [SCHED_FIFO] = "fifo",
5565 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5567 static const char* const rlimit_table[] = {
5568 [RLIMIT_CPU] = "LimitCPU",
5569 [RLIMIT_FSIZE] = "LimitFSIZE",
5570 [RLIMIT_DATA] = "LimitDATA",
5571 [RLIMIT_STACK] = "LimitSTACK",
5572 [RLIMIT_CORE] = "LimitCORE",
5573 [RLIMIT_RSS] = "LimitRSS",
5574 [RLIMIT_NOFILE] = "LimitNOFILE",
5575 [RLIMIT_AS] = "LimitAS",
5576 [RLIMIT_NPROC] = "LimitNPROC",
5577 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5578 [RLIMIT_LOCKS] = "LimitLOCKS",
5579 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5580 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5581 [RLIMIT_NICE] = "LimitNICE",
5582 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5583 [RLIMIT_RTTIME] = "LimitRTTIME"
5586 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5588 static const char* const ip_tos_table[] = {
5589 [IPTOS_LOWDELAY] = "low-delay",
5590 [IPTOS_THROUGHPUT] = "throughput",
5591 [IPTOS_RELIABILITY] = "reliability",
5592 [IPTOS_LOWCOST] = "low-cost",
5595 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5597 static const char *const signal_table[] = {
5614 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5625 [SIGVTALRM] = "VTALRM",
5627 [SIGWINCH] = "WINCH",
5633 DEFINE_STRING_TABLE_LOOKUP(signal, int);