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 get_process_exe(pid_t pid, char **name) {
1109 r = readlink_malloc("/proc/self/exe", name);
1112 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1115 r = readlink_malloc(p, name);
1122 int get_process_uid(pid_t pid, uid_t *uid) {
1132 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1142 char line[LINE_MAX], *l;
1144 if (!fgets(line, sizeof(line), f)) {
1154 if (startswith(l, "Uid:")) {
1156 l += strspn(l, WHITESPACE);
1158 l[strcspn(l, WHITESPACE)] = 0;
1160 r = parse_uid(l, uid);
1173 char *strnappend(const char *s, const char *suffix, size_t b) {
1181 return strndup(suffix, b);
1191 if (!(r = new(char, a+b+1)))
1195 memcpy(r+a, suffix, b);
1201 char *strappend(const char *s, const char *suffix) {
1202 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1205 int readlink_malloc(const char *p, char **r) {
1215 if (!(c = new(char, l)))
1218 if ((n = readlink(p, c, l-1)) < 0) {
1224 if ((size_t) n < l-1) {
1235 int readlink_and_make_absolute(const char *p, char **r) {
1242 if ((j = readlink_malloc(p, &target)) < 0)
1245 k = file_in_same_dir(p, target);
1255 int readlink_and_canonicalize(const char *p, char **r) {
1262 j = readlink_and_make_absolute(p, &t);
1266 s = canonicalize_file_name(t);
1273 path_kill_slashes(*r);
1278 int parent_of_path(const char *path, char **_r) {
1279 const char *e, *a = NULL, *b = NULL, *p;
1289 for (e = path; *e; e++) {
1291 if (!slash && *e == '/') {
1295 } else if (slash && *e != '/')
1310 r = strndup(path, p-path);
1320 char *file_name_from_path(const char *p) {
1325 if ((r = strrchr(p, '/')))
1331 bool path_is_absolute(const char *p) {
1337 bool is_path(const char *p) {
1339 return !!strchr(p, '/');
1342 char *path_make_absolute(const char *p, const char *prefix) {
1345 /* Makes every item in the list an absolute path by prepending
1346 * the prefix, if specified and necessary */
1348 if (path_is_absolute(p) || !prefix)
1351 return join(prefix, "/", p, NULL);
1354 char *path_make_absolute_cwd(const char *p) {
1359 /* Similar to path_make_absolute(), but prefixes with the
1360 * current working directory. */
1362 if (path_is_absolute(p))
1365 if (!(cwd = get_current_dir_name()))
1368 r = path_make_absolute(p, cwd);
1374 char **strv_path_make_absolute_cwd(char **l) {
1377 /* Goes through every item in the string list and makes it
1378 * absolute. This works in place and won't rollback any
1379 * changes on failure. */
1381 STRV_FOREACH(s, l) {
1384 if (!(t = path_make_absolute_cwd(*s)))
1394 char **strv_path_canonicalize(char **l) {
1397 bool enomem = false;
1399 if (strv_isempty(l))
1402 /* Goes through every item in the string list and canonicalize
1403 * the path. This works in place and won't rollback any
1404 * changes on failure. */
1406 STRV_FOREACH(s, l) {
1409 t = path_make_absolute_cwd(*s);
1418 u = canonicalize_file_name(t);
1422 if (errno == ENOMEM || !errno)
1439 char **strv_path_remove_empty(char **l) {
1445 for (f = t = l; *f; f++) {
1447 if (dir_is_empty(*f) > 0) {
1459 int reset_all_signal_handlers(void) {
1462 for (sig = 1; sig < _NSIG; sig++) {
1463 struct sigaction sa;
1465 if (sig == SIGKILL || sig == SIGSTOP)
1469 sa.sa_handler = SIG_DFL;
1470 sa.sa_flags = SA_RESTART;
1472 /* On Linux the first two RT signals are reserved by
1473 * glibc, and sigaction() will return EINVAL for them. */
1474 if ((sigaction(sig, &sa, NULL) < 0))
1475 if (errno != EINVAL)
1482 char *strstrip(char *s) {
1485 /* Drops trailing whitespace. Modifies the string in
1486 * place. Returns pointer to first non-space character */
1488 s += strspn(s, WHITESPACE);
1490 for (e = strchr(s, 0); e > s; e --)
1491 if (!strchr(WHITESPACE, e[-1]))
1499 char *delete_chars(char *s, const char *bad) {
1502 /* Drops all whitespace, regardless where in the string */
1504 for (f = s, t = s; *f; f++) {
1505 if (strchr(bad, *f))
1516 bool in_charset(const char *s, const char* charset) {
1522 for (i = s; *i; i++)
1523 if (!strchr(charset, *i))
1529 char *file_in_same_dir(const char *path, const char *filename) {
1536 /* This removes the last component of path and appends
1537 * filename, unless the latter is absolute anyway or the
1540 if (path_is_absolute(filename))
1541 return strdup(filename);
1543 if (!(e = strrchr(path, '/')))
1544 return strdup(filename);
1546 k = strlen(filename);
1547 if (!(r = new(char, e-path+1+k+1)))
1550 memcpy(r, path, e-path+1);
1551 memcpy(r+(e-path)+1, filename, k+1);
1556 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1559 if (label_mkdir(path, mode) >= 0)
1560 if (chmod_and_chown(path, mode, uid, gid) < 0)
1563 if (lstat(path, &st) < 0)
1566 if ((st.st_mode & 0777) != mode ||
1569 !S_ISDIR(st.st_mode)) {
1578 int mkdir_parents(const char *path, mode_t mode) {
1583 /* Creates every parent directory in the path except the last
1586 p = path + strspn(path, "/");
1591 e = p + strcspn(p, "/");
1592 p = e + strspn(e, "/");
1594 /* Is this the last component? If so, then we're
1599 if (!(t = strndup(path, e - path)))
1602 r = label_mkdir(t, mode);
1605 if (r < 0 && errno != EEXIST)
1610 int mkdir_p(const char *path, mode_t mode) {
1615 if ((r = mkdir_parents(path, mode)) < 0)
1618 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1624 int rmdir_parents(const char *path, const char *stop) {
1633 /* Skip trailing slashes */
1634 while (l > 0 && path[l-1] == '/')
1640 /* Skip last component */
1641 while (l > 0 && path[l-1] != '/')
1644 /* Skip trailing slashes */
1645 while (l > 0 && path[l-1] == '/')
1651 if (!(t = strndup(path, l)))
1654 if (path_startswith(stop, t)) {
1663 if (errno != ENOENT)
1671 char hexchar(int x) {
1672 static const char table[16] = "0123456789abcdef";
1674 return table[x & 15];
1677 int unhexchar(char c) {
1679 if (c >= '0' && c <= '9')
1682 if (c >= 'a' && c <= 'f')
1683 return c - 'a' + 10;
1685 if (c >= 'A' && c <= 'F')
1686 return c - 'A' + 10;
1691 char octchar(int x) {
1692 return '0' + (x & 7);
1695 int unoctchar(char c) {
1697 if (c >= '0' && c <= '7')
1703 char decchar(int x) {
1704 return '0' + (x % 10);
1707 int undecchar(char c) {
1709 if (c >= '0' && c <= '9')
1715 char *cescape(const char *s) {
1721 /* Does C style string escaping. */
1723 if (!(r = new(char, strlen(s)*4 + 1)))
1726 for (f = s, t = r; *f; f++)
1772 /* For special chars we prefer octal over
1773 * hexadecimal encoding, simply because glib's
1774 * g_strescape() does the same */
1775 if ((*f < ' ') || (*f >= 127)) {
1777 *(t++) = octchar((unsigned char) *f >> 6);
1778 *(t++) = octchar((unsigned char) *f >> 3);
1779 *(t++) = octchar((unsigned char) *f);
1790 char *cunescape_length(const char *s, size_t length) {
1796 /* Undoes C style string escaping */
1798 if (!(r = new(char, length+1)))
1801 for (f = s, t = r; f < s + length; f++) {
1844 /* This is an extension of the XDG syntax files */
1849 /* hexadecimal encoding */
1852 if ((a = unhexchar(f[1])) < 0 ||
1853 (b = unhexchar(f[2])) < 0) {
1854 /* Invalid escape code, let's take it literal then */
1858 *(t++) = (char) ((a << 4) | b);
1873 /* octal encoding */
1876 if ((a = unoctchar(f[0])) < 0 ||
1877 (b = unoctchar(f[1])) < 0 ||
1878 (c = unoctchar(f[2])) < 0) {
1879 /* Invalid escape code, let's take it literal then */
1883 *(t++) = (char) ((a << 6) | (b << 3) | c);
1891 /* premature end of string.*/
1896 /* Invalid escape code, let's take it literal then */
1908 char *cunescape(const char *s) {
1909 return cunescape_length(s, strlen(s));
1912 char *xescape(const char *s, const char *bad) {
1916 /* Escapes all chars in bad, in addition to \ and all special
1917 * chars, in \xFF style escaping. May be reversed with
1920 if (!(r = new(char, strlen(s)*4+1)))
1923 for (f = s, t = r; *f; f++) {
1925 if ((*f < ' ') || (*f >= 127) ||
1926 (*f == '\\') || strchr(bad, *f)) {
1929 *(t++) = hexchar(*f >> 4);
1930 *(t++) = hexchar(*f);
1940 char *bus_path_escape(const char *s) {
1946 /* Escapes all chars that D-Bus' object path cannot deal
1947 * with. Can be reverse with bus_path_unescape() */
1949 if (!(r = new(char, strlen(s)*3+1)))
1952 for (f = s, t = r; *f; f++) {
1954 if (!(*f >= 'A' && *f <= 'Z') &&
1955 !(*f >= 'a' && *f <= 'z') &&
1956 !(*f >= '0' && *f <= '9')) {
1958 *(t++) = hexchar(*f >> 4);
1959 *(t++) = hexchar(*f);
1969 char *bus_path_unescape(const char *f) {
1974 if (!(r = strdup(f)))
1977 for (t = r; *f; f++) {
1982 if ((a = unhexchar(f[1])) < 0 ||
1983 (b = unhexchar(f[2])) < 0) {
1984 /* Invalid escape code, let's take it literal then */
1987 *(t++) = (char) ((a << 4) | b);
1999 char *path_kill_slashes(char *path) {
2003 /* Removes redundant inner and trailing slashes. Modifies the
2004 * passed string in-place.
2006 * ///foo///bar/ becomes /foo/bar
2009 for (f = path, t = path; *f; f++) {
2024 /* Special rule, if we are talking of the root directory, a
2025 trailing slash is good */
2027 if (t == path && slash)
2034 bool path_startswith(const char *path, const char *prefix) {
2038 if ((path[0] == '/') != (prefix[0] == '/'))
2044 path += strspn(path, "/");
2045 prefix += strspn(prefix, "/");
2053 a = strcspn(path, "/");
2054 b = strcspn(prefix, "/");
2059 if (memcmp(path, prefix, a) != 0)
2067 bool path_equal(const char *a, const char *b) {
2071 if ((a[0] == '/') != (b[0] == '/'))
2077 a += strspn(a, "/");
2078 b += strspn(b, "/");
2080 if (*a == 0 && *b == 0)
2083 if (*a == 0 || *b == 0)
2086 j = strcspn(a, "/");
2087 k = strcspn(b, "/");
2092 if (memcmp(a, b, j) != 0)
2100 char *ascii_strlower(char *t) {
2105 for (p = t; *p; p++)
2106 if (*p >= 'A' && *p <= 'Z')
2107 *p = *p - 'A' + 'a';
2112 bool ignore_file(const char *filename) {
2116 filename[0] == '.' ||
2117 streq(filename, "lost+found") ||
2118 streq(filename, "aquota.user") ||
2119 streq(filename, "aquota.group") ||
2120 endswith(filename, "~") ||
2121 endswith(filename, ".rpmnew") ||
2122 endswith(filename, ".rpmsave") ||
2123 endswith(filename, ".rpmorig") ||
2124 endswith(filename, ".dpkg-old") ||
2125 endswith(filename, ".dpkg-new") ||
2126 endswith(filename, ".swp");
2129 int fd_nonblock(int fd, bool nonblock) {
2134 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2138 flags |= O_NONBLOCK;
2140 flags &= ~O_NONBLOCK;
2142 if (fcntl(fd, F_SETFL, flags) < 0)
2148 int fd_cloexec(int fd, bool cloexec) {
2153 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2157 flags |= FD_CLOEXEC;
2159 flags &= ~FD_CLOEXEC;
2161 if (fcntl(fd, F_SETFD, flags) < 0)
2167 int close_all_fds(const int except[], unsigned n_except) {
2172 if (!(d = opendir("/proc/self/fd")))
2175 while ((de = readdir(d))) {
2178 if (ignore_file(de->d_name))
2181 if (safe_atoi(de->d_name, &fd) < 0)
2182 /* Let's better ignore this, just in case */
2196 for (i = 0; i < n_except; i++)
2197 if (except[i] == fd) {
2206 if (close_nointr(fd) < 0) {
2207 /* Valgrind has its own FD and doesn't want to have it closed */
2208 if (errno != EBADF && r == 0)
2217 bool chars_intersect(const char *a, const char *b) {
2220 /* Returns true if any of the chars in a are in b. */
2221 for (p = a; *p; p++)
2228 char *format_timestamp(char *buf, size_t l, usec_t t) {
2238 sec = (time_t) (t / USEC_PER_SEC);
2240 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2246 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2249 n = now(CLOCK_REALTIME);
2251 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2256 if (d >= USEC_PER_YEAR)
2257 snprintf(buf, l, "%llu years and %llu months ago",
2258 (unsigned long long) (d / USEC_PER_YEAR),
2259 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2260 else if (d >= USEC_PER_MONTH)
2261 snprintf(buf, l, "%llu months and %llu days ago",
2262 (unsigned long long) (d / USEC_PER_MONTH),
2263 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2264 else if (d >= USEC_PER_WEEK)
2265 snprintf(buf, l, "%llu weeks and %llu days ago",
2266 (unsigned long long) (d / USEC_PER_WEEK),
2267 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2268 else if (d >= 2*USEC_PER_DAY)
2269 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2270 else if (d >= 25*USEC_PER_HOUR)
2271 snprintf(buf, l, "1 day and %lluh ago",
2272 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2273 else if (d >= 6*USEC_PER_HOUR)
2274 snprintf(buf, l, "%lluh ago",
2275 (unsigned long long) (d / USEC_PER_HOUR));
2276 else if (d >= USEC_PER_HOUR)
2277 snprintf(buf, l, "%lluh %llumin ago",
2278 (unsigned long long) (d / USEC_PER_HOUR),
2279 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2280 else if (d >= 5*USEC_PER_MINUTE)
2281 snprintf(buf, l, "%llumin ago",
2282 (unsigned long long) (d / USEC_PER_MINUTE));
2283 else if (d >= USEC_PER_MINUTE)
2284 snprintf(buf, l, "%llumin %llus ago",
2285 (unsigned long long) (d / USEC_PER_MINUTE),
2286 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2287 else if (d >= USEC_PER_SEC)
2288 snprintf(buf, l, "%llus ago",
2289 (unsigned long long) (d / USEC_PER_SEC));
2290 else if (d >= USEC_PER_MSEC)
2291 snprintf(buf, l, "%llums ago",
2292 (unsigned long long) (d / USEC_PER_MSEC));
2294 snprintf(buf, l, "%lluus ago",
2295 (unsigned long long) d);
2297 snprintf(buf, l, "now");
2303 char *format_timespan(char *buf, size_t l, usec_t t) {
2304 static const struct {
2308 { "w", USEC_PER_WEEK },
2309 { "d", USEC_PER_DAY },
2310 { "h", USEC_PER_HOUR },
2311 { "min", USEC_PER_MINUTE },
2312 { "s", USEC_PER_SEC },
2313 { "ms", USEC_PER_MSEC },
2323 if (t == (usec_t) -1)
2327 snprintf(p, l, "0");
2332 /* The result of this function can be parsed with parse_usec */
2334 for (i = 0; i < ELEMENTSOF(table); i++) {
2338 if (t < table[i].usec)
2344 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2345 n = MIN((size_t) k, l);
2358 bool fstype_is_network(const char *fstype) {
2359 static const char * const table[] = {
2371 for (i = 0; i < ELEMENTSOF(table); i++)
2372 if (streq(table[i], fstype))
2381 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2386 TIOCL_GETKMSGREDIRECT,
2390 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2395 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2398 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2402 close_nointr_nofail(fd);
2406 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2407 struct termios old_termios, new_termios;
2409 char line[LINE_MAX];
2414 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2415 new_termios = old_termios;
2417 new_termios.c_lflag &= ~ICANON;
2418 new_termios.c_cc[VMIN] = 1;
2419 new_termios.c_cc[VTIME] = 0;
2421 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2424 k = fread(&c, 1, 1, f);
2426 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2432 *need_nl = c != '\n';
2439 if (!(fgets(line, sizeof(line), f)))
2444 if (strlen(line) != 1)
2454 int ask(char *ret, const char *replies, const char *text, ...) {
2461 on_tty = isatty(STDOUT_FILENO);
2467 bool need_nl = true;
2470 fputs(ANSI_HIGHLIGHT_ON, stdout);
2477 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2481 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2483 if (r == -EBADMSG) {
2484 puts("Bad input, please try again.");
2495 if (strchr(replies, c)) {
2500 puts("Read unexpected character, please try again.");
2504 int reset_terminal_fd(int fd) {
2505 struct termios termios;
2508 /* Set terminal to some sane defaults */
2512 /* We leave locked terminal attributes untouched, so that
2513 * Plymouth may set whatever it wants to set, and we don't
2514 * interfere with that. */
2516 /* Disable exclusive mode, just in case */
2517 ioctl(fd, TIOCNXCL);
2519 /* Switch to text mode */
2520 ioctl(fd, KDSETMODE, KD_TEXT);
2522 /* Enable console unicode mode */
2523 ioctl(fd, KDSKBMODE, K_UNICODE);
2525 if (tcgetattr(fd, &termios) < 0) {
2530 /* We only reset the stuff that matters to the software. How
2531 * hardware is set up we don't touch assuming that somebody
2532 * else will do that for us */
2534 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2535 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2536 termios.c_oflag |= ONLCR;
2537 termios.c_cflag |= CREAD;
2538 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2540 termios.c_cc[VINTR] = 03; /* ^C */
2541 termios.c_cc[VQUIT] = 034; /* ^\ */
2542 termios.c_cc[VERASE] = 0177;
2543 termios.c_cc[VKILL] = 025; /* ^X */
2544 termios.c_cc[VEOF] = 04; /* ^D */
2545 termios.c_cc[VSTART] = 021; /* ^Q */
2546 termios.c_cc[VSTOP] = 023; /* ^S */
2547 termios.c_cc[VSUSP] = 032; /* ^Z */
2548 termios.c_cc[VLNEXT] = 026; /* ^V */
2549 termios.c_cc[VWERASE] = 027; /* ^W */
2550 termios.c_cc[VREPRINT] = 022; /* ^R */
2551 termios.c_cc[VEOL] = 0;
2552 termios.c_cc[VEOL2] = 0;
2554 termios.c_cc[VTIME] = 0;
2555 termios.c_cc[VMIN] = 1;
2557 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2561 /* Just in case, flush all crap out */
2562 tcflush(fd, TCIOFLUSH);
2567 int reset_terminal(const char *name) {
2570 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2574 r = reset_terminal_fd(fd);
2575 close_nointr_nofail(fd);
2580 int open_terminal(const char *name, int mode) {
2585 * If a TTY is in the process of being closed opening it might
2586 * cause EIO. This is horribly awful, but unlikely to be
2587 * changed in the kernel. Hence we work around this problem by
2588 * retrying a couple of times.
2590 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2594 if ((fd = open(name, mode)) >= 0)
2603 usleep(50 * USEC_PER_MSEC);
2610 if ((r = isatty(fd)) < 0) {
2611 close_nointr_nofail(fd);
2616 close_nointr_nofail(fd);
2623 int flush_fd(int fd) {
2624 struct pollfd pollfd;
2628 pollfd.events = POLLIN;
2635 if ((r = poll(&pollfd, 1, 0)) < 0) {
2646 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2651 if (errno == EAGAIN)
2662 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2663 int fd = -1, notify = -1, r, wd = -1;
2667 /* We use inotify to be notified when the tty is closed. We
2668 * create the watch before checking if we can actually acquire
2669 * it, so that we don't lose any event.
2671 * Note: strictly speaking this actually watches for the
2672 * device being closed, it does *not* really watch whether a
2673 * tty loses its controlling process. However, unless some
2674 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2675 * its tty otherwise this will not become a problem. As long
2676 * as the administrator makes sure not configure any service
2677 * on the same tty as an untrusted user this should not be a
2678 * problem. (Which he probably should not do anyway.) */
2680 if (!fail && !force) {
2681 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2686 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2694 if ((r = flush_fd(notify)) < 0)
2697 /* We pass here O_NOCTTY only so that we can check the return
2698 * value TIOCSCTTY and have a reliable way to figure out if we
2699 * successfully became the controlling process of the tty */
2700 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2703 /* First, try to get the tty */
2704 r = ioctl(fd, TIOCSCTTY, force);
2706 /* Sometimes it makes sense to ignore TIOCSCTTY
2707 * returning EPERM, i.e. when very likely we already
2708 * are have this controlling terminal. */
2709 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2712 if (r < 0 && (force || fail || errno != EPERM)) {
2722 assert(notify >= 0);
2725 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2727 struct inotify_event *e;
2729 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2738 e = (struct inotify_event*) inotify_buffer;
2743 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2748 step = sizeof(struct inotify_event) + e->len;
2749 assert(step <= (size_t) l);
2751 e = (struct inotify_event*) ((uint8_t*) e + step);
2758 /* We close the tty fd here since if the old session
2759 * ended our handle will be dead. It's important that
2760 * we do this after sleeping, so that we don't enter
2761 * an endless loop. */
2762 close_nointr_nofail(fd);
2766 close_nointr_nofail(notify);
2768 if ((r = reset_terminal_fd(fd)) < 0)
2769 log_warning("Failed to reset terminal: %s", strerror(-r));
2775 close_nointr_nofail(fd);
2778 close_nointr_nofail(notify);
2783 int release_terminal(void) {
2785 struct sigaction sa_old, sa_new;
2787 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2790 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2791 * by our own TIOCNOTTY */
2794 sa_new.sa_handler = SIG_IGN;
2795 sa_new.sa_flags = SA_RESTART;
2796 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2798 if (ioctl(fd, TIOCNOTTY) < 0)
2801 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2803 close_nointr_nofail(fd);
2807 int sigaction_many(const struct sigaction *sa, ...) {
2812 while ((sig = va_arg(ap, int)) > 0)
2813 if (sigaction(sig, sa, NULL) < 0)
2820 int ignore_signals(int sig, ...) {
2821 struct sigaction sa;
2826 sa.sa_handler = SIG_IGN;
2827 sa.sa_flags = SA_RESTART;
2829 if (sigaction(sig, &sa, NULL) < 0)
2833 while ((sig = va_arg(ap, int)) > 0)
2834 if (sigaction(sig, &sa, NULL) < 0)
2841 int default_signals(int sig, ...) {
2842 struct sigaction sa;
2847 sa.sa_handler = SIG_DFL;
2848 sa.sa_flags = SA_RESTART;
2850 if (sigaction(sig, &sa, NULL) < 0)
2854 while ((sig = va_arg(ap, int)) > 0)
2855 if (sigaction(sig, &sa, NULL) < 0)
2862 int close_pipe(int p[]) {
2868 a = close_nointr(p[0]);
2873 b = close_nointr(p[1]);
2877 return a < 0 ? a : b;
2880 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2889 while (nbytes > 0) {
2892 if ((k = read(fd, p, nbytes)) <= 0) {
2894 if (k < 0 && errno == EINTR)
2897 if (k < 0 && errno == EAGAIN && do_poll) {
2898 struct pollfd pollfd;
2902 pollfd.events = POLLIN;
2904 if (poll(&pollfd, 1, -1) < 0) {
2908 return n > 0 ? n : -errno;
2911 if (pollfd.revents != POLLIN)
2912 return n > 0 ? n : -EIO;
2917 return n > 0 ? n : (k < 0 ? -errno : 0);
2928 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2937 while (nbytes > 0) {
2940 k = write(fd, p, nbytes);
2943 if (k < 0 && errno == EINTR)
2946 if (k < 0 && errno == EAGAIN && do_poll) {
2947 struct pollfd pollfd;
2951 pollfd.events = POLLOUT;
2953 if (poll(&pollfd, 1, -1) < 0) {
2957 return n > 0 ? n : -errno;
2960 if (pollfd.revents != POLLOUT)
2961 return n > 0 ? n : -EIO;
2966 return n > 0 ? n : (k < 0 ? -errno : 0);
2977 int path_is_mount_point(const char *t, bool allow_symlink) {
2988 if (errno == ENOENT)
2994 r = parent_of_path(t, &parent);
2998 r = lstat(parent, &b);
3004 return a.st_dev != b.st_dev;
3007 int parse_usec(const char *t, usec_t *usec) {
3008 static const struct {
3012 { "sec", USEC_PER_SEC },
3013 { "s", USEC_PER_SEC },
3014 { "min", USEC_PER_MINUTE },
3015 { "hr", USEC_PER_HOUR },
3016 { "h", USEC_PER_HOUR },
3017 { "d", USEC_PER_DAY },
3018 { "w", USEC_PER_WEEK },
3019 { "msec", USEC_PER_MSEC },
3020 { "ms", USEC_PER_MSEC },
3021 { "m", USEC_PER_MINUTE },
3024 { "", USEC_PER_SEC },
3040 l = strtoll(p, &e, 10);
3051 e += strspn(e, WHITESPACE);
3053 for (i = 0; i < ELEMENTSOF(table); i++)
3054 if (startswith(e, table[i].suffix)) {
3055 r += (usec_t) l * table[i].usec;
3056 p = e + strlen(table[i].suffix);
3060 if (i >= ELEMENTSOF(table))
3070 int parse_bytes(const char *t, off_t *bytes) {
3071 static const struct {
3077 { "M", 1024ULL*1024ULL },
3078 { "G", 1024ULL*1024ULL*1024ULL },
3079 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3080 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3081 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3098 l = strtoll(p, &e, 10);
3109 e += strspn(e, WHITESPACE);
3111 for (i = 0; i < ELEMENTSOF(table); i++)
3112 if (startswith(e, table[i].suffix)) {
3113 r += (off_t) l * table[i].factor;
3114 p = e + strlen(table[i].suffix);
3118 if (i >= ELEMENTSOF(table))
3128 int make_stdio(int fd) {
3133 r = dup2(fd, STDIN_FILENO);
3134 s = dup2(fd, STDOUT_FILENO);
3135 t = dup2(fd, STDERR_FILENO);
3138 close_nointr_nofail(fd);
3140 if (r < 0 || s < 0 || t < 0)
3143 fd_cloexec(STDIN_FILENO, false);
3144 fd_cloexec(STDOUT_FILENO, false);
3145 fd_cloexec(STDERR_FILENO, false);
3150 int make_null_stdio(void) {
3153 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3156 return make_stdio(null_fd);
3159 bool is_device_path(const char *path) {
3161 /* Returns true on paths that refer to a device, either in
3162 * sysfs or in /dev */
3165 path_startswith(path, "/dev/") ||
3166 path_startswith(path, "/sys/");
3169 int dir_is_empty(const char *path) {
3172 struct dirent buf, *de;
3174 if (!(d = opendir(path)))
3178 if ((r = readdir_r(d, &buf, &de)) > 0) {
3188 if (!ignore_file(de->d_name)) {
3198 unsigned long long random_ull(void) {
3203 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3206 r = loop_read(fd, &ull, sizeof(ull), true);
3207 close_nointr_nofail(fd);
3209 if (r != sizeof(ull))
3215 return random() * RAND_MAX + random();
3218 void rename_process(const char name[8]) {
3221 prctl(PR_SET_NAME, name);
3223 /* This is a like a poor man's setproctitle(). The string
3224 * passed should fit in 7 chars (i.e. the length of
3227 if (program_invocation_name)
3228 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3230 if (saved_argc > 0) {
3234 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3236 for (i = 1; i < saved_argc; i++) {
3240 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3245 void sigset_add_many(sigset_t *ss, ...) {
3252 while ((sig = va_arg(ap, int)) > 0)
3253 assert_se(sigaddset(ss, sig) == 0);
3257 char* gethostname_malloc(void) {
3260 assert_se(uname(&u) >= 0);
3263 return strdup(u.nodename);
3265 return strdup(u.sysname);
3268 char* getlogname_malloc(void) {
3272 struct passwd pwbuf, *pw = NULL;
3275 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3280 /* Shortcut things to avoid NSS lookups */
3282 return strdup("root");
3284 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3287 if (!(buf = malloc(bufsize)))
3290 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3291 name = strdup(pw->pw_name);
3298 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3304 int getttyname_malloc(int fd, char **r) {
3305 char path[PATH_MAX], *c;
3310 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3315 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3322 int getttyname_harder(int fd, char **r) {
3326 if ((k = getttyname_malloc(fd, &s)) < 0)
3329 if (streq(s, "tty")) {
3331 return get_ctty(0, NULL, r);
3338 int get_ctty_devnr(pid_t pid, dev_t *d) {
3340 char line[LINE_MAX], *p, *fn;
3341 unsigned long ttynr;
3344 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3347 f = fopen(fn, "re");
3352 if (!fgets(line, sizeof(line), f)) {
3353 k = feof(f) ? -EIO : -errno;
3360 p = strrchr(line, ')');
3370 "%*d " /* session */
3379 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3381 char fn[PATH_MAX], *s, *b, *p;
3386 k = get_ctty_devnr(pid, &devnr);
3390 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3393 if ((k = readlink_malloc(fn, &s)) < 0) {
3398 /* This is an ugly hack */
3399 if (major(devnr) == 136) {
3400 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3410 /* Probably something like the ptys which have no
3411 * symlink in /dev/char. Let's return something
3412 * vaguely useful. */
3414 if (!(b = strdup(fn + 5)))
3424 if (startswith(s, "/dev/"))
3426 else if (startswith(s, "../"))
3444 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3450 /* This returns the first error we run into, but nevertheless
3453 if (!(d = fdopendir(fd))) {
3454 close_nointr_nofail(fd);
3456 return errno == ENOENT ? 0 : -errno;
3460 struct dirent buf, *de;
3461 bool is_dir, keep_around = false;
3464 if ((r = readdir_r(d, &buf, &de)) != 0) {
3473 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3476 if (de->d_type == DT_UNKNOWN) {
3479 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3480 if (ret == 0 && errno != ENOENT)
3486 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3488 is_dir = S_ISDIR(st.st_mode);
3491 if (honour_sticky) {
3494 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3495 if (ret == 0 && errno != ENOENT)
3500 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3503 is_dir = de->d_type == DT_DIR;
3509 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3510 if (ret == 0 && errno != ENOENT)
3515 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3521 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3522 if (ret == 0 && errno != ENOENT)
3526 } else if (!only_dirs && !keep_around) {
3528 if (unlinkat(fd, de->d_name, 0) < 0) {
3529 if (ret == 0 && errno != ENOENT)
3540 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3546 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3548 if (errno != ENOTDIR)
3551 if (delete_root && !only_dirs)
3552 if (unlink(path) < 0)
3558 r = rm_rf_children(fd, only_dirs, honour_sticky);
3562 if (honour_sticky && file_is_sticky(path) > 0)
3565 if (rmdir(path) < 0 && errno != ENOENT) {
3574 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3577 /* Under the assumption that we are running privileged we
3578 * first change the access mode and only then hand out
3579 * ownership to avoid a window where access is too open. */
3581 if (chmod(path, mode) < 0)
3584 if (chown(path, uid, gid) < 0)
3590 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3593 /* Under the assumption that we are running privileged we
3594 * first change the access mode and only then hand out
3595 * ownership to avoid a window where access is too open. */
3597 if (fchmod(fd, mode) < 0)
3600 if (fchown(fd, uid, gid) < 0)
3606 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3610 /* Allocates the cpuset in the right size */
3613 if (!(r = CPU_ALLOC(n)))
3616 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3617 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3627 if (errno != EINVAL)
3634 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3635 char *s = NULL, *spaces = NULL, *e;
3637 size_t emax, sl, left;
3638 struct iovec iovec[5];
3643 /* This independent of logging, as status messages are
3644 * optional and go exclusively to the console. */
3646 if (vasprintf(&s, format, ap) < 0)
3649 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3659 sl = 2 + 6 + 1; /* " [" status "]" */
3660 emax = (size_t) c > sl ? c - sl - 1 : 0;
3664 e = ellipsize(s, emax, 75);
3672 IOVEC_SET_STRING(iovec[n++], s);
3676 left = emax > sl ? emax - sl : 0;
3678 spaces = malloc(left);
3680 memset(spaces, ' ', left);
3681 iovec[n].iov_base = spaces;
3682 iovec[n].iov_len = left;
3689 IOVEC_SET_STRING(iovec[n++], " [");
3690 IOVEC_SET_STRING(iovec[n++], status);
3691 IOVEC_SET_STRING(iovec[n++], "]\n");
3693 IOVEC_SET_STRING(iovec[n++], "\n");
3695 writev(fd, iovec, n);
3702 close_nointr_nofail(fd);
3705 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3710 va_start(ap, format);
3711 status_vprintf(status, ellipse, format, ap);
3715 void status_welcome(void) {
3716 char *pretty_name = NULL, *ansi_color = NULL;
3717 const char *const_pretty = NULL, *const_color = NULL;
3720 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3721 "PRETTY_NAME", &pretty_name,
3722 "ANSI_COLOR", &ansi_color,
3726 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3729 #if defined(TARGET_FEDORA)
3731 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3734 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3738 if (!ansi_color && pretty_name) {
3740 /* This tries to mimic the color magic the old Red Hat sysinit
3743 if (startswith(pretty_name, "Red Hat"))
3744 const_color = "0;31"; /* Red for RHEL */
3745 else if (startswith(pretty_name, "Fedora"))
3746 const_color = "0;34"; /* Blue for Fedora */
3749 #elif defined(TARGET_SUSE)
3752 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3755 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3760 const_color = "0;32"; /* Green for openSUSE */
3762 #elif defined(TARGET_GENTOO)
3765 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3768 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3773 const_color = "1;34"; /* Light Blue for Gentoo */
3775 #elif defined(TARGET_ALTLINUX)
3778 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3781 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3786 const_color = "0;36"; /* Cyan for ALTLinux */
3789 #elif defined(TARGET_DEBIAN)
3794 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3797 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3799 pretty_name = strappend("Debian ", version);
3803 log_warning("Failed to allocate Debian version string.");
3808 const_color = "1;31"; /* Light Red for Debian */
3810 #elif defined(TARGET_UBUNTU)
3812 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3813 "DISTRIB_DESCRIPTION", &pretty_name,
3817 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3821 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3823 #elif defined(TARGET_MANDRIVA)
3828 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3830 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3832 p = strstr(s, " release ");
3836 p[strcspn(p, " ")] = '\0';
3838 /* This corresponds to standard rc.sysinit */
3839 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3840 const_color = "1;36";
3842 log_warning("Failed to allocate Mandriva version string.");
3844 log_warning("Failed to parse /etc/mandriva-release");
3848 #elif defined(TARGET_MEEGO)
3851 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3854 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3859 const_color = "1;35"; /* Bright Magenta for MeeGo */
3862 if (!pretty_name && !const_pretty)
3863 const_pretty = "Linux";
3865 if (!ansi_color && !const_color)
3870 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3871 const_color ? const_color : ansi_color,
3872 const_pretty ? const_pretty : pretty_name);
3878 char *replace_env(const char *format, char **env) {
3885 const char *e, *word = format;
3890 for (e = format; *e; e ++) {
3901 if (!(k = strnappend(r, word, e-word-1)))
3910 } else if (*e == '$') {
3911 if (!(k = strnappend(r, word, e-word)))
3927 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3930 if (!(k = strappend(r, t)))
3943 if (!(k = strnappend(r, word, e-word)))
3954 char **replace_env_argv(char **argv, char **env) {
3956 unsigned k = 0, l = 0;
3958 l = strv_length(argv);
3960 if (!(r = new(char*, l+1)))
3963 STRV_FOREACH(i, argv) {
3965 /* If $FOO appears as single word, replace it by the split up variable */
3966 if ((*i)[0] == '$' && (*i)[1] != '{') {
3971 if ((e = strv_env_get(env, *i+1))) {
3973 if (!(m = strv_split_quoted(e))) {
3984 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3993 memcpy(r + k, m, q * sizeof(char*));
4001 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
4002 if (!(r[k++] = replace_env(*i, env))) {
4012 int fd_columns(int fd) {
4016 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4025 unsigned columns(void) {
4026 static __thread int parsed_columns = 0;
4029 if (_likely_(parsed_columns > 0))
4030 return parsed_columns;
4032 e = getenv("COLUMNS");
4034 parsed_columns = atoi(e);
4036 if (parsed_columns <= 0)
4037 parsed_columns = fd_columns(STDOUT_FILENO);
4039 if (parsed_columns <= 0)
4040 parsed_columns = 80;
4042 return parsed_columns;
4045 int running_in_chroot(void) {
4051 /* Only works as root */
4053 if (stat("/proc/1/root", &a) < 0)
4056 if (stat("/", &b) < 0)
4060 a.st_dev != b.st_dev ||
4061 a.st_ino != b.st_ino;
4064 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4069 assert(percent <= 100);
4070 assert(new_length >= 3);
4072 if (old_length <= 3 || old_length <= new_length)
4073 return strndup(s, old_length);
4075 r = new0(char, new_length+1);
4079 x = (new_length * percent) / 100;
4081 if (x > new_length - 3)
4089 s + old_length - (new_length - x - 3),
4090 new_length - x - 3);
4095 char *ellipsize(const char *s, size_t length, unsigned percent) {
4096 return ellipsize_mem(s, strlen(s), length, percent);
4099 int touch(const char *path) {
4104 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4107 close_nointr_nofail(fd);
4111 char *unquote(const char *s, const char* quotes) {
4115 if ((l = strlen(s)) < 2)
4118 if (strchr(quotes, s[0]) && s[l-1] == s[0])
4119 return strndup(s+1, l-2);
4124 char *normalize_env_assignment(const char *s) {
4125 char *name, *value, *p, *r;
4130 if (!(r = strdup(s)))
4136 if (!(name = strndup(s, p - s)))
4139 if (!(p = strdup(p+1))) {
4144 value = unquote(strstrip(p), QUOTES);
4152 if (asprintf(&r, "%s=%s", name, value) < 0)
4161 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4172 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4184 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4191 if ((r = wait_for_terminate(pid, &status)) < 0) {
4192 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4196 if (status.si_code == CLD_EXITED) {
4197 if (status.si_status != 0) {
4198 log_warning("%s failed with error code %i.", name, status.si_status);
4199 return status.si_status;
4202 log_debug("%s succeeded.", name);
4205 } else if (status.si_code == CLD_KILLED ||
4206 status.si_code == CLD_DUMPED) {
4208 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4212 log_warning("%s failed due to unknown reason.", name);
4219 /* Make sure nobody waits for us on a socket anymore */
4220 close_all_fds(NULL, 0);
4228 bool null_or_empty(struct stat *st) {
4231 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4234 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4240 int null_or_empty_path(const char *fn) {
4245 if (stat(fn, &st) < 0)
4248 return null_or_empty(&st);
4251 DIR *xopendirat(int fd, const char *name, int flags) {
4255 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4258 if (!(d = fdopendir(nfd))) {
4259 close_nointr_nofail(nfd);
4266 int signal_from_string_try_harder(const char *s) {
4270 if ((signo = signal_from_string(s)) <= 0)
4271 if (startswith(s, "SIG"))
4272 return signal_from_string(s+3);
4277 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4283 if (!dual_timestamp_is_set(t))
4286 fprintf(f, "%s=%llu %llu\n",
4288 (unsigned long long) t->realtime,
4289 (unsigned long long) t->monotonic);
4292 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4293 unsigned long long a, b;
4298 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4299 log_debug("Failed to parse finish timestamp value %s", value);
4306 char *fstab_node_to_udev_node(const char *p) {
4310 /* FIXME: to follow udev's logic 100% we need to leave valid
4311 * UTF8 chars unescaped */
4313 if (startswith(p, "LABEL=")) {
4315 if (!(u = unquote(p+6, "\"\'")))
4318 t = xescape(u, "/ ");
4324 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4333 if (startswith(p, "UUID=")) {
4335 if (!(u = unquote(p+5, "\"\'")))
4338 t = xescape(u, "/ ");
4344 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4356 void filter_environ(const char *prefix) {
4363 for (i = 0, j = 0; environ[i]; i++) {
4365 if (startswith(environ[i], prefix))
4368 environ[j++] = environ[i];
4374 bool tty_is_vc(const char *tty) {
4377 if (startswith(tty, "/dev/"))
4380 return vtnr_from_tty(tty) >= 0;
4383 int vtnr_from_tty(const char *tty) {
4388 if (startswith(tty, "/dev/"))
4391 if (!startswith(tty, "tty") )
4394 if (tty[3] < '0' || tty[3] > '9')
4397 r = safe_atoi(tty+3, &i);
4401 if (i < 0 || i > 63)
4407 bool tty_is_vc_resolve(const char *tty) {
4408 char *active = NULL;
4413 if (startswith(tty, "/dev/"))
4416 /* Resolve where /dev/console is pointing to */
4417 if (streq(tty, "console"))
4418 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4419 /* If multiple log outputs are configured the
4420 * last one is what /dev/console points to */
4421 tty = strrchr(active, ' ');
4434 const char *default_term_for_tty(const char *tty) {
4437 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4440 bool dirent_is_file(const struct dirent *de) {
4443 if (ignore_file(de->d_name))
4446 if (de->d_type != DT_REG &&
4447 de->d_type != DT_LNK &&
4448 de->d_type != DT_UNKNOWN)
4454 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4457 if (!dirent_is_file(de))
4460 return endswith(de->d_name, suffix);
4463 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4466 Hashmap *pids = NULL;
4470 /* Executes all binaries in a directory in parallel and waits
4471 * until all they all finished. */
4474 if (!(_d = opendir(directory))) {
4476 if (errno == ENOENT)
4479 log_error("Failed to enumerate directory %s: %m", directory);
4486 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4487 log_error("Failed to allocate set.");
4491 while ((de = readdir(d))) {
4496 if (!dirent_is_file(de))
4499 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4500 log_error("Out of memory");
4504 if ((pid = fork()) < 0) {
4505 log_error("Failed to fork: %m");
4524 log_error("Failed to execute %s: %m", path);
4525 _exit(EXIT_FAILURE);
4528 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4530 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4531 log_error("Failed to add PID to set: %s", strerror(-k));
4536 while (!hashmap_isempty(pids)) {
4541 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4546 log_error("waitid() failed: %m");
4550 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4551 if (!is_clean_exit(si.si_code, si.si_status)) {
4552 if (si.si_code == CLD_EXITED)
4553 log_error("%s exited with exit status %i.", path, si.si_status);
4555 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4557 log_debug("%s exited successfully.", path);
4568 hashmap_free_free(pids);
4571 int kill_and_sigcont(pid_t pid, int sig) {
4574 r = kill(pid, sig) < 0 ? -errno : 0;
4582 bool nulstr_contains(const char*nulstr, const char *needle) {
4588 NULSTR_FOREACH(i, nulstr)
4589 if (streq(i, needle))
4595 bool plymouth_running(void) {
4596 return access("/run/plymouth/pid", F_OK) >= 0;
4599 void parse_syslog_priority(char **p, int *priority) {
4600 int a = 0, b = 0, c = 0;
4610 if (!strchr(*p, '>'))
4613 if ((*p)[2] == '>') {
4614 c = undecchar((*p)[1]);
4616 } else if ((*p)[3] == '>') {
4617 b = undecchar((*p)[1]);
4618 c = undecchar((*p)[2]);
4620 } else if ((*p)[4] == '>') {
4621 a = undecchar((*p)[1]);
4622 b = undecchar((*p)[2]);
4623 c = undecchar((*p)[3]);
4628 if (a < 0 || b < 0 || c < 0)
4631 *priority = a*100+b*10+c;
4635 void skip_syslog_pid(char **buf) {
4647 p += strspn(p, "0123456789");
4657 void skip_syslog_date(char **buf) {
4665 LETTER, LETTER, LETTER,
4667 SPACE_OR_NUMBER, NUMBER,
4669 SPACE_OR_NUMBER, NUMBER,
4671 SPACE_OR_NUMBER, NUMBER,
4673 SPACE_OR_NUMBER, NUMBER,
4685 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4690 switch (sequence[i]) {
4697 case SPACE_OR_NUMBER:
4704 if (*p < '0' || *p > '9')
4710 if (!(*p >= 'A' && *p <= 'Z') &&
4711 !(*p >= 'a' && *p <= 'z'))
4727 int have_effective_cap(int value) {
4729 cap_flag_value_t fv;
4732 if (!(cap = cap_get_proc()))
4735 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4744 char* strshorten(char *s, size_t l) {
4753 static bool hostname_valid_char(char c) {
4755 (c >= 'a' && c <= 'z') ||
4756 (c >= 'A' && c <= 'Z') ||
4757 (c >= '0' && c <= '9') ||
4763 bool hostname_is_valid(const char *s) {
4769 for (p = s; *p; p++)
4770 if (!hostname_valid_char(*p))
4773 if (p-s > HOST_NAME_MAX)
4779 char* hostname_cleanup(char *s) {
4782 for (p = s, d = s; *p; p++)
4783 if ((*p >= 'a' && *p <= 'z') ||
4784 (*p >= 'A' && *p <= 'Z') ||
4785 (*p >= '0' && *p <= '9') ||
4793 strshorten(s, HOST_NAME_MAX);
4797 int pipe_eof(int fd) {
4798 struct pollfd pollfd;
4803 pollfd.events = POLLIN|POLLHUP;
4805 r = poll(&pollfd, 1, 0);
4812 return pollfd.revents & POLLHUP;
4815 int fd_wait_for_event(int fd, int event) {
4816 struct pollfd pollfd;
4821 pollfd.events = event;
4823 r = poll(&pollfd, 1, -1);
4830 return pollfd.revents;
4833 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4844 t = new(char, strlen(path) + 1 + 6 + 1);
4848 fn = file_name_from_path(path);
4852 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4854 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4860 f = fdopen(fd, "we");
4873 int terminal_vhangup_fd(int fd) {
4876 if (ioctl(fd, TIOCVHANGUP) < 0)
4882 int terminal_vhangup(const char *name) {
4885 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4889 r = terminal_vhangup_fd(fd);
4890 close_nointr_nofail(fd);
4895 int vt_disallocate(const char *name) {
4899 /* Deallocate the VT if possible. If not possible
4900 * (i.e. because it is the active one), at least clear it
4901 * entirely (including the scrollback buffer) */
4903 if (!startswith(name, "/dev/"))
4906 if (!tty_is_vc(name)) {
4907 /* So this is not a VT. I guess we cannot deallocate
4908 * it then. But let's at least clear the screen */
4910 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4915 "\033[r" /* clear scrolling region */
4916 "\033[H" /* move home */
4917 "\033[2J", /* clear screen */
4919 close_nointr_nofail(fd);
4924 if (!startswith(name, "/dev/tty"))
4927 r = safe_atou(name+8, &u);
4934 /* Try to deallocate */
4935 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4939 r = ioctl(fd, VT_DISALLOCATE, u);
4940 close_nointr_nofail(fd);
4948 /* Couldn't deallocate, so let's clear it fully with
4950 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4955 "\033[r" /* clear scrolling region */
4956 "\033[H" /* move home */
4957 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4959 close_nointr_nofail(fd);
4964 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4966 struct dirent buffer, *de;
4969 dir = opendir(path);
4971 if (errno == ENOENT)
4980 k = readdir_r(dir, &buffer, &de);
4989 if (!dirent_is_file_with_suffix(de, suffix))
4992 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4997 f = canonicalize_file_name(p);
4999 log_error("Failed to canonicalize file name '%s': %m", p);
5005 log_debug("found: %s\n", f);
5006 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5015 static int base_cmp(const void *a, const void *b) {
5016 const char *s1, *s2;
5018 s1 = *(char * const *)a;
5019 s2 = *(char * const *)b;
5020 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5023 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5026 char **files = NULL;
5032 dirs = strv_new_ap(dir, ap);
5038 if (!strv_path_canonicalize(dirs)) {
5042 if (!strv_uniq(dirs)) {
5047 fh = hashmap_new(string_hash_func, string_compare_func);
5053 STRV_FOREACH(p, dirs) {
5054 if (files_add(fh, *p, suffix) < 0) {
5055 log_error("Failed to search for files.");
5061 files = hashmap_get_strv(fh);
5062 if (files == NULL) {
5063 log_error("Failed to compose list of files.");
5068 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5077 int hwclock_is_localtime(void) {
5082 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5088 f = fopen("/etc/adjtime", "re");
5090 char line[LINE_MAX];
5093 b = fgets(line, sizeof(line), f) &&
5094 fgets(line, sizeof(line), f) &&
5095 fgets(line, sizeof(line), f);
5104 local = streq(line, "LOCAL");
5106 } else if (errno != -ENOENT)
5112 int hwclock_apply_localtime_delta(int *min) {
5113 const struct timeval *tv_null = NULL;
5119 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5120 assert_se(tm = localtime(&ts.tv_sec));
5121 minuteswest = tm->tm_gmtoff / 60;
5123 tz.tz_minuteswest = -minuteswest;
5124 tz.tz_dsttime = 0; /* DST_NONE*/
5127 * If the hardware clock does not run in UTC, but in local time:
5128 * The very first time we set the kernel's timezone, it will warp
5129 * the clock so that it runs in UTC instead of local time.
5131 if (settimeofday(tv_null, &tz) < 0)
5138 int hwclock_reset_localtime_delta(void) {
5139 const struct timeval *tv_null = NULL;
5142 tz.tz_minuteswest = 0;
5143 tz.tz_dsttime = 0; /* DST_NONE*/
5145 if (settimeofday(tv_null, &tz) < 0)
5151 int hwclock_get_time(struct tm *tm) {
5157 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5161 /* This leaves the timezone fields of struct tm
5163 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5166 /* We don't now daylight saving, so we reset this in order not
5167 * to confused mktime(). */
5170 close_nointr_nofail(fd);
5175 int hwclock_set_time(const struct tm *tm) {
5181 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5185 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5188 close_nointr_nofail(fd);
5193 int copy_file(const char *from, const char *to) {
5199 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5203 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5205 close_nointr_nofail(fdf);
5213 n = read(fdf, buf, sizeof(buf));
5217 close_nointr_nofail(fdf);
5228 k = loop_write(fdt, buf, n, false);
5230 r = k < 0 ? k : (errno ? -errno : -EIO);
5232 close_nointr_nofail(fdf);
5240 close_nointr_nofail(fdf);
5241 r = close_nointr(fdt);
5251 int symlink_or_copy(const char *from, const char *to) {
5252 char *pf = NULL, *pt = NULL;
5259 if (parent_of_path(from, &pf) < 0 ||
5260 parent_of_path(to, &pt) < 0) {
5265 if (stat(pf, &a) < 0 ||
5271 if (a.st_dev != b.st_dev) {
5275 return copy_file(from, to);
5278 if (symlink(from, to) < 0) {
5292 int symlink_or_copy_atomic(const char *from, const char *to) {
5296 unsigned long long ull;
5303 t = new(char, strlen(to) + 1 + 16 + 1);
5307 fn = file_name_from_path(to);
5311 x = stpcpy(t+k+1, fn);
5314 for (i = 0; i < 16; i++) {
5315 *(x++) = hexchar(ull & 0xF);
5321 r = symlink_or_copy(from, t);
5328 if (rename(t, to) < 0) {
5339 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5346 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5350 r = read_one_line_file("/proc/self/sessionid", &s);
5354 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5357 r = read_one_line_file(p, &s);
5364 r = safe_atou32(s, &u);
5370 if (u == (uint32_t) -1 || u <= 0)
5377 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5384 /* Only use audit login uid if we are executed with sufficient
5385 * capabilities so that pam_loginuid could do its job. If we
5386 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5387 * are being run in a container and /proc/self/loginuid is
5388 * useless since it probably contains a uid of the host
5391 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5395 r = read_one_line_file("/proc/self/loginuid", &s);
5399 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5402 r = read_one_line_file(p, &s);
5409 r = parse_uid(s, &u);
5415 if (u == (uid_t) -1)
5422 bool display_is_local(const char *display) {
5426 display[0] == ':' &&
5427 display[1] >= '0' &&
5431 int socket_from_display(const char *display, char **path) {
5438 if (!display_is_local(display))
5441 k = strspn(display+1, "0123456789");
5443 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5447 c = stpcpy(f, "/tmp/.X11-unix/X");
5448 memcpy(c, display+1, k);
5456 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5463 /* We enforce some special rules for uid=0: in order to avoid
5464 * NSS lookups for root we hardcode its data. */
5466 if (streq(*username, "root") || streq(*username, "0")) {
5480 if (parse_uid(*username, &u) >= 0) {
5484 /* If there are multiple users with the same id, make
5485 * sure to leave $USER to the configured value instead
5486 * of the first occurrence in the database. However if
5487 * the uid was configured by a numeric uid, then let's
5488 * pick the real username from /etc/passwd. */
5490 *username = p->pw_name;
5493 p = getpwnam(*username);
5497 return errno != 0 ? -errno : -ESRCH;
5511 int get_group_creds(const char **groupname, gid_t *gid) {
5517 /* We enforce some special rules for gid=0: in order to avoid
5518 * NSS lookups for root we hardcode its data. */
5520 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5521 *groupname = "root";
5529 if (parse_gid(*groupname, &id) >= 0) {
5534 *groupname = g->gr_name;
5537 g = getgrnam(*groupname);
5541 return errno != 0 ? -errno : -ESRCH;
5549 int glob_exists(const char *path) {
5557 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5559 if (k == GLOB_NOMATCH)
5561 else if (k == GLOB_NOSPACE)
5564 r = !strv_isempty(g.gl_pathv);
5566 r = errno ? -errno : -EIO;
5573 int dirent_ensure_type(DIR *d, struct dirent *de) {
5579 if (de->d_type != DT_UNKNOWN)
5582 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5586 S_ISREG(st.st_mode) ? DT_REG :
5587 S_ISDIR(st.st_mode) ? DT_DIR :
5588 S_ISLNK(st.st_mode) ? DT_LNK :
5589 S_ISFIFO(st.st_mode) ? DT_FIFO :
5590 S_ISSOCK(st.st_mode) ? DT_SOCK :
5591 S_ISCHR(st.st_mode) ? DT_CHR :
5592 S_ISBLK(st.st_mode) ? DT_BLK :
5598 int in_search_path(const char *path, char **search) {
5602 r = parent_of_path(path, &parent);
5608 STRV_FOREACH(i, search) {
5609 if (path_equal(parent, *i)) {
5620 int get_files_in_directory(const char *path, char ***list) {
5628 /* Returns all files in a directory in *list, and the number
5629 * of files as return value. If list is NULL returns only the
5637 struct dirent buffer, *de;
5640 k = readdir_r(d, &buffer, &de);
5649 dirent_ensure_type(d, de);
5651 if (!dirent_is_file(de))
5655 if ((unsigned) r >= n) {
5659 t = realloc(l, sizeof(char*) * n);
5668 assert((unsigned) r < n);
5670 l[r] = strdup(de->d_name);
5694 char *join(const char *x, ...) {
5707 t = va_arg(ap, const char *);
5730 t = va_arg(ap, const char *);
5744 bool is_main_thread(void) {
5745 static __thread int cached = 0;
5747 if (_unlikely_(cached == 0))
5748 cached = getpid() == gettid() ? 1 : -1;
5753 int block_get_whole_disk(dev_t d, dev_t *ret) {
5760 /* If it has a queue this is good enough for us */
5761 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5764 r = access(p, F_OK);
5772 /* If it is a partition find the originating device */
5773 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5776 r = access(p, F_OK);
5782 /* Get parent dev_t */
5783 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5786 r = read_one_line_file(p, &s);
5792 r = sscanf(s, "%u:%u", &m, &n);
5798 /* Only return this if it is really good enough for us. */
5799 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5802 r = access(p, F_OK);
5806 *ret = makedev(m, n);
5813 int file_is_sticky(const char *p) {
5818 if (lstat(p, &st) < 0)
5823 (st.st_mode & S_ISVTX);
5826 static const char *const ioprio_class_table[] = {
5827 [IOPRIO_CLASS_NONE] = "none",
5828 [IOPRIO_CLASS_RT] = "realtime",
5829 [IOPRIO_CLASS_BE] = "best-effort",
5830 [IOPRIO_CLASS_IDLE] = "idle"
5833 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5835 static const char *const sigchld_code_table[] = {
5836 [CLD_EXITED] = "exited",
5837 [CLD_KILLED] = "killed",
5838 [CLD_DUMPED] = "dumped",
5839 [CLD_TRAPPED] = "trapped",
5840 [CLD_STOPPED] = "stopped",
5841 [CLD_CONTINUED] = "continued",
5844 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5846 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5847 [LOG_FAC(LOG_KERN)] = "kern",
5848 [LOG_FAC(LOG_USER)] = "user",
5849 [LOG_FAC(LOG_MAIL)] = "mail",
5850 [LOG_FAC(LOG_DAEMON)] = "daemon",
5851 [LOG_FAC(LOG_AUTH)] = "auth",
5852 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5853 [LOG_FAC(LOG_LPR)] = "lpr",
5854 [LOG_FAC(LOG_NEWS)] = "news",
5855 [LOG_FAC(LOG_UUCP)] = "uucp",
5856 [LOG_FAC(LOG_CRON)] = "cron",
5857 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5858 [LOG_FAC(LOG_FTP)] = "ftp",
5859 [LOG_FAC(LOG_LOCAL0)] = "local0",
5860 [LOG_FAC(LOG_LOCAL1)] = "local1",
5861 [LOG_FAC(LOG_LOCAL2)] = "local2",
5862 [LOG_FAC(LOG_LOCAL3)] = "local3",
5863 [LOG_FAC(LOG_LOCAL4)] = "local4",
5864 [LOG_FAC(LOG_LOCAL5)] = "local5",
5865 [LOG_FAC(LOG_LOCAL6)] = "local6",
5866 [LOG_FAC(LOG_LOCAL7)] = "local7"
5869 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5871 static const char *const log_level_table[] = {
5872 [LOG_EMERG] = "emerg",
5873 [LOG_ALERT] = "alert",
5874 [LOG_CRIT] = "crit",
5876 [LOG_WARNING] = "warning",
5877 [LOG_NOTICE] = "notice",
5878 [LOG_INFO] = "info",
5879 [LOG_DEBUG] = "debug"
5882 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5884 static const char* const sched_policy_table[] = {
5885 [SCHED_OTHER] = "other",
5886 [SCHED_BATCH] = "batch",
5887 [SCHED_IDLE] = "idle",
5888 [SCHED_FIFO] = "fifo",
5892 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5894 static const char* const rlimit_table[] = {
5895 [RLIMIT_CPU] = "LimitCPU",
5896 [RLIMIT_FSIZE] = "LimitFSIZE",
5897 [RLIMIT_DATA] = "LimitDATA",
5898 [RLIMIT_STACK] = "LimitSTACK",
5899 [RLIMIT_CORE] = "LimitCORE",
5900 [RLIMIT_RSS] = "LimitRSS",
5901 [RLIMIT_NOFILE] = "LimitNOFILE",
5902 [RLIMIT_AS] = "LimitAS",
5903 [RLIMIT_NPROC] = "LimitNPROC",
5904 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5905 [RLIMIT_LOCKS] = "LimitLOCKS",
5906 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5907 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5908 [RLIMIT_NICE] = "LimitNICE",
5909 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5910 [RLIMIT_RTTIME] = "LimitRTTIME"
5913 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5915 static const char* const ip_tos_table[] = {
5916 [IPTOS_LOWDELAY] = "low-delay",
5917 [IPTOS_THROUGHPUT] = "throughput",
5918 [IPTOS_RELIABILITY] = "reliability",
5919 [IPTOS_LOWCOST] = "low-cost",
5922 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5924 static const char *const __signal_table[] = {
5941 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5952 [SIGVTALRM] = "VTALRM",
5954 [SIGWINCH] = "WINCH",
5960 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5962 const char *signal_to_string(int signo) {
5963 static __thread char buf[12];
5966 name = __signal_to_string(signo);
5970 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5971 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5973 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5978 int signal_from_string(const char *s) {
5983 signo =__signal_from_string(s);
5987 if (startswith(s, "RTMIN+")) {
5991 if (safe_atou(s, &u) >= 0) {
5992 signo = (int) u + offset;
5993 if (signo > 0 && signo < _NSIG)
5999 bool kexec_loaded(void) {
6000 bool loaded = false;
6003 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6011 int strdup_or_null(const char *a, char **b) {
6029 int prot_from_flags(int flags) {
6031 switch (flags & O_ACCMODE) {
6040 return PROT_READ|PROT_WRITE;
6047 unsigned long cap_last_cap(void) {
6048 static __thread unsigned long saved;
6049 static __thread bool valid = false;
6055 p = (unsigned long) CAP_LAST_CAP;
6057 if (prctl(PR_CAPBSET_READ, p) < 0) {
6059 /* Hmm, look downwards, until we find one that
6061 for (p--; p > 0; p --)
6062 if (prctl(PR_CAPBSET_READ, p) >= 0)
6067 /* Hmm, look upwards, until we find one that doesn't
6070 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6080 char *format_bytes(char *buf, size_t l, off_t t) {
6083 static const struct {
6087 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6088 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6089 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6090 { "G", 1024ULL*1024ULL*1024ULL },
6091 { "M", 1024ULL*1024ULL },
6095 for (i = 0; i < ELEMENTSOF(table); i++) {
6097 if (t >= table[i].factor) {
6100 (unsigned long long) (t / table[i].factor),
6101 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6108 snprintf(buf, l, "%lluB", (unsigned long long) t);
6116 void* memdup(const void *p, size_t l) {