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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser 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>
59 #include <sys/statvfs.h>
68 #include "exit-status.h"
72 char **saved_argv = NULL;
74 size_t page_size(void) {
75 static __thread size_t pgsz = 0;
78 if (_likely_(pgsz > 0))
81 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
88 bool streq_ptr(const char *a, const char *b) {
90 /* Like streq(), but tries to make sense of NULL pointers */
101 usec_t now(clockid_t clock_id) {
104 assert_se(clock_gettime(clock_id, &ts) == 0);
106 return timespec_load(&ts);
109 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
112 ts->realtime = now(CLOCK_REALTIME);
113 ts->monotonic = now(CLOCK_MONOTONIC);
118 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
127 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
129 ts->monotonic = now(CLOCK_MONOTONIC);
131 if ((int64_t) ts->monotonic > delta)
132 ts->monotonic -= delta;
140 usec_t timespec_load(const struct timespec *ts) {
144 (usec_t) ts->tv_sec * USEC_PER_SEC +
145 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
148 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
151 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
152 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
157 usec_t timeval_load(const struct timeval *tv) {
161 (usec_t) tv->tv_sec * USEC_PER_SEC +
162 (usec_t) tv->tv_usec;
165 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
168 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
169 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
174 bool endswith(const char *s, const char *postfix) {
181 pl = strlen(postfix);
189 return memcmp(s + sl - pl, postfix, pl) == 0;
192 bool startswith(const char *s, const char *prefix) {
207 return memcmp(s, prefix, pl) == 0;
210 bool startswith_no_case(const char *s, const char *prefix) {
226 for(i = 0; i < pl; ++i) {
227 if (tolower(s[i]) != tolower(prefix[i]))
234 bool first_word(const char *s, const char *word) {
249 if (memcmp(s, word, wl) != 0)
253 strchr(WHITESPACE, s[wl]);
256 int close_nointr(int fd) {
271 void close_nointr_nofail(int fd) {
272 int saved_errno = errno;
274 /* like close_nointr() but cannot fail, and guarantees errno
277 assert_se(close_nointr(fd) == 0);
282 void close_many(const int fds[], unsigned n_fd) {
285 for (i = 0; i < n_fd; i++)
286 close_nointr_nofail(fds[i]);
289 int parse_boolean(const char *v) {
292 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
294 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
300 int parse_pid(const char *s, pid_t* ret_pid) {
301 unsigned long ul = 0;
308 if ((r = safe_atolu(s, &ul)) < 0)
313 if ((unsigned long) pid != ul)
323 int parse_uid(const char *s, uid_t* ret_uid) {
324 unsigned long ul = 0;
331 if ((r = safe_atolu(s, &ul)) < 0)
336 if ((unsigned long) uid != ul)
343 int safe_atou(const char *s, unsigned *ret_u) {
351 l = strtoul(s, &x, 0);
353 if (!x || *x || errno)
354 return errno ? -errno : -EINVAL;
356 if ((unsigned long) (unsigned) l != l)
359 *ret_u = (unsigned) l;
363 int safe_atoi(const char *s, int *ret_i) {
371 l = strtol(s, &x, 0);
373 if (!x || *x || errno)
374 return errno ? -errno : -EINVAL;
376 if ((long) (int) l != l)
383 int safe_atollu(const char *s, long long unsigned *ret_llu) {
385 unsigned long long l;
391 l = strtoull(s, &x, 0);
393 if (!x || *x || errno)
394 return errno ? -errno : -EINVAL;
400 int safe_atolli(const char *s, long long int *ret_lli) {
408 l = strtoll(s, &x, 0);
410 if (!x || *x || errno)
411 return errno ? -errno : -EINVAL;
417 /* Split a string into words. */
418 char *split(const char *c, size_t *l, const char *separator, char **state) {
421 current = *state ? *state : (char*) c;
423 if (!*current || *c == 0)
426 current += strspn(current, separator);
427 *l = strcspn(current, separator);
430 return (char*) current;
433 /* Split a string into words, but consider strings enclosed in '' and
434 * "" as words even if they include spaces. */
435 char *split_quoted(const char *c, size_t *l, char **state) {
437 bool escaped = false;
439 current = *state ? *state : (char*) c;
441 if (!*current || *c == 0)
444 current += strspn(current, WHITESPACE);
446 if (*current == '\'') {
449 for (e = current; *e; e++) {
459 *state = *e == 0 ? e : e+1;
460 } else if (*current == '\"') {
463 for (e = current; *e; e++) {
473 *state = *e == 0 ? e : e+1;
475 for (e = current; *e; e++) {
480 else if (strchr(WHITESPACE, *e))
487 return (char*) current;
490 char **split_path_and_make_absolute(const char *p) {
494 if (!(l = strv_split(p, ":")))
497 if (!strv_path_make_absolute_cwd(l)) {
505 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
508 char fn[PATH_MAX], line[LINE_MAX], *p;
514 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
517 if (!(f = fopen(fn, "re")))
520 if (!(fgets(line, sizeof(line), f))) {
521 r = feof(f) ? -EIO : -errno;
528 /* Let's skip the pid and comm fields. The latter is enclosed
529 * in () but does not escape any () in its value, so let's
530 * skip over it manually */
532 if (!(p = strrchr(line, ')')))
543 if ((long unsigned) (pid_t) ppid != ppid)
546 *_ppid = (pid_t) ppid;
551 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
554 char fn[PATH_MAX], line[LINE_MAX], *p;
559 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
562 if (!(f = fopen(fn, "re")))
565 if (!(fgets(line, sizeof(line), f))) {
566 r = feof(f) ? -EIO : -errno;
573 /* Let's skip the pid and comm fields. The latter is enclosed
574 * in () but does not escape any () in its value, so let's
575 * skip over it manually */
577 if (!(p = strrchr(line, ')')))
598 "%*d " /* priority */
600 "%*d " /* num_threads */
601 "%*d " /* itrealvalue */
602 "%llu " /* starttime */,
609 int write_one_line_file(const char *fn, const char *line) {
616 if (!(f = fopen(fn, "we")))
620 if (fputs(line, f) < 0) {
625 if (!endswith(line, "\n"))
643 int fchmod_umask(int fd, mode_t m) {
648 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
654 int write_one_line_file_atomic(const char *fn, const char *line) {
662 r = fopen_temporary(fn, &f, &p);
666 fchmod_umask(fileno(f), 0644);
669 if (fputs(line, f) < 0) {
674 if (!endswith(line, "\n"))
685 if (rename(p, fn) < 0)
701 int read_one_line_file(const char *fn, char **line) {
704 char t[LINE_MAX], *c;
713 if (!fgets(t, sizeof(t), f)) {
739 int read_full_file(const char *fn, char **contents, size_t *size) {
746 if (!(f = fopen(fn, "re")))
749 if (fstat(fileno(f), &st) < 0) {
755 if (st.st_size > 4*1024*1024) {
760 n = st.st_size > 0 ? st.st_size : LINE_MAX;
767 if (!(t = realloc(buf, n+1))) {
773 k = fread(buf + l, 1, n - l, f);
788 if (n > 4*1024*1024) {
812 const char *separator, ...) {
815 char *contents = NULL, *p;
820 if ((r = read_full_file(fname, &contents, NULL)) < 0)
825 const char *key = NULL;
827 p += strspn(p, separator);
828 p += strspn(p, WHITESPACE);
833 if (!strchr(COMMENTS, *p)) {
837 va_start(ap, separator);
838 while ((key = va_arg(ap, char *))) {
842 value = va_arg(ap, char **);
845 if (strncmp(p, key, n) != 0 ||
850 n = strcspn(p, separator);
853 strchr(QUOTES, p[0]) &&
855 v = strndup(p+1, n-2);
866 /* return empty value strings as NULL */
883 p += strcspn(p, separator);
902 if (!(f = fopen(fname, "re")))
906 char l[LINE_MAX], *p, *u;
909 if (!fgets(l, sizeof(l), f)) {
922 if (strchr(COMMENTS, *p))
925 if (!(u = normalize_env_assignment(p))) {
926 log_error("Out of memory");
931 t = strv_append(m, u);
935 log_error("Out of memory");
958 int write_env_file(const char *fname, char **l) {
963 r = fopen_temporary(fname, &f, &p);
967 fchmod_umask(fileno(f), 0644);
983 if (rename(p, fname) < 0)
998 char *truncate_nl(char *s) {
1001 s[strcspn(s, NEWLINE)] = 0;
1005 int get_process_comm(pid_t pid, char **name) {
1011 r = read_one_line_file("/proc/self/comm", name);
1014 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1017 r = read_one_line_file(p, name);
1024 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1031 assert(max_length > 0);
1035 f = fopen("/proc/self/cmdline", "re");
1038 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1048 r = new(char, max_length);
1056 while ((c = getc(f)) != EOF) {
1078 size_t n = MIN(left-1, 3U);
1079 memcpy(k, "...", n);
1086 /* Kernel threads have no argv[] */
1096 h = get_process_comm(pid, &t);
1100 r = join("[", t, "]", NULL);
1111 int is_kernel_thread(pid_t pid) {
1121 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1130 count = fread(&c, 1, 1, f);
1134 /* Kernel threads have an empty cmdline */
1137 return eof ? 1 : -errno;
1142 int get_process_exe(pid_t pid, char **name) {
1148 r = readlink_malloc("/proc/self/exe", name);
1151 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1154 r = readlink_malloc(p, name);
1161 int get_process_uid(pid_t pid, uid_t *uid) {
1171 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1181 char line[LINE_MAX], *l;
1183 if (!fgets(line, sizeof(line), f)) {
1193 if (startswith(l, "Uid:")) {
1195 l += strspn(l, WHITESPACE);
1197 l[strcspn(l, WHITESPACE)] = 0;
1199 r = parse_uid(l, uid);
1212 char *strnappend(const char *s, const char *suffix, size_t b) {
1220 return strndup(suffix, b);
1230 if (!(r = new(char, a+b+1)))
1234 memcpy(r+a, suffix, b);
1240 char *strappend(const char *s, const char *suffix) {
1241 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1244 int readlink_malloc(const char *p, char **r) {
1254 if (!(c = new(char, l)))
1257 if ((n = readlink(p, c, l-1)) < 0) {
1263 if ((size_t) n < l-1) {
1274 int readlink_and_make_absolute(const char *p, char **r) {
1281 if ((j = readlink_malloc(p, &target)) < 0)
1284 k = file_in_same_dir(p, target);
1294 int readlink_and_canonicalize(const char *p, char **r) {
1301 j = readlink_and_make_absolute(p, &t);
1305 s = canonicalize_file_name(t);
1312 path_kill_slashes(*r);
1317 int parent_of_path(const char *path, char **_r) {
1318 const char *e, *a = NULL, *b = NULL, *p;
1328 for (e = path; *e; e++) {
1330 if (!slash && *e == '/') {
1334 } else if (slash && *e != '/')
1349 r = strndup(path, p-path);
1359 char *file_name_from_path(const char *p) {
1364 if ((r = strrchr(p, '/')))
1370 bool path_is_absolute(const char *p) {
1376 bool is_path(const char *p) {
1378 return !!strchr(p, '/');
1381 char *path_make_absolute(const char *p, const char *prefix) {
1384 /* Makes every item in the list an absolute path by prepending
1385 * the prefix, if specified and necessary */
1387 if (path_is_absolute(p) || !prefix)
1390 return join(prefix, "/", p, NULL);
1393 char *path_make_absolute_cwd(const char *p) {
1398 /* Similar to path_make_absolute(), but prefixes with the
1399 * current working directory. */
1401 if (path_is_absolute(p))
1404 if (!(cwd = get_current_dir_name()))
1407 r = path_make_absolute(p, cwd);
1413 char **strv_path_make_absolute_cwd(char **l) {
1416 /* Goes through every item in the string list and makes it
1417 * absolute. This works in place and won't rollback any
1418 * changes on failure. */
1420 STRV_FOREACH(s, l) {
1423 if (!(t = path_make_absolute_cwd(*s)))
1433 char **strv_path_canonicalize(char **l) {
1436 bool enomem = false;
1438 if (strv_isempty(l))
1441 /* Goes through every item in the string list and canonicalize
1442 * the path. This works in place and won't rollback any
1443 * changes on failure. */
1445 STRV_FOREACH(s, l) {
1448 t = path_make_absolute_cwd(*s);
1457 u = canonicalize_file_name(t);
1461 if (errno == ENOMEM || !errno)
1478 char **strv_path_remove_empty(char **l) {
1484 for (f = t = l; *f; f++) {
1486 if (dir_is_empty(*f) > 0) {
1498 int reset_all_signal_handlers(void) {
1501 for (sig = 1; sig < _NSIG; sig++) {
1502 struct sigaction sa;
1504 if (sig == SIGKILL || sig == SIGSTOP)
1508 sa.sa_handler = SIG_DFL;
1509 sa.sa_flags = SA_RESTART;
1511 /* On Linux the first two RT signals are reserved by
1512 * glibc, and sigaction() will return EINVAL for them. */
1513 if ((sigaction(sig, &sa, NULL) < 0))
1514 if (errno != EINVAL)
1521 char *strstrip(char *s) {
1524 /* Drops trailing whitespace. Modifies the string in
1525 * place. Returns pointer to first non-space character */
1527 s += strspn(s, WHITESPACE);
1529 for (e = strchr(s, 0); e > s; e --)
1530 if (!strchr(WHITESPACE, e[-1]))
1538 char *delete_chars(char *s, const char *bad) {
1541 /* Drops all whitespace, regardless where in the string */
1543 for (f = s, t = s; *f; f++) {
1544 if (strchr(bad, *f))
1555 bool in_charset(const char *s, const char* charset) {
1561 for (i = s; *i; i++)
1562 if (!strchr(charset, *i))
1568 char *file_in_same_dir(const char *path, const char *filename) {
1575 /* This removes the last component of path and appends
1576 * filename, unless the latter is absolute anyway or the
1579 if (path_is_absolute(filename))
1580 return strdup(filename);
1582 if (!(e = strrchr(path, '/')))
1583 return strdup(filename);
1585 k = strlen(filename);
1586 if (!(r = new(char, e-path+1+k+1)))
1589 memcpy(r, path, e-path+1);
1590 memcpy(r+(e-path)+1, filename, k+1);
1595 int rmdir_parents(const char *path, const char *stop) {
1604 /* Skip trailing slashes */
1605 while (l > 0 && path[l-1] == '/')
1611 /* Skip last component */
1612 while (l > 0 && path[l-1] != '/')
1615 /* Skip trailing slashes */
1616 while (l > 0 && path[l-1] == '/')
1622 if (!(t = strndup(path, l)))
1625 if (path_startswith(stop, t)) {
1634 if (errno != ENOENT)
1642 char hexchar(int x) {
1643 static const char table[16] = "0123456789abcdef";
1645 return table[x & 15];
1648 int unhexchar(char c) {
1650 if (c >= '0' && c <= '9')
1653 if (c >= 'a' && c <= 'f')
1654 return c - 'a' + 10;
1656 if (c >= 'A' && c <= 'F')
1657 return c - 'A' + 10;
1662 char octchar(int x) {
1663 return '0' + (x & 7);
1666 int unoctchar(char c) {
1668 if (c >= '0' && c <= '7')
1674 char decchar(int x) {
1675 return '0' + (x % 10);
1678 int undecchar(char c) {
1680 if (c >= '0' && c <= '9')
1686 char *cescape(const char *s) {
1692 /* Does C style string escaping. */
1694 r = new(char, strlen(s)*4 + 1);
1698 for (f = s, t = r; *f; f++)
1744 /* For special chars we prefer octal over
1745 * hexadecimal encoding, simply because glib's
1746 * g_strescape() does the same */
1747 if ((*f < ' ') || (*f >= 127)) {
1749 *(t++) = octchar((unsigned char) *f >> 6);
1750 *(t++) = octchar((unsigned char) *f >> 3);
1751 *(t++) = octchar((unsigned char) *f);
1762 char *cunescape_length(const char *s, size_t length) {
1768 /* Undoes C style string escaping */
1770 r = new(char, length+1);
1774 for (f = s, t = r; f < s + length; f++) {
1817 /* This is an extension of the XDG syntax files */
1822 /* hexadecimal encoding */
1825 a = unhexchar(f[1]);
1826 b = unhexchar(f[2]);
1828 if (a < 0 || b < 0) {
1829 /* Invalid escape code, let's take it literal then */
1833 *(t++) = (char) ((a << 4) | b);
1848 /* octal encoding */
1851 a = unoctchar(f[0]);
1852 b = unoctchar(f[1]);
1853 c = unoctchar(f[2]);
1855 if (a < 0 || b < 0 || c < 0) {
1856 /* Invalid escape code, let's take it literal then */
1860 *(t++) = (char) ((a << 6) | (b << 3) | c);
1868 /* premature end of string.*/
1873 /* Invalid escape code, let's take it literal then */
1885 char *cunescape(const char *s) {
1886 return cunescape_length(s, strlen(s));
1889 char *xescape(const char *s, const char *bad) {
1893 /* Escapes all chars in bad, in addition to \ and all special
1894 * chars, in \xFF style escaping. May be reversed with
1897 if (!(r = new(char, strlen(s)*4+1)))
1900 for (f = s, t = r; *f; f++) {
1902 if ((*f < ' ') || (*f >= 127) ||
1903 (*f == '\\') || strchr(bad, *f)) {
1906 *(t++) = hexchar(*f >> 4);
1907 *(t++) = hexchar(*f);
1917 char *bus_path_escape(const char *s) {
1923 /* Escapes all chars that D-Bus' object path cannot deal
1924 * with. Can be reverse with bus_path_unescape() */
1926 if (!(r = new(char, strlen(s)*3+1)))
1929 for (f = s, t = r; *f; f++) {
1931 if (!(*f >= 'A' && *f <= 'Z') &&
1932 !(*f >= 'a' && *f <= 'z') &&
1933 !(*f >= '0' && *f <= '9')) {
1935 *(t++) = hexchar(*f >> 4);
1936 *(t++) = hexchar(*f);
1946 char *bus_path_unescape(const char *f) {
1951 if (!(r = strdup(f)))
1954 for (t = r; *f; f++) {
1959 if ((a = unhexchar(f[1])) < 0 ||
1960 (b = unhexchar(f[2])) < 0) {
1961 /* Invalid escape code, let's take it literal then */
1964 *(t++) = (char) ((a << 4) | b);
1976 char *path_kill_slashes(char *path) {
1980 /* Removes redundant inner and trailing slashes. Modifies the
1981 * passed string in-place.
1983 * ///foo///bar/ becomes /foo/bar
1986 for (f = path, t = path; *f; f++) {
2001 /* Special rule, if we are talking of the root directory, a
2002 trailing slash is good */
2004 if (t == path && slash)
2011 bool path_startswith(const char *path, const char *prefix) {
2015 if ((path[0] == '/') != (prefix[0] == '/'))
2021 path += strspn(path, "/");
2022 prefix += strspn(prefix, "/");
2030 a = strcspn(path, "/");
2031 b = strcspn(prefix, "/");
2036 if (memcmp(path, prefix, a) != 0)
2044 bool path_equal(const char *a, const char *b) {
2048 if ((a[0] == '/') != (b[0] == '/'))
2054 a += strspn(a, "/");
2055 b += strspn(b, "/");
2057 if (*a == 0 && *b == 0)
2060 if (*a == 0 || *b == 0)
2063 j = strcspn(a, "/");
2064 k = strcspn(b, "/");
2069 if (memcmp(a, b, j) != 0)
2077 char *ascii_strlower(char *t) {
2082 for (p = t; *p; p++)
2083 if (*p >= 'A' && *p <= 'Z')
2084 *p = *p - 'A' + 'a';
2089 bool ignore_file(const char *filename) {
2093 filename[0] == '.' ||
2094 streq(filename, "lost+found") ||
2095 streq(filename, "aquota.user") ||
2096 streq(filename, "aquota.group") ||
2097 endswith(filename, "~") ||
2098 endswith(filename, ".rpmnew") ||
2099 endswith(filename, ".rpmsave") ||
2100 endswith(filename, ".rpmorig") ||
2101 endswith(filename, ".dpkg-old") ||
2102 endswith(filename, ".dpkg-new") ||
2103 endswith(filename, ".swp");
2106 int fd_nonblock(int fd, bool nonblock) {
2111 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2115 flags |= O_NONBLOCK;
2117 flags &= ~O_NONBLOCK;
2119 if (fcntl(fd, F_SETFL, flags) < 0)
2125 int fd_cloexec(int fd, bool cloexec) {
2130 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2134 flags |= FD_CLOEXEC;
2136 flags &= ~FD_CLOEXEC;
2138 if (fcntl(fd, F_SETFD, flags) < 0)
2144 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
2147 assert(n_fdset == 0 || fdset);
2149 for (i = 0; i < n_fdset; i++)
2156 int close_all_fds(const int except[], unsigned n_except) {
2161 assert(n_except == 0 || except);
2163 d = opendir("/proc/self/fd");
2168 /* When /proc isn't available (for example in chroots)
2169 * the fallback is brute forcing through the fd
2172 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
2173 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
2175 if (fd_in_set(fd, except, n_except))
2178 if (close_nointr(fd) < 0)
2179 if (errno != EBADF && r == 0)
2186 while ((de = readdir(d))) {
2189 if (ignore_file(de->d_name))
2192 if (safe_atoi(de->d_name, &fd) < 0)
2193 /* Let's better ignore this, just in case */
2202 if (fd_in_set(fd, except, n_except))
2205 if (close_nointr(fd) < 0) {
2206 /* Valgrind has its own FD and doesn't want to have it closed */
2207 if (errno != EBADF && r == 0)
2216 bool chars_intersect(const char *a, const char *b) {
2219 /* Returns true if any of the chars in a are in b. */
2220 for (p = a; *p; p++)
2227 char *format_timestamp(char *buf, size_t l, usec_t t) {
2237 sec = (time_t) (t / USEC_PER_SEC);
2239 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2245 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2248 n = now(CLOCK_REALTIME);
2250 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2255 if (d >= USEC_PER_YEAR)
2256 snprintf(buf, l, "%llu years and %llu months ago",
2257 (unsigned long long) (d / USEC_PER_YEAR),
2258 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2259 else if (d >= USEC_PER_MONTH)
2260 snprintf(buf, l, "%llu months and %llu days ago",
2261 (unsigned long long) (d / USEC_PER_MONTH),
2262 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2263 else if (d >= USEC_PER_WEEK)
2264 snprintf(buf, l, "%llu weeks and %llu days ago",
2265 (unsigned long long) (d / USEC_PER_WEEK),
2266 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2267 else if (d >= 2*USEC_PER_DAY)
2268 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2269 else if (d >= 25*USEC_PER_HOUR)
2270 snprintf(buf, l, "1 day and %lluh ago",
2271 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2272 else if (d >= 6*USEC_PER_HOUR)
2273 snprintf(buf, l, "%lluh ago",
2274 (unsigned long long) (d / USEC_PER_HOUR));
2275 else if (d >= USEC_PER_HOUR)
2276 snprintf(buf, l, "%lluh %llumin ago",
2277 (unsigned long long) (d / USEC_PER_HOUR),
2278 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2279 else if (d >= 5*USEC_PER_MINUTE)
2280 snprintf(buf, l, "%llumin ago",
2281 (unsigned long long) (d / USEC_PER_MINUTE));
2282 else if (d >= USEC_PER_MINUTE)
2283 snprintf(buf, l, "%llumin %llus ago",
2284 (unsigned long long) (d / USEC_PER_MINUTE),
2285 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2286 else if (d >= USEC_PER_SEC)
2287 snprintf(buf, l, "%llus ago",
2288 (unsigned long long) (d / USEC_PER_SEC));
2289 else if (d >= USEC_PER_MSEC)
2290 snprintf(buf, l, "%llums ago",
2291 (unsigned long long) (d / USEC_PER_MSEC));
2293 snprintf(buf, l, "%lluus ago",
2294 (unsigned long long) d);
2296 snprintf(buf, l, "now");
2302 char *format_timespan(char *buf, size_t l, usec_t t) {
2303 static const struct {
2307 { "w", USEC_PER_WEEK },
2308 { "d", USEC_PER_DAY },
2309 { "h", USEC_PER_HOUR },
2310 { "min", USEC_PER_MINUTE },
2311 { "s", USEC_PER_SEC },
2312 { "ms", USEC_PER_MSEC },
2322 if (t == (usec_t) -1)
2326 snprintf(p, l, "0");
2331 /* The result of this function can be parsed with parse_usec */
2333 for (i = 0; i < ELEMENTSOF(table); i++) {
2337 if (t < table[i].usec)
2343 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2344 n = MIN((size_t) k, l);
2357 bool fstype_is_network(const char *fstype) {
2358 static const char * const table[] = {
2370 for (i = 0; i < ELEMENTSOF(table); i++)
2371 if (streq(table[i], fstype))
2380 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2385 TIOCL_GETKMSGREDIRECT,
2389 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2394 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2397 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2401 close_nointr_nofail(fd);
2405 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2406 struct termios old_termios, new_termios;
2408 char line[LINE_MAX];
2413 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2414 new_termios = old_termios;
2416 new_termios.c_lflag &= ~ICANON;
2417 new_termios.c_cc[VMIN] = 1;
2418 new_termios.c_cc[VTIME] = 0;
2420 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2423 if (t != (usec_t) -1) {
2424 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2425 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2430 k = fread(&c, 1, 1, f);
2432 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2438 *need_nl = c != '\n';
2445 if (t != (usec_t) -1)
2446 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2449 if (!fgets(line, sizeof(line), f))
2454 if (strlen(line) != 1)
2464 int ask(char *ret, const char *replies, const char *text, ...) {
2471 on_tty = isatty(STDOUT_FILENO);
2477 bool need_nl = true;
2480 fputs(ANSI_HIGHLIGHT_ON, stdout);
2487 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2491 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2494 if (r == -EBADMSG) {
2495 puts("Bad input, please try again.");
2506 if (strchr(replies, c)) {
2511 puts("Read unexpected character, please try again.");
2515 int reset_terminal_fd(int fd, bool switch_to_text) {
2516 struct termios termios;
2519 /* Set terminal to some sane defaults */
2523 /* We leave locked terminal attributes untouched, so that
2524 * Plymouth may set whatever it wants to set, and we don't
2525 * interfere with that. */
2527 /* Disable exclusive mode, just in case */
2528 ioctl(fd, TIOCNXCL);
2530 /* Switch to text mode */
2532 ioctl(fd, KDSETMODE, KD_TEXT);
2534 /* Enable console unicode mode */
2535 ioctl(fd, KDSKBMODE, K_UNICODE);
2537 if (tcgetattr(fd, &termios) < 0) {
2542 /* We only reset the stuff that matters to the software. How
2543 * hardware is set up we don't touch assuming that somebody
2544 * else will do that for us */
2546 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2547 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2548 termios.c_oflag |= ONLCR;
2549 termios.c_cflag |= CREAD;
2550 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2552 termios.c_cc[VINTR] = 03; /* ^C */
2553 termios.c_cc[VQUIT] = 034; /* ^\ */
2554 termios.c_cc[VERASE] = 0177;
2555 termios.c_cc[VKILL] = 025; /* ^X */
2556 termios.c_cc[VEOF] = 04; /* ^D */
2557 termios.c_cc[VSTART] = 021; /* ^Q */
2558 termios.c_cc[VSTOP] = 023; /* ^S */
2559 termios.c_cc[VSUSP] = 032; /* ^Z */
2560 termios.c_cc[VLNEXT] = 026; /* ^V */
2561 termios.c_cc[VWERASE] = 027; /* ^W */
2562 termios.c_cc[VREPRINT] = 022; /* ^R */
2563 termios.c_cc[VEOL] = 0;
2564 termios.c_cc[VEOL2] = 0;
2566 termios.c_cc[VTIME] = 0;
2567 termios.c_cc[VMIN] = 1;
2569 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2573 /* Just in case, flush all crap out */
2574 tcflush(fd, TCIOFLUSH);
2579 int reset_terminal(const char *name) {
2582 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2586 r = reset_terminal_fd(fd, true);
2587 close_nointr_nofail(fd);
2592 int open_terminal(const char *name, int mode) {
2597 * If a TTY is in the process of being closed opening it might
2598 * cause EIO. This is horribly awful, but unlikely to be
2599 * changed in the kernel. Hence we work around this problem by
2600 * retrying a couple of times.
2602 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2606 if ((fd = open(name, mode)) >= 0)
2615 usleep(50 * USEC_PER_MSEC);
2622 if ((r = isatty(fd)) < 0) {
2623 close_nointr_nofail(fd);
2628 close_nointr_nofail(fd);
2635 int flush_fd(int fd) {
2636 struct pollfd pollfd;
2640 pollfd.events = POLLIN;
2647 if ((r = poll(&pollfd, 1, 0)) < 0) {
2658 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2663 if (errno == EAGAIN)
2674 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2675 int fd = -1, notify = -1, r, wd = -1;
2679 /* We use inotify to be notified when the tty is closed. We
2680 * create the watch before checking if we can actually acquire
2681 * it, so that we don't lose any event.
2683 * Note: strictly speaking this actually watches for the
2684 * device being closed, it does *not* really watch whether a
2685 * tty loses its controlling process. However, unless some
2686 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2687 * its tty otherwise this will not become a problem. As long
2688 * as the administrator makes sure not configure any service
2689 * on the same tty as an untrusted user this should not be a
2690 * problem. (Which he probably should not do anyway.) */
2692 if (!fail && !force) {
2693 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2698 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2706 if ((r = flush_fd(notify)) < 0)
2709 /* We pass here O_NOCTTY only so that we can check the return
2710 * value TIOCSCTTY and have a reliable way to figure out if we
2711 * successfully became the controlling process of the tty */
2712 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2715 /* First, try to get the tty */
2716 r = ioctl(fd, TIOCSCTTY, force);
2718 /* Sometimes it makes sense to ignore TIOCSCTTY
2719 * returning EPERM, i.e. when very likely we already
2720 * are have this controlling terminal. */
2721 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2724 if (r < 0 && (force || fail || errno != EPERM)) {
2734 assert(notify >= 0);
2737 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2739 struct inotify_event *e;
2741 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2750 e = (struct inotify_event*) inotify_buffer;
2755 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2760 step = sizeof(struct inotify_event) + e->len;
2761 assert(step <= (size_t) l);
2763 e = (struct inotify_event*) ((uint8_t*) e + step);
2770 /* We close the tty fd here since if the old session
2771 * ended our handle will be dead. It's important that
2772 * we do this after sleeping, so that we don't enter
2773 * an endless loop. */
2774 close_nointr_nofail(fd);
2778 close_nointr_nofail(notify);
2780 r = reset_terminal_fd(fd, true);
2782 log_warning("Failed to reset terminal: %s", strerror(-r));
2788 close_nointr_nofail(fd);
2791 close_nointr_nofail(notify);
2796 int release_terminal(void) {
2798 struct sigaction sa_old, sa_new;
2800 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2803 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2804 * by our own TIOCNOTTY */
2807 sa_new.sa_handler = SIG_IGN;
2808 sa_new.sa_flags = SA_RESTART;
2809 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2811 if (ioctl(fd, TIOCNOTTY) < 0)
2814 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2816 close_nointr_nofail(fd);
2820 int sigaction_many(const struct sigaction *sa, ...) {
2825 while ((sig = va_arg(ap, int)) > 0)
2826 if (sigaction(sig, sa, NULL) < 0)
2833 int ignore_signals(int sig, ...) {
2834 struct sigaction sa;
2839 sa.sa_handler = SIG_IGN;
2840 sa.sa_flags = SA_RESTART;
2842 if (sigaction(sig, &sa, NULL) < 0)
2846 while ((sig = va_arg(ap, int)) > 0)
2847 if (sigaction(sig, &sa, NULL) < 0)
2854 int default_signals(int sig, ...) {
2855 struct sigaction sa;
2860 sa.sa_handler = SIG_DFL;
2861 sa.sa_flags = SA_RESTART;
2863 if (sigaction(sig, &sa, NULL) < 0)
2867 while ((sig = va_arg(ap, int)) > 0)
2868 if (sigaction(sig, &sa, NULL) < 0)
2875 int close_pipe(int p[]) {
2881 a = close_nointr(p[0]);
2886 b = close_nointr(p[1]);
2890 return a < 0 ? a : b;
2893 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2902 while (nbytes > 0) {
2905 if ((k = read(fd, p, nbytes)) <= 0) {
2907 if (k < 0 && errno == EINTR)
2910 if (k < 0 && errno == EAGAIN && do_poll) {
2911 struct pollfd pollfd;
2915 pollfd.events = POLLIN;
2917 if (poll(&pollfd, 1, -1) < 0) {
2921 return n > 0 ? n : -errno;
2924 if (pollfd.revents != POLLIN)
2925 return n > 0 ? n : -EIO;
2930 return n > 0 ? n : (k < 0 ? -errno : 0);
2941 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2950 while (nbytes > 0) {
2953 k = write(fd, p, nbytes);
2956 if (k < 0 && errno == EINTR)
2959 if (k < 0 && errno == EAGAIN && do_poll) {
2960 struct pollfd pollfd;
2964 pollfd.events = POLLOUT;
2966 if (poll(&pollfd, 1, -1) < 0) {
2970 return n > 0 ? n : -errno;
2973 if (pollfd.revents != POLLOUT)
2974 return n > 0 ? n : -EIO;
2979 return n > 0 ? n : (k < 0 ? -errno : 0);
2990 int path_is_mount_point(const char *t, bool allow_symlink) {
3001 if (errno == ENOENT)
3007 r = parent_of_path(t, &parent);
3011 r = lstat(parent, &b);
3017 return a.st_dev != b.st_dev;
3020 int parse_usec(const char *t, usec_t *usec) {
3021 static const struct {
3025 { "sec", USEC_PER_SEC },
3026 { "s", USEC_PER_SEC },
3027 { "min", USEC_PER_MINUTE },
3028 { "hr", USEC_PER_HOUR },
3029 { "h", USEC_PER_HOUR },
3030 { "d", USEC_PER_DAY },
3031 { "w", USEC_PER_WEEK },
3032 { "msec", USEC_PER_MSEC },
3033 { "ms", USEC_PER_MSEC },
3034 { "m", USEC_PER_MINUTE },
3037 { "", USEC_PER_SEC },
3053 l = strtoll(p, &e, 10);
3064 e += strspn(e, WHITESPACE);
3066 for (i = 0; i < ELEMENTSOF(table); i++)
3067 if (startswith(e, table[i].suffix)) {
3068 r += (usec_t) l * table[i].usec;
3069 p = e + strlen(table[i].suffix);
3073 if (i >= ELEMENTSOF(table))
3083 int parse_bytes(const char *t, off_t *bytes) {
3084 static const struct {
3090 { "M", 1024ULL*1024ULL },
3091 { "G", 1024ULL*1024ULL*1024ULL },
3092 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3093 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3094 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3111 l = strtoll(p, &e, 10);
3122 e += strspn(e, WHITESPACE);
3124 for (i = 0; i < ELEMENTSOF(table); i++)
3125 if (startswith(e, table[i].suffix)) {
3126 r += (off_t) l * table[i].factor;
3127 p = e + strlen(table[i].suffix);
3131 if (i >= ELEMENTSOF(table))
3141 int make_stdio(int fd) {
3146 r = dup2(fd, STDIN_FILENO);
3147 s = dup2(fd, STDOUT_FILENO);
3148 t = dup2(fd, STDERR_FILENO);
3151 close_nointr_nofail(fd);
3153 if (r < 0 || s < 0 || t < 0)
3156 fd_cloexec(STDIN_FILENO, false);
3157 fd_cloexec(STDOUT_FILENO, false);
3158 fd_cloexec(STDERR_FILENO, false);
3163 int make_null_stdio(void) {
3166 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3169 return make_stdio(null_fd);
3172 bool is_device_path(const char *path) {
3174 /* Returns true on paths that refer to a device, either in
3175 * sysfs or in /dev */
3178 path_startswith(path, "/dev/") ||
3179 path_startswith(path, "/sys/");
3182 int dir_is_empty(const char *path) {
3185 struct dirent buf, *de;
3187 if (!(d = opendir(path)))
3191 if ((r = readdir_r(d, &buf, &de)) > 0) {
3201 if (!ignore_file(de->d_name)) {
3211 unsigned long long random_ull(void) {
3216 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3219 r = loop_read(fd, &ull, sizeof(ull), true);
3220 close_nointr_nofail(fd);
3222 if (r != sizeof(ull))
3228 return random() * RAND_MAX + random();
3231 void rename_process(const char name[8]) {
3234 /* This is a like a poor man's setproctitle(). It changes the
3235 * comm field, argv[0], and also the glibc's internally used
3236 * name of the process. For the first one a limit of 16 chars
3237 * applies, to the second one usually one of 10 (i.e. length
3238 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3239 * "systemd"). If you pass a longer string it will be
3242 prctl(PR_SET_NAME, name);
3244 if (program_invocation_name)
3245 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3247 if (saved_argc > 0) {
3251 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3253 for (i = 1; i < saved_argc; i++) {
3257 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3262 void sigset_add_many(sigset_t *ss, ...) {
3269 while ((sig = va_arg(ap, int)) > 0)
3270 assert_se(sigaddset(ss, sig) == 0);
3274 char* gethostname_malloc(void) {
3277 assert_se(uname(&u) >= 0);
3280 return strdup(u.nodename);
3282 return strdup(u.sysname);
3285 char* getlogname_malloc(void) {
3289 struct passwd pwbuf, *pw = NULL;
3292 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3297 /* Shortcut things to avoid NSS lookups */
3299 return strdup("root");
3301 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3304 if (!(buf = malloc(bufsize)))
3307 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3308 name = strdup(pw->pw_name);
3315 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3321 int getttyname_malloc(int fd, char **r) {
3322 char path[PATH_MAX], *c;
3327 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3332 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3339 int getttyname_harder(int fd, char **r) {
3343 if ((k = getttyname_malloc(fd, &s)) < 0)
3346 if (streq(s, "tty")) {
3348 return get_ctty(0, NULL, r);
3355 int get_ctty_devnr(pid_t pid, dev_t *d) {
3357 char line[LINE_MAX], *p, *fn;
3358 unsigned long ttynr;
3361 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3364 f = fopen(fn, "re");
3369 if (!fgets(line, sizeof(line), f)) {
3370 k = feof(f) ? -EIO : -errno;
3377 p = strrchr(line, ')');
3387 "%*d " /* session */
3396 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3398 char fn[PATH_MAX], *s, *b, *p;
3403 k = get_ctty_devnr(pid, &devnr);
3407 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3410 if ((k = readlink_malloc(fn, &s)) < 0) {
3415 /* This is an ugly hack */
3416 if (major(devnr) == 136) {
3417 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3427 /* Probably something like the ptys which have no
3428 * symlink in /dev/char. Let's return something
3429 * vaguely useful. */
3431 if (!(b = strdup(fn + 5)))
3441 if (startswith(s, "/dev/"))