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, 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 k = fread(&c, 1, 1, f);
2457 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2463 *need_nl = c != '\n';
2470 if (!(fgets(line, sizeof(line), f)))
2475 if (strlen(line) != 1)
2485 int ask(char *ret, const char *replies, const char *text, ...) {
2492 on_tty = isatty(STDOUT_FILENO);
2498 bool need_nl = true;
2501 fputs(ANSI_HIGHLIGHT_ON, stdout);
2508 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2512 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2514 if (r == -EBADMSG) {
2515 puts("Bad input, please try again.");
2526 if (strchr(replies, c)) {
2531 puts("Read unexpected character, please try again.");
2535 int reset_terminal_fd(int fd) {
2536 struct termios termios;
2539 /* Set terminal to some sane defaults */
2543 /* We leave locked terminal attributes untouched, so that
2544 * Plymouth may set whatever it wants to set, and we don't
2545 * interfere with that. */
2547 /* Disable exclusive mode, just in case */
2548 ioctl(fd, TIOCNXCL);
2550 /* Switch to text mode */
2551 ioctl(fd, KDSETMODE, KD_TEXT);
2553 /* Enable console unicode mode */
2554 ioctl(fd, KDSKBMODE, K_UNICODE);
2556 if (tcgetattr(fd, &termios) < 0) {
2561 /* We only reset the stuff that matters to the software. How
2562 * hardware is set up we don't touch assuming that somebody
2563 * else will do that for us */
2565 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2566 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2567 termios.c_oflag |= ONLCR;
2568 termios.c_cflag |= CREAD;
2569 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2571 termios.c_cc[VINTR] = 03; /* ^C */
2572 termios.c_cc[VQUIT] = 034; /* ^\ */
2573 termios.c_cc[VERASE] = 0177;
2574 termios.c_cc[VKILL] = 025; /* ^X */
2575 termios.c_cc[VEOF] = 04; /* ^D */
2576 termios.c_cc[VSTART] = 021; /* ^Q */
2577 termios.c_cc[VSTOP] = 023; /* ^S */
2578 termios.c_cc[VSUSP] = 032; /* ^Z */
2579 termios.c_cc[VLNEXT] = 026; /* ^V */
2580 termios.c_cc[VWERASE] = 027; /* ^W */
2581 termios.c_cc[VREPRINT] = 022; /* ^R */
2582 termios.c_cc[VEOL] = 0;
2583 termios.c_cc[VEOL2] = 0;
2585 termios.c_cc[VTIME] = 0;
2586 termios.c_cc[VMIN] = 1;
2588 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2592 /* Just in case, flush all crap out */
2593 tcflush(fd, TCIOFLUSH);
2598 int reset_terminal(const char *name) {
2601 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2605 r = reset_terminal_fd(fd);
2606 close_nointr_nofail(fd);
2611 int open_terminal(const char *name, int mode) {
2616 * If a TTY is in the process of being closed opening it might
2617 * cause EIO. This is horribly awful, but unlikely to be
2618 * changed in the kernel. Hence we work around this problem by
2619 * retrying a couple of times.
2621 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2625 if ((fd = open(name, mode)) >= 0)
2634 usleep(50 * USEC_PER_MSEC);
2641 if ((r = isatty(fd)) < 0) {
2642 close_nointr_nofail(fd);
2647 close_nointr_nofail(fd);
2654 int flush_fd(int fd) {
2655 struct pollfd pollfd;
2659 pollfd.events = POLLIN;
2666 if ((r = poll(&pollfd, 1, 0)) < 0) {
2677 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2682 if (errno == EAGAIN)
2693 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2694 int fd = -1, notify = -1, r, wd = -1;
2698 /* We use inotify to be notified when the tty is closed. We
2699 * create the watch before checking if we can actually acquire
2700 * it, so that we don't lose any event.
2702 * Note: strictly speaking this actually watches for the
2703 * device being closed, it does *not* really watch whether a
2704 * tty loses its controlling process. However, unless some
2705 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2706 * its tty otherwise this will not become a problem. As long
2707 * as the administrator makes sure not configure any service
2708 * on the same tty as an untrusted user this should not be a
2709 * problem. (Which he probably should not do anyway.) */
2711 if (!fail && !force) {
2712 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2717 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2725 if ((r = flush_fd(notify)) < 0)
2728 /* We pass here O_NOCTTY only so that we can check the return
2729 * value TIOCSCTTY and have a reliable way to figure out if we
2730 * successfully became the controlling process of the tty */
2731 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2734 /* First, try to get the tty */
2735 r = ioctl(fd, TIOCSCTTY, force);
2737 /* Sometimes it makes sense to ignore TIOCSCTTY
2738 * returning EPERM, i.e. when very likely we already
2739 * are have this controlling terminal. */
2740 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2743 if (r < 0 && (force || fail || errno != EPERM)) {
2753 assert(notify >= 0);
2756 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2758 struct inotify_event *e;
2760 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2769 e = (struct inotify_event*) inotify_buffer;
2774 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2779 step = sizeof(struct inotify_event) + e->len;
2780 assert(step <= (size_t) l);
2782 e = (struct inotify_event*) ((uint8_t*) e + step);
2789 /* We close the tty fd here since if the old session
2790 * ended our handle will be dead. It's important that
2791 * we do this after sleeping, so that we don't enter
2792 * an endless loop. */
2793 close_nointr_nofail(fd);
2797 close_nointr_nofail(notify);
2799 if ((r = reset_terminal_fd(fd)) < 0)
2800 log_warning("Failed to reset terminal: %s", strerror(-r));
2806 close_nointr_nofail(fd);
2809 close_nointr_nofail(notify);
2814 int release_terminal(void) {
2816 struct sigaction sa_old, sa_new;
2818 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2821 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2822 * by our own TIOCNOTTY */
2825 sa_new.sa_handler = SIG_IGN;
2826 sa_new.sa_flags = SA_RESTART;
2827 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2829 if (ioctl(fd, TIOCNOTTY) < 0)
2832 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2834 close_nointr_nofail(fd);
2838 int sigaction_many(const struct sigaction *sa, ...) {
2843 while ((sig = va_arg(ap, int)) > 0)
2844 if (sigaction(sig, sa, NULL) < 0)
2851 int ignore_signals(int sig, ...) {
2852 struct sigaction sa;
2857 sa.sa_handler = SIG_IGN;
2858 sa.sa_flags = SA_RESTART;
2860 if (sigaction(sig, &sa, NULL) < 0)
2864 while ((sig = va_arg(ap, int)) > 0)
2865 if (sigaction(sig, &sa, NULL) < 0)
2872 int default_signals(int sig, ...) {
2873 struct sigaction sa;
2878 sa.sa_handler = SIG_DFL;
2879 sa.sa_flags = SA_RESTART;
2881 if (sigaction(sig, &sa, NULL) < 0)
2885 while ((sig = va_arg(ap, int)) > 0)
2886 if (sigaction(sig, &sa, NULL) < 0)
2893 int close_pipe(int p[]) {
2899 a = close_nointr(p[0]);
2904 b = close_nointr(p[1]);
2908 return a < 0 ? a : b;
2911 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2920 while (nbytes > 0) {
2923 if ((k = read(fd, p, nbytes)) <= 0) {
2925 if (k < 0 && errno == EINTR)
2928 if (k < 0 && errno == EAGAIN && do_poll) {
2929 struct pollfd pollfd;
2933 pollfd.events = POLLIN;
2935 if (poll(&pollfd, 1, -1) < 0) {
2939 return n > 0 ? n : -errno;
2942 if (pollfd.revents != POLLIN)
2943 return n > 0 ? n : -EIO;
2948 return n > 0 ? n : (k < 0 ? -errno : 0);
2959 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2968 while (nbytes > 0) {
2971 k = write(fd, p, nbytes);
2974 if (k < 0 && errno == EINTR)
2977 if (k < 0 && errno == EAGAIN && do_poll) {
2978 struct pollfd pollfd;
2982 pollfd.events = POLLOUT;
2984 if (poll(&pollfd, 1, -1) < 0) {
2988 return n > 0 ? n : -errno;
2991 if (pollfd.revents != POLLOUT)
2992 return n > 0 ? n : -EIO;
2997 return n > 0 ? n : (k < 0 ? -errno : 0);
3008 int path_is_mount_point(const char *t, bool allow_symlink) {
3019 if (errno == ENOENT)
3025 r = parent_of_path(t, &parent);
3029 r = lstat(parent, &b);
3035 return a.st_dev != b.st_dev;
3038 int parse_usec(const char *t, usec_t *usec) {
3039 static const struct {
3043 { "sec", USEC_PER_SEC },
3044 { "s", USEC_PER_SEC },
3045 { "min", USEC_PER_MINUTE },
3046 { "hr", USEC_PER_HOUR },
3047 { "h", USEC_PER_HOUR },
3048 { "d", USEC_PER_DAY },
3049 { "w", USEC_PER_WEEK },
3050 { "msec", USEC_PER_MSEC },
3051 { "ms", USEC_PER_MSEC },
3052 { "m", USEC_PER_MINUTE },
3055 { "", USEC_PER_SEC },
3071 l = strtoll(p, &e, 10);
3082 e += strspn(e, WHITESPACE);
3084 for (i = 0; i < ELEMENTSOF(table); i++)
3085 if (startswith(e, table[i].suffix)) {
3086 r += (usec_t) l * table[i].usec;
3087 p = e + strlen(table[i].suffix);
3091 if (i >= ELEMENTSOF(table))
3101 int parse_bytes(const char *t, off_t *bytes) {
3102 static const struct {
3108 { "M", 1024ULL*1024ULL },
3109 { "G", 1024ULL*1024ULL*1024ULL },
3110 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3111 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3112 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3129 l = strtoll(p, &e, 10);
3140 e += strspn(e, WHITESPACE);
3142 for (i = 0; i < ELEMENTSOF(table); i++)
3143 if (startswith(e, table[i].suffix)) {
3144 r += (off_t) l * table[i].factor;
3145 p = e + strlen(table[i].suffix);
3149 if (i >= ELEMENTSOF(table))
3159 int make_stdio(int fd) {
3164 r = dup2(fd, STDIN_FILENO);
3165 s = dup2(fd, STDOUT_FILENO);
3166 t = dup2(fd, STDERR_FILENO);
3169 close_nointr_nofail(fd);
3171 if (r < 0 || s < 0 || t < 0)
3174 fd_cloexec(STDIN_FILENO, false);
3175 fd_cloexec(STDOUT_FILENO, false);
3176 fd_cloexec(STDERR_FILENO, false);
3181 int make_null_stdio(void) {
3184 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3187 return make_stdio(null_fd);
3190 bool is_device_path(const char *path) {
3192 /* Returns true on paths that refer to a device, either in
3193 * sysfs or in /dev */
3196 path_startswith(path, "/dev/") ||
3197 path_startswith(path, "/sys/");
3200 int dir_is_empty(const char *path) {
3203 struct dirent buf, *de;
3205 if (!(d = opendir(path)))
3209 if ((r = readdir_r(d, &buf, &de)) > 0) {
3219 if (!ignore_file(de->d_name)) {
3229 unsigned long long random_ull(void) {
3234 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3237 r = loop_read(fd, &ull, sizeof(ull), true);
3238 close_nointr_nofail(fd);
3240 if (r != sizeof(ull))
3246 return random() * RAND_MAX + random();
3249 void rename_process(const char name[8]) {
3252 prctl(PR_SET_NAME, name);
3254 /* This is a like a poor man's setproctitle(). The string
3255 * passed should fit in 7 chars (i.e. the length of
3258 if (program_invocation_name)
3259 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3261 if (saved_argc > 0) {
3265 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3267 for (i = 1; i < saved_argc; i++) {
3271 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3276 void sigset_add_many(sigset_t *ss, ...) {
3283 while ((sig = va_arg(ap, int)) > 0)
3284 assert_se(sigaddset(ss, sig) == 0);
3288 char* gethostname_malloc(void) {
3291 assert_se(uname(&u) >= 0);
3294 return strdup(u.nodename);
3296 return strdup(u.sysname);
3299 char* getlogname_malloc(void) {
3303 struct passwd pwbuf, *pw = NULL;
3306 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3311 /* Shortcut things to avoid NSS lookups */
3313 return strdup("root");
3315 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3318 if (!(buf = malloc(bufsize)))
3321 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3322 name = strdup(pw->pw_name);
3329 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3335 int getttyname_malloc(int fd, char **r) {
3336 char path[PATH_MAX], *c;
3341 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3346 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3353 int getttyname_harder(int fd, char **r) {
3357 if ((k = getttyname_malloc(fd, &s)) < 0)
3360 if (streq(s, "tty")) {
3362 return get_ctty(0, NULL, r);
3369 int get_ctty_devnr(pid_t pid, dev_t *d) {
3371 char line[LINE_MAX], *p, *fn;
3372 unsigned long ttynr;
3375 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3378 f = fopen(fn, "re");
3383 if (!fgets(line, sizeof(line), f)) {
3384 k = feof(f) ? -EIO : -errno;
3391 p = strrchr(line, ')');
3401 "%*d " /* session */
3410 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3412 char fn[PATH_MAX], *s, *b, *p;
3417 k = get_ctty_devnr(pid, &devnr);
3421 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3424 if ((k = readlink_malloc(fn, &s)) < 0) {
3429 /* This is an ugly hack */
3430 if (major(devnr) == 136) {
3431 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3441 /* Probably something like the ptys which have no
3442 * symlink in /dev/char. Let's return something
3443 * vaguely useful. */
3445 if (!(b = strdup(fn + 5)))
3455 if (startswith(s, "/dev/"))
3457 else if (startswith(s, "../"))
3475 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3481 /* This returns the first error we run into, but nevertheless
3484 if (!(d = fdopendir(fd))) {
3485 close_nointr_nofail(fd);
3487 return errno == ENOENT ? 0 : -errno;
3491 struct dirent buf, *de;
3492 bool is_dir, keep_around = false;
3495 if ((r = readdir_r(d, &buf, &de)) != 0) {
3504 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3507 if (de->d_type == DT_UNKNOWN) {
3510 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3511 if (ret == 0 && errno != ENOENT)
3518 (st.st_uid == 0 || st.st_uid == getuid()) &&
3519 (st.st_mode & S_ISVTX);
3521 is_dir = S_ISDIR(st.st_mode);
3524 if (honour_sticky) {
3527 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3528 if (ret == 0 && errno != ENOENT)
3534 (st.st_uid == 0 || st.st_uid == getuid()) &&
3535 (st.st_mode & S_ISVTX);
3538 is_dir = de->d_type == DT_DIR;
3544 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3545 if (ret == 0 && errno != ENOENT)
3550 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3556 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3557 if (ret == 0 && errno != ENOENT)
3561 } else if (!only_dirs && !keep_around) {
3563 if (unlinkat(fd, de->d_name, 0) < 0) {
3564 if (ret == 0 && errno != ENOENT)
3575 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3581 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3583 if (errno != ENOTDIR)
3586 if (delete_root && !only_dirs)
3587 if (unlink(path) < 0)
3593 r = rm_rf_children(fd, only_dirs, honour_sticky);
3597 if (honour_sticky && file_is_priv_sticky(path) > 0)
3600 if (rmdir(path) < 0 && errno != ENOENT) {
3609 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3612 /* Under the assumption that we are running privileged we
3613 * first change the access mode and only then hand out
3614 * ownership to avoid a window where access is too open. */
3616 if (mode != (mode_t) -1)
3617 if (chmod(path, mode) < 0)
3620 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3621 if (chown(path, uid, gid) < 0)
3627 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3630 /* Under the assumption that we are running privileged we
3631 * first change the access mode and only then hand out
3632 * ownership to avoid a window where access is too open. */
3634 if (fchmod(fd, mode) < 0)
3637 if (fchown(fd, uid, gid) < 0)
3643 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3647 /* Allocates the cpuset in the right size */
3650 if (!(r = CPU_ALLOC(n)))
3653 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3654 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3664 if (errno != EINVAL)
3671 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3672 char *s = NULL, *spaces = NULL, *e;
3674 size_t emax, sl, left;
3675 struct iovec iovec[5];
3680 /* This independent of logging, as status messages are
3681 * optional and go exclusively to the console. */
3683 if (vasprintf(&s, format, ap) < 0)
3686 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3696 sl = 2 + 6 + 1; /* " [" status "]" */
3697 emax = (size_t) c > sl ? c - sl - 1 : 0;
3701 e = ellipsize(s, emax, 75);
3709 IOVEC_SET_STRING(iovec[n++], s);
3713 left = emax > sl ? emax - sl : 0;
3715 spaces = malloc(left);
3717 memset(spaces, ' ', left);
3718 iovec[n].iov_base = spaces;
3719 iovec[n].iov_len = left;
3726 IOVEC_SET_STRING(iovec[n++], " [");
3727 IOVEC_SET_STRING(iovec[n++], status);
3728 IOVEC_SET_STRING(iovec[n++], "]\n");
3730 IOVEC_SET_STRING(iovec[n++], "\n");
3732 writev(fd, iovec, n);
3739 close_nointr_nofail(fd);
3742 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3747 va_start(ap, format);
3748 status_vprintf(status, ellipse, format, ap);
3752 void status_welcome(void) {
3753 char *pretty_name = NULL, *ansi_color = NULL;
3754 const char *const_pretty = NULL, *const_color = NULL;
3757 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3758 "PRETTY_NAME", &pretty_name,
3759 "ANSI_COLOR", &ansi_color,
3763 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3766 #if defined(TARGET_FEDORA)
3768 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3771 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3775 if (!ansi_color && pretty_name) {
3777 /* This tries to mimic the color magic the old Red Hat sysinit
3780 if (startswith(pretty_name, "Red Hat"))
3781 const_color = "0;31"; /* Red for RHEL */
3782 else if (startswith(pretty_name, "Fedora"))
3783 const_color = "0;34"; /* Blue for Fedora */
3786 #elif defined(TARGET_SUSE)
3789 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3792 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3797 const_color = "0;32"; /* Green for openSUSE */
3799 #elif defined(TARGET_GENTOO)
3802 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3805 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3810 const_color = "1;34"; /* Light Blue for Gentoo */
3812 #elif defined(TARGET_ALTLINUX)
3815 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3818 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3823 const_color = "0;36"; /* Cyan for ALTLinux */
3826 #elif defined(TARGET_DEBIAN)
3831 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3834 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3836 pretty_name = strappend("Debian ", version);
3840 log_warning("Failed to allocate Debian version string.");
3845 const_color = "1;31"; /* Light Red for Debian */
3847 #elif defined(TARGET_UBUNTU)
3849 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3850 "DISTRIB_DESCRIPTION", &pretty_name,
3854 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3858 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3860 #elif defined(TARGET_MANDRIVA)
3865 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3867 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3869 p = strstr(s, " release ");
3873 p[strcspn(p, " ")] = '\0';
3875 /* This corresponds to standard rc.sysinit */
3876 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3877 const_color = "1;36";
3879 log_warning("Failed to allocate Mandriva version string.");
3881 log_warning("Failed to parse /etc/mandriva-release");
3885 #elif defined(TARGET_MEEGO)
3888 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3891 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3896 const_color = "1;35"; /* Bright Magenta for MeeGo */
3899 if (!pretty_name && !const_pretty)
3900 const_pretty = "Linux";
3902 if (!ansi_color && !const_color)
3907 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3908 const_color ? const_color : ansi_color,
3909 const_pretty ? const_pretty : pretty_name);
3915 char *replace_env(const char *format, char **env) {
3922 const char *e, *word = format;
3927 for (e = format; *e; e ++) {
3938 if (!(k = strnappend(r, word, e-word-1)))
3947 } else if (*e == '$') {
3948 if (!(k = strnappend(r, word, e-word)))
3964 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3967 if (!(k = strappend(r, t)))
3980 if (!(k = strnappend(r, word, e-word)))
3991 char **replace_env_argv(char **argv, char **env) {
3993 unsigned k = 0, l = 0;
3995 l = strv_length(argv);
3997 if (!(r = new(char*, l+1)))
4000 STRV_FOREACH(i, argv) {
4002 /* If $FOO appears as single word, replace it by the split up variable */
4003 if ((*i)[0] == '$' && (*i)[1] != '{') {
4008 if ((e = strv_env_get(env, *i+1))) {
4010 if (!(m = strv_split_quoted(e))) {
4021 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
4030 memcpy(r + k, m, q * sizeof(char*));
4038 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
4039 if (!(r[k++] = replace_env(*i, env))) {
4049 int fd_columns(int fd) {
4053 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4062 unsigned columns(void) {
4063 static __thread int parsed_columns = 0;
4066 if (_likely_(parsed_columns > 0))
4067 return parsed_columns;
4069 e = getenv("COLUMNS");
4071 parsed_columns = atoi(e);
4073 if (parsed_columns <= 0)
4074 parsed_columns = fd_columns(STDOUT_FILENO);
4076 if (parsed_columns <= 0)
4077 parsed_columns = 80;
4079 return parsed_columns;
4082 int running_in_chroot(void) {
4088 /* Only works as root */
4090 if (stat("/proc/1/root", &a) < 0)
4093 if (stat("/", &b) < 0)
4097 a.st_dev != b.st_dev ||
4098 a.st_ino != b.st_ino;
4101 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4106 assert(percent <= 100);
4107 assert(new_length >= 3);
4109 if (old_length <= 3 || old_length <= new_length)
4110 return strndup(s, old_length);
4112 r = new0(char, new_length+1);
4116 x = (new_length * percent) / 100;
4118 if (x > new_length - 3)
4126 s + old_length - (new_length - x - 3),
4127 new_length - x - 3);
4132 char *ellipsize(const char *s, size_t length, unsigned percent) {
4133 return ellipsize_mem(s, strlen(s), length, percent);
4136 int touch(const char *path) {
4141 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4144 close_nointr_nofail(fd);
4148 char *unquote(const char *s, const char* quotes) {
4156 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4157 return strndup(s+1, l-2);
4162 char *normalize_env_assignment(const char *s) {
4163 char *name, *value, *p, *r;
4168 if (!(r = strdup(s)))
4174 if (!(name = strndup(s, p - s)))
4177 if (!(p = strdup(p+1))) {
4182 value = unquote(strstrip(p), QUOTES);
4190 if (asprintf(&r, "%s=%s", name, value) < 0)
4199 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4210 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4222 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4229 if ((r = wait_for_terminate(pid, &status)) < 0) {
4230 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4234 if (status.si_code == CLD_EXITED) {
4235 if (status.si_status != 0) {
4236 log_warning("%s failed with error code %i.", name, status.si_status);
4237 return status.si_status;
4240 log_debug("%s succeeded.", name);
4243 } else if (status.si_code == CLD_KILLED ||
4244 status.si_code == CLD_DUMPED) {
4246 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4250 log_warning("%s failed due to unknown reason.", name);
4257 /* Make sure nobody waits for us on a socket anymore */
4258 close_all_fds(NULL, 0);
4266 bool null_or_empty(struct stat *st) {
4269 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4272 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4278 int null_or_empty_path(const char *fn) {
4283 if (stat(fn, &st) < 0)
4286 return null_or_empty(&st);
4289 DIR *xopendirat(int fd, const char *name, int flags) {
4293 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4296 if (!(d = fdopendir(nfd))) {
4297 close_nointr_nofail(nfd);
4304 int signal_from_string_try_harder(const char *s) {
4308 if ((signo = signal_from_string(s)) <= 0)
4309 if (startswith(s, "SIG"))
4310 return signal_from_string(s+3);
4315 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4321 if (!dual_timestamp_is_set(t))
4324 fprintf(f, "%s=%llu %llu\n",
4326 (unsigned long long) t->realtime,
4327 (unsigned long long) t->monotonic);
4330 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4331 unsigned long long a, b;
4336 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4337 log_debug("Failed to parse finish timestamp value %s", value);
4344 char *fstab_node_to_udev_node(const char *p) {
4348 /* FIXME: to follow udev's logic 100% we need to leave valid
4349 * UTF8 chars unescaped */
4351 if (startswith(p, "LABEL=")) {
4353 if (!(u = unquote(p+6, "\"\'")))
4356 t = xescape(u, "/ ");
4362 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4371 if (startswith(p, "UUID=")) {
4373 if (!(u = unquote(p+5, "\"\'")))
4376 t = xescape(u, "/ ");
4382 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4394 void filter_environ(const char *prefix) {
4401 for (i = 0, j = 0; environ[i]; i++) {
4403 if (startswith(environ[i], prefix))
4406 environ[j++] = environ[i];
4412 bool tty_is_vc(const char *tty) {
4415 if (startswith(tty, "/dev/"))
4418 return vtnr_from_tty(tty) >= 0;
4421 int vtnr_from_tty(const char *tty) {
4426 if (startswith(tty, "/dev/"))
4429 if (!startswith(tty, "tty") )
4432 if (tty[3] < '0' || tty[3] > '9')
4435 r = safe_atoi(tty+3, &i);
4439 if (i < 0 || i > 63)
4445 bool tty_is_vc_resolve(const char *tty) {
4446 char *active = NULL;
4451 if (startswith(tty, "/dev/"))
4454 /* Resolve where /dev/console is pointing to */
4455 if (streq(tty, "console"))
4456 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4457 /* If multiple log outputs are configured the
4458 * last one is what /dev/console points to */
4459 tty = strrchr(active, ' ');
4472 const char *default_term_for_tty(const char *tty) {
4475 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4478 bool dirent_is_file(const struct dirent *de) {
4481 if (ignore_file(de->d_name))
4484 if (de->d_type != DT_REG &&
4485 de->d_type != DT_LNK &&
4486 de->d_type != DT_UNKNOWN)
4492 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4495 if (!dirent_is_file(de))
4498 return endswith(de->d_name, suffix);
4501 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4504 Hashmap *pids = NULL;
4508 /* Executes all binaries in a directory in parallel and waits
4509 * until all they all finished. */
4512 if (!(_d = opendir(directory))) {
4514 if (errno == ENOENT)
4517 log_error("Failed to enumerate directory %s: %m", directory);
4524 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4525 log_error("Failed to allocate set.");
4529 while ((de = readdir(d))) {
4534 if (!dirent_is_file(de))
4537 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4538 log_error("Out of memory");
4542 if ((pid = fork()) < 0) {
4543 log_error("Failed to fork: %m");
4562 log_error("Failed to execute %s: %m", path);
4563 _exit(EXIT_FAILURE);
4566 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4568 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4569 log_error("Failed to add PID to set: %s", strerror(-k));
4574 while (!hashmap_isempty(pids)) {
4579 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4584 log_error("waitid() failed: %m");
4588 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4589 if (!is_clean_exit(si.si_code, si.si_status)) {
4590 if (si.si_code == CLD_EXITED)
4591 log_error("%s exited with exit status %i.", path, si.si_status);
4593 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4595 log_debug("%s exited successfully.", path);
4606 hashmap_free_free(pids);
4609 int kill_and_sigcont(pid_t pid, int sig) {
4612 r = kill(pid, sig) < 0 ? -errno : 0;
4620 bool nulstr_contains(const char*nulstr, const char *needle) {
4626 NULSTR_FOREACH(i, nulstr)
4627 if (streq(i, needle))
4633 bool plymouth_running(void) {
4634 return access("/run/plymouth/pid", F_OK) >= 0;
4637 void parse_syslog_priority(char **p, int *priority) {
4638 int a = 0, b = 0, c = 0;
4648 if (!strchr(*p, '>'))
4651 if ((*p)[2] == '>') {
4652 c = undecchar((*p)[1]);
4654 } else if ((*p)[3] == '>') {
4655 b = undecchar((*p)[1]);
4656 c = undecchar((*p)[2]);
4658 } else if ((*p)[4] == '>') {
4659 a = undecchar((*p)[1]);
4660 b = undecchar((*p)[2]);
4661 c = undecchar((*p)[3]);
4666 if (a < 0 || b < 0 || c < 0)
4669 *priority = a*100+b*10+c;
4673 void skip_syslog_pid(char **buf) {
4685 p += strspn(p, "0123456789");
4695 void skip_syslog_date(char **buf) {
4703 LETTER, LETTER, LETTER,
4705 SPACE_OR_NUMBER, NUMBER,
4707 SPACE_OR_NUMBER, NUMBER,
4709 SPACE_OR_NUMBER, NUMBER,
4711 SPACE_OR_NUMBER, NUMBER,
4723 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4728 switch (sequence[i]) {
4735 case SPACE_OR_NUMBER:
4742 if (*p < '0' || *p > '9')
4748 if (!(*p >= 'A' && *p <= 'Z') &&
4749 !(*p >= 'a' && *p <= 'z'))
4765 int have_effective_cap(int value) {
4767 cap_flag_value_t fv;
4770 if (!(cap = cap_get_proc()))
4773 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4782 char* strshorten(char *s, size_t l) {
4791 static bool hostname_valid_char(char c) {
4793 (c >= 'a' && c <= 'z') ||
4794 (c >= 'A' && c <= 'Z') ||
4795 (c >= '0' && c <= '9') ||
4801 bool hostname_is_valid(const char *s) {
4807 for (p = s; *p; p++)
4808 if (!hostname_valid_char(*p))
4811 if (p-s > HOST_NAME_MAX)
4817 char* hostname_cleanup(char *s) {
4820 for (p = s, d = s; *p; p++)
4821 if ((*p >= 'a' && *p <= 'z') ||
4822 (*p >= 'A' && *p <= 'Z') ||
4823 (*p >= '0' && *p <= '9') ||
4831 strshorten(s, HOST_NAME_MAX);
4835 int pipe_eof(int fd) {
4836 struct pollfd pollfd;
4841 pollfd.events = POLLIN|POLLHUP;
4843 r = poll(&pollfd, 1, 0);
4850 return pollfd.revents & POLLHUP;
4853 int fd_wait_for_event(int fd, int event) {
4854 struct pollfd pollfd;
4859 pollfd.events = event;
4861 r = poll(&pollfd, 1, -1);
4868 return pollfd.revents;
4871 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4882 t = new(char, strlen(path) + 1 + 6 + 1);
4886 fn = file_name_from_path(path);
4890 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4892 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4898 f = fdopen(fd, "we");
4911 int terminal_vhangup_fd(int fd) {
4914 if (ioctl(fd, TIOCVHANGUP) < 0)
4920 int terminal_vhangup(const char *name) {
4923 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4927 r = terminal_vhangup_fd(fd);
4928 close_nointr_nofail(fd);
4933 int vt_disallocate(const char *name) {
4937 /* Deallocate the VT if possible. If not possible
4938 * (i.e. because it is the active one), at least clear it
4939 * entirely (including the scrollback buffer) */
4941 if (!startswith(name, "/dev/"))
4944 if (!tty_is_vc(name)) {
4945 /* So this is not a VT. I guess we cannot deallocate
4946 * it then. But let's at least clear the screen */
4948 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4953 "\033[r" /* clear scrolling region */
4954 "\033[H" /* move home */
4955 "\033[2J", /* clear screen */
4957 close_nointr_nofail(fd);
4962 if (!startswith(name, "/dev/tty"))
4965 r = safe_atou(name+8, &u);
4972 /* Try to deallocate */
4973 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4977 r = ioctl(fd, VT_DISALLOCATE, u);
4978 close_nointr_nofail(fd);
4986 /* Couldn't deallocate, so let's clear it fully with
4988 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4993 "\033[r" /* clear scrolling region */
4994 "\033[H" /* move home */
4995 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4997 close_nointr_nofail(fd);
5002 static int files_add(Hashmap *h, const char *path, const char *suffix) {
5004 struct dirent buffer, *de;
5007 dir = opendir(path);
5009 if (errno == ENOENT)
5018 k = readdir_r(dir, &buffer, &de);
5027 if (!dirent_is_file_with_suffix(de, suffix))
5030 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
5035 f = canonicalize_file_name(p);
5037 log_error("Failed to canonicalize file name '%s': %m", p);
5043 log_debug("found: %s\n", f);
5044 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5053 static int base_cmp(const void *a, const void *b) {
5054 const char *s1, *s2;
5056 s1 = *(char * const *)a;
5057 s2 = *(char * const *)b;
5058 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5061 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5064 char **files = NULL;
5070 dirs = strv_new_ap(dir, ap);
5076 if (!strv_path_canonicalize(dirs)) {
5080 if (!strv_uniq(dirs)) {
5085 fh = hashmap_new(string_hash_func, string_compare_func);
5091 STRV_FOREACH(p, dirs) {
5092 if (files_add(fh, *p, suffix) < 0) {
5093 log_error("Failed to search for files.");
5099 files = hashmap_get_strv(fh);
5100 if (files == NULL) {
5101 log_error("Failed to compose list of files.");
5106 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5115 int hwclock_is_localtime(void) {
5120 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5126 f = fopen("/etc/adjtime", "re");
5128 char line[LINE_MAX];
5131 b = fgets(line, sizeof(line), f) &&
5132 fgets(line, sizeof(line), f) &&
5133 fgets(line, sizeof(line), f);
5142 local = streq(line, "LOCAL");
5144 } else if (errno != -ENOENT)
5150 int hwclock_apply_localtime_delta(int *min) {
5151 const struct timeval *tv_null = NULL;
5157 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5158 assert_se(tm = localtime(&ts.tv_sec));
5159 minuteswest = tm->tm_gmtoff / 60;
5161 tz.tz_minuteswest = -minuteswest;
5162 tz.tz_dsttime = 0; /* DST_NONE*/
5165 * If the hardware clock does not run in UTC, but in local time:
5166 * The very first time we set the kernel's timezone, it will warp
5167 * the clock so that it runs in UTC instead of local time.
5169 if (settimeofday(tv_null, &tz) < 0)
5176 int hwclock_reset_localtime_delta(void) {
5177 const struct timeval *tv_null = NULL;
5180 tz.tz_minuteswest = 0;
5181 tz.tz_dsttime = 0; /* DST_NONE*/
5183 if (settimeofday(tv_null, &tz) < 0)
5189 int rtc_open(int flags) {
5193 /* We open the first RTC which has hctosys=1 set. If we don't
5194 * find any we just take the first one */
5196 d = opendir("/sys/class/rtc");
5202 struct dirent buf, *de;
5205 r = readdir_r(d, &buf, &de);
5212 if (ignore_file(de->d_name))
5215 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5221 r = read_one_line_file(p, &v);
5227 r = parse_boolean(v);
5233 p = strappend("/dev/", de->d_name);
5234 fd = open(p, flags);
5247 fd = open("/dev/rtc0", flags);
5254 int hwclock_get_time(struct tm *tm) {
5260 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5264 /* This leaves the timezone fields of struct tm
5266 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5269 /* We don't now daylight saving, so we reset this in order not
5270 * to confused mktime(). */
5273 close_nointr_nofail(fd);
5278 int hwclock_set_time(const struct tm *tm) {
5284 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5288 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5291 close_nointr_nofail(fd);
5296 int copy_file(const char *from, const char *to) {
5302 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5306 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5308 close_nointr_nofail(fdf);
5316 n = read(fdf, buf, sizeof(buf));
5320 close_nointr_nofail(fdf);
5331 k = loop_write(fdt, buf, n, false);
5333 r = k < 0 ? k : (errno ? -errno : -EIO);
5335 close_nointr_nofail(fdf);
5343 close_nointr_nofail(fdf);
5344 r = close_nointr(fdt);
5354 int symlink_or_copy(const char *from, const char *to) {
5355 char *pf = NULL, *pt = NULL;
5362 if (parent_of_path(from, &pf) < 0 ||
5363 parent_of_path(to, &pt) < 0) {
5368 if (stat(pf, &a) < 0 ||
5374 if (a.st_dev != b.st_dev) {
5378 return copy_file(from, to);
5381 if (symlink(from, to) < 0) {
5395 int symlink_or_copy_atomic(const char *from, const char *to) {
5399 unsigned long long ull;
5406 t = new(char, strlen(to) + 1 + 16 + 1);
5410 fn = file_name_from_path(to);
5414 x = stpcpy(t+k+1, fn);
5417 for (i = 0; i < 16; i++) {
5418 *(x++) = hexchar(ull & 0xF);
5424 r = symlink_or_copy(from, t);
5431 if (rename(t, to) < 0) {
5442 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5449 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5453 r = read_one_line_file("/proc/self/sessionid", &s);
5457 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5460 r = read_one_line_file(p, &s);
5467 r = safe_atou32(s, &u);
5473 if (u == (uint32_t) -1 || u <= 0)
5480 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5487 /* Only use audit login uid if we are executed with sufficient
5488 * capabilities so that pam_loginuid could do its job. If we
5489 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5490 * are being run in a container and /proc/self/loginuid is
5491 * useless since it probably contains a uid of the host
5494 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5498 r = read_one_line_file("/proc/self/loginuid", &s);
5502 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5505 r = read_one_line_file(p, &s);
5512 r = parse_uid(s, &u);
5518 if (u == (uid_t) -1)
5525 bool display_is_local(const char *display) {
5529 display[0] == ':' &&
5530 display[1] >= '0' &&
5534 int socket_from_display(const char *display, char **path) {
5541 if (!display_is_local(display))
5544 k = strspn(display+1, "0123456789");
5546 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5550 c = stpcpy(f, "/tmp/.X11-unix/X");
5551 memcpy(c, display+1, k);
5559 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5566 /* We enforce some special rules for uid=0: in order to avoid
5567 * NSS lookups for root we hardcode its data. */
5569 if (streq(*username, "root") || streq(*username, "0")) {
5583 if (parse_uid(*username, &u) >= 0) {
5587 /* If there are multiple users with the same id, make
5588 * sure to leave $USER to the configured value instead
5589 * of the first occurrence in the database. However if
5590 * the uid was configured by a numeric uid, then let's
5591 * pick the real username from /etc/passwd. */
5593 *username = p->pw_name;
5596 p = getpwnam(*username);
5600 return errno != 0 ? -errno : -ESRCH;
5614 int get_group_creds(const char **groupname, gid_t *gid) {
5620 /* We enforce some special rules for gid=0: in order to avoid
5621 * NSS lookups for root we hardcode its data. */
5623 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5624 *groupname = "root";
5632 if (parse_gid(*groupname, &id) >= 0) {
5637 *groupname = g->gr_name;
5640 g = getgrnam(*groupname);
5644 return errno != 0 ? -errno : -ESRCH;
5652 int glob_exists(const char *path) {
5660 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5662 if (k == GLOB_NOMATCH)
5664 else if (k == GLOB_NOSPACE)
5667 r = !strv_isempty(g.gl_pathv);
5669 r = errno ? -errno : -EIO;
5676 int dirent_ensure_type(DIR *d, struct dirent *de) {
5682 if (de->d_type != DT_UNKNOWN)
5685 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5689 S_ISREG(st.st_mode) ? DT_REG :
5690 S_ISDIR(st.st_mode) ? DT_DIR :
5691 S_ISLNK(st.st_mode) ? DT_LNK :
5692 S_ISFIFO(st.st_mode) ? DT_FIFO :
5693 S_ISSOCK(st.st_mode) ? DT_SOCK :
5694 S_ISCHR(st.st_mode) ? DT_CHR :
5695 S_ISBLK(st.st_mode) ? DT_BLK :
5701 int in_search_path(const char *path, char **search) {
5705 r = parent_of_path(path, &parent);
5711 STRV_FOREACH(i, search) {
5712 if (path_equal(parent, *i)) {
5723 int get_files_in_directory(const char *path, char ***list) {
5731 /* Returns all files in a directory in *list, and the number
5732 * of files as return value. If list is NULL returns only the
5740 struct dirent buffer, *de;
5743 k = readdir_r(d, &buffer, &de);
5752 dirent_ensure_type(d, de);
5754 if (!dirent_is_file(de))
5758 if ((unsigned) r >= n) {
5762 t = realloc(l, sizeof(char*) * n);
5771 assert((unsigned) r < n);
5773 l[r] = strdup(de->d_name);
5797 char *join(const char *x, ...) {
5810 t = va_arg(ap, const char *);
5833 t = va_arg(ap, const char *);
5847 bool is_main_thread(void) {
5848 static __thread int cached = 0;
5850 if (_unlikely_(cached == 0))
5851 cached = getpid() == gettid() ? 1 : -1;
5856 int block_get_whole_disk(dev_t d, dev_t *ret) {
5863 /* If it has a queue this is good enough for us */
5864 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5867 r = access(p, F_OK);
5875 /* If it is a partition find the originating device */
5876 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5879 r = access(p, F_OK);
5885 /* Get parent dev_t */
5886 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5889 r = read_one_line_file(p, &s);
5895 r = sscanf(s, "%u:%u", &m, &n);
5901 /* Only return this if it is really good enough for us. */
5902 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5905 r = access(p, F_OK);
5909 *ret = makedev(m, n);
5916 int file_is_priv_sticky(const char *p) {
5921 if (lstat(p, &st) < 0)
5925 (st.st_uid == 0 || st.st_uid == getuid()) &&
5926 (st.st_mode & S_ISVTX);
5929 static const char *const ioprio_class_table[] = {
5930 [IOPRIO_CLASS_NONE] = "none",
5931 [IOPRIO_CLASS_RT] = "realtime",
5932 [IOPRIO_CLASS_BE] = "best-effort",
5933 [IOPRIO_CLASS_IDLE] = "idle"
5936 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5938 static const char *const sigchld_code_table[] = {
5939 [CLD_EXITED] = "exited",
5940 [CLD_KILLED] = "killed",
5941 [CLD_DUMPED] = "dumped",
5942 [CLD_TRAPPED] = "trapped",
5943 [CLD_STOPPED] = "stopped",
5944 [CLD_CONTINUED] = "continued",
5947 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5949 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5950 [LOG_FAC(LOG_KERN)] = "kern",
5951 [LOG_FAC(LOG_USER)] = "user",
5952 [LOG_FAC(LOG_MAIL)] = "mail",
5953 [LOG_FAC(LOG_DAEMON)] = "daemon",
5954 [LOG_FAC(LOG_AUTH)] = "auth",
5955 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5956 [LOG_FAC(LOG_LPR)] = "lpr",
5957 [LOG_FAC(LOG_NEWS)] = "news",
5958 [LOG_FAC(LOG_UUCP)] = "uucp",
5959 [LOG_FAC(LOG_CRON)] = "cron",
5960 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5961 [LOG_FAC(LOG_FTP)] = "ftp",
5962 [LOG_FAC(LOG_LOCAL0)] = "local0",
5963 [LOG_FAC(LOG_LOCAL1)] = "local1",
5964 [LOG_FAC(LOG_LOCAL2)] = "local2",
5965 [LOG_FAC(LOG_LOCAL3)] = "local3",
5966 [LOG_FAC(LOG_LOCAL4)] = "local4",
5967 [LOG_FAC(LOG_LOCAL5)] = "local5",
5968 [LOG_FAC(LOG_LOCAL6)] = "local6",
5969 [LOG_FAC(LOG_LOCAL7)] = "local7"
5972 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5974 static const char *const log_level_table[] = {
5975 [LOG_EMERG] = "emerg",
5976 [LOG_ALERT] = "alert",
5977 [LOG_CRIT] = "crit",
5979 [LOG_WARNING] = "warning",
5980 [LOG_NOTICE] = "notice",
5981 [LOG_INFO] = "info",
5982 [LOG_DEBUG] = "debug"
5985 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5987 static const char* const sched_policy_table[] = {
5988 [SCHED_OTHER] = "other",
5989 [SCHED_BATCH] = "batch",
5990 [SCHED_IDLE] = "idle",
5991 [SCHED_FIFO] = "fifo",
5995 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5997 static const char* const rlimit_table[] = {
5998 [RLIMIT_CPU] = "LimitCPU",
5999 [RLIMIT_FSIZE] = "LimitFSIZE",
6000 [RLIMIT_DATA] = "LimitDATA",
6001 [RLIMIT_STACK] = "LimitSTACK",
6002 [RLIMIT_CORE] = "LimitCORE",
6003 [RLIMIT_RSS] = "LimitRSS",
6004 [RLIMIT_NOFILE] = "LimitNOFILE",
6005 [RLIMIT_AS] = "LimitAS",
6006 [RLIMIT_NPROC] = "LimitNPROC",
6007 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
6008 [RLIMIT_LOCKS] = "LimitLOCKS",
6009 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
6010 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
6011 [RLIMIT_NICE] = "LimitNICE",
6012 [RLIMIT_RTPRIO] = "LimitRTPRIO",
6013 [RLIMIT_RTTIME] = "LimitRTTIME"
6016 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
6018 static const char* const ip_tos_table[] = {
6019 [IPTOS_LOWDELAY] = "low-delay",
6020 [IPTOS_THROUGHPUT] = "throughput",
6021 [IPTOS_RELIABILITY] = "reliability",
6022 [IPTOS_LOWCOST] = "low-cost",
6025 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
6027 static const char *const __signal_table[] = {
6044 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
6055 [SIGVTALRM] = "VTALRM",
6057 [SIGWINCH] = "WINCH",
6063 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6065 const char *signal_to_string(int signo) {
6066 static __thread char buf[12];
6069 name = __signal_to_string(signo);
6073 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6074 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6076 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6081 int signal_from_string(const char *s) {
6086 signo =__signal_from_string(s);
6090 if (startswith(s, "RTMIN+")) {
6094 if (safe_atou(s, &u) >= 0) {
6095 signo = (int) u + offset;
6096 if (signo > 0 && signo < _NSIG)
6102 bool kexec_loaded(void) {
6103 bool loaded = false;
6106 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6114 int strdup_or_null(const char *a, char **b) {
6132 int prot_from_flags(int flags) {
6134 switch (flags & O_ACCMODE) {
6143 return PROT_READ|PROT_WRITE;
6150 unsigned long cap_last_cap(void) {
6151 static __thread unsigned long saved;
6152 static __thread bool valid = false;
6158 p = (unsigned long) CAP_LAST_CAP;
6160 if (prctl(PR_CAPBSET_READ, p) < 0) {
6162 /* Hmm, look downwards, until we find one that
6164 for (p--; p > 0; p --)
6165 if (prctl(PR_CAPBSET_READ, p) >= 0)
6170 /* Hmm, look upwards, until we find one that doesn't
6173 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6183 char *format_bytes(char *buf, size_t l, off_t t) {
6186 static const struct {
6190 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6191 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6192 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6193 { "G", 1024ULL*1024ULL*1024ULL },
6194 { "M", 1024ULL*1024ULL },
6198 for (i = 0; i < ELEMENTSOF(table); i++) {
6200 if (t >= table[i].factor) {
6203 (unsigned long long) (t / table[i].factor),
6204 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6211 snprintf(buf, l, "%lluB", (unsigned long long) t);
6219 void* memdup(const void *p, size_t l) {