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, bool switch_to_text) {
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 */
2564 ioctl(fd, KDSETMODE, KD_TEXT);
2566 /* Enable console unicode mode */
2567 ioctl(fd, KDSKBMODE, K_UNICODE);
2569 if (tcgetattr(fd, &termios) < 0) {
2574 /* We only reset the stuff that matters to the software. How
2575 * hardware is set up we don't touch assuming that somebody
2576 * else will do that for us */
2578 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2579 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2580 termios.c_oflag |= ONLCR;
2581 termios.c_cflag |= CREAD;
2582 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2584 termios.c_cc[VINTR] = 03; /* ^C */
2585 termios.c_cc[VQUIT] = 034; /* ^\ */
2586 termios.c_cc[VERASE] = 0177;
2587 termios.c_cc[VKILL] = 025; /* ^X */
2588 termios.c_cc[VEOF] = 04; /* ^D */
2589 termios.c_cc[VSTART] = 021; /* ^Q */
2590 termios.c_cc[VSTOP] = 023; /* ^S */
2591 termios.c_cc[VSUSP] = 032; /* ^Z */
2592 termios.c_cc[VLNEXT] = 026; /* ^V */
2593 termios.c_cc[VWERASE] = 027; /* ^W */
2594 termios.c_cc[VREPRINT] = 022; /* ^R */
2595 termios.c_cc[VEOL] = 0;
2596 termios.c_cc[VEOL2] = 0;
2598 termios.c_cc[VTIME] = 0;
2599 termios.c_cc[VMIN] = 1;
2601 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2605 /* Just in case, flush all crap out */
2606 tcflush(fd, TCIOFLUSH);
2611 int reset_terminal(const char *name) {
2614 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2618 r = reset_terminal_fd(fd, true);
2619 close_nointr_nofail(fd);
2624 int open_terminal(const char *name, int mode) {
2629 * If a TTY is in the process of being closed opening it might
2630 * cause EIO. This is horribly awful, but unlikely to be
2631 * changed in the kernel. Hence we work around this problem by
2632 * retrying a couple of times.
2634 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2638 if ((fd = open(name, mode)) >= 0)
2647 usleep(50 * USEC_PER_MSEC);
2654 if ((r = isatty(fd)) < 0) {
2655 close_nointr_nofail(fd);
2660 close_nointr_nofail(fd);
2667 int flush_fd(int fd) {
2668 struct pollfd pollfd;
2672 pollfd.events = POLLIN;
2679 if ((r = poll(&pollfd, 1, 0)) < 0) {
2690 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2695 if (errno == EAGAIN)
2706 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2707 int fd = -1, notify = -1, r, wd = -1;
2711 /* We use inotify to be notified when the tty is closed. We
2712 * create the watch before checking if we can actually acquire
2713 * it, so that we don't lose any event.
2715 * Note: strictly speaking this actually watches for the
2716 * device being closed, it does *not* really watch whether a
2717 * tty loses its controlling process. However, unless some
2718 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2719 * its tty otherwise this will not become a problem. As long
2720 * as the administrator makes sure not configure any service
2721 * on the same tty as an untrusted user this should not be a
2722 * problem. (Which he probably should not do anyway.) */
2724 if (!fail && !force) {
2725 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2730 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2738 if ((r = flush_fd(notify)) < 0)
2741 /* We pass here O_NOCTTY only so that we can check the return
2742 * value TIOCSCTTY and have a reliable way to figure out if we
2743 * successfully became the controlling process of the tty */
2744 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2747 /* First, try to get the tty */
2748 r = ioctl(fd, TIOCSCTTY, force);
2750 /* Sometimes it makes sense to ignore TIOCSCTTY
2751 * returning EPERM, i.e. when very likely we already
2752 * are have this controlling terminal. */
2753 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2756 if (r < 0 && (force || fail || errno != EPERM)) {
2766 assert(notify >= 0);
2769 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2771 struct inotify_event *e;
2773 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2782 e = (struct inotify_event*) inotify_buffer;
2787 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2792 step = sizeof(struct inotify_event) + e->len;
2793 assert(step <= (size_t) l);
2795 e = (struct inotify_event*) ((uint8_t*) e + step);
2802 /* We close the tty fd here since if the old session
2803 * ended our handle will be dead. It's important that
2804 * we do this after sleeping, so that we don't enter
2805 * an endless loop. */
2806 close_nointr_nofail(fd);
2810 close_nointr_nofail(notify);
2812 r = reset_terminal_fd(fd, true);
2814 log_warning("Failed to reset terminal: %s", strerror(-r));
2820 close_nointr_nofail(fd);
2823 close_nointr_nofail(notify);
2828 int release_terminal(void) {
2830 struct sigaction sa_old, sa_new;
2832 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2835 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2836 * by our own TIOCNOTTY */
2839 sa_new.sa_handler = SIG_IGN;
2840 sa_new.sa_flags = SA_RESTART;
2841 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2843 if (ioctl(fd, TIOCNOTTY) < 0)
2846 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2848 close_nointr_nofail(fd);
2852 int sigaction_many(const struct sigaction *sa, ...) {
2857 while ((sig = va_arg(ap, int)) > 0)
2858 if (sigaction(sig, sa, NULL) < 0)
2865 int ignore_signals(int sig, ...) {
2866 struct sigaction sa;
2871 sa.sa_handler = SIG_IGN;
2872 sa.sa_flags = SA_RESTART;
2874 if (sigaction(sig, &sa, NULL) < 0)
2878 while ((sig = va_arg(ap, int)) > 0)
2879 if (sigaction(sig, &sa, NULL) < 0)
2886 int default_signals(int sig, ...) {
2887 struct sigaction sa;
2892 sa.sa_handler = SIG_DFL;
2893 sa.sa_flags = SA_RESTART;
2895 if (sigaction(sig, &sa, NULL) < 0)
2899 while ((sig = va_arg(ap, int)) > 0)
2900 if (sigaction(sig, &sa, NULL) < 0)
2907 int close_pipe(int p[]) {
2913 a = close_nointr(p[0]);
2918 b = close_nointr(p[1]);
2922 return a < 0 ? a : b;
2925 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2934 while (nbytes > 0) {
2937 if ((k = read(fd, p, nbytes)) <= 0) {
2939 if (k < 0 && errno == EINTR)
2942 if (k < 0 && errno == EAGAIN && do_poll) {
2943 struct pollfd pollfd;
2947 pollfd.events = POLLIN;
2949 if (poll(&pollfd, 1, -1) < 0) {
2953 return n > 0 ? n : -errno;
2956 if (pollfd.revents != POLLIN)
2957 return n > 0 ? n : -EIO;
2962 return n > 0 ? n : (k < 0 ? -errno : 0);
2973 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2982 while (nbytes > 0) {
2985 k = write(fd, p, nbytes);
2988 if (k < 0 && errno == EINTR)
2991 if (k < 0 && errno == EAGAIN && do_poll) {
2992 struct pollfd pollfd;
2996 pollfd.events = POLLOUT;
2998 if (poll(&pollfd, 1, -1) < 0) {
3002 return n > 0 ? n : -errno;
3005 if (pollfd.revents != POLLOUT)
3006 return n > 0 ? n : -EIO;
3011 return n > 0 ? n : (k < 0 ? -errno : 0);
3022 int path_is_mount_point(const char *t, bool allow_symlink) {
3033 if (errno == ENOENT)
3039 r = parent_of_path(t, &parent);
3043 r = lstat(parent, &b);
3049 return a.st_dev != b.st_dev;
3052 int parse_usec(const char *t, usec_t *usec) {
3053 static const struct {
3057 { "sec", USEC_PER_SEC },
3058 { "s", USEC_PER_SEC },
3059 { "min", USEC_PER_MINUTE },
3060 { "hr", USEC_PER_HOUR },
3061 { "h", USEC_PER_HOUR },
3062 { "d", USEC_PER_DAY },
3063 { "w", USEC_PER_WEEK },
3064 { "msec", USEC_PER_MSEC },
3065 { "ms", USEC_PER_MSEC },
3066 { "m", USEC_PER_MINUTE },
3069 { "", USEC_PER_SEC },
3085 l = strtoll(p, &e, 10);
3096 e += strspn(e, WHITESPACE);
3098 for (i = 0; i < ELEMENTSOF(table); i++)
3099 if (startswith(e, table[i].suffix)) {
3100 r += (usec_t) l * table[i].usec;
3101 p = e + strlen(table[i].suffix);
3105 if (i >= ELEMENTSOF(table))
3115 int parse_bytes(const char *t, off_t *bytes) {
3116 static const struct {
3122 { "M", 1024ULL*1024ULL },
3123 { "G", 1024ULL*1024ULL*1024ULL },
3124 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3125 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3126 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3143 l = strtoll(p, &e, 10);
3154 e += strspn(e, WHITESPACE);
3156 for (i = 0; i < ELEMENTSOF(table); i++)
3157 if (startswith(e, table[i].suffix)) {
3158 r += (off_t) l * table[i].factor;
3159 p = e + strlen(table[i].suffix);
3163 if (i >= ELEMENTSOF(table))
3173 int make_stdio(int fd) {
3178 r = dup2(fd, STDIN_FILENO);
3179 s = dup2(fd, STDOUT_FILENO);
3180 t = dup2(fd, STDERR_FILENO);
3183 close_nointr_nofail(fd);
3185 if (r < 0 || s < 0 || t < 0)
3188 fd_cloexec(STDIN_FILENO, false);
3189 fd_cloexec(STDOUT_FILENO, false);
3190 fd_cloexec(STDERR_FILENO, false);
3195 int make_null_stdio(void) {
3198 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3201 return make_stdio(null_fd);
3204 bool is_device_path(const char *path) {
3206 /* Returns true on paths that refer to a device, either in
3207 * sysfs or in /dev */
3210 path_startswith(path, "/dev/") ||
3211 path_startswith(path, "/sys/");
3214 int dir_is_empty(const char *path) {
3217 struct dirent buf, *de;
3219 if (!(d = opendir(path)))
3223 if ((r = readdir_r(d, &buf, &de)) > 0) {
3233 if (!ignore_file(de->d_name)) {
3243 unsigned long long random_ull(void) {
3248 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3251 r = loop_read(fd, &ull, sizeof(ull), true);
3252 close_nointr_nofail(fd);
3254 if (r != sizeof(ull))
3260 return random() * RAND_MAX + random();
3263 void rename_process(const char name[8]) {
3266 /* This is a like a poor man's setproctitle(). It changes the
3267 * comm field, argv[0], and also the glibc's internally used
3268 * name of the process. For the first one a limit of 16 chars
3269 * applies, to the second one usually one of 10 (i.e. length
3270 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3271 * "systemd"). If you pass a longer string it will be
3274 prctl(PR_SET_NAME, name);
3276 if (program_invocation_name)
3277 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3279 if (saved_argc > 0) {
3283 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3285 for (i = 1; i < saved_argc; i++) {
3289 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3294 void sigset_add_many(sigset_t *ss, ...) {
3301 while ((sig = va_arg(ap, int)) > 0)
3302 assert_se(sigaddset(ss, sig) == 0);
3306 char* gethostname_malloc(void) {
3309 assert_se(uname(&u) >= 0);
3312 return strdup(u.nodename);
3314 return strdup(u.sysname);
3317 char* getlogname_malloc(void) {
3321 struct passwd pwbuf, *pw = NULL;
3324 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3329 /* Shortcut things to avoid NSS lookups */
3331 return strdup("root");
3333 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3336 if (!(buf = malloc(bufsize)))
3339 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3340 name = strdup(pw->pw_name);
3347 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3353 int getttyname_malloc(int fd, char **r) {
3354 char path[PATH_MAX], *c;
3359 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3364 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3371 int getttyname_harder(int fd, char **r) {
3375 if ((k = getttyname_malloc(fd, &s)) < 0)
3378 if (streq(s, "tty")) {
3380 return get_ctty(0, NULL, r);
3387 int get_ctty_devnr(pid_t pid, dev_t *d) {
3389 char line[LINE_MAX], *p, *fn;
3390 unsigned long ttynr;
3393 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3396 f = fopen(fn, "re");
3401 if (!fgets(line, sizeof(line), f)) {
3402 k = feof(f) ? -EIO : -errno;
3409 p = strrchr(line, ')');
3419 "%*d " /* session */
3428 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3430 char fn[PATH_MAX], *s, *b, *p;
3435 k = get_ctty_devnr(pid, &devnr);
3439 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3442 if ((k = readlink_malloc(fn, &s)) < 0) {
3447 /* This is an ugly hack */
3448 if (major(devnr) == 136) {
3449 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3459 /* Probably something like the ptys which have no
3460 * symlink in /dev/char. Let's return something
3461 * vaguely useful. */
3463 if (!(b = strdup(fn + 5)))
3473 if (startswith(s, "/dev/"))
3475 else if (startswith(s, "../"))
3493 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3499 /* This returns the first error we run into, but nevertheless
3502 if (!(d = fdopendir(fd))) {
3503 close_nointr_nofail(fd);
3505 return errno == ENOENT ? 0 : -errno;
3509 struct dirent buf, *de;
3510 bool is_dir, keep_around = false;
3513 if ((r = readdir_r(d, &buf, &de)) != 0) {
3522 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3525 if (de->d_type == DT_UNKNOWN) {
3528 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3529 if (ret == 0 && errno != ENOENT)
3536 (st.st_uid == 0 || st.st_uid == getuid()) &&
3537 (st.st_mode & S_ISVTX);
3539 is_dir = S_ISDIR(st.st_mode);
3542 if (honour_sticky) {
3545 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3546 if (ret == 0 && errno != ENOENT)
3552 (st.st_uid == 0 || st.st_uid == getuid()) &&
3553 (st.st_mode & S_ISVTX);
3556 is_dir = de->d_type == DT_DIR;
3562 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3563 if (ret == 0 && errno != ENOENT)
3568 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3574 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3575 if (ret == 0 && errno != ENOENT)
3579 } else if (!only_dirs && !keep_around) {
3581 if (unlinkat(fd, de->d_name, 0) < 0) {
3582 if (ret == 0 && errno != ENOENT)
3593 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3599 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3601 if (errno != ENOTDIR)
3604 if (delete_root && !only_dirs)
3605 if (unlink(path) < 0)
3611 r = rm_rf_children(fd, only_dirs, honour_sticky);
3615 if (honour_sticky && file_is_priv_sticky(path) > 0)
3618 if (rmdir(path) < 0 && errno != ENOENT) {
3627 int chmod_and_chown(const char *path, 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 (mode != (mode_t) -1)
3635 if (chmod(path, mode) < 0)
3638 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3639 if (chown(path, uid, gid) < 0)
3645 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3648 /* Under the assumption that we are running privileged we
3649 * first change the access mode and only then hand out
3650 * ownership to avoid a window where access is too open. */
3652 if (fchmod(fd, mode) < 0)
3655 if (fchown(fd, uid, gid) < 0)
3661 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3665 /* Allocates the cpuset in the right size */
3668 if (!(r = CPU_ALLOC(n)))
3671 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3672 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3682 if (errno != EINVAL)
3689 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3690 char *s = NULL, *spaces = NULL, *e;
3692 size_t emax, sl, left;
3693 struct iovec iovec[5];
3698 /* This independent of logging, as status messages are
3699 * optional and go exclusively to the console. */
3701 if (vasprintf(&s, format, ap) < 0)
3704 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3714 sl = 2 + 6 + 1; /* " [" status "]" */
3715 emax = (size_t) c > sl ? c - sl - 1 : 0;
3719 e = ellipsize(s, emax, 75);
3727 IOVEC_SET_STRING(iovec[n++], s);
3731 left = emax > sl ? emax - sl : 0;
3733 spaces = malloc(left);
3735 memset(spaces, ' ', left);
3736 iovec[n].iov_base = spaces;
3737 iovec[n].iov_len = left;
3744 IOVEC_SET_STRING(iovec[n++], " [");
3745 IOVEC_SET_STRING(iovec[n++], status);
3746 IOVEC_SET_STRING(iovec[n++], "]\n");
3748 IOVEC_SET_STRING(iovec[n++], "\n");
3750 writev(fd, iovec, n);
3757 close_nointr_nofail(fd);
3760 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3765 va_start(ap, format);
3766 status_vprintf(status, ellipse, format, ap);
3770 void status_welcome(void) {
3771 char *pretty_name = NULL, *ansi_color = NULL;
3772 const char *const_pretty = NULL, *const_color = NULL;
3775 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3776 "PRETTY_NAME", &pretty_name,
3777 "ANSI_COLOR", &ansi_color,
3781 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3784 #if defined(TARGET_FEDORA)
3786 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3789 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3793 if (!ansi_color && pretty_name) {
3795 /* This tries to mimic the color magic the old Red Hat sysinit
3798 if (startswith(pretty_name, "Red Hat"))
3799 const_color = "0;31"; /* Red for RHEL */
3800 else if (startswith(pretty_name, "Fedora"))
3801 const_color = "0;34"; /* Blue for Fedora */
3804 #elif defined(TARGET_SUSE)
3807 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3810 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3815 const_color = "0;32"; /* Green for openSUSE */
3817 #elif defined(TARGET_GENTOO)
3820 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3823 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3828 const_color = "1;34"; /* Light Blue for Gentoo */
3830 #elif defined(TARGET_ALTLINUX)
3833 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3836 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3841 const_color = "0;36"; /* Cyan for ALTLinux */
3844 #elif defined(TARGET_DEBIAN)
3849 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3852 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3854 pretty_name = strappend("Debian ", version);
3858 log_warning("Failed to allocate Debian version string.");
3863 const_color = "1;31"; /* Light Red for Debian */
3865 #elif defined(TARGET_UBUNTU)
3867 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3868 "DISTRIB_DESCRIPTION", &pretty_name,
3872 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3876 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3878 #elif defined(TARGET_MANDRIVA)
3883 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3885 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3887 p = strstr(s, " release ");
3891 p[strcspn(p, " ")] = '\0';
3893 /* This corresponds to standard rc.sysinit */
3894 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3895 const_color = "1;36";
3897 log_warning("Failed to allocate Mandriva version string.");
3899 log_warning("Failed to parse /etc/mandriva-release");
3903 #elif defined(TARGET_MEEGO)
3906 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3909 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3914 const_color = "1;35"; /* Bright Magenta for MeeGo */
3917 if (!pretty_name && !const_pretty)
3918 const_pretty = "Linux";
3920 if (!ansi_color && !const_color)
3925 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3926 const_color ? const_color : ansi_color,
3927 const_pretty ? const_pretty : pretty_name);
3933 char *replace_env(const char *format, char **env) {
3940 const char *e, *word = format;
3945 for (e = format; *e; e ++) {
3956 if (!(k = strnappend(r, word, e-word-1)))
3965 } else if (*e == '$') {
3966 if (!(k = strnappend(r, word, e-word)))
3982 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3985 if (!(k = strappend(r, t)))
3998 if (!(k = strnappend(r, word, e-word)))
4009 char **replace_env_argv(char **argv, char **env) {
4011 unsigned k = 0, l = 0;
4013 l = strv_length(argv);
4015 if (!(r = new(char*, l+1)))
4018 STRV_FOREACH(i, argv) {
4020 /* If $FOO appears as single word, replace it by the split up variable */
4021 if ((*i)[0] == '$' && (*i)[1] != '{') {
4026 if ((e = strv_env_get(env, *i+1))) {
4028 if (!(m = strv_split_quoted(e))) {
4039 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
4048 memcpy(r + k, m, q * sizeof(char*));
4056 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
4057 if (!(r[k++] = replace_env(*i, env))) {
4067 int fd_columns(int fd) {
4071 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4080 unsigned columns(void) {
4081 static __thread int parsed_columns = 0;
4084 if (_likely_(parsed_columns > 0))
4085 return parsed_columns;
4087 e = getenv("COLUMNS");
4089 parsed_columns = atoi(e);
4091 if (parsed_columns <= 0)
4092 parsed_columns = fd_columns(STDOUT_FILENO);
4094 if (parsed_columns <= 0)
4095 parsed_columns = 80;
4097 return parsed_columns;
4100 int fd_lines(int fd) {
4104 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4113 unsigned lines(void) {
4114 static __thread int parsed_lines = 0;
4117 if (_likely_(parsed_lines > 0))
4118 return parsed_lines;
4120 e = getenv("LINES");
4122 parsed_lines = atoi(e);
4124 if (parsed_lines <= 0)
4125 parsed_lines = fd_lines(STDOUT_FILENO);
4127 if (parsed_lines <= 0)
4130 return parsed_lines;
4133 int running_in_chroot(void) {
4139 /* Only works as root */
4141 if (stat("/proc/1/root", &a) < 0)
4144 if (stat("/", &b) < 0)
4148 a.st_dev != b.st_dev ||
4149 a.st_ino != b.st_ino;
4152 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4157 assert(percent <= 100);
4158 assert(new_length >= 3);
4160 if (old_length <= 3 || old_length <= new_length)
4161 return strndup(s, old_length);
4163 r = new0(char, new_length+1);
4167 x = (new_length * percent) / 100;
4169 if (x > new_length - 3)
4177 s + old_length - (new_length - x - 3),
4178 new_length - x - 3);
4183 char *ellipsize(const char *s, size_t length, unsigned percent) {
4184 return ellipsize_mem(s, strlen(s), length, percent);
4187 int touch(const char *path) {
4192 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4195 close_nointr_nofail(fd);
4199 char *unquote(const char *s, const char* quotes) {
4207 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4208 return strndup(s+1, l-2);
4213 char *normalize_env_assignment(const char *s) {
4214 char *name, *value, *p, *r;
4219 if (!(r = strdup(s)))
4225 if (!(name = strndup(s, p - s)))
4228 if (!(p = strdup(p+1))) {
4233 value = unquote(strstrip(p), QUOTES);
4241 if (asprintf(&r, "%s=%s", name, value) < 0)
4250 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4261 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4273 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4280 if ((r = wait_for_terminate(pid, &status)) < 0) {
4281 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4285 if (status.si_code == CLD_EXITED) {
4286 if (status.si_status != 0) {
4287 log_warning("%s failed with error code %i.", name, status.si_status);
4288 return status.si_status;
4291 log_debug("%s succeeded.", name);
4294 } else if (status.si_code == CLD_KILLED ||
4295 status.si_code == CLD_DUMPED) {
4297 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4301 log_warning("%s failed due to unknown reason.", name);
4308 /* Make sure nobody waits for us on a socket anymore */
4309 close_all_fds(NULL, 0);
4317 bool null_or_empty(struct stat *st) {
4320 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4323 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4329 int null_or_empty_path(const char *fn) {
4334 if (stat(fn, &st) < 0)
4337 return null_or_empty(&st);
4340 DIR *xopendirat(int fd, const char *name, int flags) {
4344 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4347 if (!(d = fdopendir(nfd))) {
4348 close_nointr_nofail(nfd);
4355 int signal_from_string_try_harder(const char *s) {
4359 if ((signo = signal_from_string(s)) <= 0)
4360 if (startswith(s, "SIG"))
4361 return signal_from_string(s+3);
4366 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4372 if (!dual_timestamp_is_set(t))
4375 fprintf(f, "%s=%llu %llu\n",
4377 (unsigned long long) t->realtime,
4378 (unsigned long long) t->monotonic);
4381 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4382 unsigned long long a, b;
4387 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4388 log_debug("Failed to parse finish timestamp value %s", value);
4395 char *fstab_node_to_udev_node(const char *p) {
4399 /* FIXME: to follow udev's logic 100% we need to leave valid
4400 * UTF8 chars unescaped */
4402 if (startswith(p, "LABEL=")) {
4404 if (!(u = unquote(p+6, "\"\'")))
4407 t = xescape(u, "/ ");
4413 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4422 if (startswith(p, "UUID=")) {
4424 if (!(u = unquote(p+5, "\"\'")))
4427 t = xescape(u, "/ ");
4433 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4445 void filter_environ(const char *prefix) {
4452 for (i = 0, j = 0; environ[i]; i++) {
4454 if (startswith(environ[i], prefix))
4457 environ[j++] = environ[i];
4463 bool tty_is_vc(const char *tty) {
4466 if (startswith(tty, "/dev/"))
4469 return vtnr_from_tty(tty) >= 0;
4472 int vtnr_from_tty(const char *tty) {
4477 if (startswith(tty, "/dev/"))
4480 if (!startswith(tty, "tty") )
4483 if (tty[3] < '0' || tty[3] > '9')
4486 r = safe_atoi(tty+3, &i);
4490 if (i < 0 || i > 63)
4496 bool tty_is_vc_resolve(const char *tty) {
4497 char *active = NULL;
4502 if (startswith(tty, "/dev/"))
4505 /* Resolve where /dev/console is pointing to */
4506 if (streq(tty, "console"))
4507 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4508 /* If multiple log outputs are configured the
4509 * last one is what /dev/console points to */
4510 tty = strrchr(active, ' ');
4523 const char *default_term_for_tty(const char *tty) {
4526 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4529 bool dirent_is_file(const struct dirent *de) {
4532 if (ignore_file(de->d_name))
4535 if (de->d_type != DT_REG &&
4536 de->d_type != DT_LNK &&
4537 de->d_type != DT_UNKNOWN)
4543 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4546 if (!dirent_is_file(de))
4549 return endswith(de->d_name, suffix);
4552 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4555 Hashmap *pids = NULL;
4559 /* Executes all binaries in a directory in parallel and waits
4560 * until all they all finished. */
4563 if (!(_d = opendir(directory))) {
4565 if (errno == ENOENT)
4568 log_error("Failed to enumerate directory %s: %m", directory);
4575 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4576 log_error("Failed to allocate set.");
4580 while ((de = readdir(d))) {
4585 if (!dirent_is_file(de))
4588 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4589 log_error("Out of memory");
4593 if ((pid = fork()) < 0) {
4594 log_error("Failed to fork: %m");
4613 log_error("Failed to execute %s: %m", path);
4614 _exit(EXIT_FAILURE);
4617 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4619 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4620 log_error("Failed to add PID to set: %s", strerror(-k));
4625 while (!hashmap_isempty(pids)) {
4626 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4631 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4636 log_error("waitid() failed: %m");
4640 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4641 if (!is_clean_exit(si.si_code, si.si_status)) {
4642 if (si.si_code == CLD_EXITED)
4643 log_error("%s exited with exit status %i.", path, si.si_status);
4645 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4647 log_debug("%s exited successfully.", path);
4658 hashmap_free_free(pids);
4661 int kill_and_sigcont(pid_t pid, int sig) {
4664 r = kill(pid, sig) < 0 ? -errno : 0;
4672 bool nulstr_contains(const char*nulstr, const char *needle) {
4678 NULSTR_FOREACH(i, nulstr)
4679 if (streq(i, needle))
4685 bool plymouth_running(void) {
4686 return access("/run/plymouth/pid", F_OK) >= 0;
4689 void parse_syslog_priority(char **p, int *priority) {
4690 int a = 0, b = 0, c = 0;
4700 if (!strchr(*p, '>'))
4703 if ((*p)[2] == '>') {
4704 c = undecchar((*p)[1]);
4706 } else if ((*p)[3] == '>') {
4707 b = undecchar((*p)[1]);
4708 c = undecchar((*p)[2]);
4710 } else if ((*p)[4] == '>') {
4711 a = undecchar((*p)[1]);
4712 b = undecchar((*p)[2]);
4713 c = undecchar((*p)[3]);
4718 if (a < 0 || b < 0 || c < 0)
4721 *priority = a*100+b*10+c;
4725 void skip_syslog_pid(char **buf) {
4737 p += strspn(p, "0123456789");
4747 void skip_syslog_date(char **buf) {
4755 LETTER, LETTER, LETTER,
4757 SPACE_OR_NUMBER, NUMBER,
4759 SPACE_OR_NUMBER, NUMBER,
4761 SPACE_OR_NUMBER, NUMBER,
4763 SPACE_OR_NUMBER, NUMBER,
4775 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4780 switch (sequence[i]) {
4787 case SPACE_OR_NUMBER:
4794 if (*p < '0' || *p > '9')
4800 if (!(*p >= 'A' && *p <= 'Z') &&
4801 !(*p >= 'a' && *p <= 'z'))
4817 int have_effective_cap(int value) {
4819 cap_flag_value_t fv;
4822 if (!(cap = cap_get_proc()))
4825 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4834 char* strshorten(char *s, size_t l) {
4843 static bool hostname_valid_char(char c) {
4845 (c >= 'a' && c <= 'z') ||
4846 (c >= 'A' && c <= 'Z') ||
4847 (c >= '0' && c <= '9') ||
4853 bool hostname_is_valid(const char *s) {
4859 for (p = s; *p; p++)
4860 if (!hostname_valid_char(*p))
4863 if (p-s > HOST_NAME_MAX)
4869 char* hostname_cleanup(char *s) {
4872 for (p = s, d = s; *p; p++)
4873 if ((*p >= 'a' && *p <= 'z') ||
4874 (*p >= 'A' && *p <= 'Z') ||
4875 (*p >= '0' && *p <= '9') ||
4883 strshorten(s, HOST_NAME_MAX);
4887 int pipe_eof(int fd) {
4888 struct pollfd pollfd;
4893 pollfd.events = POLLIN|POLLHUP;
4895 r = poll(&pollfd, 1, 0);
4902 return pollfd.revents & POLLHUP;
4905 int fd_wait_for_event(int fd, int event, usec_t t) {
4906 struct pollfd pollfd;
4911 pollfd.events = event;
4913 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4920 return pollfd.revents;
4923 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4934 t = new(char, strlen(path) + 1 + 6 + 1);
4938 fn = file_name_from_path(path);
4942 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4944 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4950 f = fdopen(fd, "we");
4963 int terminal_vhangup_fd(int fd) {
4966 if (ioctl(fd, TIOCVHANGUP) < 0)
4972 int terminal_vhangup(const char *name) {
4975 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4979 r = terminal_vhangup_fd(fd);
4980 close_nointr_nofail(fd);
4985 int vt_disallocate(const char *name) {
4989 /* Deallocate the VT if possible. If not possible
4990 * (i.e. because it is the active one), at least clear it
4991 * entirely (including the scrollback buffer) */
4993 if (!startswith(name, "/dev/"))
4996 if (!tty_is_vc(name)) {
4997 /* So this is not a VT. I guess we cannot deallocate
4998 * it then. But let's at least clear the screen */
5000 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5005 "\033[r" /* clear scrolling region */
5006 "\033[H" /* move home */
5007 "\033[2J", /* clear screen */
5009 close_nointr_nofail(fd);
5014 if (!startswith(name, "/dev/tty"))
5017 r = safe_atou(name+8, &u);
5024 /* Try to deallocate */
5025 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
5029 r = ioctl(fd, VT_DISALLOCATE, u);
5030 close_nointr_nofail(fd);
5038 /* Couldn't deallocate, so let's clear it fully with
5040 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5045 "\033[r" /* clear scrolling region */
5046 "\033[H" /* move home */
5047 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
5049 close_nointr_nofail(fd);
5054 static int files_add(Hashmap *h, const char *path, const char *suffix) {
5056 struct dirent buffer, *de;
5059 dir = opendir(path);
5061 if (errno == ENOENT)
5070 k = readdir_r(dir, &buffer, &de);
5079 if (!dirent_is_file_with_suffix(de, suffix))
5082 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
5087 f = canonicalize_file_name(p);
5089 log_error("Failed to canonicalize file name '%s': %m", p);
5095 log_debug("found: %s\n", f);
5096 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5105 static int base_cmp(const void *a, const void *b) {
5106 const char *s1, *s2;
5108 s1 = *(char * const *)a;
5109 s2 = *(char * const *)b;
5110 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5113 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5116 char **files = NULL;
5122 dirs = strv_new_ap(dir, ap);
5128 if (!strv_path_canonicalize(dirs)) {
5132 if (!strv_uniq(dirs)) {
5137 fh = hashmap_new(string_hash_func, string_compare_func);
5143 STRV_FOREACH(p, dirs) {
5144 if (files_add(fh, *p, suffix) < 0) {
5145 log_error("Failed to search for files.");
5151 files = hashmap_get_strv(fh);
5152 if (files == NULL) {
5153 log_error("Failed to compose list of files.");
5158 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5167 int hwclock_is_localtime(void) {
5172 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5178 f = fopen("/etc/adjtime", "re");
5180 char line[LINE_MAX];
5183 b = fgets(line, sizeof(line), f) &&
5184 fgets(line, sizeof(line), f) &&
5185 fgets(line, sizeof(line), f);
5194 local = streq(line, "LOCAL");
5196 } else if (errno != -ENOENT)
5202 int hwclock_apply_localtime_delta(int *min) {
5203 const struct timeval *tv_null = NULL;
5209 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5210 assert_se(tm = localtime(&ts.tv_sec));
5211 minuteswest = tm->tm_gmtoff / 60;
5213 tz.tz_minuteswest = -minuteswest;
5214 tz.tz_dsttime = 0; /* DST_NONE*/
5217 * If the hardware clock does not run in UTC, but in local time:
5218 * The very first time we set the kernel's timezone, it will warp
5219 * the clock so that it runs in UTC instead of local time.
5221 if (settimeofday(tv_null, &tz) < 0)
5228 int hwclock_reset_localtime_delta(void) {
5229 const struct timeval *tv_null = NULL;
5232 tz.tz_minuteswest = 0;
5233 tz.tz_dsttime = 0; /* DST_NONE*/
5235 if (settimeofday(tv_null, &tz) < 0)
5241 int rtc_open(int flags) {
5245 /* First, we try to make use of the /dev/rtc symlink. If that
5246 * doesn't exist, we open the first RTC which has hctosys=1
5247 * set. If we don't find any we just take the first RTC that
5250 fd = open("/dev/rtc", flags);
5254 d = opendir("/sys/class/rtc");
5260 struct dirent buf, *de;
5263 r = readdir_r(d, &buf, &de);
5270 if (ignore_file(de->d_name))
5273 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5279 r = read_one_line_file(p, &v);
5285 r = parse_boolean(v);
5291 p = strappend("/dev/", de->d_name);
5292 fd = open(p, flags);
5305 fd = open("/dev/rtc0", flags);
5312 int hwclock_get_time(struct tm *tm) {
5318 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5322 /* This leaves the timezone fields of struct tm
5324 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5327 /* We don't now daylight saving, so we reset this in order not
5328 * to confused mktime(). */
5331 close_nointr_nofail(fd);
5336 int hwclock_set_time(const struct tm *tm) {
5342 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5346 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5349 close_nointr_nofail(fd);
5354 int copy_file(const char *from, const char *to) {
5360 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5364 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5366 close_nointr_nofail(fdf);
5374 n = read(fdf, buf, sizeof(buf));
5378 close_nointr_nofail(fdf);
5389 k = loop_write(fdt, buf, n, false);
5391 r = k < 0 ? k : (errno ? -errno : -EIO);
5393 close_nointr_nofail(fdf);
5401 close_nointr_nofail(fdf);
5402 r = close_nointr(fdt);
5412 int symlink_or_copy(const char *from, const char *to) {
5413 char *pf = NULL, *pt = NULL;
5420 if (parent_of_path(from, &pf) < 0 ||
5421 parent_of_path(to, &pt) < 0) {
5426 if (stat(pf, &a) < 0 ||
5432 if (a.st_dev != b.st_dev) {
5436 return copy_file(from, to);
5439 if (symlink(from, to) < 0) {
5453 int symlink_or_copy_atomic(const char *from, const char *to) {
5457 unsigned long long ull;
5464 t = new(char, strlen(to) + 1 + 16 + 1);
5468 fn = file_name_from_path(to);
5472 x = stpcpy(t+k+1, fn);
5475 for (i = 0; i < 16; i++) {
5476 *(x++) = hexchar(ull & 0xF);
5482 r = symlink_or_copy(from, t);
5489 if (rename(t, to) < 0) {
5500 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5507 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5511 r = read_one_line_file("/proc/self/sessionid", &s);
5515 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5518 r = read_one_line_file(p, &s);
5525 r = safe_atou32(s, &u);
5531 if (u == (uint32_t) -1 || u <= 0)
5538 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5545 /* Only use audit login uid if we are executed with sufficient
5546 * capabilities so that pam_loginuid could do its job. If we
5547 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5548 * are being run in a container and /proc/self/loginuid is
5549 * useless since it probably contains a uid of the host
5552 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5556 r = read_one_line_file("/proc/self/loginuid", &s);
5560 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5563 r = read_one_line_file(p, &s);
5570 r = parse_uid(s, &u);
5576 if (u == (uid_t) -1)
5583 bool display_is_local(const char *display) {
5587 display[0] == ':' &&
5588 display[1] >= '0' &&
5592 int socket_from_display(const char *display, char **path) {
5599 if (!display_is_local(display))
5602 k = strspn(display+1, "0123456789");
5604 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5608 c = stpcpy(f, "/tmp/.X11-unix/X");
5609 memcpy(c, display+1, k);
5617 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5624 /* We enforce some special rules for uid=0: in order to avoid
5625 * NSS lookups for root we hardcode its data. */
5627 if (streq(*username, "root") || streq(*username, "0")) {
5641 if (parse_uid(*username, &u) >= 0) {
5645 /* If there are multiple users with the same id, make
5646 * sure to leave $USER to the configured value instead
5647 * of the first occurrence in the database. However if
5648 * the uid was configured by a numeric uid, then let's
5649 * pick the real username from /etc/passwd. */
5651 *username = p->pw_name;
5654 p = getpwnam(*username);
5658 return errno != 0 ? -errno : -ESRCH;
5672 int get_group_creds(const char **groupname, gid_t *gid) {
5678 /* We enforce some special rules for gid=0: in order to avoid
5679 * NSS lookups for root we hardcode its data. */
5681 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5682 *groupname = "root";
5690 if (parse_gid(*groupname, &id) >= 0) {
5695 *groupname = g->gr_name;
5698 g = getgrnam(*groupname);
5702 return errno != 0 ? -errno : -ESRCH;
5710 int glob_exists(const char *path) {
5718 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5720 if (k == GLOB_NOMATCH)
5722 else if (k == GLOB_NOSPACE)
5725 r = !strv_isempty(g.gl_pathv);
5727 r = errno ? -errno : -EIO;
5734 int dirent_ensure_type(DIR *d, struct dirent *de) {
5740 if (de->d_type != DT_UNKNOWN)
5743 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5747 S_ISREG(st.st_mode) ? DT_REG :
5748 S_ISDIR(st.st_mode) ? DT_DIR :
5749 S_ISLNK(st.st_mode) ? DT_LNK :
5750 S_ISFIFO(st.st_mode) ? DT_FIFO :
5751 S_ISSOCK(st.st_mode) ? DT_SOCK :
5752 S_ISCHR(st.st_mode) ? DT_CHR :
5753 S_ISBLK(st.st_mode) ? DT_BLK :
5759 int in_search_path(const char *path, char **search) {
5763 r = parent_of_path(path, &parent);
5769 STRV_FOREACH(i, search) {
5770 if (path_equal(parent, *i)) {
5781 int get_files_in_directory(const char *path, char ***list) {
5789 /* Returns all files in a directory in *list, and the number
5790 * of files as return value. If list is NULL returns only the
5798 struct dirent buffer, *de;
5801 k = readdir_r(d, &buffer, &de);
5810 dirent_ensure_type(d, de);
5812 if (!dirent_is_file(de))
5816 if ((unsigned) r >= n) {
5820 t = realloc(l, sizeof(char*) * n);
5829 assert((unsigned) r < n);
5831 l[r] = strdup(de->d_name);
5855 char *join(const char *x, ...) {
5868 t = va_arg(ap, const char *);
5891 t = va_arg(ap, const char *);
5905 bool is_main_thread(void) {
5906 static __thread int cached = 0;
5908 if (_unlikely_(cached == 0))
5909 cached = getpid() == gettid() ? 1 : -1;
5914 int block_get_whole_disk(dev_t d, dev_t *ret) {
5921 /* If it has a queue this is good enough for us */
5922 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5925 r = access(p, F_OK);
5933 /* If it is a partition find the originating device */
5934 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5937 r = access(p, F_OK);
5943 /* Get parent dev_t */
5944 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5947 r = read_one_line_file(p, &s);
5953 r = sscanf(s, "%u:%u", &m, &n);
5959 /* Only return this if it is really good enough for us. */
5960 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5963 r = access(p, F_OK);
5967 *ret = makedev(m, n);
5974 int file_is_priv_sticky(const char *p) {
5979 if (lstat(p, &st) < 0)
5983 (st.st_uid == 0 || st.st_uid == getuid()) &&
5984 (st.st_mode & S_ISVTX);
5987 static const char *const ioprio_class_table[] = {
5988 [IOPRIO_CLASS_NONE] = "none",
5989 [IOPRIO_CLASS_RT] = "realtime",
5990 [IOPRIO_CLASS_BE] = "best-effort",
5991 [IOPRIO_CLASS_IDLE] = "idle"
5994 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5996 static const char *const sigchld_code_table[] = {
5997 [CLD_EXITED] = "exited",
5998 [CLD_KILLED] = "killed",
5999 [CLD_DUMPED] = "dumped",
6000 [CLD_TRAPPED] = "trapped",
6001 [CLD_STOPPED] = "stopped",
6002 [CLD_CONTINUED] = "continued",
6005 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
6007 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
6008 [LOG_FAC(LOG_KERN)] = "kern",
6009 [LOG_FAC(LOG_USER)] = "user",
6010 [LOG_FAC(LOG_MAIL)] = "mail",
6011 [LOG_FAC(LOG_DAEMON)] = "daemon",
6012 [LOG_FAC(LOG_AUTH)] = "auth",
6013 [LOG_FAC(LOG_SYSLOG)] = "syslog",
6014 [LOG_FAC(LOG_LPR)] = "lpr",
6015 [LOG_FAC(LOG_NEWS)] = "news",
6016 [LOG_FAC(LOG_UUCP)] = "uucp",
6017 [LOG_FAC(LOG_CRON)] = "cron",
6018 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
6019 [LOG_FAC(LOG_FTP)] = "ftp",
6020 [LOG_FAC(LOG_LOCAL0)] = "local0",
6021 [LOG_FAC(LOG_LOCAL1)] = "local1",
6022 [LOG_FAC(LOG_LOCAL2)] = "local2",
6023 [LOG_FAC(LOG_LOCAL3)] = "local3",
6024 [LOG_FAC(LOG_LOCAL4)] = "local4",
6025 [LOG_FAC(LOG_LOCAL5)] = "local5",
6026 [LOG_FAC(LOG_LOCAL6)] = "local6",
6027 [LOG_FAC(LOG_LOCAL7)] = "local7"
6030 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
6032 static const char *const log_level_table[] = {
6033 [LOG_EMERG] = "emerg",
6034 [LOG_ALERT] = "alert",
6035 [LOG_CRIT] = "crit",
6037 [LOG_WARNING] = "warning",
6038 [LOG_NOTICE] = "notice",
6039 [LOG_INFO] = "info",
6040 [LOG_DEBUG] = "debug"
6043 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
6045 static const char* const sched_policy_table[] = {
6046 [SCHED_OTHER] = "other",
6047 [SCHED_BATCH] = "batch",
6048 [SCHED_IDLE] = "idle",
6049 [SCHED_FIFO] = "fifo",
6053 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
6055 static const char* const rlimit_table[] = {
6056 [RLIMIT_CPU] = "LimitCPU",
6057 [RLIMIT_FSIZE] = "LimitFSIZE",
6058 [RLIMIT_DATA] = "LimitDATA",
6059 [RLIMIT_STACK] = "LimitSTACK",
6060 [RLIMIT_CORE] = "LimitCORE",
6061 [RLIMIT_RSS] = "LimitRSS",
6062 [RLIMIT_NOFILE] = "LimitNOFILE",
6063 [RLIMIT_AS] = "LimitAS",
6064 [RLIMIT_NPROC] = "LimitNPROC",
6065 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
6066 [RLIMIT_LOCKS] = "LimitLOCKS",
6067 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
6068 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
6069 [RLIMIT_NICE] = "LimitNICE",
6070 [RLIMIT_RTPRIO] = "LimitRTPRIO",
6071 [RLIMIT_RTTIME] = "LimitRTTIME"
6074 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
6076 static const char* const ip_tos_table[] = {
6077 [IPTOS_LOWDELAY] = "low-delay",
6078 [IPTOS_THROUGHPUT] = "throughput",
6079 [IPTOS_RELIABILITY] = "reliability",
6080 [IPTOS_LOWCOST] = "low-cost",
6083 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
6085 static const char *const __signal_table[] = {
6102 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
6113 [SIGVTALRM] = "VTALRM",
6115 [SIGWINCH] = "WINCH",
6121 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6123 const char *signal_to_string(int signo) {
6124 static __thread char buf[12];
6127 name = __signal_to_string(signo);
6131 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6132 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6134 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6139 int signal_from_string(const char *s) {
6144 signo =__signal_from_string(s);
6148 if (startswith(s, "RTMIN+")) {
6152 if (safe_atou(s, &u) >= 0) {
6153 signo = (int) u + offset;
6154 if (signo > 0 && signo < _NSIG)
6160 bool kexec_loaded(void) {
6161 bool loaded = false;
6164 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6172 int strdup_or_null(const char *a, char **b) {
6190 int prot_from_flags(int flags) {
6192 switch (flags & O_ACCMODE) {
6201 return PROT_READ|PROT_WRITE;
6208 unsigned long cap_last_cap(void) {
6209 static __thread unsigned long saved;
6210 static __thread bool valid = false;
6216 p = (unsigned long) CAP_LAST_CAP;
6218 if (prctl(PR_CAPBSET_READ, p) < 0) {
6220 /* Hmm, look downwards, until we find one that
6222 for (p--; p > 0; p --)
6223 if (prctl(PR_CAPBSET_READ, p) >= 0)
6228 /* Hmm, look upwards, until we find one that doesn't
6231 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6241 char *format_bytes(char *buf, size_t l, off_t t) {
6244 static const struct {
6248 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6249 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6250 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6251 { "G", 1024ULL*1024ULL*1024ULL },
6252 { "M", 1024ULL*1024ULL },
6256 for (i = 0; i < ELEMENTSOF(table); i++) {
6258 if (t >= table[i].factor) {
6261 (unsigned long long) (t / table[i].factor),
6262 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6269 snprintf(buf, l, "%lluB", (unsigned long long) t);
6277 void* memdup(const void *p, size_t l) {
6290 int fd_inc_sndbuf(int fd, size_t n) {
6292 socklen_t l = sizeof(value);
6294 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6296 l == sizeof(value) &&
6297 (size_t) value >= n*2)
6301 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6308 int fd_inc_rcvbuf(int fd, size_t n) {
6310 socklen_t l = sizeof(value);
6312 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6314 l == sizeof(value) &&
6315 (size_t) value >= n*2)
6319 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));