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;
712 if (!fgets(t, sizeof(t), f)) {
738 int read_full_file(const char *fn, char **contents, size_t *size) {
745 if (!(f = fopen(fn, "re")))
748 if (fstat(fileno(f), &st) < 0) {
754 if (st.st_size > 4*1024*1024) {
759 n = st.st_size > 0 ? st.st_size : LINE_MAX;
766 if (!(t = realloc(buf, n+1))) {
772 k = fread(buf + l, 1, n - l, f);
787 if (n > 4*1024*1024) {
811 const char *separator, ...) {
814 char *contents = NULL, *p;
819 if ((r = read_full_file(fname, &contents, NULL)) < 0)
824 const char *key = NULL;
826 p += strspn(p, separator);
827 p += strspn(p, WHITESPACE);
832 if (!strchr(COMMENTS, *p)) {
836 va_start(ap, separator);
837 while ((key = va_arg(ap, char *))) {
841 value = va_arg(ap, char **);
844 if (strncmp(p, key, n) != 0 ||
849 n = strcspn(p, separator);
852 strchr(QUOTES, p[0]) &&
854 v = strndup(p+1, n-2);
865 /* return empty value strings as NULL */
882 p += strcspn(p, separator);
901 if (!(f = fopen(fname, "re")))
905 char l[LINE_MAX], *p, *u;
908 if (!fgets(l, sizeof(l), f)) {
921 if (strchr(COMMENTS, *p))
924 if (!(u = normalize_env_assignment(p))) {
925 log_error("Out of memory");
930 t = strv_append(m, u);
934 log_error("Out of memory");
957 int write_env_file(const char *fname, char **l) {
962 r = fopen_temporary(fname, &f, &p);
966 fchmod_umask(fileno(f), 0644);
982 if (rename(p, fname) < 0)
997 char *truncate_nl(char *s) {
1000 s[strcspn(s, NEWLINE)] = 0;
1004 int get_process_comm(pid_t pid, char **name) {
1010 r = read_one_line_file("/proc/self/comm", name);
1013 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1016 r = read_one_line_file(p, name);
1023 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1030 assert(max_length > 0);
1034 f = fopen("/proc/self/cmdline", "re");
1037 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1047 r = new(char, max_length);
1055 while ((c = getc(f)) != EOF) {
1077 size_t n = MIN(left-1, 3U);
1078 memcpy(k, "...", n);
1085 /* Kernel threads have no argv[] */
1095 h = get_process_comm(pid, &t);
1099 r = join("[", t, "]", NULL);
1110 int is_kernel_thread(pid_t pid) {
1120 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1129 count = fread(&c, 1, 1, f);
1133 /* Kernel threads have an empty cmdline */
1136 return eof ? 1 : -errno;
1141 int get_process_exe(pid_t pid, char **name) {
1147 r = readlink_malloc("/proc/self/exe", name);
1150 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1153 r = readlink_malloc(p, name);
1160 int get_process_uid(pid_t pid, uid_t *uid) {
1170 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1180 char line[LINE_MAX], *l;
1182 if (!fgets(line, sizeof(line), f)) {
1192 if (startswith(l, "Uid:")) {
1194 l += strspn(l, WHITESPACE);
1196 l[strcspn(l, WHITESPACE)] = 0;
1198 r = parse_uid(l, uid);
1211 char *strnappend(const char *s, const char *suffix, size_t b) {
1219 return strndup(suffix, b);
1229 if (!(r = new(char, a+b+1)))
1233 memcpy(r+a, suffix, b);
1239 char *strappend(const char *s, const char *suffix) {
1240 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1243 int readlink_malloc(const char *p, char **r) {
1253 if (!(c = new(char, l)))
1256 if ((n = readlink(p, c, l-1)) < 0) {
1262 if ((size_t) n < l-1) {
1273 int readlink_and_make_absolute(const char *p, char **r) {
1280 if ((j = readlink_malloc(p, &target)) < 0)
1283 k = file_in_same_dir(p, target);
1293 int readlink_and_canonicalize(const char *p, char **r) {
1300 j = readlink_and_make_absolute(p, &t);
1304 s = canonicalize_file_name(t);
1311 path_kill_slashes(*r);
1316 int parent_of_path(const char *path, char **_r) {
1317 const char *e, *a = NULL, *b = NULL, *p;
1327 for (e = path; *e; e++) {
1329 if (!slash && *e == '/') {
1333 } else if (slash && *e != '/')
1348 r = strndup(path, p-path);
1358 char *file_name_from_path(const char *p) {
1363 if ((r = strrchr(p, '/')))
1369 bool path_is_absolute(const char *p) {
1375 bool is_path(const char *p) {
1377 return !!strchr(p, '/');
1380 char *path_make_absolute(const char *p, const char *prefix) {
1383 /* Makes every item in the list an absolute path by prepending
1384 * the prefix, if specified and necessary */
1386 if (path_is_absolute(p) || !prefix)
1389 return join(prefix, "/", p, NULL);
1392 char *path_make_absolute_cwd(const char *p) {
1397 /* Similar to path_make_absolute(), but prefixes with the
1398 * current working directory. */
1400 if (path_is_absolute(p))
1403 if (!(cwd = get_current_dir_name()))
1406 r = path_make_absolute(p, cwd);
1412 char **strv_path_make_absolute_cwd(char **l) {
1415 /* Goes through every item in the string list and makes it
1416 * absolute. This works in place and won't rollback any
1417 * changes on failure. */
1419 STRV_FOREACH(s, l) {
1422 if (!(t = path_make_absolute_cwd(*s)))
1432 char **strv_path_canonicalize(char **l) {
1435 bool enomem = false;
1437 if (strv_isempty(l))
1440 /* Goes through every item in the string list and canonicalize
1441 * the path. This works in place and won't rollback any
1442 * changes on failure. */
1444 STRV_FOREACH(s, l) {
1447 t = path_make_absolute_cwd(*s);
1456 u = canonicalize_file_name(t);
1460 if (errno == ENOMEM || !errno)
1477 char **strv_path_remove_empty(char **l) {
1483 for (f = t = l; *f; f++) {
1485 if (dir_is_empty(*f) > 0) {
1497 int reset_all_signal_handlers(void) {
1500 for (sig = 1; sig < _NSIG; sig++) {
1501 struct sigaction sa;
1503 if (sig == SIGKILL || sig == SIGSTOP)
1507 sa.sa_handler = SIG_DFL;
1508 sa.sa_flags = SA_RESTART;
1510 /* On Linux the first two RT signals are reserved by
1511 * glibc, and sigaction() will return EINVAL for them. */
1512 if ((sigaction(sig, &sa, NULL) < 0))
1513 if (errno != EINVAL)
1520 char *strstrip(char *s) {
1523 /* Drops trailing whitespace. Modifies the string in
1524 * place. Returns pointer to first non-space character */
1526 s += strspn(s, WHITESPACE);
1528 for (e = strchr(s, 0); e > s; e --)
1529 if (!strchr(WHITESPACE, e[-1]))
1537 char *delete_chars(char *s, const char *bad) {
1540 /* Drops all whitespace, regardless where in the string */
1542 for (f = s, t = s; *f; f++) {
1543 if (strchr(bad, *f))
1554 bool in_charset(const char *s, const char* charset) {
1560 for (i = s; *i; i++)
1561 if (!strchr(charset, *i))
1567 char *file_in_same_dir(const char *path, const char *filename) {
1574 /* This removes the last component of path and appends
1575 * filename, unless the latter is absolute anyway or the
1578 if (path_is_absolute(filename))
1579 return strdup(filename);
1581 if (!(e = strrchr(path, '/')))
1582 return strdup(filename);
1584 k = strlen(filename);
1585 if (!(r = new(char, e-path+1+k+1)))
1588 memcpy(r, path, e-path+1);
1589 memcpy(r+(e-path)+1, filename, k+1);
1594 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1597 if (label_mkdir(path, mode) >= 0)
1598 if (chmod_and_chown(path, mode, uid, gid) < 0)
1601 if (lstat(path, &st) < 0)
1604 if ((st.st_mode & 0777) != mode ||
1607 !S_ISDIR(st.st_mode)) {
1616 int mkdir_parents(const char *path, mode_t mode) {
1621 /* Creates every parent directory in the path except the last
1624 p = path + strspn(path, "/");
1629 e = p + strcspn(p, "/");
1630 p = e + strspn(e, "/");
1632 /* Is this the last component? If so, then we're
1637 if (!(t = strndup(path, e - path)))
1640 r = label_mkdir(t, mode);
1643 if (r < 0 && errno != EEXIST)
1648 int mkdir_p(const char *path, mode_t mode) {
1653 if ((r = mkdir_parents(path, mode)) < 0)
1656 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1662 int rmdir_parents(const char *path, const char *stop) {
1671 /* Skip trailing slashes */
1672 while (l > 0 && path[l-1] == '/')
1678 /* Skip last component */
1679 while (l > 0 && path[l-1] != '/')
1682 /* Skip trailing slashes */
1683 while (l > 0 && path[l-1] == '/')
1689 if (!(t = strndup(path, l)))
1692 if (path_startswith(stop, t)) {
1701 if (errno != ENOENT)
1709 char hexchar(int x) {
1710 static const char table[16] = "0123456789abcdef";
1712 return table[x & 15];
1715 int unhexchar(char c) {
1717 if (c >= '0' && c <= '9')
1720 if (c >= 'a' && c <= 'f')
1721 return c - 'a' + 10;
1723 if (c >= 'A' && c <= 'F')
1724 return c - 'A' + 10;
1729 char octchar(int x) {
1730 return '0' + (x & 7);
1733 int unoctchar(char c) {
1735 if (c >= '0' && c <= '7')
1741 char decchar(int x) {
1742 return '0' + (x % 10);
1745 int undecchar(char c) {
1747 if (c >= '0' && c <= '9')
1753 char *cescape(const char *s) {
1759 /* Does C style string escaping. */
1761 if (!(r = new(char, strlen(s)*4 + 1)))
1764 for (f = s, t = r; *f; f++)
1810 /* For special chars we prefer octal over
1811 * hexadecimal encoding, simply because glib's
1812 * g_strescape() does the same */
1813 if ((*f < ' ') || (*f >= 127)) {
1815 *(t++) = octchar((unsigned char) *f >> 6);
1816 *(t++) = octchar((unsigned char) *f >> 3);
1817 *(t++) = octchar((unsigned char) *f);
1828 char *cunescape_length(const char *s, size_t length) {
1834 /* Undoes C style string escaping */
1836 r = new(char, length+1);
1840 for (f = s, t = r; f < s + length; f++) {
1883 /* This is an extension of the XDG syntax files */
1888 /* hexadecimal encoding */
1891 a = unhexchar(f[1]);
1892 b = unhexchar(f[2]);
1894 if (a < 0 || b < 0) {
1895 /* Invalid escape code, let's take it literal then */
1899 *(t++) = (char) ((a << 4) | b);
1914 /* octal encoding */
1917 a = unoctchar(f[0]);
1918 b = unoctchar(f[1]);
1919 c = unoctchar(f[2]);
1921 if (a < 0 || b < 0 || c < 0) {
1922 /* Invalid escape code, let's take it literal then */
1926 *(t++) = (char) ((a << 6) | (b << 3) | c);
1934 /* premature end of string.*/
1939 /* Invalid escape code, let's take it literal then */
1951 char *cunescape(const char *s) {
1952 return cunescape_length(s, strlen(s));
1955 char *xescape(const char *s, const char *bad) {
1959 /* Escapes all chars in bad, in addition to \ and all special
1960 * chars, in \xFF style escaping. May be reversed with
1963 if (!(r = new(char, strlen(s)*4+1)))
1966 for (f = s, t = r; *f; f++) {
1968 if ((*f < ' ') || (*f >= 127) ||
1969 (*f == '\\') || strchr(bad, *f)) {
1972 *(t++) = hexchar(*f >> 4);
1973 *(t++) = hexchar(*f);
1983 char *bus_path_escape(const char *s) {
1989 /* Escapes all chars that D-Bus' object path cannot deal
1990 * with. Can be reverse with bus_path_unescape() */
1992 if (!(r = new(char, strlen(s)*3+1)))
1995 for (f = s, t = r; *f; f++) {
1997 if (!(*f >= 'A' && *f <= 'Z') &&
1998 !(*f >= 'a' && *f <= 'z') &&
1999 !(*f >= '0' && *f <= '9')) {
2001 *(t++) = hexchar(*f >> 4);
2002 *(t++) = hexchar(*f);
2012 char *bus_path_unescape(const char *f) {
2017 if (!(r = strdup(f)))
2020 for (t = r; *f; f++) {
2025 if ((a = unhexchar(f[1])) < 0 ||
2026 (b = unhexchar(f[2])) < 0) {
2027 /* Invalid escape code, let's take it literal then */
2030 *(t++) = (char) ((a << 4) | b);
2042 char *path_kill_slashes(char *path) {
2046 /* Removes redundant inner and trailing slashes. Modifies the
2047 * passed string in-place.
2049 * ///foo///bar/ becomes /foo/bar
2052 for (f = path, t = path; *f; f++) {
2067 /* Special rule, if we are talking of the root directory, a
2068 trailing slash is good */
2070 if (t == path && slash)
2077 bool path_startswith(const char *path, const char *prefix) {
2081 if ((path[0] == '/') != (prefix[0] == '/'))
2087 path += strspn(path, "/");
2088 prefix += strspn(prefix, "/");
2096 a = strcspn(path, "/");
2097 b = strcspn(prefix, "/");
2102 if (memcmp(path, prefix, a) != 0)
2110 bool path_equal(const char *a, const char *b) {
2114 if ((a[0] == '/') != (b[0] == '/'))
2120 a += strspn(a, "/");
2121 b += strspn(b, "/");
2123 if (*a == 0 && *b == 0)
2126 if (*a == 0 || *b == 0)
2129 j = strcspn(a, "/");
2130 k = strcspn(b, "/");
2135 if (memcmp(a, b, j) != 0)
2143 char *ascii_strlower(char *t) {
2148 for (p = t; *p; p++)
2149 if (*p >= 'A' && *p <= 'Z')
2150 *p = *p - 'A' + 'a';
2155 bool ignore_file(const char *filename) {
2159 filename[0] == '.' ||
2160 streq(filename, "lost+found") ||
2161 streq(filename, "aquota.user") ||
2162 streq(filename, "aquota.group") ||
2163 endswith(filename, "~") ||
2164 endswith(filename, ".rpmnew") ||
2165 endswith(filename, ".rpmsave") ||
2166 endswith(filename, ".rpmorig") ||
2167 endswith(filename, ".dpkg-old") ||
2168 endswith(filename, ".dpkg-new") ||
2169 endswith(filename, ".swp");
2172 int fd_nonblock(int fd, bool nonblock) {
2177 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2181 flags |= O_NONBLOCK;
2183 flags &= ~O_NONBLOCK;
2185 if (fcntl(fd, F_SETFL, flags) < 0)
2191 int fd_cloexec(int fd, bool cloexec) {
2196 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2200 flags |= FD_CLOEXEC;
2202 flags &= ~FD_CLOEXEC;
2204 if (fcntl(fd, F_SETFD, flags) < 0)
2210 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
2213 assert(n_fdset == 0 || fdset);
2215 for (i = 0; i < n_fdset; i++)
2222 int close_all_fds(const int except[], unsigned n_except) {
2227 assert(n_except == 0 || except);
2229 d = opendir("/proc/self/fd");
2234 /* When /proc isn't available (for example in chroots)
2235 * the fallback is brute forcing through the fd
2238 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
2239 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
2241 if (fd_in_set(fd, except, n_except))
2244 if (close_nointr(fd) < 0)
2245 if (errno != EBADF && r == 0)
2252 while ((de = readdir(d))) {
2255 if (ignore_file(de->d_name))
2258 if (safe_atoi(de->d_name, &fd) < 0)
2259 /* Let's better ignore this, just in case */
2268 if (fd_in_set(fd, except, n_except))
2271 if (close_nointr(fd) < 0) {
2272 /* Valgrind has its own FD and doesn't want to have it closed */
2273 if (errno != EBADF && r == 0)
2282 bool chars_intersect(const char *a, const char *b) {
2285 /* Returns true if any of the chars in a are in b. */
2286 for (p = a; *p; p++)
2293 char *format_timestamp(char *buf, size_t l, usec_t t) {
2303 sec = (time_t) (t / USEC_PER_SEC);
2305 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2311 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2314 n = now(CLOCK_REALTIME);
2316 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2321 if (d >= USEC_PER_YEAR)
2322 snprintf(buf, l, "%llu years and %llu months ago",
2323 (unsigned long long) (d / USEC_PER_YEAR),
2324 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2325 else if (d >= USEC_PER_MONTH)
2326 snprintf(buf, l, "%llu months and %llu days ago",
2327 (unsigned long long) (d / USEC_PER_MONTH),
2328 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2329 else if (d >= USEC_PER_WEEK)
2330 snprintf(buf, l, "%llu weeks and %llu days ago",
2331 (unsigned long long) (d / USEC_PER_WEEK),
2332 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2333 else if (d >= 2*USEC_PER_DAY)
2334 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2335 else if (d >= 25*USEC_PER_HOUR)
2336 snprintf(buf, l, "1 day and %lluh ago",
2337 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2338 else if (d >= 6*USEC_PER_HOUR)
2339 snprintf(buf, l, "%lluh ago",
2340 (unsigned long long) (d / USEC_PER_HOUR));
2341 else if (d >= USEC_PER_HOUR)
2342 snprintf(buf, l, "%lluh %llumin ago",
2343 (unsigned long long) (d / USEC_PER_HOUR),
2344 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2345 else if (d >= 5*USEC_PER_MINUTE)
2346 snprintf(buf, l, "%llumin ago",
2347 (unsigned long long) (d / USEC_PER_MINUTE));
2348 else if (d >= USEC_PER_MINUTE)
2349 snprintf(buf, l, "%llumin %llus ago",
2350 (unsigned long long) (d / USEC_PER_MINUTE),
2351 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2352 else if (d >= USEC_PER_SEC)
2353 snprintf(buf, l, "%llus ago",
2354 (unsigned long long) (d / USEC_PER_SEC));
2355 else if (d >= USEC_PER_MSEC)
2356 snprintf(buf, l, "%llums ago",
2357 (unsigned long long) (d / USEC_PER_MSEC));
2359 snprintf(buf, l, "%lluus ago",
2360 (unsigned long long) d);
2362 snprintf(buf, l, "now");
2368 char *format_timespan(char *buf, size_t l, usec_t t) {
2369 static const struct {
2373 { "w", USEC_PER_WEEK },
2374 { "d", USEC_PER_DAY },
2375 { "h", USEC_PER_HOUR },
2376 { "min", USEC_PER_MINUTE },
2377 { "s", USEC_PER_SEC },
2378 { "ms", USEC_PER_MSEC },
2388 if (t == (usec_t) -1)
2392 snprintf(p, l, "0");
2397 /* The result of this function can be parsed with parse_usec */
2399 for (i = 0; i < ELEMENTSOF(table); i++) {
2403 if (t < table[i].usec)
2409 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2410 n = MIN((size_t) k, l);
2423 bool fstype_is_network(const char *fstype) {
2424 static const char * const table[] = {
2436 for (i = 0; i < ELEMENTSOF(table); i++)
2437 if (streq(table[i], fstype))
2446 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2451 TIOCL_GETKMSGREDIRECT,
2455 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2460 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2463 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2467 close_nointr_nofail(fd);
2471 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2472 struct termios old_termios, new_termios;
2474 char line[LINE_MAX];
2479 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2480 new_termios = old_termios;
2482 new_termios.c_lflag &= ~ICANON;
2483 new_termios.c_cc[VMIN] = 1;
2484 new_termios.c_cc[VTIME] = 0;
2486 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2489 if (t != (usec_t) -1) {
2490 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2491 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2496 k = fread(&c, 1, 1, f);
2498 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2504 *need_nl = c != '\n';
2511 if (t != (usec_t) -1)
2512 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2515 if (!fgets(line, sizeof(line), f))
2520 if (strlen(line) != 1)
2530 int ask(char *ret, const char *replies, const char *text, ...) {
2537 on_tty = isatty(STDOUT_FILENO);
2543 bool need_nl = true;
2546 fputs(ANSI_HIGHLIGHT_ON, stdout);
2553 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2557 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2560 if (r == -EBADMSG) {
2561 puts("Bad input, please try again.");
2572 if (strchr(replies, c)) {
2577 puts("Read unexpected character, please try again.");
2581 int reset_terminal_fd(int fd, bool switch_to_text) {
2582 struct termios termios;
2585 /* Set terminal to some sane defaults */
2589 /* We leave locked terminal attributes untouched, so that
2590 * Plymouth may set whatever it wants to set, and we don't
2591 * interfere with that. */
2593 /* Disable exclusive mode, just in case */
2594 ioctl(fd, TIOCNXCL);
2596 /* Switch to text mode */
2598 ioctl(fd, KDSETMODE, KD_TEXT);
2600 /* Enable console unicode mode */
2601 ioctl(fd, KDSKBMODE, K_UNICODE);
2603 if (tcgetattr(fd, &termios) < 0) {
2608 /* We only reset the stuff that matters to the software. How
2609 * hardware is set up we don't touch assuming that somebody
2610 * else will do that for us */
2612 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2613 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2614 termios.c_oflag |= ONLCR;
2615 termios.c_cflag |= CREAD;
2616 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2618 termios.c_cc[VINTR] = 03; /* ^C */
2619 termios.c_cc[VQUIT] = 034; /* ^\ */
2620 termios.c_cc[VERASE] = 0177;
2621 termios.c_cc[VKILL] = 025; /* ^X */
2622 termios.c_cc[VEOF] = 04; /* ^D */
2623 termios.c_cc[VSTART] = 021; /* ^Q */
2624 termios.c_cc[VSTOP] = 023; /* ^S */
2625 termios.c_cc[VSUSP] = 032; /* ^Z */
2626 termios.c_cc[VLNEXT] = 026; /* ^V */
2627 termios.c_cc[VWERASE] = 027; /* ^W */
2628 termios.c_cc[VREPRINT] = 022; /* ^R */
2629 termios.c_cc[VEOL] = 0;
2630 termios.c_cc[VEOL2] = 0;
2632 termios.c_cc[VTIME] = 0;
2633 termios.c_cc[VMIN] = 1;
2635 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2639 /* Just in case, flush all crap out */
2640 tcflush(fd, TCIOFLUSH);
2645 int reset_terminal(const char *name) {
2648 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2652 r = reset_terminal_fd(fd, true);
2653 close_nointr_nofail(fd);
2658 int open_terminal(const char *name, int mode) {
2663 * If a TTY is in the process of being closed opening it might
2664 * cause EIO. This is horribly awful, but unlikely to be
2665 * changed in the kernel. Hence we work around this problem by
2666 * retrying a couple of times.
2668 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2672 if ((fd = open(name, mode)) >= 0)
2681 usleep(50 * USEC_PER_MSEC);
2688 if ((r = isatty(fd)) < 0) {
2689 close_nointr_nofail(fd);
2694 close_nointr_nofail(fd);
2701 int flush_fd(int fd) {
2702 struct pollfd pollfd;
2706 pollfd.events = POLLIN;
2713 if ((r = poll(&pollfd, 1, 0)) < 0) {
2724 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2729 if (errno == EAGAIN)
2740 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2741 int fd = -1, notify = -1, r, wd = -1;
2745 /* We use inotify to be notified when the tty is closed. We
2746 * create the watch before checking if we can actually acquire
2747 * it, so that we don't lose any event.
2749 * Note: strictly speaking this actually watches for the
2750 * device being closed, it does *not* really watch whether a
2751 * tty loses its controlling process. However, unless some
2752 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2753 * its tty otherwise this will not become a problem. As long
2754 * as the administrator makes sure not configure any service
2755 * on the same tty as an untrusted user this should not be a
2756 * problem. (Which he probably should not do anyway.) */
2758 if (!fail && !force) {
2759 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2764 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2772 if ((r = flush_fd(notify)) < 0)
2775 /* We pass here O_NOCTTY only so that we can check the return
2776 * value TIOCSCTTY and have a reliable way to figure out if we
2777 * successfully became the controlling process of the tty */
2778 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2781 /* First, try to get the tty */
2782 r = ioctl(fd, TIOCSCTTY, force);
2784 /* Sometimes it makes sense to ignore TIOCSCTTY
2785 * returning EPERM, i.e. when very likely we already
2786 * are have this controlling terminal. */
2787 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2790 if (r < 0 && (force || fail || errno != EPERM)) {
2800 assert(notify >= 0);
2803 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2805 struct inotify_event *e;
2807 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2816 e = (struct inotify_event*) inotify_buffer;
2821 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2826 step = sizeof(struct inotify_event) + e->len;
2827 assert(step <= (size_t) l);
2829 e = (struct inotify_event*) ((uint8_t*) e + step);
2836 /* We close the tty fd here since if the old session
2837 * ended our handle will be dead. It's important that
2838 * we do this after sleeping, so that we don't enter
2839 * an endless loop. */
2840 close_nointr_nofail(fd);
2844 close_nointr_nofail(notify);
2846 r = reset_terminal_fd(fd, true);
2848 log_warning("Failed to reset terminal: %s", strerror(-r));
2854 close_nointr_nofail(fd);
2857 close_nointr_nofail(notify);
2862 int release_terminal(void) {
2864 struct sigaction sa_old, sa_new;
2866 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2869 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2870 * by our own TIOCNOTTY */
2873 sa_new.sa_handler = SIG_IGN;
2874 sa_new.sa_flags = SA_RESTART;
2875 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2877 if (ioctl(fd, TIOCNOTTY) < 0)
2880 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2882 close_nointr_nofail(fd);
2886 int sigaction_many(const struct sigaction *sa, ...) {
2891 while ((sig = va_arg(ap, int)) > 0)
2892 if (sigaction(sig, sa, NULL) < 0)
2899 int ignore_signals(int sig, ...) {
2900 struct sigaction sa;
2905 sa.sa_handler = SIG_IGN;
2906 sa.sa_flags = SA_RESTART;
2908 if (sigaction(sig, &sa, NULL) < 0)
2912 while ((sig = va_arg(ap, int)) > 0)
2913 if (sigaction(sig, &sa, NULL) < 0)
2920 int default_signals(int sig, ...) {
2921 struct sigaction sa;
2926 sa.sa_handler = SIG_DFL;
2927 sa.sa_flags = SA_RESTART;
2929 if (sigaction(sig, &sa, NULL) < 0)
2933 while ((sig = va_arg(ap, int)) > 0)
2934 if (sigaction(sig, &sa, NULL) < 0)
2941 int close_pipe(int p[]) {
2947 a = close_nointr(p[0]);
2952 b = close_nointr(p[1]);
2956 return a < 0 ? a : b;
2959 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2968 while (nbytes > 0) {
2971 if ((k = read(fd, p, nbytes)) <= 0) {
2973 if (k < 0 && errno == EINTR)
2976 if (k < 0 && errno == EAGAIN && do_poll) {
2977 struct pollfd pollfd;
2981 pollfd.events = POLLIN;
2983 if (poll(&pollfd, 1, -1) < 0) {
2987 return n > 0 ? n : -errno;
2990 if (pollfd.revents != POLLIN)
2991 return n > 0 ? n : -EIO;
2996 return n > 0 ? n : (k < 0 ? -errno : 0);
3007 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
3016 while (nbytes > 0) {
3019 k = write(fd, p, nbytes);
3022 if (k < 0 && errno == EINTR)
3025 if (k < 0 && errno == EAGAIN && do_poll) {
3026 struct pollfd pollfd;
3030 pollfd.events = POLLOUT;
3032 if (poll(&pollfd, 1, -1) < 0) {
3036 return n > 0 ? n : -errno;
3039 if (pollfd.revents != POLLOUT)
3040 return n > 0 ? n : -EIO;
3045 return n > 0 ? n : (k < 0 ? -errno : 0);
3056 int path_is_mount_point(const char *t, bool allow_symlink) {
3067 if (errno == ENOENT)
3073 r = parent_of_path(t, &parent);
3077 r = lstat(parent, &b);
3083 return a.st_dev != b.st_dev;
3086 int parse_usec(const char *t, usec_t *usec) {
3087 static const struct {
3091 { "sec", USEC_PER_SEC },
3092 { "s", USEC_PER_SEC },
3093 { "min", USEC_PER_MINUTE },
3094 { "hr", USEC_PER_HOUR },
3095 { "h", USEC_PER_HOUR },
3096 { "d", USEC_PER_DAY },
3097 { "w", USEC_PER_WEEK },
3098 { "msec", USEC_PER_MSEC },
3099 { "ms", USEC_PER_MSEC },
3100 { "m", USEC_PER_MINUTE },
3103 { "", USEC_PER_SEC },
3119 l = strtoll(p, &e, 10);
3130 e += strspn(e, WHITESPACE);
3132 for (i = 0; i < ELEMENTSOF(table); i++)
3133 if (startswith(e, table[i].suffix)) {
3134 r += (usec_t) l * table[i].usec;
3135 p = e + strlen(table[i].suffix);
3139 if (i >= ELEMENTSOF(table))
3149 int parse_bytes(const char *t, off_t *bytes) {
3150 static const struct {
3156 { "M", 1024ULL*1024ULL },
3157 { "G", 1024ULL*1024ULL*1024ULL },
3158 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3159 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3160 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3177 l = strtoll(p, &e, 10);
3188 e += strspn(e, WHITESPACE);
3190 for (i = 0; i < ELEMENTSOF(table); i++)
3191 if (startswith(e, table[i].suffix)) {
3192 r += (off_t) l * table[i].factor;
3193 p = e + strlen(table[i].suffix);
3197 if (i >= ELEMENTSOF(table))
3207 int make_stdio(int fd) {
3212 r = dup2(fd, STDIN_FILENO);
3213 s = dup2(fd, STDOUT_FILENO);
3214 t = dup2(fd, STDERR_FILENO);
3217 close_nointr_nofail(fd);
3219 if (r < 0 || s < 0 || t < 0)
3222 fd_cloexec(STDIN_FILENO, false);
3223 fd_cloexec(STDOUT_FILENO, false);
3224 fd_cloexec(STDERR_FILENO, false);
3229 int make_null_stdio(void) {
3232 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3235 return make_stdio(null_fd);
3238 bool is_device_path(const char *path) {
3240 /* Returns true on paths that refer to a device, either in
3241 * sysfs or in /dev */
3244 path_startswith(path, "/dev/") ||
3245 path_startswith(path, "/sys/");
3248 int dir_is_empty(const char *path) {
3251 struct dirent buf, *de;
3253 if (!(d = opendir(path)))
3257 if ((r = readdir_r(d, &buf, &de)) > 0) {
3267 if (!ignore_file(de->d_name)) {
3277 unsigned long long random_ull(void) {
3282 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3285 r = loop_read(fd, &ull, sizeof(ull), true);
3286 close_nointr_nofail(fd);
3288 if (r != sizeof(ull))
3294 return random() * RAND_MAX + random();
3297 void rename_process(const char name[8]) {
3300 /* This is a like a poor man's setproctitle(). It changes the
3301 * comm field, argv[0], and also the glibc's internally used
3302 * name of the process. For the first one a limit of 16 chars
3303 * applies, to the second one usually one of 10 (i.e. length
3304 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3305 * "systemd"). If you pass a longer string it will be
3308 prctl(PR_SET_NAME, name);
3310 if (program_invocation_name)
3311 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3313 if (saved_argc > 0) {
3317 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3319 for (i = 1; i < saved_argc; i++) {
3323 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3328 void sigset_add_many(sigset_t *ss, ...) {
3335 while ((sig = va_arg(ap, int)) > 0)
3336 assert_se(sigaddset(ss, sig) == 0);
3340 char* gethostname_malloc(void) {
3343 assert_se(uname(&u) >= 0);
3346 return strdup(u.nodename);
3348 return strdup(u.sysname);
3351 char* getlogname_malloc(void) {
3355 struct passwd pwbuf, *pw = NULL;
3358 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3363 /* Shortcut things to avoid NSS lookups */
3365 return strdup("root");
3367 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3370 if (!(buf = malloc(bufsize)))
3373 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3374 name = strdup(pw->pw_name);
3381 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3387 int getttyname_malloc(int fd, char **r) {
3388 char path[PATH_MAX], *c;
3393 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3398 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3405 int getttyname_harder(int fd, char **r) {
3409 if ((k = getttyname_malloc(fd, &s)) < 0)
3412 if (streq(s, "tty")) {
3414 return get_ctty(0, NULL, r);
3421 int get_ctty_devnr(pid_t pid, dev_t *d) {
3423 char line[LINE_MAX], *p, *fn;
3424 unsigned long ttynr;
3427 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3430 f = fopen(fn, "re");
3435 if (!fgets(line, sizeof(line), f)) {
3436 k = feof(f) ? -EIO : -errno;
3443 p = strrchr(line, ')');
3453 "%*d " /* session */
3462 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3464 char fn[PATH_MAX], *s, *b, *p;
3469 k = get_ctty_devnr(pid, &devnr);
3473 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3476 if ((k = readlink_malloc(fn, &s)) < 0) {
3481 /* This is an ugly hack */
3482 if (major(devnr) == 136) {
3483 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3493 /* Probably something like the ptys which have no
3494 * symlink in /dev/char. Let's return something
3495 * vaguely useful. */
3497 if (!(b = strdup(fn + 5)))
3507 if (startswith(s, "/dev/"))
3509 else if (startswith(s, "../"))
3527 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3533 /* This returns the first error we run into, but nevertheless
3536 if (!(d = fdopendir(fd))) {
3537 close_nointr_nofail(fd);
3539 return errno == ENOENT ? 0 : -errno;
3543 struct dirent buf, *de;
3544 bool is_dir, keep_around = false;
3547 if ((r = readdir_r(d, &buf, &de)) != 0) {
3556 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3559 if (de->d_type == DT_UNKNOWN) {
3562 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3563 if (ret == 0 && errno != ENOENT)
3570 (st.st_uid == 0 || st.st_uid == getuid()) &&
3571 (st.st_mode & S_ISVTX);
3573 is_dir = S_ISDIR(st.st_mode);
3576 if (honour_sticky) {
3579 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3580 if (ret == 0 && errno != ENOENT)
3586 (st.st_uid == 0 || st.st_uid == getuid()) &&
3587 (st.st_mode & S_ISVTX);
3590 is_dir = de->d_type == DT_DIR;
3596 subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
3597 if (subdir_fd < 0) {
3598 if (ret == 0 && errno != ENOENT)
3603 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3609 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3610 if (ret == 0 && errno != ENOENT)
3614 } else if (!only_dirs && !keep_around) {
3616 if (unlinkat(fd, de->d_name, 0) < 0) {
3617 if (ret == 0 && errno != ENOENT)
3628 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3634 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3636 if (errno != ENOTDIR)
3639 if (delete_root && !only_dirs)
3640 if (unlink(path) < 0)
3646 r = rm_rf_children(fd, only_dirs, honour_sticky);
3650 if (honour_sticky && file_is_priv_sticky(path) > 0)
3653 if (rmdir(path) < 0 && errno != ENOENT) {
3662 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3665 /* Under the assumption that we are running privileged we
3666 * first change the access mode and only then hand out
3667 * ownership to avoid a window where access is too open. */
3669 if (mode != (mode_t) -1)
3670 if (chmod(path, mode) < 0)
3673 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3674 if (chown(path, uid, gid) < 0)
3680 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3683 /* Under the assumption that we are running privileged we
3684 * first change the access mode and only then hand out
3685 * ownership to avoid a window where access is too open. */
3687 if (fchmod(fd, mode) < 0)
3690 if (fchown(fd, uid, gid) < 0)
3696 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3700 /* Allocates the cpuset in the right size */
3703 if (!(r = CPU_ALLOC(n)))
3706 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3707 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3717 if (errno != EINVAL)
3724 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3725 char *s = NULL, *spaces = NULL, *e;
3727 size_t emax, sl, left;
3728 struct iovec iovec[5];
3733 /* This independent of logging, as status messages are
3734 * optional and go exclusively to the console. */
3736 if (vasprintf(&s, format, ap) < 0)
3739 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3749 sl = 2 + 6 + 1; /* " [" status "]" */
3750 emax = (size_t) c > sl ? c - sl - 1 : 0;
3754 e = ellipsize(s, emax, 75);
3762 IOVEC_SET_STRING(iovec[n++], s);
3766 left = emax > sl ? emax - sl : 0;
3768 spaces = malloc(left);
3770 memset(spaces, ' ', left);
3771 iovec[n].iov_base = spaces;
3772 iovec[n].iov_len = left;
3779 IOVEC_SET_STRING(iovec[n++], " [");
3780 IOVEC_SET_STRING(iovec[n++], status);
3781 IOVEC_SET_STRING(iovec[n++], "]\n");
3783 IOVEC_SET_STRING(iovec[n++], "\n");
3785 writev(fd, iovec, n);
3792 close_nointr_nofail(fd);
3795 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3800 va_start(ap, format);
3801 status_vprintf(status, ellipse, format, ap);
3805 void status_welcome(void) {
3806 char *pretty_name = NULL, *ansi_color = NULL;
3807 const char *const_pretty = NULL, *const_color = NULL;
3810 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3811 "PRETTY_NAME", &pretty_name,
3812 "ANSI_COLOR", &ansi_color,
3816 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3819 if (!pretty_name && !const_pretty)
3820 const_pretty = "Linux";
3822 if (!ansi_color && !const_color)
3827 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3828 const_color ? const_color : ansi_color,
3829 const_pretty ? const_pretty : pretty_name);
3835 char *replace_env(const char *format, char **env) {
3842 const char *e, *word = format;
3847 for (e = format; *e; e ++) {
3858 if (!(k = strnappend(r, word, e-word-1)))
3867 } else if (*e == '$') {
3868 if (!(k = strnappend(r, word, e-word)))
3884 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3887 if (!(k = strappend(r, t)))
3900 if (!(k = strnappend(r, word, e-word)))
3911 char **replace_env_argv(char **argv, char **env) {
3913 unsigned k = 0, l = 0;
3915 l = strv_length(argv);
3917 if (!(r = new(char*, l+1)))
3920 STRV_FOREACH(i, argv) {
3922 /* If $FOO appears as single word, replace it by the split up variable */
3923 if ((*i)[0] == '$' && (*i)[1] != '{') {
3928 if ((e = strv_env_get(env, *i+1))) {
3930 if (!(m = strv_split_quoted(e))) {
3941 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3950 memcpy(r + k, m, q * sizeof(char*));
3958 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3959 if (!(r[k++] = replace_env(*i, env))) {
3969 int fd_columns(int fd) {
3973 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3982 unsigned columns(void) {
3983 static __thread int parsed_columns = 0;
3986 if (_likely_(parsed_columns > 0))
3987 return parsed_columns;
3989 e = getenv("COLUMNS");
3991 parsed_columns = atoi(e);
3993 if (parsed_columns <= 0)
3994 parsed_columns = fd_columns(STDOUT_FILENO);
3996 if (parsed_columns <= 0)
3997 parsed_columns = 80;
3999 return parsed_columns;
4002 int fd_lines(int fd) {
4006 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4015 unsigned lines(void) {
4016 static __thread int parsed_lines = 0;
4019 if (_likely_(parsed_lines > 0))
4020 return parsed_lines;
4022 e = getenv("LINES");
4024 parsed_lines = atoi(e);
4026 if (parsed_lines <= 0)
4027 parsed_lines = fd_lines(STDOUT_FILENO);
4029 if (parsed_lines <= 0)
4032 return parsed_lines;
4035 int running_in_chroot(void) {
4041 /* Only works as root */
4043 if (stat("/proc/1/root", &a) < 0)
4046 if (stat("/", &b) < 0)
4050 a.st_dev != b.st_dev ||
4051 a.st_ino != b.st_ino;
4054 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4059 assert(percent <= 100);
4060 assert(new_length >= 3);
4062 if (old_length <= 3 || old_length <= new_length)
4063 return strndup(s, old_length);
4065 r = new0(char, new_length+1);
4069 x = (new_length * percent) / 100;
4071 if (x > new_length - 3)
4079 s + old_length - (new_length - x - 3),
4080 new_length - x - 3);
4085 char *ellipsize(const char *s, size_t length, unsigned percent) {
4086 return ellipsize_mem(s, strlen(s), length, percent);
4089 int touch(const char *path) {
4094 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4097 close_nointr_nofail(fd);
4101 char *unquote(const char *s, const char* quotes) {
4109 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4110 return strndup(s+1, l-2);
4115 char *normalize_env_assignment(const char *s) {
4116 char *name, *value, *p, *r;
4121 if (!(r = strdup(s)))
4127 if (!(name = strndup(s, p - s)))
4130 if (!(p = strdup(p+1))) {
4135 value = unquote(strstrip(p), QUOTES);
4143 if (asprintf(&r, "%s=%s", name, value) < 0)
4152 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4163 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4175 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4182 if ((r = wait_for_terminate(pid, &status)) < 0) {
4183 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4187 if (status.si_code == CLD_EXITED) {
4188 if (status.si_status != 0) {
4189 log_warning("%s failed with error code %i.", name, status.si_status);
4190 return status.si_status;
4193 log_debug("%s succeeded.", name);
4196 } else if (status.si_code == CLD_KILLED ||
4197 status.si_code == CLD_DUMPED) {
4199 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4203 log_warning("%s failed due to unknown reason.", name);
4208 _noreturn_ void freeze(void) {
4210 /* Make sure nobody waits for us on a socket anymore */
4211 close_all_fds(NULL, 0);
4219 bool null_or_empty(struct stat *st) {
4222 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4225 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4231 int null_or_empty_path(const char *fn) {
4236 if (stat(fn, &st) < 0)
4239 return null_or_empty(&st);
4242 DIR *xopendirat(int fd, const char *name, int flags) {
4246 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4249 if (!(d = fdopendir(nfd))) {
4250 close_nointr_nofail(nfd);
4257 int signal_from_string_try_harder(const char *s) {
4261 if ((signo = signal_from_string(s)) <= 0)
4262 if (startswith(s, "SIG"))
4263 return signal_from_string(s+3);
4268 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4274 if (!dual_timestamp_is_set(t))
4277 fprintf(f, "%s=%llu %llu\n",
4279 (unsigned long long) t->realtime,
4280 (unsigned long long) t->monotonic);
4283 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4284 unsigned long long a, b;
4289 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4290 log_debug("Failed to parse finish timestamp value %s", value);
4297 char *fstab_node_to_udev_node(const char *p) {
4301 /* FIXME: to follow udev's logic 100% we need to leave valid
4302 * UTF8 chars unescaped */
4304 if (startswith(p, "LABEL=")) {
4306 if (!(u = unquote(p+6, "\"\'")))
4309 t = xescape(u, "/ ");
4315 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4324 if (startswith(p, "UUID=")) {
4326 if (!(u = unquote(p+5, "\"\'")))
4329 t = xescape(u, "/ ");
4335 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4347 void filter_environ(const char *prefix) {
4354 for (i = 0, j = 0; environ[i]; i++) {
4356 if (startswith(environ[i], prefix))
4359 environ[j++] = environ[i];
4365 bool tty_is_vc(const char *tty) {
4368 if (startswith(tty, "/dev/"))
4371 return vtnr_from_tty(tty) >= 0;
4374 int vtnr_from_tty(const char *tty) {
4379 if (startswith(tty, "/dev/"))
4382 if (!startswith(tty, "tty") )
4385 if (tty[3] < '0' || tty[3] > '9')
4388 r = safe_atoi(tty+3, &i);
4392 if (i < 0 || i > 63)
4398 bool tty_is_vc_resolve(const char *tty) {
4399 char *active = NULL;
4404 if (startswith(tty, "/dev/"))
4407 /* Resolve where /dev/console is pointing to */
4408 if (streq(tty, "console"))
4409 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4410 /* If multiple log outputs are configured the
4411 * last one is what /dev/console points to */
4412 tty = strrchr(active, ' ');
4425 const char *default_term_for_tty(const char *tty) {
4428 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4431 bool dirent_is_file(const struct dirent *de) {
4434 if (ignore_file(de->d_name))
4437 if (de->d_type != DT_REG &&
4438 de->d_type != DT_LNK &&
4439 de->d_type != DT_UNKNOWN)
4445 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4448 if (!dirent_is_file(de))
4451 return endswith(de->d_name, suffix);
4454 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4457 Hashmap *pids = NULL;
4461 /* Executes all binaries in a directory in parallel and waits
4462 * until all they all finished. */
4465 if (!(_d = opendir(directory))) {
4467 if (errno == ENOENT)
4470 log_error("Failed to enumerate directory %s: %m", directory);
4477 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4478 log_error("Failed to allocate set.");
4482 while ((de = readdir(d))) {
4487 if (!dirent_is_file(de))
4490 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4491 log_error("Out of memory");
4495 if ((pid = fork()) < 0) {
4496 log_error("Failed to fork: %m");
4515 log_error("Failed to execute %s: %m", path);
4516 _exit(EXIT_FAILURE);
4519 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4521 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4522 log_error("Failed to add PID to set: %s", strerror(-k));
4527 while (!hashmap_isempty(pids)) {
4528 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4533 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4538 log_error("waitid() failed: %m");
4542 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4543 if (!is_clean_exit(si.si_code, si.si_status)) {
4544 if (si.si_code == CLD_EXITED)
4545 log_error("%s exited with exit status %i.", path, si.si_status);
4547 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4549 log_debug("%s exited successfully.", path);
4560 hashmap_free_free(pids);
4563 int kill_and_sigcont(pid_t pid, int sig) {
4566 r = kill(pid, sig) < 0 ? -errno : 0;
4574 bool nulstr_contains(const char*nulstr, const char *needle) {
4580 NULSTR_FOREACH(i, nulstr)
4581 if (streq(i, needle))
4587 bool plymouth_running(void) {
4588 return access("/run/plymouth/pid", F_OK) >= 0;
4591 void parse_syslog_priority(char **p, int *priority) {
4592 int a = 0, b = 0, c = 0;
4602 if (!strchr(*p, '>'))
4605 if ((*p)[2] == '>') {
4606 c = undecchar((*p)[1]);
4608 } else if ((*p)[3] == '>') {
4609 b = undecchar((*p)[1]);
4610 c = undecchar((*p)[2]);
4612 } else if ((*p)[4] == '>') {
4613 a = undecchar((*p)[1]);
4614 b = undecchar((*p)[2]);
4615 c = undecchar((*p)[3]);
4620 if (a < 0 || b < 0 || c < 0)
4623 *priority = a*100+b*10+c;
4627 void skip_syslog_pid(char **buf) {
4639 p += strspn(p, "0123456789");
4649 void skip_syslog_date(char **buf) {
4657 LETTER, LETTER, LETTER,
4659 SPACE_OR_NUMBER, NUMBER,
4661 SPACE_OR_NUMBER, NUMBER,
4663 SPACE_OR_NUMBER, NUMBER,
4665 SPACE_OR_NUMBER, NUMBER,
4677 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4682 switch (sequence[i]) {
4689 case SPACE_OR_NUMBER:
4696 if (*p < '0' || *p > '9')
4702 if (!(*p >= 'A' && *p <= 'Z') &&
4703 !(*p >= 'a' && *p <= 'z'))
4719 int have_effective_cap(int value) {
4721 cap_flag_value_t fv;
4724 if (!(cap = cap_get_proc()))
4727 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4736 char* strshorten(char *s, size_t l) {
4745 static bool hostname_valid_char(char c) {
4747 (c >= 'a' && c <= 'z') ||
4748 (c >= 'A' && c <= 'Z') ||
4749 (c >= '0' && c <= '9') ||
4755 bool hostname_is_valid(const char *s) {
4761 for (p = s; *p; p++)
4762 if (!hostname_valid_char(*p))
4765 if (p-s > HOST_NAME_MAX)
4771 char* hostname_cleanup(char *s) {
4774 for (p = s, d = s; *p; p++)
4775 if ((*p >= 'a' && *p <= 'z') ||
4776 (*p >= 'A' && *p <= 'Z') ||
4777 (*p >= '0' && *p <= '9') ||
4785 strshorten(s, HOST_NAME_MAX);
4789 int pipe_eof(int fd) {
4790 struct pollfd pollfd;
4795 pollfd.events = POLLIN|POLLHUP;
4797 r = poll(&pollfd, 1, 0);
4804 return pollfd.revents & POLLHUP;
4807 int fd_wait_for_event(int fd, int event, usec_t t) {
4808 struct pollfd pollfd;
4813 pollfd.events = event;
4815 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4822 return pollfd.revents;
4825 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4836 t = new(char, strlen(path) + 1 + 6 + 1);
4840 fn = file_name_from_path(path);
4844 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4846 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4852 f = fdopen(fd, "we");
4865 int terminal_vhangup_fd(int fd) {
4868 if (ioctl(fd, TIOCVHANGUP) < 0)
4874 int terminal_vhangup(const char *name) {
4877 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4881 r = terminal_vhangup_fd(fd);
4882 close_nointr_nofail(fd);
4887 int vt_disallocate(const char *name) {
4891 /* Deallocate the VT if possible. If not possible
4892 * (i.e. because it is the active one), at least clear it
4893 * entirely (including the scrollback buffer) */
4895 if (!startswith(name, "/dev/"))
4898 if (!tty_is_vc(name)) {
4899 /* So this is not a VT. I guess we cannot deallocate
4900 * it then. But let's at least clear the screen */
4902 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4907 "\033[r" /* clear scrolling region */
4908 "\033[H" /* move home */
4909 "\033[2J", /* clear screen */
4911 close_nointr_nofail(fd);
4916 if (!startswith(name, "/dev/tty"))
4919 r = safe_atou(name+8, &u);
4926 /* Try to deallocate */
4927 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4931 r = ioctl(fd, VT_DISALLOCATE, u);
4932 close_nointr_nofail(fd);
4940 /* Couldn't deallocate, so let's clear it fully with
4942 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4947 "\033[r" /* clear scrolling region */
4948 "\033[H" /* move home */
4949 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4951 close_nointr_nofail(fd);
4956 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4958 struct dirent buffer, *de;
4961 dir = opendir(path);
4963 if (errno == ENOENT)
4972 k = readdir_r(dir, &buffer, &de);
4981 if (!dirent_is_file_with_suffix(de, suffix))
4984 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4989 f = canonicalize_file_name(p);
4991 log_error("Failed to canonicalize file name '%s': %m", p);
4997 log_debug("found: %s\n", f);
4998 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5007 static int base_cmp(const void *a, const void *b) {
5008 const char *s1, *s2;
5010 s1 = *(char * const *)a;
5011 s2 = *(char * const *)b;
5012 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5015 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5018 char **files = NULL;
5024 dirs = strv_new_ap(dir, ap);
5030 if (!strv_path_canonicalize(dirs)) {
5034 if (!strv_uniq(dirs)) {
5039 fh = hashmap_new(string_hash_func, string_compare_func);
5045 STRV_FOREACH(p, dirs) {
5046 if (files_add(fh, *p, suffix) < 0) {
5047 log_error("Failed to search for files.");
5053 files = hashmap_get_strv(fh);
5054 if (files == NULL) {
5055 log_error("Failed to compose list of files.");
5060 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5069 int hwclock_is_localtime(void) {
5074 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5080 f = fopen("/etc/adjtime", "re");
5082 char line[LINE_MAX];
5085 b = fgets(line, sizeof(line), f) &&
5086 fgets(line, sizeof(line), f) &&
5087 fgets(line, sizeof(line), f);
5096 local = streq(line, "LOCAL");
5098 } else if (errno != -ENOENT)
5104 int hwclock_apply_localtime_delta(int *min) {
5105 const struct timeval *tv_null = NULL;
5111 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5112 assert_se(tm = localtime(&ts.tv_sec));
5113 minuteswest = tm->tm_gmtoff / 60;
5115 tz.tz_minuteswest = -minuteswest;
5116 tz.tz_dsttime = 0; /* DST_NONE*/
5119 * If the hardware clock does not run in UTC, but in local time:
5120 * The very first time we set the kernel's timezone, it will warp
5121 * the clock so that it runs in UTC instead of local time.
5123 if (settimeofday(tv_null, &tz) < 0)
5130 int hwclock_reset_localtime_delta(void) {
5131 const struct timeval *tv_null = NULL;
5134 tz.tz_minuteswest = 0;
5135 tz.tz_dsttime = 0; /* DST_NONE*/
5137 if (settimeofday(tv_null, &tz) < 0)
5143 int rtc_open(int flags) {
5147 /* First, we try to make use of the /dev/rtc symlink. If that
5148 * doesn't exist, we open the first RTC which has hctosys=1
5149 * set. If we don't find any we just take the first RTC that
5152 fd = open("/dev/rtc", flags);
5156 d = opendir("/sys/class/rtc");
5162 struct dirent buf, *de;
5165 r = readdir_r(d, &buf, &de);
5172 if (ignore_file(de->d_name))
5175 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5181 r = read_one_line_file(p, &v);
5187 r = parse_boolean(v);
5193 p = strappend("/dev/", de->d_name);
5194 fd = open(p, flags);
5207 fd = open("/dev/rtc0", flags);
5214 int hwclock_get_time(struct tm *tm) {
5220 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5224 /* This leaves the timezone fields of struct tm
5226 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5229 /* We don't now daylight saving, so we reset this in order not
5230 * to confused mktime(). */
5233 close_nointr_nofail(fd);
5238 int hwclock_set_time(const struct tm *tm) {
5244 fd = rtc_open(O_RDONLY|O_CLOEXEC);
5248 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5251 close_nointr_nofail(fd);
5256 int copy_file(const char *from, const char *to) {
5262 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5266 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5268 close_nointr_nofail(fdf);
5276 n = read(fdf, buf, sizeof(buf));
5280 close_nointr_nofail(fdf);
5291 k = loop_write(fdt, buf, n, false);
5293 r = k < 0 ? k : (errno ? -errno : -EIO);
5295 close_nointr_nofail(fdf);
5303 close_nointr_nofail(fdf);
5304 r = close_nointr(fdt);
5314 int symlink_or_copy(const char *from, const char *to) {
5315 char *pf = NULL, *pt = NULL;
5322 if (parent_of_path(from, &pf) < 0 ||
5323 parent_of_path(to, &pt) < 0) {
5328 if (stat(pf, &a) < 0 ||
5334 if (a.st_dev != b.st_dev) {
5338 return copy_file(from, to);
5341 if (symlink(from, to) < 0) {
5355 int symlink_or_copy_atomic(const char *from, const char *to) {
5359 unsigned long long ull;
5366 t = new(char, strlen(to) + 1 + 16 + 1);
5370 fn = file_name_from_path(to);
5374 x = stpcpy(t+k+1, fn);
5377 for (i = 0; i < 16; i++) {
5378 *(x++) = hexchar(ull & 0xF);
5384 r = symlink_or_copy(from, t);
5391 if (rename(t, to) < 0) {
5402 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5409 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5413 r = read_one_line_file("/proc/self/sessionid", &s);
5417 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5420 r = read_one_line_file(p, &s);
5427 r = safe_atou32(s, &u);
5433 if (u == (uint32_t) -1 || u <= 0)
5440 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5447 /* Only use audit login uid if we are executed with sufficient
5448 * capabilities so that pam_loginuid could do its job. If we
5449 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5450 * are being run in a container and /proc/self/loginuid is
5451 * useless since it probably contains a uid of the host
5454 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5458 r = read_one_line_file("/proc/self/loginuid", &s);
5462 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5465 r = read_one_line_file(p, &s);
5472 r = parse_uid(s, &u);
5478 if (u == (uid_t) -1)
5485 bool display_is_local(const char *display) {
5489 display[0] == ':' &&
5490 display[1] >= '0' &&
5494 int socket_from_display(const char *display, char **path) {
5501 if (!display_is_local(display))
5504 k = strspn(display+1, "0123456789");
5506 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5510 c = stpcpy(f, "/tmp/.X11-unix/X");
5511 memcpy(c, display+1, k);
5519 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5526 /* We enforce some special rules for uid=0: in order to avoid
5527 * NSS lookups for root we hardcode its data. */
5529 if (streq(*username, "root") || streq(*username, "0")) {
5543 if (parse_uid(*username, &u) >= 0) {
5547 /* If there are multiple users with the same id, make
5548 * sure to leave $USER to the configured value instead
5549 * of the first occurrence in the database. However if
5550 * the uid was configured by a numeric uid, then let's
5551 * pick the real username from /etc/passwd. */
5553 *username = p->pw_name;
5556 p = getpwnam(*username);
5560 return errno != 0 ? -errno : -ESRCH;
5574 int get_group_creds(const char **groupname, gid_t *gid) {
5580 /* We enforce some special rules for gid=0: in order to avoid
5581 * NSS lookups for root we hardcode its data. */
5583 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5584 *groupname = "root";
5592 if (parse_gid(*groupname, &id) >= 0) {
5597 *groupname = g->gr_name;
5600 g = getgrnam(*groupname);
5604 return errno != 0 ? -errno : -ESRCH;
5612 int in_group(const char *name) {
5614 int ngroups_max, r, i;
5616 r = get_group_creds(&name, &gid);
5620 if (getgid() == gid)
5623 if (getegid() == gid)
5626 ngroups_max = sysconf(_SC_NGROUPS_MAX);
5627 assert(ngroups_max > 0);
5629 gids = alloca(sizeof(gid_t) * ngroups_max);
5631 r = getgroups(ngroups_max, gids);
5635 for (i = 0; i < r; i++)
5642 int glob_exists(const char *path) {
5650 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5652 if (k == GLOB_NOMATCH)
5654 else if (k == GLOB_NOSPACE)
5657 r = !strv_isempty(g.gl_pathv);
5659 r = errno ? -errno : -EIO;
5666 int dirent_ensure_type(DIR *d, struct dirent *de) {
5672 if (de->d_type != DT_UNKNOWN)
5675 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5679 S_ISREG(st.st_mode) ? DT_REG :
5680 S_ISDIR(st.st_mode) ? DT_DIR :
5681 S_ISLNK(st.st_mode) ? DT_LNK :
5682 S_ISFIFO(st.st_mode) ? DT_FIFO :
5683 S_ISSOCK(st.st_mode) ? DT_SOCK :
5684 S_ISCHR(st.st_mode) ? DT_CHR :
5685 S_ISBLK(st.st_mode) ? DT_BLK :
5691 int in_search_path(const char *path, char **search) {
5695 r = parent_of_path(path, &parent);
5701 STRV_FOREACH(i, search) {
5702 if (path_equal(parent, *i)) {
5713 int get_files_in_directory(const char *path, char ***list) {
5721 /* Returns all files in a directory in *list, and the number
5722 * of files as return value. If list is NULL returns only the
5730 struct dirent buffer, *de;
5733 k = readdir_r(d, &buffer, &de);
5742 dirent_ensure_type(d, de);
5744 if (!dirent_is_file(de))
5748 if ((unsigned) r >= n) {
5752 t = realloc(l, sizeof(char*) * n);
5761 assert((unsigned) r < n);
5763 l[r] = strdup(de->d_name);
5787 char *join(const char *x, ...) {
5800 t = va_arg(ap, const char *);
5823 t = va_arg(ap, const char *);
5837 bool is_main_thread(void) {
5838 static __thread int cached = 0;
5840 if (_unlikely_(cached == 0))
5841 cached = getpid() == gettid() ? 1 : -1;
5846 int block_get_whole_disk(dev_t d, dev_t *ret) {
5853 /* If it has a queue this is good enough for us */
5854 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5857 r = access(p, F_OK);
5865 /* If it is a partition find the originating device */
5866 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5869 r = access(p, F_OK);
5875 /* Get parent dev_t */
5876 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5879 r = read_one_line_file(p, &s);
5885 r = sscanf(s, "%u:%u", &m, &n);
5891 /* Only return this if it is really good enough for us. */
5892 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5895 r = access(p, F_OK);
5899 *ret = makedev(m, n);
5906 int file_is_priv_sticky(const char *p) {
5911 if (lstat(p, &st) < 0)
5915 (st.st_uid == 0 || st.st_uid == getuid()) &&
5916 (st.st_mode & S_ISVTX);
5919 static const char *const ioprio_class_table[] = {
5920 [IOPRIO_CLASS_NONE] = "none",
5921 [IOPRIO_CLASS_RT] = "realtime",
5922 [IOPRIO_CLASS_BE] = "best-effort",
5923 [IOPRIO_CLASS_IDLE] = "idle"
5926 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5928 static const char *const sigchld_code_table[] = {
5929 [CLD_EXITED] = "exited",
5930 [CLD_KILLED] = "killed",
5931 [CLD_DUMPED] = "dumped",
5932 [CLD_TRAPPED] = "trapped",
5933 [CLD_STOPPED] = "stopped",
5934 [CLD_CONTINUED] = "continued",
5937 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5939 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5940 [LOG_FAC(LOG_KERN)] = "kern",
5941 [LOG_FAC(LOG_USER)] = "user",
5942 [LOG_FAC(LOG_MAIL)] = "mail",
5943 [LOG_FAC(LOG_DAEMON)] = "daemon",
5944 [LOG_FAC(LOG_AUTH)] = "auth",
5945 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5946 [LOG_FAC(LOG_LPR)] = "lpr",
5947 [LOG_FAC(LOG_NEWS)] = "news",
5948 [LOG_FAC(LOG_UUCP)] = "uucp",
5949 [LOG_FAC(LOG_CRON)] = "cron",
5950 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5951 [LOG_FAC(LOG_FTP)] = "ftp",
5952 [LOG_FAC(LOG_LOCAL0)] = "local0",
5953 [LOG_FAC(LOG_LOCAL1)] = "local1",
5954 [LOG_FAC(LOG_LOCAL2)] = "local2",
5955 [LOG_FAC(LOG_LOCAL3)] = "local3",
5956 [LOG_FAC(LOG_LOCAL4)] = "local4",
5957 [LOG_FAC(LOG_LOCAL5)] = "local5",
5958 [LOG_FAC(LOG_LOCAL6)] = "local6",
5959 [LOG_FAC(LOG_LOCAL7)] = "local7"
5962 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5964 static const char *const log_level_table[] = {
5965 [LOG_EMERG] = "emerg",
5966 [LOG_ALERT] = "alert",
5967 [LOG_CRIT] = "crit",
5969 [LOG_WARNING] = "warning",
5970 [LOG_NOTICE] = "notice",
5971 [LOG_INFO] = "info",
5972 [LOG_DEBUG] = "debug"
5975 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5977 static const char* const sched_policy_table[] = {
5978 [SCHED_OTHER] = "other",
5979 [SCHED_BATCH] = "batch",
5980 [SCHED_IDLE] = "idle",
5981 [SCHED_FIFO] = "fifo",
5985 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5987 static const char* const rlimit_table[] = {
5988 [RLIMIT_CPU] = "LimitCPU",
5989 [RLIMIT_FSIZE] = "LimitFSIZE",
5990 [RLIMIT_DATA] = "LimitDATA",
5991 [RLIMIT_STACK] = "LimitSTACK",
5992 [RLIMIT_CORE] = "LimitCORE",
5993 [RLIMIT_RSS] = "LimitRSS",
5994 [RLIMIT_NOFILE] = "LimitNOFILE",
5995 [RLIMIT_AS] = "LimitAS",
5996 [RLIMIT_NPROC] = "LimitNPROC",
5997 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5998 [RLIMIT_LOCKS] = "LimitLOCKS",
5999 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
6000 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
6001 [RLIMIT_NICE] = "LimitNICE",
6002 [RLIMIT_RTPRIO] = "LimitRTPRIO",
6003 [RLIMIT_RTTIME] = "LimitRTTIME"
6006 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
6008 static const char* const ip_tos_table[] = {
6009 [IPTOS_LOWDELAY] = "low-delay",
6010 [IPTOS_THROUGHPUT] = "throughput",
6011 [IPTOS_RELIABILITY] = "reliability",
6012 [IPTOS_LOWCOST] = "low-cost",
6015 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
6017 static const char *const __signal_table[] = {
6034 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
6045 [SIGVTALRM] = "VTALRM",
6047 [SIGWINCH] = "WINCH",
6053 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6055 const char *signal_to_string(int signo) {
6056 static __thread char buf[12];
6059 name = __signal_to_string(signo);
6063 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6064 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6066 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6071 int signal_from_string(const char *s) {
6076 signo =__signal_from_string(s);
6080 if (startswith(s, "RTMIN+")) {
6084 if (safe_atou(s, &u) >= 0) {
6085 signo = (int) u + offset;
6086 if (signo > 0 && signo < _NSIG)
6092 bool kexec_loaded(void) {
6093 bool loaded = false;
6096 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6104 int strdup_or_null(const char *a, char **b) {
6122 int prot_from_flags(int flags) {
6124 switch (flags & O_ACCMODE) {
6133 return PROT_READ|PROT_WRITE;
6140 unsigned long cap_last_cap(void) {
6141 static __thread unsigned long saved;
6142 static __thread bool valid = false;
6148 p = (unsigned long) CAP_LAST_CAP;
6150 if (prctl(PR_CAPBSET_READ, p) < 0) {
6152 /* Hmm, look downwards, until we find one that
6154 for (p--; p > 0; p --)
6155 if (prctl(PR_CAPBSET_READ, p) >= 0)
6160 /* Hmm, look upwards, until we find one that doesn't
6163 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6173 char *format_bytes(char *buf, size_t l, off_t t) {
6176 static const struct {
6180 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6181 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6182 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6183 { "G", 1024ULL*1024ULL*1024ULL },
6184 { "M", 1024ULL*1024ULL },
6188 for (i = 0; i < ELEMENTSOF(table); i++) {
6190 if (t >= table[i].factor) {
6193 (unsigned long long) (t / table[i].factor),
6194 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6201 snprintf(buf, l, "%lluB", (unsigned long long) t);
6209 void* memdup(const void *p, size_t l) {
6222 int fd_inc_sndbuf(int fd, size_t n) {
6224 socklen_t l = sizeof(value);
6226 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6228 l == sizeof(value) &&
6229 (size_t) value >= n*2)
6233 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6240 int fd_inc_rcvbuf(int fd, size_t n) {
6242 socklen_t l = sizeof(value);
6244 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6246 l == sizeof(value) &&
6247 (size_t) value >= n*2)
6251 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));