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>
67 #include "exit-status.h"
71 char **saved_argv = NULL;
73 size_t page_size(void) {
74 static __thread size_t pgsz = 0;
77 if (_likely_(pgsz > 0))
80 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
87 bool streq_ptr(const char *a, const char *b) {
89 /* Like streq(), but tries to make sense of NULL pointers */
100 usec_t now(clockid_t clock_id) {
103 assert_se(clock_gettime(clock_id, &ts) == 0);
105 return timespec_load(&ts);
108 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
111 ts->realtime = now(CLOCK_REALTIME);
112 ts->monotonic = now(CLOCK_MONOTONIC);
117 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
126 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
128 ts->monotonic = now(CLOCK_MONOTONIC);
130 if ((int64_t) ts->monotonic > delta)
131 ts->monotonic -= delta;
139 usec_t timespec_load(const struct timespec *ts) {
143 (usec_t) ts->tv_sec * USEC_PER_SEC +
144 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
147 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
150 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
151 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
156 usec_t timeval_load(const struct timeval *tv) {
160 (usec_t) tv->tv_sec * USEC_PER_SEC +
161 (usec_t) tv->tv_usec;
164 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
167 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
168 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
173 bool endswith(const char *s, const char *postfix) {
180 pl = strlen(postfix);
188 return memcmp(s + sl - pl, postfix, pl) == 0;
191 bool startswith(const char *s, const char *prefix) {
206 return memcmp(s, prefix, pl) == 0;
209 bool startswith_no_case(const char *s, const char *prefix) {
225 for(i = 0; i < pl; ++i) {
226 if (tolower(s[i]) != tolower(prefix[i]))
233 bool first_word(const char *s, const char *word) {
248 if (memcmp(s, word, wl) != 0)
252 strchr(WHITESPACE, s[wl]);
255 int close_nointr(int fd) {
270 void close_nointr_nofail(int fd) {
271 int saved_errno = errno;
273 /* like close_nointr() but cannot fail, and guarantees errno
276 assert_se(close_nointr(fd) == 0);
281 void close_many(const int fds[], unsigned n_fd) {
284 for (i = 0; i < n_fd; i++)
285 close_nointr_nofail(fds[i]);
288 int parse_boolean(const char *v) {
291 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
293 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
299 int parse_pid(const char *s, pid_t* ret_pid) {
300 unsigned long ul = 0;
307 if ((r = safe_atolu(s, &ul)) < 0)
312 if ((unsigned long) pid != ul)
322 int parse_uid(const char *s, uid_t* ret_uid) {
323 unsigned long ul = 0;
330 if ((r = safe_atolu(s, &ul)) < 0)
335 if ((unsigned long) uid != ul)
342 int safe_atou(const char *s, unsigned *ret_u) {
350 l = strtoul(s, &x, 0);
352 if (!x || *x || errno)
353 return errno ? -errno : -EINVAL;
355 if ((unsigned long) (unsigned) l != l)
358 *ret_u = (unsigned) l;
362 int safe_atoi(const char *s, int *ret_i) {
370 l = strtol(s, &x, 0);
372 if (!x || *x || errno)
373 return errno ? -errno : -EINVAL;
375 if ((long) (int) l != l)
382 int safe_atollu(const char *s, long long unsigned *ret_llu) {
384 unsigned long long l;
390 l = strtoull(s, &x, 0);
392 if (!x || *x || errno)
393 return errno ? -errno : -EINVAL;
399 int safe_atolli(const char *s, long long int *ret_lli) {
407 l = strtoll(s, &x, 0);
409 if (!x || *x || errno)
410 return errno ? -errno : -EINVAL;
416 /* Split a string into words. */
417 char *split(const char *c, size_t *l, const char *separator, char **state) {
420 current = *state ? *state : (char*) c;
422 if (!*current || *c == 0)
425 current += strspn(current, separator);
426 *l = strcspn(current, separator);
429 return (char*) current;
432 /* Split a string into words, but consider strings enclosed in '' and
433 * "" as words even if they include spaces. */
434 char *split_quoted(const char *c, size_t *l, char **state) {
436 bool escaped = false;
438 current = *state ? *state : (char*) c;
440 if (!*current || *c == 0)
443 current += strspn(current, WHITESPACE);
445 if (*current == '\'') {
448 for (e = current; *e; e++) {
458 *state = *e == 0 ? e : e+1;
459 } else if (*current == '\"') {
462 for (e = current; *e; e++) {
472 *state = *e == 0 ? e : e+1;
474 for (e = current; *e; e++) {
479 else if (strchr(WHITESPACE, *e))
486 return (char*) current;
489 char **split_path_and_make_absolute(const char *p) {
493 if (!(l = strv_split(p, ":")))
496 if (!strv_path_make_absolute_cwd(l)) {
504 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
507 char fn[PATH_MAX], line[LINE_MAX], *p;
513 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
516 if (!(f = fopen(fn, "re")))
519 if (!(fgets(line, sizeof(line), f))) {
520 r = feof(f) ? -EIO : -errno;
527 /* Let's skip the pid and comm fields. The latter is enclosed
528 * in () but does not escape any () in its value, so let's
529 * skip over it manually */
531 if (!(p = strrchr(line, ')')))
542 if ((long unsigned) (pid_t) ppid != ppid)
545 *_ppid = (pid_t) ppid;
550 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
553 char fn[PATH_MAX], line[LINE_MAX], *p;
558 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
561 if (!(f = fopen(fn, "re")))
564 if (!(fgets(line, sizeof(line), f))) {
565 r = feof(f) ? -EIO : -errno;
572 /* Let's skip the pid and comm fields. The latter is enclosed
573 * in () but does not escape any () in its value, so let's
574 * skip over it manually */
576 if (!(p = strrchr(line, ')')))
597 "%*d " /* priority */
599 "%*d " /* num_threads */
600 "%*d " /* itrealvalue */
601 "%llu " /* starttime */,
608 int write_one_line_file(const char *fn, const char *line) {
615 if (!(f = fopen(fn, "we")))
619 if (fputs(line, f) < 0) {
624 if (!endswith(line, "\n"))
642 int fchmod_umask(int fd, mode_t m) {
647 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
653 int write_one_line_file_atomic(const char *fn, const char *line) {
661 r = fopen_temporary(fn, &f, &p);
665 fchmod_umask(fileno(f), 0644);
668 if (fputs(line, f) < 0) {
673 if (!endswith(line, "\n"))
684 if (rename(p, fn) < 0)
700 int read_one_line_file(const char *fn, char **line) {
703 char t[LINE_MAX], *c;
708 if (!(f = fopen(fn, "re")))
711 if (!(fgets(t, sizeof(t), f))) {
712 r = feof(f) ? -EIO : -errno;
716 if (!(c = strdup(t))) {
731 int read_full_file(const char *fn, char **contents, size_t *size) {
738 if (!(f = fopen(fn, "re")))
741 if (fstat(fileno(f), &st) < 0) {
747 if (st.st_size > 4*1024*1024) {
752 n = st.st_size > 0 ? st.st_size : LINE_MAX;
759 if (!(t = realloc(buf, n+1))) {
765 k = fread(buf + l, 1, n - l, f);
780 if (n > 4*1024*1024) {
804 const char *separator, ...) {
807 char *contents = NULL, *p;
812 if ((r = read_full_file(fname, &contents, NULL)) < 0)
817 const char *key = NULL;
819 p += strspn(p, separator);
820 p += strspn(p, WHITESPACE);
825 if (!strchr(COMMENTS, *p)) {
829 va_start(ap, separator);
830 while ((key = va_arg(ap, char *))) {
834 value = va_arg(ap, char **);
837 if (strncmp(p, key, n) != 0 ||
842 n = strcspn(p, separator);
845 strchr(QUOTES, p[0]) &&
847 v = strndup(p+1, n-2);
858 /* return empty value strings as NULL */
875 p += strcspn(p, separator);
894 if (!(f = fopen(fname, "re")))
898 char l[LINE_MAX], *p, *u;
901 if (!fgets(l, sizeof(l), f)) {
914 if (strchr(COMMENTS, *p))
917 if (!(u = normalize_env_assignment(p))) {
918 log_error("Out of memory");
923 t = strv_append(m, u);
927 log_error("Out of memory");
950 int write_env_file(const char *fname, char **l) {
955 r = fopen_temporary(fname, &f, &p);
959 fchmod_umask(fileno(f), 0644);
975 if (rename(p, fname) < 0)
990 char *truncate_nl(char *s) {
993 s[strcspn(s, NEWLINE)] = 0;
997 int get_process_comm(pid_t pid, char **name) {
1003 r = read_one_line_file("/proc/self/comm", name);
1006 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1009 r = read_one_line_file(p, name);
1016 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1023 assert(max_length > 0);
1027 f = fopen("/proc/self/cmdline", "re");
1030 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1040 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[] */
1088 h = get_process_comm(pid, &t);
1092 r = join("[", t, "]", NULL);
1103 int is_kernel_thread(pid_t pid) {
1113 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1122 count = fread(&c, 1, 1, f);
1126 /* Kernel threads have an empty cmdline */
1129 return eof ? 1 : -errno;
1134 int get_process_exe(pid_t pid, char **name) {
1140 r = readlink_malloc("/proc/self/exe", name);
1143 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1146 r = readlink_malloc(p, name);
1153 int get_process_uid(pid_t pid, uid_t *uid) {
1163 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1173 char line[LINE_MAX], *l;
1175 if (!fgets(line, sizeof(line), f)) {
1185 if (startswith(l, "Uid:")) {
1187 l += strspn(l, WHITESPACE);
1189 l[strcspn(l, WHITESPACE)] = 0;
1191 r = parse_uid(l, uid);
1204 char *strnappend(const char *s, const char *suffix, size_t b) {
1212 return strndup(suffix, b);
1222 if (!(r = new(char, a+b+1)))
1226 memcpy(r+a, suffix, b);
1232 char *strappend(const char *s, const char *suffix) {
1233 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1236 int readlink_malloc(const char *p, char **r) {
1246 if (!(c = new(char, l)))
1249 if ((n = readlink(p, c, l-1)) < 0) {
1255 if ((size_t) n < l-1) {
1266 int readlink_and_make_absolute(const char *p, char **r) {
1273 if ((j = readlink_malloc(p, &target)) < 0)
1276 k = file_in_same_dir(p, target);
1286 int readlink_and_canonicalize(const char *p, char **r) {
1293 j = readlink_and_make_absolute(p, &t);
1297 s = canonicalize_file_name(t);
1304 path_kill_slashes(*r);
1309 int parent_of_path(const char *path, char **_r) {
1310 const char *e, *a = NULL, *b = NULL, *p;
1320 for (e = path; *e; e++) {
1322 if (!slash && *e == '/') {
1326 } else if (slash && *e != '/')
1341 r = strndup(path, p-path);
1351 char *file_name_from_path(const char *p) {
1356 if ((r = strrchr(p, '/')))
1362 bool path_is_absolute(const char *p) {
1368 bool is_path(const char *p) {
1370 return !!strchr(p, '/');
1373 char *path_make_absolute(const char *p, const char *prefix) {
1376 /* Makes every item in the list an absolute path by prepending
1377 * the prefix, if specified and necessary */
1379 if (path_is_absolute(p) || !prefix)
1382 return join(prefix, "/", p, NULL);
1385 char *path_make_absolute_cwd(const char *p) {
1390 /* Similar to path_make_absolute(), but prefixes with the
1391 * current working directory. */
1393 if (path_is_absolute(p))
1396 if (!(cwd = get_current_dir_name()))
1399 r = path_make_absolute(p, cwd);
1405 char **strv_path_make_absolute_cwd(char **l) {
1408 /* Goes through every item in the string list and makes it
1409 * absolute. This works in place and won't rollback any
1410 * changes on failure. */
1412 STRV_FOREACH(s, l) {
1415 if (!(t = path_make_absolute_cwd(*s)))
1425 char **strv_path_canonicalize(char **l) {
1428 bool enomem = false;
1430 if (strv_isempty(l))
1433 /* Goes through every item in the string list and canonicalize
1434 * the path. This works in place and won't rollback any
1435 * changes on failure. */
1437 STRV_FOREACH(s, l) {
1440 t = path_make_absolute_cwd(*s);
1449 u = canonicalize_file_name(t);
1453 if (errno == ENOMEM || !errno)
1470 char **strv_path_remove_empty(char **l) {
1476 for (f = t = l; *f; f++) {
1478 if (dir_is_empty(*f) > 0) {
1490 int reset_all_signal_handlers(void) {
1493 for (sig = 1; sig < _NSIG; sig++) {
1494 struct sigaction sa;
1496 if (sig == SIGKILL || sig == SIGSTOP)
1500 sa.sa_handler = SIG_DFL;
1501 sa.sa_flags = SA_RESTART;
1503 /* On Linux the first two RT signals are reserved by
1504 * glibc, and sigaction() will return EINVAL for them. */
1505 if ((sigaction(sig, &sa, NULL) < 0))
1506 if (errno != EINVAL)
1513 char *strstrip(char *s) {
1516 /* Drops trailing whitespace. Modifies the string in
1517 * place. Returns pointer to first non-space character */
1519 s += strspn(s, WHITESPACE);
1521 for (e = strchr(s, 0); e > s; e --)
1522 if (!strchr(WHITESPACE, e[-1]))
1530 char *delete_chars(char *s, const char *bad) {
1533 /* Drops all whitespace, regardless where in the string */
1535 for (f = s, t = s; *f; f++) {
1536 if (strchr(bad, *f))
1547 bool in_charset(const char *s, const char* charset) {
1553 for (i = s; *i; i++)
1554 if (!strchr(charset, *i))
1560 char *file_in_same_dir(const char *path, const char *filename) {
1567 /* This removes the last component of path and appends
1568 * filename, unless the latter is absolute anyway or the
1571 if (path_is_absolute(filename))
1572 return strdup(filename);
1574 if (!(e = strrchr(path, '/')))
1575 return strdup(filename);
1577 k = strlen(filename);
1578 if (!(r = new(char, e-path+1+k+1)))
1581 memcpy(r, path, e-path+1);
1582 memcpy(r+(e-path)+1, filename, k+1);
1587 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1590 if (label_mkdir(path, mode) >= 0)
1591 if (chmod_and_chown(path, mode, uid, gid) < 0)
1594 if (lstat(path, &st) < 0)
1597 if ((st.st_mode & 0777) != mode ||
1600 !S_ISDIR(st.st_mode)) {
1609 int mkdir_parents(const char *path, mode_t mode) {
1614 /* Creates every parent directory in the path except the last
1617 p = path + strspn(path, "/");
1622 e = p + strcspn(p, "/");
1623 p = e + strspn(e, "/");
1625 /* Is this the last component? If so, then we're
1630 if (!(t = strndup(path, e - path)))
1633 r = label_mkdir(t, mode);
1636 if (r < 0 && errno != EEXIST)
1641 int mkdir_p(const char *path, mode_t mode) {
1646 if ((r = mkdir_parents(path, mode)) < 0)
1649 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1655 int rmdir_parents(const char *path, const char *stop) {
1664 /* Skip trailing slashes */
1665 while (l > 0 && path[l-1] == '/')
1671 /* Skip last component */
1672 while (l > 0 && path[l-1] != '/')
1675 /* Skip trailing slashes */
1676 while (l > 0 && path[l-1] == '/')
1682 if (!(t = strndup(path, l)))
1685 if (path_startswith(stop, t)) {
1694 if (errno != ENOENT)
1702 char hexchar(int x) {
1703 static const char table[16] = "0123456789abcdef";
1705 return table[x & 15];
1708 int unhexchar(char c) {
1710 if (c >= '0' && c <= '9')
1713 if (c >= 'a' && c <= 'f')
1714 return c - 'a' + 10;
1716 if (c >= 'A' && c <= 'F')
1717 return c - 'A' + 10;
1722 char octchar(int x) {
1723 return '0' + (x & 7);
1726 int unoctchar(char c) {
1728 if (c >= '0' && c <= '7')
1734 char decchar(int x) {
1735 return '0' + (x % 10);
1738 int undecchar(char c) {
1740 if (c >= '0' && c <= '9')
1746 char *cescape(const char *s) {
1752 /* Does C style string escaping. */
1754 if (!(r = new(char, strlen(s)*4 + 1)))
1757 for (f = s, t = r; *f; f++)
1803 /* For special chars we prefer octal over
1804 * hexadecimal encoding, simply because glib's
1805 * g_strescape() does the same */
1806 if ((*f < ' ') || (*f >= 127)) {
1808 *(t++) = octchar((unsigned char) *f >> 6);
1809 *(t++) = octchar((unsigned char) *f >> 3);
1810 *(t++) = octchar((unsigned char) *f);
1821 char *cunescape_length(const char *s, size_t length) {
1827 /* Undoes C style string escaping */
1829 if (!(r = new(char, length+1)))
1832 for (f = s, t = r; f < s + length; f++) {
1875 /* This is an extension of the XDG syntax files */
1880 /* hexadecimal encoding */
1883 if ((a = unhexchar(f[1])) < 0 ||
1884 (b = unhexchar(f[2])) < 0) {
1885 /* Invalid escape code, let's take it literal then */
1889 *(t++) = (char) ((a << 4) | b);
1904 /* octal encoding */
1907 if ((a = unoctchar(f[0])) < 0 ||
1908 (b = unoctchar(f[1])) < 0 ||
1909 (c = unoctchar(f[2])) < 0) {
1910 /* Invalid escape code, let's take it literal then */
1914 *(t++) = (char) ((a << 6) | (b << 3) | c);
1922 /* premature end of string.*/
1927 /* Invalid escape code, let's take it literal then */
1939 char *cunescape(const char *s) {
1940 return cunescape_length(s, strlen(s));
1943 char *xescape(const char *s, const char *bad) {
1947 /* Escapes all chars in bad, in addition to \ and all special
1948 * chars, in \xFF style escaping. May be reversed with
1951 if (!(r = new(char, strlen(s)*4+1)))
1954 for (f = s, t = r; *f; f++) {
1956 if ((*f < ' ') || (*f >= 127) ||
1957 (*f == '\\') || strchr(bad, *f)) {
1960 *(t++) = hexchar(*f >> 4);
1961 *(t++) = hexchar(*f);
1971 char *bus_path_escape(const char *s) {
1977 /* Escapes all chars that D-Bus' object path cannot deal
1978 * with. Can be reverse with bus_path_unescape() */
1980 if (!(r = new(char, strlen(s)*3+1)))
1983 for (f = s, t = r; *f; f++) {
1985 if (!(*f >= 'A' && *f <= 'Z') &&
1986 !(*f >= 'a' && *f <= 'z') &&
1987 !(*f >= '0' && *f <= '9')) {
1989 *(t++) = hexchar(*f >> 4);
1990 *(t++) = hexchar(*f);
2000 char *bus_path_unescape(const char *f) {
2005 if (!(r = strdup(f)))
2008 for (t = r; *f; f++) {
2013 if ((a = unhexchar(f[1])) < 0 ||
2014 (b = unhexchar(f[2])) < 0) {
2015 /* Invalid escape code, let's take it literal then */
2018 *(t++) = (char) ((a << 4) | b);
2030 char *path_kill_slashes(char *path) {
2034 /* Removes redundant inner and trailing slashes. Modifies the
2035 * passed string in-place.
2037 * ///foo///bar/ becomes /foo/bar
2040 for (f = path, t = path; *f; f++) {
2055 /* Special rule, if we are talking of the root directory, a
2056 trailing slash is good */
2058 if (t == path && slash)
2065 bool path_startswith(const char *path, const char *prefix) {
2069 if ((path[0] == '/') != (prefix[0] == '/'))
2075 path += strspn(path, "/");
2076 prefix += strspn(prefix, "/");
2084 a = strcspn(path, "/");
2085 b = strcspn(prefix, "/");
2090 if (memcmp(path, prefix, a) != 0)
2098 bool path_equal(const char *a, const char *b) {
2102 if ((a[0] == '/') != (b[0] == '/'))
2108 a += strspn(a, "/");
2109 b += strspn(b, "/");
2111 if (*a == 0 && *b == 0)
2114 if (*a == 0 || *b == 0)
2117 j = strcspn(a, "/");
2118 k = strcspn(b, "/");
2123 if (memcmp(a, b, j) != 0)
2131 char *ascii_strlower(char *t) {
2136 for (p = t; *p; p++)
2137 if (*p >= 'A' && *p <= 'Z')
2138 *p = *p - 'A' + 'a';
2143 bool ignore_file(const char *filename) {
2147 filename[0] == '.' ||
2148 streq(filename, "lost+found") ||
2149 streq(filename, "aquota.user") ||
2150 streq(filename, "aquota.group") ||
2151 endswith(filename, "~") ||
2152 endswith(filename, ".rpmnew") ||
2153 endswith(filename, ".rpmsave") ||
2154 endswith(filename, ".rpmorig") ||
2155 endswith(filename, ".dpkg-old") ||
2156 endswith(filename, ".dpkg-new") ||
2157 endswith(filename, ".swp");
2160 int fd_nonblock(int fd, bool nonblock) {
2165 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2169 flags |= O_NONBLOCK;
2171 flags &= ~O_NONBLOCK;
2173 if (fcntl(fd, F_SETFL, flags) < 0)
2179 int fd_cloexec(int fd, bool cloexec) {
2184 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2188 flags |= FD_CLOEXEC;
2190 flags &= ~FD_CLOEXEC;
2192 if (fcntl(fd, F_SETFD, flags) < 0)
2198 int close_all_fds(const int except[], unsigned n_except) {
2203 if (!(d = opendir("/proc/self/fd")))
2206 while ((de = readdir(d))) {
2209 if (ignore_file(de->d_name))
2212 if (safe_atoi(de->d_name, &fd) < 0)
2213 /* Let's better ignore this, just in case */
2227 for (i = 0; i < n_except; i++)
2228 if (except[i] == fd) {
2237 if (close_nointr(fd) < 0) {
2238 /* Valgrind has its own FD and doesn't want to have it closed */
2239 if (errno != EBADF && r == 0)
2248 bool chars_intersect(const char *a, const char *b) {
2251 /* Returns true if any of the chars in a are in b. */
2252 for (p = a; *p; p++)
2259 char *format_timestamp(char *buf, size_t l, usec_t t) {
2269 sec = (time_t) (t / USEC_PER_SEC);
2271 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2277 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2280 n = now(CLOCK_REALTIME);
2282 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2287 if (d >= USEC_PER_YEAR)
2288 snprintf(buf, l, "%llu years and %llu months ago",
2289 (unsigned long long) (d / USEC_PER_YEAR),
2290 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2291 else if (d >= USEC_PER_MONTH)
2292 snprintf(buf, l, "%llu months and %llu days ago",
2293 (unsigned long long) (d / USEC_PER_MONTH),
2294 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2295 else if (d >= USEC_PER_WEEK)
2296 snprintf(buf, l, "%llu weeks and %llu days ago",
2297 (unsigned long long) (d / USEC_PER_WEEK),
2298 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2299 else if (d >= 2*USEC_PER_DAY)
2300 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2301 else if (d >= 25*USEC_PER_HOUR)
2302 snprintf(buf, l, "1 day and %lluh ago",
2303 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2304 else if (d >= 6*USEC_PER_HOUR)
2305 snprintf(buf, l, "%lluh ago",
2306 (unsigned long long) (d / USEC_PER_HOUR));
2307 else if (d >= USEC_PER_HOUR)
2308 snprintf(buf, l, "%lluh %llumin ago",
2309 (unsigned long long) (d / USEC_PER_HOUR),
2310 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2311 else if (d >= 5*USEC_PER_MINUTE)
2312 snprintf(buf, l, "%llumin ago",
2313 (unsigned long long) (d / USEC_PER_MINUTE));
2314 else if (d >= USEC_PER_MINUTE)
2315 snprintf(buf, l, "%llumin %llus ago",
2316 (unsigned long long) (d / USEC_PER_MINUTE),
2317 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2318 else if (d >= USEC_PER_SEC)
2319 snprintf(buf, l, "%llus ago",
2320 (unsigned long long) (d / USEC_PER_SEC));
2321 else if (d >= USEC_PER_MSEC)
2322 snprintf(buf, l, "%llums ago",
2323 (unsigned long long) (d / USEC_PER_MSEC));
2325 snprintf(buf, l, "%lluus ago",
2326 (unsigned long long) d);
2328 snprintf(buf, l, "now");
2334 char *format_timespan(char *buf, size_t l, usec_t t) {
2335 static const struct {
2339 { "w", USEC_PER_WEEK },
2340 { "d", USEC_PER_DAY },
2341 { "h", USEC_PER_HOUR },
2342 { "min", USEC_PER_MINUTE },
2343 { "s", USEC_PER_SEC },
2344 { "ms", USEC_PER_MSEC },
2354 if (t == (usec_t) -1)
2358 snprintf(p, l, "0");
2363 /* The result of this function can be parsed with parse_usec */
2365 for (i = 0; i < ELEMENTSOF(table); i++) {
2369 if (t < table[i].usec)
2375 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2376 n = MIN((size_t) k, l);
2389 bool fstype_is_network(const char *fstype) {
2390 static const char * const table[] = {
2402 for (i = 0; i < ELEMENTSOF(table); i++)
2403 if (streq(table[i], fstype))
2412 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2417 TIOCL_GETKMSGREDIRECT,
2421 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2426 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2429 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2433 close_nointr_nofail(fd);
2437 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2438 struct termios old_termios, new_termios;
2440 char line[LINE_MAX];
2445 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2446 new_termios = old_termios;
2448 new_termios.c_lflag &= ~ICANON;
2449 new_termios.c_cc[VMIN] = 1;
2450 new_termios.c_cc[VTIME] = 0;
2452 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2455 if (t != (usec_t) -1) {
2456 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2457 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2462 k = fread(&c, 1, 1, f);
2464 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2470 *need_nl = c != '\n';
2477 if (t != (usec_t) -1)
2478 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2481 if (!fgets(line, sizeof(line), f))
2486 if (strlen(line) != 1)
2496 int ask(char *ret, const char *replies, const char *text, ...) {
2503 on_tty = isatty(STDOUT_FILENO);
2509 bool need_nl = true;
2512 fputs(ANSI_HIGHLIGHT_ON, stdout);
2519 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2523 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2526 if (r == -EBADMSG) {
2527 puts("Bad input, please try again.");
2538 if (strchr(replies, c)) {
2543 puts("Read unexpected character, please try again.");
2547 int reset_terminal_fd(int fd) {
2548 struct termios termios;
2551 /* Set terminal to some sane defaults */
2555 /* We leave locked terminal attributes untouched, so that
2556 * Plymouth may set whatever it wants to set, and we don't
2557 * interfere with that. */
2559 /* Disable exclusive mode, just in case */
2560 ioctl(fd, TIOCNXCL);
2562 /* Switch to text mode */
2563 ioctl(fd, KDSETMODE, KD_TEXT);
2565 /* Enable console unicode mode */
2566 ioctl(fd, KDSKBMODE, K_UNICODE);
2568 if (tcgetattr(fd, &termios) < 0) {
2573 /* We only reset the stuff that matters to the software. How
2574 * hardware is set up we don't touch assuming that somebody
2575 * else will do that for us */
2577 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2578 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2579 termios.c_oflag |= ONLCR;
2580 termios.c_cflag |= CREAD;
2581 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2583 termios.c_cc[VINTR] = 03; /* ^C */
2584 termios.c_cc[VQUIT] = 034; /* ^\ */
2585 termios.c_cc[VERASE] = 0177;
2586 termios.c_cc[VKILL] = 025; /* ^X */
2587 termios.c_cc[VEOF] = 04; /* ^D */
2588 termios.c_cc[VSTART] = 021; /* ^Q */
2589 termios.c_cc[VSTOP] = 023; /* ^S */
2590 termios.c_cc[VSUSP] = 032; /* ^Z */
2591 termios.c_cc[VLNEXT] = 026; /* ^V */
2592 termios.c_cc[VWERASE] = 027; /* ^W */
2593 termios.c_cc[VREPRINT] = 022; /* ^R */
2594 termios.c_cc[VEOL] = 0;
2595 termios.c_cc[VEOL2] = 0;
2597 termios.c_cc[VTIME] = 0;
2598 termios.c_cc[VMIN] = 1;
2600 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2604 /* Just in case, flush all crap out */
2605 tcflush(fd, TCIOFLUSH);
2610 int reset_terminal(const char *name) {
2613 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2617 r = reset_terminal_fd(fd);
2618 close_nointr_nofail(fd);
2623 int open_terminal(const char *name, int mode) {
2628 * If a TTY is in the process of being closed opening it might
2629 * cause EIO. This is horribly awful, but unlikely to be
2630 * changed in the kernel. Hence we work around this problem by
2631 * retrying a couple of times.
2633 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2637 if ((fd = open(name, mode)) >= 0)
2646 usleep(50 * USEC_PER_MSEC);
2653 if ((r = isatty(fd)) < 0) {
2654 close_nointr_nofail(fd);
2659 close_nointr_nofail(fd);
2666 int flush_fd(int fd) {
2667 struct pollfd pollfd;
2671 pollfd.events = POLLIN;
2678 if ((r = poll(&pollfd, 1, 0)) < 0) {
2689 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2694 if (errno == EAGAIN)
2705 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2706 int fd = -1, notify = -1, r, wd = -1;
2710 /* We use inotify to be notified when the tty is closed. We
2711 * create the watch before checking if we can actually acquire
2712 * it, so that we don't lose any event.
2714 * Note: strictly speaking this actually watches for the
2715 * device being closed, it does *not* really watch whether a
2716 * tty loses its controlling process. However, unless some
2717 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2718 * its tty otherwise this will not become a problem. As long
2719 * as the administrator makes sure not configure any service
2720 * on the same tty as an untrusted user this should not be a
2721 * problem. (Which he probably should not do anyway.) */
2723 if (!fail && !force) {
2724 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2729 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2737 if ((r = flush_fd(notify)) < 0)
2740 /* We pass here O_NOCTTY only so that we can check the return
2741 * value TIOCSCTTY and have a reliable way to figure out if we
2742 * successfully became the controlling process of the tty */
2743 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2746 /* First, try to get the tty */
2747 r = ioctl(fd, TIOCSCTTY, force);
2749 /* Sometimes it makes sense to ignore TIOCSCTTY
2750 * returning EPERM, i.e. when very likely we already
2751 * are have this controlling terminal. */
2752 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2755 if (r < 0 && (force || fail || errno != EPERM)) {
2765 assert(notify >= 0);
2768 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2770 struct inotify_event *e;
2772 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2781 e = (struct inotify_event*) inotify_buffer;
2786 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2791 step = sizeof(struct inotify_event) + e->len;
2792 assert(step <= (size_t) l);
2794 e = (struct inotify_event*) ((uint8_t*) e + step);
2801 /* We close the tty fd here since if the old session
2802 * ended our handle will be dead. It's important that
2803 * we do this after sleeping, so that we don't enter
2804 * an endless loop. */
2805 close_nointr_nofail(fd);
2809 close_nointr_nofail(notify);
2811 if ((r = reset_terminal_fd(fd)) < 0)
2812 log_warning("Failed to reset terminal: %s", strerror(-r));
2818 close_nointr_nofail(fd);
2821 close_nointr_nofail(notify);
2826 int release_terminal(void) {
2828 struct sigaction sa_old, sa_new;
2830 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2833 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2834 * by our own TIOCNOTTY */
2837 sa_new.sa_handler = SIG_IGN;
2838 sa_new.sa_flags = SA_RESTART;
2839 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2841 if (ioctl(fd, TIOCNOTTY) < 0)
2844 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2846 close_nointr_nofail(fd);
2850 int sigaction_many(const struct sigaction *sa, ...) {
2855 while ((sig = va_arg(ap, int)) > 0)
2856 if (sigaction(sig, sa, NULL) < 0)
2863 int ignore_signals(int sig, ...) {
2864 struct sigaction sa;
2869 sa.sa_handler = SIG_IGN;
2870 sa.sa_flags = SA_RESTART;
2872 if (sigaction(sig, &sa, NULL) < 0)
2876 while ((sig = va_arg(ap, int)) > 0)
2877 if (sigaction(sig, &sa, NULL) < 0)
2884 int default_signals(int sig, ...) {
2885 struct sigaction sa;
2890 sa.sa_handler = SIG_DFL;
2891 sa.sa_flags = SA_RESTART;
2893 if (sigaction(sig, &sa, NULL) < 0)
2897 while ((sig = va_arg(ap, int)) > 0)
2898 if (sigaction(sig, &sa, NULL) < 0)
2905 int close_pipe(int p[]) {
2911 a = close_nointr(p[0]);
2916 b = close_nointr(p[1]);
2920 return a < 0 ? a : b;
2923 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2932 while (nbytes > 0) {
2935 if ((k = read(fd, p, nbytes)) <= 0) {
2937 if (k < 0 && errno == EINTR)
2940 if (k < 0 && errno == EAGAIN && do_poll) {
2941 struct pollfd pollfd;
2945 pollfd.events = POLLIN;
2947 if (poll(&pollfd, 1, -1) < 0) {
2951 return n > 0 ? n : -errno;
2954 if (pollfd.revents != POLLIN)
2955 return n > 0 ? n : -EIO;
2960 return n > 0 ? n : (k < 0 ? -errno : 0);
2971 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2980 while (nbytes > 0) {
2983 k = write(fd, p, nbytes);
2986 if (k < 0 && errno == EINTR)
2989 if (k < 0 && errno == EAGAIN && do_poll) {
2990 struct pollfd pollfd;
2994 pollfd.events = POLLOUT;
2996 if (poll(&pollfd, 1, -1) < 0) {
3000 return n > 0 ? n : -errno;
3003 if (pollfd.revents != POLLOUT)
3004 return n > 0 ? n : -EIO;
3009 return n > 0 ? n : (k < 0 ? -errno : 0);
3020 int path_is_mount_point(const char *t, bool allow_symlink) {
3031 if (errno == ENOENT)
3037 r = parent_of_path(t, &parent);
3041 r = lstat(parent, &b);
3047 return a.st_dev != b.st_dev;
3050 int parse_usec(const char *t, usec_t *usec) {
3051 static const struct {
3055 { "sec", USEC_PER_SEC },
3056 { "s", USEC_PER_SEC },
3057 { "min", USEC_PER_MINUTE },
3058 { "hr", USEC_PER_HOUR },
3059 { "h", USEC_PER_HOUR },
3060 { "d", USEC_PER_DAY },
3061 { "w", USEC_PER_WEEK },
3062 { "msec", USEC_PER_MSEC },
3063 { "ms", USEC_PER_MSEC },
3064 { "m", USEC_PER_MINUTE },
3067 { "", USEC_PER_SEC },
3083 l = strtoll(p, &e, 10);
3094 e += strspn(e, WHITESPACE);
3096 for (i = 0; i < ELEMENTSOF(table); i++)
3097 if (startswith(e, table[i].suffix)) {
3098 r += (usec_t) l * table[i].usec;
3099 p = e + strlen(table[i].suffix);
3103 if (i >= ELEMENTSOF(table))
3113 int parse_bytes(const char *t, off_t *bytes) {
3114 static const struct {
3120 { "M", 1024ULL*1024ULL },
3121 { "G", 1024ULL*1024ULL*1024ULL },
3122 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3123 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3124 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3141 l = strtoll(p, &e, 10);
3152 e += strspn(e, WHITESPACE);
3154 for (i = 0; i < ELEMENTSOF(table); i++)
3155 if (startswith(e, table[i].suffix)) {
3156 r += (off_t) l * table[i].factor;
3157 p = e + strlen(table[i].suffix);
3161 if (i >= ELEMENTSOF(table))
3171 int make_stdio(int fd) {
3176 r = dup2(fd, STDIN_FILENO);
3177 s = dup2(fd, STDOUT_FILENO);
3178 t = dup2(fd, STDERR_FILENO);
3181 close_nointr_nofail(fd);
3183 if (r < 0 || s < 0 || t < 0)
3186 fd_cloexec(STDIN_FILENO, false);
3187 fd_cloexec(STDOUT_FILENO, false);
3188 fd_cloexec(STDERR_FILENO, false);
3193 int make_null_stdio(void) {
3196 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3199 return make_stdio(null_fd);
3202 bool is_device_path(const char *path) {
3204 /* Returns true on paths that refer to a device, either in
3205 * sysfs or in /dev */
3208 path_startswith(path, "/dev/") ||
3209 path_startswith(path, "/sys/");
3212 int dir_is_empty(const char *path) {
3215 struct dirent buf, *de;
3217 if (!(d = opendir(path)))
3221 if ((r = readdir_r(d, &buf, &de)) > 0) {
3231 if (!ignore_file(de->d_name)) {
3241 unsigned long long random_ull(void) {
3246 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3249 r = loop_read(fd, &ull, sizeof(ull), true);
3250 close_nointr_nofail(fd);
3252 if (r != sizeof(ull))
3258 return random() * RAND_MAX + random();
3261 void rename_process(const char name[8]) {
3264 prctl(PR_SET_NAME, name);
3266 /* This is a like a poor man's setproctitle(). The string
3267 * passed should fit in 7 chars (i.e. the length of
3270 if (program_invocation_name)
3271 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3273 if (saved_argc > 0) {
3277 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3279 for (i = 1; i < saved_argc; i++) {
3283 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3288 void sigset_add_many(sigset_t *ss, ...) {
3295 while ((sig = va_arg(ap, int)) > 0)
3296 assert_se(sigaddset(ss, sig) == 0);
3300 char* gethostname_malloc(void) {
3303 assert_se(uname(&u) >= 0);
3306 return strdup(u.nodename);
3308 return strdup(u.sysname);
3311 char* getlogname_malloc(void) {
3315 struct passwd pwbuf, *pw = NULL;
3318 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3323 /* Shortcut things to avoid NSS lookups */
3325 return strdup("root");
3327 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3330 if (!(buf = malloc(bufsize)))
3333 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3334 name = strdup(pw->pw_name);
3341 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3347 int getttyname_malloc(int fd, char **r) {
3348 char path[PATH_MAX], *c;
3353 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3358 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3365 int getttyname_harder(int fd, char **r) {
3369 if ((k = getttyname_malloc(fd, &s)) < 0)
3372 if (streq(s, "tty")) {
3374 return get_ctty(0, NULL, r);
3381 int get_ctty_devnr(pid_t pid, dev_t *d) {
3383 char line[LINE_MAX], *p, *fn;
3384 unsigned long ttynr;
3387 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3390 f = fopen(fn, "re");
3395 if (!fgets(line, sizeof(line), f)) {
3396 k = feof(f) ? -EIO : -errno;
3403 p = strrchr(line, ')');
3413 "%*d " /* session */
3422 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3424 char fn[PATH_MAX], *s, *b, *p;
3429 k = get_ctty_devnr(pid, &devnr);
3433 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3436 if ((k = readlink_malloc(fn, &s)) < 0) {
3441 /* This is an ugly hack */
3442 if (major(devnr) == 136) {
3443 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3453 /* Probably something like the ptys which have no
3454 * symlink in /dev/char. Let's return something
3455 * vaguely useful. */
3457 if (!(b = strdup(fn + 5)))
3467 if (startswith(s, "/dev/"))
3469 else if (startswith(s, "../"))
3487 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3493 /* This returns the first error we run into, but nevertheless
3496 if (!(d = fdopendir(fd))) {
3497 close_nointr_nofail(fd);
3499 return errno == ENOENT ? 0 : -errno;
3503 struct dirent buf, *de;
3504 bool is_dir, keep_around = false;
3507 if ((r = readdir_r(d, &buf, &de)) != 0) {
3516 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3519 if (de->d_type == DT_UNKNOWN) {
3522 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3523 if (ret == 0 && errno != ENOENT)
3530 (st.st_uid == 0 || st.st_uid == getuid()) &&
3531 (st.st_mode & S_ISVTX);
3533 is_dir = S_ISDIR(st.st_mode);
3536 if (honour_sticky) {
3539 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3540 if (ret == 0 && errno != ENOENT)
3546 (st.st_uid == 0 || st.st_uid == getuid()) &&
3547 (st.st_mode & S_ISVTX);
3550 is_dir = de->d_type == DT_DIR;
3556 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3557 if (ret == 0 && errno != ENOENT)
3562 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3568 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3569 if (ret == 0 && errno != ENOENT)
3573 } else if (!only_dirs && !keep_around) {
3575 if (unlinkat(fd, de->d_name, 0) < 0) {
3576 if (ret == 0 && errno != ENOENT)
3587 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3593 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3595 if (errno != ENOTDIR)
3598 if (delete_root && !only_dirs)
3599 if (unlink(path) < 0)
3605 r = rm_rf_children(fd, only_dirs, honour_sticky);
3609 if (honour_sticky && file_is_priv_sticky(path) > 0)
3612 if (rmdir(path) < 0 && errno != ENOENT) {
3621 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3624 /* Under the assumption that we are running privileged we
3625 * first change the access mode and only then hand out
3626 * ownership to avoid a window where access is too open. */
3628 if (mode != (mode_t) -1)
3629 if (chmod(path, mode) < 0)
3632 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3633 if (chown(path, uid, gid) < 0)
3639 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3642 /* Under the assumption that we are running privileged we
3643 * first change the access mode and only then hand out
3644 * ownership to avoid a window where access is too open. */
3646 if (fchmod(fd, mode) < 0)
3649 if (fchown(fd, uid, gid) < 0)
3655 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3659 /* Allocates the cpuset in the right size */
3662 if (!(r = CPU_ALLOC(n)))
3665 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3666 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3676 if (errno != EINVAL)
3683 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3684 char *s = NULL, *spaces = NULL, *e;
3686 size_t emax, sl, left;
3687 struct iovec iovec[5];
3692 /* This independent of logging, as status messages are
3693 * optional and go exclusively to the console. */
3695 if (vasprintf(&s, format, ap) < 0)
3698 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3708 sl = 2 + 6 + 1; /* " [" status "]" */
3709 emax = (size_t) c > sl ? c - sl - 1 : 0;
3713 e = ellipsize(s, emax, 75);
3721 IOVEC_SET_STRING(iovec[n++], s);
3725 left = emax > sl ? emax - sl : 0;
3727 spaces = malloc(left);
3729 memset(spaces, ' ', left);
3730 iovec[n].iov_base = spaces;
3731 iovec[n].iov_len = left;
3738 IOVEC_SET_STRING(iovec[n++], " [");
3739 IOVEC_SET_STRING(iovec[n++], status);
3740 IOVEC_SET_STRING(iovec[n++], "]\n");
3742 IOVEC_SET_STRING(iovec[n++], "\n");
3744 writev(fd, iovec, n);
3751 close_nointr_nofail(fd);
3754 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3759 va_start(ap, format);
3760 status_vprintf(status, ellipse, format, ap);
3764 void status_welcome(void) {
3765 char *pretty_name = NULL, *ansi_color = NULL;
3766 const char *const_pretty = NULL, *const_color = NULL;
3769 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3770 "PRETTY_NAME", &pretty_name,
3771 "ANSI_COLOR", &ansi_color,
3775 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3778 #if defined(TARGET_FEDORA)
3780 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3783 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3787 if (!ansi_color && pretty_name) {
3789 /* This tries to mimic the color magic the old Red Hat sysinit
3792 if (startswith(pretty_name, "Red Hat"))
3793 const_color = "0;31"; /* Red for RHEL */
3794 else if (startswith(pretty_name, "Fedora"))
3795 const_color = "0;34"; /* Blue for Fedora */
3798 #elif defined(TARGET_SUSE)
3801 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3804 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3809 const_color = "0;32"; /* Green for openSUSE */
3811 #elif defined(TARGET_GENTOO)
3814 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3817 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3822 const_color = "1;34"; /* Light Blue for Gentoo */
3824 #elif defined(TARGET_ALTLINUX)
3827 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3830 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3835 const_color = "0;36"; /* Cyan for ALTLinux */
3838 #elif defined(TARGET_DEBIAN)
3843 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3846 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3848 pretty_name = strappend("Debian ", version);
3852 log_warning("Failed to allocate Debian version string.");
3857 const_color = "1;31"; /* Light Red for Debian */
3859 #elif defined(TARGET_UBUNTU)
3861 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3862 "DISTRIB_DESCRIPTION", &pretty_name,
3866 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3870 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3872 #elif defined(TARGET_MANDRIVA)
3877 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3879 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3881 p = strstr(s, " release ");
3885 p[strcspn(p, " ")] = '\0';
3887 /* This corresponds to standard rc.sysinit */
3888 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3889 const_color = "1;36";
3891 log_warning("Failed to allocate Mandriva version string.");
3893 log_warning("Failed to parse /etc/mandriva-release");
3897 #elif defined(TARGET_MEEGO)
3900 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3903 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3908 const_color = "1;35"; /* Bright Magenta for MeeGo */
3911 if (!pretty_name && !const_pretty)
3912 const_pretty = "Linux";
3914 if (!ansi_color && !const_color)
3919 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3920 const_color ? const_color : ansi_color,
3921 const_pretty ? const_pretty : pretty_name);
3927 char *replace_env(const char *format, char **env) {
3934 const char *e, *word = format;
3939 for (e = format; *e; e ++) {
3950 if (!(k = strnappend(r, word, e-word-1)))
3959 } else if (*e == '$') {
3960 if (!(k = strnappend(r, word, e-word)))
3976 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3979 if (!(k = strappend(r, t)))
3992 if (!(k = strnappend(r, word, e-word)))
4003 char **replace_env_argv(char **argv, char **env) {
4005 unsigned k = 0, l = 0;
4007 l = strv_length(argv);
4009 if (!(r = new(char*, l+1)))
4012 STRV_FOREACH(i, argv) {
4014 /* If $FOO appears as single word, replace it by the split up variable */
4015 if ((*i)[0] == '$' && (*i)[1] != '{') {
4020 if ((e = strv_env_get(env, *i+1))) {
4022 if (!(m = strv_split_quoted(e))) {
4033 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
4042 memcpy(r + k, m, q * sizeof(char*));
4050 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
4051 if (!(r[k++] = replace_env(*i, env))) {
4061 int fd_columns(int fd) {
4065 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4074 unsigned columns(void) {
4075 static __thread int parsed_columns = 0;
4078 if (_likely_(parsed_columns > 0))
4079 return parsed_columns;
4081 e = getenv("COLUMNS");
4083 parsed_columns = atoi(e);
4085 if (parsed_columns <= 0)
4086 parsed_columns = fd_columns(STDOUT_FILENO);
4088 if (parsed_columns <= 0)
4089 parsed_columns = 80;
4091 return parsed_columns;
4094 int fd_lines(int fd) {
4098 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4107 unsigned lines(void) {
4108 static __thread int parsed_lines = 0;
4111 if (_likely_(parsed_lines > 0))
4112 return parsed_lines;
4114 e = getenv("LINES");
4116 parsed_lines = atoi(e);
4118 if (parsed_lines <= 0)
4119 parsed_lines = fd_lines(STDOUT_FILENO);
4121 if (parsed_lines <= 0)
4124 return parsed_lines;
4127 int running_in_chroot(void) {
4133 /* Only works as root */
4135 if (stat("/proc/1/root", &a) < 0)
4138 if (stat("/", &b) < 0)
4142 a.st_dev != b.st_dev ||
4143 a.st_ino != b.st_ino;
4146 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4151 assert(percent <= 100);
4152 assert(new_length >= 3);
4154 if (old_length <= 3 || old_length <= new_length)
4155 return strndup(s, old_length);
4157 r = new0(char, new_length+1);
4161 x = (new_length * percent) / 100;
4163 if (x > new_length - 3)
4171 s + old_length - (new_length - x - 3),
4172 new_length - x - 3);
4177 char *ellipsize(const char *s, size_t length, unsigned percent) {
4178 return ellipsize_mem(s, strlen(s), length, percent);
4181 int touch(const char *path) {
4186 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4189 close_nointr_nofail(fd);
4193 char *unquote(const char *s, const char* quotes) {
4201 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4202 return strndup(s+1, l-2);
4207 char *normalize_env_assignment(const char *s) {
4208 char *name, *value, *p, *r;
4213 if (!(r = strdup(s)))
4219 if (!(name = strndup(s, p - s)))
4222 if (!(p = strdup(p+1))) {
4227 value = unquote(strstrip(p), QUOTES);
4235 if (asprintf(&r, "%s=%s", name, value) < 0)
4244 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4255 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4267 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4274 if ((r = wait_for_terminate(pid, &status)) < 0) {
4275 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4279 if (status.si_code == CLD_EXITED) {
4280 if (status.si_status != 0) {
4281 log_warning("%s failed with error code %i.", name, status.si_status);
4282 return status.si_status;
4285 log_debug("%s succeeded.", name);
4288 } else if (status.si_code == CLD_KILLED ||
4289 status.si_code == CLD_DUMPED) {
4291 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4295 log_warning("%s failed due to unknown reason.", name);
4302 /* Make sure nobody waits for us on a socket anymore */
4303 close_all_fds(NULL, 0);
4311 bool null_or_empty(struct stat *st) {
4314 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4317 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4323 int null_or_empty_path(const char *fn) {
4328 if (stat(fn, &st) < 0)
4331 return null_or_empty(&st);
4334 DIR *xopendirat(int fd, const char *name, int flags) {
4338 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4341 if (!(d = fdopendir(nfd))) {
4342 close_nointr_nofail(nfd);
4349 int signal_from_string_try_harder(const char *s) {
4353 if ((signo = signal_from_string(s)) <= 0)
4354 if (startswith(s, "SIG"))
4355 return signal_from_string(s+3);
4360 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4366 if (!dual_timestamp_is_set(t))
4369 fprintf(f, "%s=%llu %llu\n",
4371 (unsigned long long) t->realtime,
4372 (unsigned long long) t->monotonic);
4375 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4376 unsigned long long a, b;
4381 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4382 log_debug("Failed to parse finish timestamp value %s", value);
4389 char *fstab_node_to_udev_node(const char *p) {
4393 /* FIXME: to follow udev's logic 100% we need to leave valid
4394 * UTF8 chars unescaped */
4396 if (startswith(p, "LABEL=")) {
4398 if (!(u = unquote(p+6, "\"\'")))
4401 t = xescape(u, "/ ");
4407 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4416 if (startswith(p, "UUID=")) {
4418 if (!(u = unquote(p+5, "\"\'")))
4421 t = xescape(u, "/ ");
4427 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4439 void filter_environ(const char *prefix) {
4446 for (i = 0, j = 0; environ[i]; i++) {
4448 if (startswith(environ[i], prefix))
4451 environ[j++] = environ[i];
4457 bool tty_is_vc(const char *tty) {
4460 if (startswith(tty, "/dev/"))
4463 return vtnr_from_tty(tty) >= 0;
4466 int vtnr_from_tty(const char *tty) {
4471 if (startswith(tty, "/dev/"))
4474 if (!startswith(tty, "tty") )
4477 if (tty[3] < '0' || tty[3] > '9')
4480 r = safe_atoi(tty+3, &i);
4484 if (i < 0 || i > 63)
4490 bool tty_is_vc_resolve(const char *tty) {
4491 char *active = NULL;
4496 if (startswith(tty, "/dev/"))
4499 /* Resolve where /dev/console is pointing to */
4500 if (streq(tty, "console"))
4501 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4502 /* If multiple log outputs are configured the
4503 * last one is what /dev/console points to */
4504 tty = strrchr(active, ' ');
4517 const char *default_term_for_tty(const char *tty) {
4520 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4523 bool dirent_is_file(const struct dirent *de) {
4526 if (ignore_file(de->d_name))
4529 if (de->d_type != DT_REG &&
4530 de->d_type != DT_LNK &&
4531 de->d_type != DT_UNKNOWN)
4537 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4540 if (!dirent_is_file(de))
4543 return endswith(de->d_name, suffix);
4546 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4549 Hashmap *pids = NULL;
4553 /* Executes all binaries in a directory in parallel and waits
4554 * until all they all finished. */
4557 if (!(_d = opendir(directory))) {
4559 if (errno == ENOENT)
4562 log_error("Failed to enumerate directory %s: %m", directory);
4569 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4570 log_error("Failed to allocate set.");
4574 while ((de = readdir(d))) {
4579 if (!dirent_is_file(de))
4582 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4583 log_error("Out of memory");
4587 if ((pid = fork()) < 0) {
4588 log_error("Failed to fork: %m");
4607 log_error("Failed to execute %s: %m", path);
4608 _exit(EXIT_FAILURE);
4611 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4613 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4614 log_error("Failed to add PID to set: %s", strerror(-k));
4619 while (!hashmap_isempty(pids)) {
4624 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4629 log_error("waitid() failed: %m");
4633 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4634 if (!is_clean_exit(si.si_code, si.si_status)) {
4635 if (si.si_code == CLD_EXITED)
4636 log_error("%s exited with exit status %i.", path, si.si_status);
4638 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4640 log_debug("%s exited successfully.", path);
4651 hashmap_free_free(pids);
4654 int kill_and_sigcont(pid_t pid, int sig) {
4657 r = kill(pid, sig) < 0 ? -errno : 0;
4665 bool nulstr_contains(const char*nulstr, const char *needle) {
4671 NULSTR_FOREACH(i, nulstr)
4672 if (streq(i, needle))
4678 bool plymouth_running(void) {
4679 return access("/run/plymouth/pid", F_OK) >= 0;
4682 void parse_syslog_priority(char **p, int *priority) {
4683 int a = 0, b = 0, c = 0;
4693 if (!strchr(*p, '>'))
4696 if ((*p)[2] == '>') {
4697 c = undecchar((*p)[1]);
4699 } else if ((*p)[3] == '>') {
4700 b = undecchar((*p)[1]);
4701 c = undecchar((*p)[2]);
4703 } else if ((*p)[4] == '>') {
4704 a = undecchar((*p)[1]);
4705 b = undecchar((*p)[2]);
4706 c = undecchar((*p)[3]);
4711 if (a < 0 || b < 0 || c < 0)
4714 *priority = a*100+b*10+c;
4718 void skip_syslog_pid(char **buf) {
4730 p += strspn(p, "0123456789");
4740 void skip_syslog_date(char **buf) {
4748 LETTER, LETTER, LETTER,
4750 SPACE_OR_NUMBER, NUMBER,
4752 SPACE_OR_NUMBER, NUMBER,
4754 SPACE_OR_NUMBER, NUMBER,
4756 SPACE_OR_NUMBER, NUMBER,
4768 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4773 switch (sequence[i]) {
4780 case SPACE_OR_NUMBER:
4787 if (*p < '0' || *p > '9')
4793 if (!(*p >= 'A' && *p <= 'Z') &&
4794 !(*p >= 'a' && *p <= 'z'))
4810 int have_effective_cap(int value) {
4812 cap_flag_value_t fv;
4815 if (!(cap = cap_get_proc()))
4818 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4827 char* strshorten(char *s, size_t l) {
4836 static bool hostname_valid_char(char c) {
4838 (c >= 'a' && c <= 'z') ||
4839 (c >= 'A' && c <= 'Z') ||
4840 (c >= '0' && c <= '9') ||
4846 bool hostname_is_valid(const char *s) {
4852 for (p = s; *p; p++)
4853 if (!hostname_valid_char(*p))
4856 if (p-s > HOST_NAME_MAX)
4862 char* hostname_cleanup(char *s) {
4865 for (p = s, d = s; *p; p++)
4866 if ((*p >= 'a' && *p <= 'z') ||
4867 (*p >= 'A' && *p <= 'Z') ||
4868 (*p >= '0' && *p <= '9') ||
4876 strshorten(s, HOST_NAME_MAX);
4880 int pipe_eof(int fd) {
4881 struct pollfd pollfd;
4886 pollfd.events = POLLIN|POLLHUP;
4888 r = poll(&pollfd, 1, 0);
4895 return pollfd.revents & POLLHUP;
4898 int fd_wait_for_event(int fd, int event, usec_t t) {
4899 struct pollfd pollfd;
4904 pollfd.events = event;
4906 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4913 return pollfd.revents;
4916 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4927 t = new(char, strlen(path) + 1 + 6 + 1);
4931 fn = file_name_from_path(path);
4935 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4937 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4943 f = fdopen(fd, "we");
4956 int terminal_vhangup_fd(int fd) {
4959 if (ioctl(fd, TIOCVHANGUP) < 0)
4965 int terminal_vhangup(const char *name) {
4968 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4972 r = terminal_vhangup_fd(fd);
4973 close_nointr_nofail(fd);
4978 int vt_disallocate(const char *name) {
4982 /* Deallocate the VT if possible. If not possible
4983 * (i.e. because it is the active one), at least clear it
4984 * entirely (including the scrollback buffer) */
4986 if (!startswith(name, "/dev/"))
4989 if (!tty_is_vc(name)) {
4990 /* So this is not a VT. I guess we cannot deallocate
4991 * it then. But let's at least clear the screen */
4993 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4998 "\033[r" /* clear scrolling region */
4999 "\033[H" /* move home */
5000 "\033[2J", /* clear screen */
5002 close_nointr_nofail(fd);
5007 if (!startswith(name, "/dev/tty"))
5010 r = safe_atou(name+8, &u);
5017 /* Try to deallocate */
5018 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
5022 r = ioctl(fd, VT_DISALLOCATE, u);
5023 close_nointr_nofail(fd);
5031 /* Couldn't deallocate, so let's clear it fully with
5033 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5038 "\033[r" /* clear scrolling region */
5039 "\033[H" /* move home */
5040 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
5042 close_nointr_nofail(fd);
5047 static int files_add(Hashmap *h, const char *path, const char *suffix) {
5049 struct dirent buffer, *de;
5052 dir = opendir(path);
5054 if (errno == ENOENT)
5063 k = readdir_r(dir, &buffer, &de);
5072 if (!dirent_is_file_with_suffix(de, suffix))
5075 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
5080 f = canonicalize_file_name(p);
5082 log_error("Failed to canonicalize file name '%s': %m", p);
5088 log_debug("found: %s\n", f);
5089 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5098 static int base_cmp(const void *a, const void *b) {
5099 const char *s1, *s2;
5101 s1 = *(char * const *)a;
5102 s2 = *(char * const *)b;
5103 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5106 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5109 char **files = NULL;
5115 dirs = strv_new_ap(dir, ap);
5121 if (!strv_path_canonicalize(dirs)) {
5125 if (!strv_uniq(dirs)) {
5130 fh = hashmap_new(string_hash_func, string_compare_func);
5136 STRV_FOREACH(p, dirs) {
5137 if (files_add(fh, *p, suffix) < 0) {
5138 log_error("Failed to search for files.");
5144 files = hashmap_get_strv(fh);
5145 if (files == NULL) {
5146 log_error("Failed to compose list of files.");
5151 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5160 int hwclock_is_localtime(void) {
5165 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5171 f = fopen("/etc/adjtime", "re");
5173 char line[LINE_MAX];
5176 b = fgets(line, sizeof(line), f) &&
5177 fgets(line, sizeof(line), f) &&
5178 fgets(line, sizeof(line), f);
5187 local = streq(line, "LOCAL");
5189 } else if (errno != -ENOENT)
5195 int hwclock_apply_localtime_delta(int *min) {
5196 const struct timeval *tv_null = NULL;
5202 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5203 assert_se(tm = localtime(&ts.tv_sec));
5204 minuteswest = tm->tm_gmtoff / 60;
5206 tz.tz_minuteswest = -minuteswest;
5207 tz.tz_dsttime = 0; /* DST_NONE*/
5210 * If the hardware clock does not run in UTC, but in local time:
5211 * The very first time we set the kernel's timezone, it will warp
5212 * the clock so that it runs in UTC instead of local time.
5214 if (settimeofday(tv_null, &tz) < 0)
5221 int hwclock_reset_localtime_delta(void) {
5222 const struct timeval *tv_null = NULL;
5225 tz.tz_minuteswest = 0;
5226 tz.tz_dsttime = 0; /* DST_NONE*/
5228 if (settimeofday(tv_null, &tz) < 0)
5234 int rtc_open(int flags) {
5238 /* First, we try to make use of the /dev/rtc symlink. If that
5239 * doesn't exist, we open the first RTC which has hctosys=1
5240 * set. If we don't find any we just take the first RTC that
5243 fd = open("/dev/rtc", flags);
5247 d = opendir("/sys/class/rtc");
5253 struct dirent buf, *de;
5256 r = readdir_r(d, &buf, &de);
5263 if (ignore_file(de->d_name))
5266 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5272 r = read_one_line_file(p, &v);
5278 r = parse_boolean(v);
5284 p = strappend("/dev/", de->d_name);
5285 fd = open(p, flags);
5298 fd = open("/dev/rtc0", flags);
5305 int hwclock_get_time(struct tm *tm) {
5311 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5315 /* This leaves the timezone fields of struct tm
5317 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5320 /* We don't now daylight saving, so we reset this in order not
5321 * to confused mktime(). */
5324 close_nointr_nofail(fd);
5329 int hwclock_set_time(const struct tm *tm) {
5335 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5339 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5342 close_nointr_nofail(fd);
5347 int copy_file(const char *from, const char *to) {
5353 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5357 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5359 close_nointr_nofail(fdf);
5367 n = read(fdf, buf, sizeof(buf));
5371 close_nointr_nofail(fdf);
5382 k = loop_write(fdt, buf, n, false);
5384 r = k < 0 ? k : (errno ? -errno : -EIO);
5386 close_nointr_nofail(fdf);
5394 close_nointr_nofail(fdf);
5395 r = close_nointr(fdt);
5405 int symlink_or_copy(const char *from, const char *to) {
5406 char *pf = NULL, *pt = NULL;
5413 if (parent_of_path(from, &pf) < 0 ||
5414 parent_of_path(to, &pt) < 0) {
5419 if (stat(pf, &a) < 0 ||
5425 if (a.st_dev != b.st_dev) {
5429 return copy_file(from, to);
5432 if (symlink(from, to) < 0) {
5446 int symlink_or_copy_atomic(const char *from, const char *to) {
5450 unsigned long long ull;
5457 t = new(char, strlen(to) + 1 + 16 + 1);
5461 fn = file_name_from_path(to);
5465 x = stpcpy(t+k+1, fn);
5468 for (i = 0; i < 16; i++) {
5469 *(x++) = hexchar(ull & 0xF);
5475 r = symlink_or_copy(from, t);
5482 if (rename(t, to) < 0) {
5493 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5500 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5504 r = read_one_line_file("/proc/self/sessionid", &s);
5508 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5511 r = read_one_line_file(p, &s);
5518 r = safe_atou32(s, &u);
5524 if (u == (uint32_t) -1 || u <= 0)
5531 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5538 /* Only use audit login uid if we are executed with sufficient
5539 * capabilities so that pam_loginuid could do its job. If we
5540 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5541 * are being run in a container and /proc/self/loginuid is
5542 * useless since it probably contains a uid of the host
5545 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5549 r = read_one_line_file("/proc/self/loginuid", &s);
5553 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5556 r = read_one_line_file(p, &s);
5563 r = parse_uid(s, &u);
5569 if (u == (uid_t) -1)
5576 bool display_is_local(const char *display) {
5580 display[0] == ':' &&
5581 display[1] >= '0' &&
5585 int socket_from_display(const char *display, char **path) {
5592 if (!display_is_local(display))
5595 k = strspn(display+1, "0123456789");
5597 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5601 c = stpcpy(f, "/tmp/.X11-unix/X");
5602 memcpy(c, display+1, k);
5610 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5617 /* We enforce some special rules for uid=0: in order to avoid
5618 * NSS lookups for root we hardcode its data. */
5620 if (streq(*username, "root") || streq(*username, "0")) {
5634 if (parse_uid(*username, &u) >= 0) {
5638 /* If there are multiple users with the same id, make
5639 * sure to leave $USER to the configured value instead
5640 * of the first occurrence in the database. However if
5641 * the uid was configured by a numeric uid, then let's
5642 * pick the real username from /etc/passwd. */
5644 *username = p->pw_name;
5647 p = getpwnam(*username);
5651 return errno != 0 ? -errno : -ESRCH;
5665 int get_group_creds(const char **groupname, gid_t *gid) {
5671 /* We enforce some special rules for gid=0: in order to avoid
5672 * NSS lookups for root we hardcode its data. */
5674 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5675 *groupname = "root";
5683 if (parse_gid(*groupname, &id) >= 0) {
5688 *groupname = g->gr_name;
5691 g = getgrnam(*groupname);
5695 return errno != 0 ? -errno : -ESRCH;
5703 int glob_exists(const char *path) {
5711 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5713 if (k == GLOB_NOMATCH)
5715 else if (k == GLOB_NOSPACE)
5718 r = !strv_isempty(g.gl_pathv);
5720 r = errno ? -errno : -EIO;
5727 int dirent_ensure_type(DIR *d, struct dirent *de) {
5733 if (de->d_type != DT_UNKNOWN)
5736 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5740 S_ISREG(st.st_mode) ? DT_REG :
5741 S_ISDIR(st.st_mode) ? DT_DIR :
5742 S_ISLNK(st.st_mode) ? DT_LNK :
5743 S_ISFIFO(st.st_mode) ? DT_FIFO :
5744 S_ISSOCK(st.st_mode) ? DT_SOCK :
5745 S_ISCHR(st.st_mode) ? DT_CHR :
5746 S_ISBLK(st.st_mode) ? DT_BLK :
5752 int in_search_path(const char *path, char **search) {
5756 r = parent_of_path(path, &parent);
5762 STRV_FOREACH(i, search) {
5763 if (path_equal(parent, *i)) {
5774 int get_files_in_directory(const char *path, char ***list) {
5782 /* Returns all files in a directory in *list, and the number
5783 * of files as return value. If list is NULL returns only the
5791 struct dirent buffer, *de;
5794 k = readdir_r(d, &buffer, &de);
5803 dirent_ensure_type(d, de);
5805 if (!dirent_is_file(de))
5809 if ((unsigned) r >= n) {
5813 t = realloc(l, sizeof(char*) * n);
5822 assert((unsigned) r < n);
5824 l[r] = strdup(de->d_name);
5848 char *join(const char *x, ...) {
5861 t = va_arg(ap, const char *);
5884 t = va_arg(ap, const char *);
5898 bool is_main_thread(void) {
5899 static __thread int cached = 0;
5901 if (_unlikely_(cached == 0))
5902 cached = getpid() == gettid() ? 1 : -1;
5907 int block_get_whole_disk(dev_t d, dev_t *ret) {
5914 /* If it has a queue this is good enough for us */
5915 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5918 r = access(p, F_OK);
5926 /* If it is a partition find the originating device */
5927 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5930 r = access(p, F_OK);
5936 /* Get parent dev_t */
5937 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5940 r = read_one_line_file(p, &s);
5946 r = sscanf(s, "%u:%u", &m, &n);
5952 /* Only return this if it is really good enough for us. */
5953 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5956 r = access(p, F_OK);
5960 *ret = makedev(m, n);
5967 int file_is_priv_sticky(const char *p) {
5972 if (lstat(p, &st) < 0)
5976 (st.st_uid == 0 || st.st_uid == getuid()) &&
5977 (st.st_mode & S_ISVTX);
5980 static const char *const ioprio_class_table[] = {
5981 [IOPRIO_CLASS_NONE] = "none",
5982 [IOPRIO_CLASS_RT] = "realtime",
5983 [IOPRIO_CLASS_BE] = "best-effort",
5984 [IOPRIO_CLASS_IDLE] = "idle"
5987 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5989 static const char *const sigchld_code_table[] = {
5990 [CLD_EXITED] = "exited",
5991 [CLD_KILLED] = "killed",
5992 [CLD_DUMPED] = "dumped",
5993 [CLD_TRAPPED] = "trapped",
5994 [CLD_STOPPED] = "stopped",
5995 [CLD_CONTINUED] = "continued",
5998 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
6000 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
6001 [LOG_FAC(LOG_KERN)] = "kern",
6002 [LOG_FAC(LOG_USER)] = "user",
6003 [LOG_FAC(LOG_MAIL)] = "mail",
6004 [LOG_FAC(LOG_DAEMON)] = "daemon",
6005 [LOG_FAC(LOG_AUTH)] = "auth",
6006 [LOG_FAC(LOG_SYSLOG)] = "syslog",
6007 [LOG_FAC(LOG_LPR)] = "lpr",
6008 [LOG_FAC(LOG_NEWS)] = "news",
6009 [LOG_FAC(LOG_UUCP)] = "uucp",
6010 [LOG_FAC(LOG_CRON)] = "cron",
6011 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
6012 [LOG_FAC(LOG_FTP)] = "ftp",
6013 [LOG_FAC(LOG_LOCAL0)] = "local0",
6014 [LOG_FAC(LOG_LOCAL1)] = "local1",
6015 [LOG_FAC(LOG_LOCAL2)] = "local2",
6016 [LOG_FAC(LOG_LOCAL3)] = "local3",
6017 [LOG_FAC(LOG_LOCAL4)] = "local4",
6018 [LOG_FAC(LOG_LOCAL5)] = "local5",
6019 [LOG_FAC(LOG_LOCAL6)] = "local6",
6020 [LOG_FAC(LOG_LOCAL7)] = "local7"
6023 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
6025 static const char *const log_level_table[] = {
6026 [LOG_EMERG] = "emerg",
6027 [LOG_ALERT] = "alert",
6028 [LOG_CRIT] = "crit",
6030 [LOG_WARNING] = "warning",
6031 [LOG_NOTICE] = "notice",
6032 [LOG_INFO] = "info",
6033 [LOG_DEBUG] = "debug"
6036 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
6038 static const char* const sched_policy_table[] = {
6039 [SCHED_OTHER] = "other",
6040 [SCHED_BATCH] = "batch",
6041 [SCHED_IDLE] = "idle",
6042 [SCHED_FIFO] = "fifo",
6046 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
6048 static const char* const rlimit_table[] = {
6049 [RLIMIT_CPU] = "LimitCPU",
6050 [RLIMIT_FSIZE] = "LimitFSIZE",
6051 [RLIMIT_DATA] = "LimitDATA",
6052 [RLIMIT_STACK] = "LimitSTACK",
6053 [RLIMIT_CORE] = "LimitCORE",
6054 [RLIMIT_RSS] = "LimitRSS",
6055 [RLIMIT_NOFILE] = "LimitNOFILE",
6056 [RLIMIT_AS] = "LimitAS",
6057 [RLIMIT_NPROC] = "LimitNPROC",
6058 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
6059 [RLIMIT_LOCKS] = "LimitLOCKS",
6060 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
6061 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
6062 [RLIMIT_NICE] = "LimitNICE",
6063 [RLIMIT_RTPRIO] = "LimitRTPRIO",
6064 [RLIMIT_RTTIME] = "LimitRTTIME"
6067 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
6069 static const char* const ip_tos_table[] = {
6070 [IPTOS_LOWDELAY] = "low-delay",
6071 [IPTOS_THROUGHPUT] = "throughput",
6072 [IPTOS_RELIABILITY] = "reliability",
6073 [IPTOS_LOWCOST] = "low-cost",
6076 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
6078 static const char *const __signal_table[] = {
6095 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
6106 [SIGVTALRM] = "VTALRM",
6108 [SIGWINCH] = "WINCH",
6114 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6116 const char *signal_to_string(int signo) {
6117 static __thread char buf[12];
6120 name = __signal_to_string(signo);
6124 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6125 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6127 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6132 int signal_from_string(const char *s) {
6137 signo =__signal_from_string(s);
6141 if (startswith(s, "RTMIN+")) {
6145 if (safe_atou(s, &u) >= 0) {
6146 signo = (int) u + offset;
6147 if (signo > 0 && signo < _NSIG)
6153 bool kexec_loaded(void) {
6154 bool loaded = false;
6157 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6165 int strdup_or_null(const char *a, char **b) {
6183 int prot_from_flags(int flags) {
6185 switch (flags & O_ACCMODE) {
6194 return PROT_READ|PROT_WRITE;
6201 unsigned long cap_last_cap(void) {
6202 static __thread unsigned long saved;
6203 static __thread bool valid = false;
6209 p = (unsigned long) CAP_LAST_CAP;
6211 if (prctl(PR_CAPBSET_READ, p) < 0) {
6213 /* Hmm, look downwards, until we find one that
6215 for (p--; p > 0; p --)
6216 if (prctl(PR_CAPBSET_READ, p) >= 0)
6221 /* Hmm, look upwards, until we find one that doesn't
6224 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6234 char *format_bytes(char *buf, size_t l, off_t t) {
6237 static const struct {
6241 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6242 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6243 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6244 { "G", 1024ULL*1024ULL*1024ULL },
6245 { "M", 1024ULL*1024ULL },
6249 for (i = 0; i < ELEMENTSOF(table); i++) {
6251 if (t >= table[i].factor) {
6254 (unsigned long long) (t / table[i].factor),
6255 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6262 snprintf(buf, l, "%lluB", (unsigned long long) t);
6270 void* memdup(const void *p, size_t l) {