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>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
75 char **saved_argv = NULL;
77 static volatile unsigned cached_columns = 0;
78 static volatile unsigned cached_lines = 0;
80 size_t page_size(void) {
81 static __thread size_t pgsz = 0;
84 if (_likely_(pgsz > 0))
87 r = sysconf(_SC_PAGESIZE);
94 bool streq_ptr(const char *a, const char *b) {
96 /* Like streq(), but tries to make sense of NULL pointers */
107 usec_t now(clockid_t clock_id) {
110 assert_se(clock_gettime(clock_id, &ts) == 0);
112 return timespec_load(&ts);
115 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
118 ts->realtime = now(CLOCK_REALTIME);
119 ts->monotonic = now(CLOCK_MONOTONIC);
124 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
133 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
135 ts->monotonic = now(CLOCK_MONOTONIC);
137 if ((int64_t) ts->monotonic > delta)
138 ts->monotonic -= delta;
146 usec_t timespec_load(const struct timespec *ts) {
149 if (ts->tv_sec == (time_t) -1 &&
150 ts->tv_nsec == (long) -1)
153 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
157 (usec_t) ts->tv_sec * USEC_PER_SEC +
158 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
161 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
164 if (u == (usec_t) -1) {
165 ts->tv_sec = (time_t) -1;
166 ts->tv_nsec = (long) -1;
170 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
171 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
176 usec_t timeval_load(const struct timeval *tv) {
179 if (tv->tv_sec == (time_t) -1 &&
180 tv->tv_usec == (suseconds_t) -1)
183 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
187 (usec_t) tv->tv_sec * USEC_PER_SEC +
188 (usec_t) tv->tv_usec;
191 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
194 if (u == (usec_t) -1) {
195 tv->tv_sec = (time_t) -1;
196 tv->tv_usec = (suseconds_t) -1;
200 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
201 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
206 char* endswith(const char *s, const char *postfix) {
213 pl = strlen(postfix);
216 return (char*) s + sl;
221 if (memcmp(s + sl - pl, postfix, pl) != 0)
224 return (char*) s + sl - pl;
227 char* startswith(const char *s, const char *prefix) {
244 char* startswith_no_case(const char *s, const char *prefix) {
254 if (tolower(*a) != tolower(*b))
261 bool first_word(const char *s, const char *word) {
276 if (memcmp(s, word, wl) != 0)
280 strchr(WHITESPACE, s[wl]);
283 int close_nointr(int fd) {
298 void close_nointr_nofail(int fd) {
299 int saved_errno = errno;
301 /* like close_nointr() but cannot fail, and guarantees errno
304 assert_se(close_nointr(fd) == 0);
309 void close_many(const int fds[], unsigned n_fd) {
312 for (i = 0; i < n_fd; i++)
313 close_nointr_nofail(fds[i]);
316 int parse_boolean(const char *v) {
319 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
321 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
327 int parse_pid(const char *s, pid_t* ret_pid) {
328 unsigned long ul = 0;
335 r = safe_atolu(s, &ul);
341 if ((unsigned long) pid != ul)
351 int parse_uid(const char *s, uid_t* ret_uid) {
352 unsigned long ul = 0;
359 r = safe_atolu(s, &ul);
365 if ((unsigned long) uid != ul)
372 int safe_atou(const char *s, unsigned *ret_u) {
380 l = strtoul(s, &x, 0);
382 if (!x || x == s || *x || errno)
383 return errno ? -errno : -EINVAL;
385 if ((unsigned long) (unsigned) l != l)
388 *ret_u = (unsigned) l;
392 int safe_atoi(const char *s, int *ret_i) {
400 l = strtol(s, &x, 0);
402 if (!x || x == s || *x || errno)
403 return errno ? -errno : -EINVAL;
405 if ((long) (int) l != l)
412 int safe_atollu(const char *s, long long unsigned *ret_llu) {
414 unsigned long long l;
420 l = strtoull(s, &x, 0);
422 if (!x || x == s || *x || errno)
423 return errno ? -errno : -EINVAL;
429 int safe_atolli(const char *s, long long int *ret_lli) {
437 l = strtoll(s, &x, 0);
439 if (!x || x == s || *x || errno)
440 return errno ? -errno : -EINVAL;
446 /* Split a string into words. */
447 char *split(const char *c, size_t *l, const char *separator, char **state) {
450 current = *state ? *state : (char*) c;
452 if (!*current || *c == 0)
455 current += strspn(current, separator);
456 *l = strcspn(current, separator);
459 return (char*) current;
462 /* Split a string into words, but consider strings enclosed in '' and
463 * "" as words even if they include spaces. */
464 char *split_quoted(const char *c, size_t *l, char **state) {
466 bool escaped = false;
468 current = *state ? *state : (char*) c;
470 if (!*current || *c == 0)
473 current += strspn(current, WHITESPACE);
475 if (*current == '\'') {
478 for (e = current; *e; e++) {
488 *state = *e == 0 ? e : e+1;
489 } else if (*current == '\"') {
492 for (e = current; *e; e++) {
502 *state = *e == 0 ? e : e+1;
504 for (e = current; *e; e++) {
509 else if (strchr(WHITESPACE, *e))
516 return (char*) current;
519 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
521 _cleanup_fclose_ FILE *f = NULL;
522 char fn[PATH_MAX], line[LINE_MAX], *p;
528 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
535 if (!fgets(line, sizeof(line), f)) {
536 r = feof(f) ? -EIO : -errno;
541 /* Let's skip the pid and comm fields. The latter is enclosed
542 * in () but does not escape any () in its value, so let's
543 * skip over it manually */
545 p = strrchr(line, ')');
557 if ((long unsigned) (pid_t) ppid != ppid)
560 *_ppid = (pid_t) ppid;
565 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
566 _cleanup_fclose_ FILE *f = NULL;
567 char fn[PATH_MAX], line[LINE_MAX], *p;
572 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
579 if (!fgets(line, sizeof(line), f)) {
586 /* Let's skip the pid and comm fields. The latter is enclosed
587 * in () but does not escape any () in its value, so let's
588 * skip over it manually */
590 p = strrchr(line, ')');
612 "%*d " /* priority */
614 "%*d " /* num_threads */
615 "%*d " /* itrealvalue */
616 "%llu " /* starttime */,
623 int write_one_line_file(const char *fn, const char *line) {
624 _cleanup_fclose_ FILE *f = NULL;
634 if (fputs(line, f) < 0)
635 return errno ? -errno : -EIO;
637 if (!endswith(line, "\n"))
643 return errno ? -errno : -EIO;
648 int fchmod_umask(int fd, mode_t m) {
653 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
659 int write_one_line_file_atomic(const char *fn, const char *line) {
667 r = fopen_temporary(fn, &f, &p);
671 fchmod_umask(fileno(f), 0644);
674 if (fputs(line, f) < 0) {
679 if (!endswith(line, "\n"))
690 if (rename(p, fn) < 0)
706 int read_one_line_file(const char *fn, char **line) {
707 _cleanup_fclose_ FILE *f = NULL;
708 char t[LINE_MAX], *c;
717 if (!fgets(t, sizeof(t), f)) {
720 return errno ? -errno : -EIO;
734 int read_full_file(const char *fn, char **contents, size_t *size) {
735 _cleanup_fclose_ FILE *f = NULL;
737 _cleanup_free_ char *buf = NULL;
744 if (fstat(fileno(f), &st) < 0)
748 if (st.st_size > 4*1024*1024)
751 n = st.st_size > 0 ? st.st_size : LINE_MAX;
758 t = realloc(buf, n+1);
763 k = fread(buf + l, 1, n - l, f);
792 const char *separator, ...) {
795 char *contents = NULL, *p;
800 if ((r = read_full_file(fname, &contents, NULL)) < 0)
805 const char *key = NULL;
807 p += strspn(p, separator);
808 p += strspn(p, WHITESPACE);
813 if (!strchr(COMMENTS, *p)) {
817 va_start(ap, separator);
818 while ((key = va_arg(ap, char *))) {
822 value = va_arg(ap, char **);
825 if (strncmp(p, key, n) != 0 ||
830 n = strcspn(p, separator);
833 strchr(QUOTES, p[0]) &&
835 v = strndup(p+1, n-2);
846 /* return empty value strings as NULL */
863 p += strcspn(p, separator);
882 if (!(f = fopen(fname, "re")))
886 char l[LINE_MAX], *p, *u;
889 if (!fgets(l, sizeof(l), f)) {
902 if (strchr(COMMENTS, *p))
905 if (!(u = normalize_env_assignment(p))) {
910 t = strv_append(m, u);
936 int write_env_file(const char *fname, char **l) {
941 r = fopen_temporary(fname, &f, &p);
945 fchmod_umask(fileno(f), 0644);
961 if (rename(p, fname) < 0)
976 char *truncate_nl(char *s) {
979 s[strcspn(s, NEWLINE)] = 0;
983 int get_process_comm(pid_t pid, char **name) {
989 r = read_one_line_file("/proc/self/comm", name);
992 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
995 r = read_one_line_file(p, name);
1002 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1009 assert(max_length > 0);
1013 f = fopen("/proc/self/cmdline", "re");
1016 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1026 r = new(char, max_length);
1034 while ((c = getc(f)) != EOF) {
1056 size_t n = MIN(left-1, 3U);
1057 memcpy(k, "...", n);
1064 /* Kernel threads have no argv[] */
1074 h = get_process_comm(pid, &t);
1078 r = strjoin("[", t, "]", NULL);
1089 int is_kernel_thread(pid_t pid) {
1099 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1108 count = fread(&c, 1, 1, f);
1112 /* Kernel threads have an empty cmdline */
1115 return eof ? 1 : -errno;
1120 int get_process_exe(pid_t pid, char **name) {
1126 r = readlink_malloc("/proc/self/exe", name);
1129 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1132 r = readlink_malloc(p, name);
1139 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1149 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1159 char line[LINE_MAX], *l;
1161 if (!fgets(line, sizeof(line), f)) {
1171 if (startswith(l, field)) {
1173 l += strspn(l, WHITESPACE);
1175 l[strcspn(l, WHITESPACE)] = 0;
1177 r = parse_uid(l, uid);
1190 int get_process_uid(pid_t pid, uid_t *uid) {
1191 return get_process_id(pid, "Uid:", uid);
1194 int get_process_gid(pid_t pid, gid_t *gid) {
1195 return get_process_id(pid, "Gid:", gid);
1198 char *strnappend(const char *s, const char *suffix, size_t b) {
1206 return strndup(suffix, b);
1215 if (b > ((size_t) -1) - a)
1218 r = new(char, a+b+1);
1223 memcpy(r+a, suffix, b);
1229 char *strappend(const char *s, const char *suffix) {
1230 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1233 int readlink_malloc(const char *p, char **r) {
1243 if (!(c = new(char, l)))
1246 if ((n = readlink(p, c, l-1)) < 0) {
1252 if ((size_t) n < l-1) {
1263 int readlink_and_make_absolute(const char *p, char **r) {
1270 if ((j = readlink_malloc(p, &target)) < 0)
1273 k = file_in_same_dir(p, target);
1283 int readlink_and_canonicalize(const char *p, char **r) {
1290 j = readlink_and_make_absolute(p, &t);
1294 s = canonicalize_file_name(t);
1301 path_kill_slashes(*r);
1306 int reset_all_signal_handlers(void) {
1309 for (sig = 1; sig < _NSIG; sig++) {
1310 struct sigaction sa;
1312 if (sig == SIGKILL || sig == SIGSTOP)
1316 sa.sa_handler = SIG_DFL;
1317 sa.sa_flags = SA_RESTART;
1319 /* On Linux the first two RT signals are reserved by
1320 * glibc, and sigaction() will return EINVAL for them. */
1321 if ((sigaction(sig, &sa, NULL) < 0))
1322 if (errno != EINVAL)
1329 char *strstrip(char *s) {
1332 /* Drops trailing whitespace. Modifies the string in
1333 * place. Returns pointer to first non-space character */
1335 s += strspn(s, WHITESPACE);
1337 for (e = strchr(s, 0); e > s; e --)
1338 if (!strchr(WHITESPACE, e[-1]))
1346 char *delete_chars(char *s, const char *bad) {
1349 /* Drops all whitespace, regardless where in the string */
1351 for (f = s, t = s; *f; f++) {
1352 if (strchr(bad, *f))
1363 bool in_charset(const char *s, const char* charset) {
1369 for (i = s; *i; i++)
1370 if (!strchr(charset, *i))
1376 char *file_in_same_dir(const char *path, const char *filename) {
1383 /* This removes the last component of path and appends
1384 * filename, unless the latter is absolute anyway or the
1387 if (path_is_absolute(filename))
1388 return strdup(filename);
1390 if (!(e = strrchr(path, '/')))
1391 return strdup(filename);
1393 k = strlen(filename);
1394 if (!(r = new(char, e-path+1+k+1)))
1397 memcpy(r, path, e-path+1);
1398 memcpy(r+(e-path)+1, filename, k+1);
1403 int rmdir_parents(const char *path, const char *stop) {
1412 /* Skip trailing slashes */
1413 while (l > 0 && path[l-1] == '/')
1419 /* Skip last component */
1420 while (l > 0 && path[l-1] != '/')
1423 /* Skip trailing slashes */
1424 while (l > 0 && path[l-1] == '/')
1430 if (!(t = strndup(path, l)))
1433 if (path_startswith(stop, t)) {
1442 if (errno != ENOENT)
1450 char hexchar(int x) {
1451 static const char table[16] = "0123456789abcdef";
1453 return table[x & 15];
1456 int unhexchar(char c) {
1458 if (c >= '0' && c <= '9')
1461 if (c >= 'a' && c <= 'f')
1462 return c - 'a' + 10;
1464 if (c >= 'A' && c <= 'F')
1465 return c - 'A' + 10;
1470 char octchar(int x) {
1471 return '0' + (x & 7);
1474 int unoctchar(char c) {
1476 if (c >= '0' && c <= '7')
1482 char decchar(int x) {
1483 return '0' + (x % 10);
1486 int undecchar(char c) {
1488 if (c >= '0' && c <= '9')
1494 char *cescape(const char *s) {
1500 /* Does C style string escaping. */
1502 r = new(char, strlen(s)*4 + 1);
1506 for (f = s, t = r; *f; f++)
1552 /* For special chars we prefer octal over
1553 * hexadecimal encoding, simply because glib's
1554 * g_strescape() does the same */
1555 if ((*f < ' ') || (*f >= 127)) {
1557 *(t++) = octchar((unsigned char) *f >> 6);
1558 *(t++) = octchar((unsigned char) *f >> 3);
1559 *(t++) = octchar((unsigned char) *f);
1570 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1577 /* Undoes C style string escaping, and optionally prefixes it. */
1579 pl = prefix ? strlen(prefix) : 0;
1581 r = new(char, pl+length+1);
1586 memcpy(r, prefix, pl);
1588 for (f = s, t = r + pl; f < s + length; f++) {
1631 /* This is an extension of the XDG syntax files */
1636 /* hexadecimal encoding */
1639 a = unhexchar(f[1]);
1640 b = unhexchar(f[2]);
1642 if (a < 0 || b < 0) {
1643 /* Invalid escape code, let's take it literal then */
1647 *(t++) = (char) ((a << 4) | b);
1662 /* octal encoding */
1665 a = unoctchar(f[0]);
1666 b = unoctchar(f[1]);
1667 c = unoctchar(f[2]);
1669 if (a < 0 || b < 0 || c < 0) {
1670 /* Invalid escape code, let's take it literal then */
1674 *(t++) = (char) ((a << 6) | (b << 3) | c);
1682 /* premature end of string.*/
1687 /* Invalid escape code, let's take it literal then */
1699 char *cunescape_length(const char *s, size_t length) {
1700 return cunescape_length_with_prefix(s, length, NULL);
1703 char *cunescape(const char *s) {
1706 return cunescape_length(s, strlen(s));
1709 char *xescape(const char *s, const char *bad) {
1713 /* Escapes all chars in bad, in addition to \ and all special
1714 * chars, in \xFF style escaping. May be reversed with
1717 r = new(char, strlen(s) * 4 + 1);
1721 for (f = s, t = r; *f; f++) {
1723 if ((*f < ' ') || (*f >= 127) ||
1724 (*f == '\\') || strchr(bad, *f)) {
1727 *(t++) = hexchar(*f >> 4);
1728 *(t++) = hexchar(*f);
1738 char *bus_path_escape(const char *s) {
1744 /* Escapes all chars that D-Bus' object path cannot deal
1745 * with. Can be reverse with bus_path_unescape() */
1747 if (!(r = new(char, strlen(s)*3+1)))
1750 for (f = s, t = r; *f; f++) {
1752 if (!(*f >= 'A' && *f <= 'Z') &&
1753 !(*f >= 'a' && *f <= 'z') &&
1754 !(*f >= '0' && *f <= '9')) {
1756 *(t++) = hexchar(*f >> 4);
1757 *(t++) = hexchar(*f);
1767 char *bus_path_unescape(const char *f) {
1772 if (!(r = strdup(f)))
1775 for (t = r; *f; f++) {
1780 if ((a = unhexchar(f[1])) < 0 ||
1781 (b = unhexchar(f[2])) < 0) {
1782 /* Invalid escape code, let's take it literal then */
1785 *(t++) = (char) ((a << 4) | b);
1797 char *ascii_strlower(char *t) {
1802 for (p = t; *p; p++)
1803 if (*p >= 'A' && *p <= 'Z')
1804 *p = *p - 'A' + 'a';
1809 static bool ignore_file_allow_backup(const char *filename) {
1813 filename[0] == '.' ||
1814 streq(filename, "lost+found") ||
1815 streq(filename, "aquota.user") ||
1816 streq(filename, "aquota.group") ||
1817 endswith(filename, ".rpmnew") ||
1818 endswith(filename, ".rpmsave") ||
1819 endswith(filename, ".rpmorig") ||
1820 endswith(filename, ".dpkg-old") ||
1821 endswith(filename, ".dpkg-new") ||
1822 endswith(filename, ".swp");
1825 bool ignore_file(const char *filename) {
1828 if (endswith(filename, "~"))
1831 return ignore_file_allow_backup(filename);
1834 int fd_nonblock(int fd, bool nonblock) {
1839 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1843 flags |= O_NONBLOCK;
1845 flags &= ~O_NONBLOCK;
1847 if (fcntl(fd, F_SETFL, flags) < 0)
1853 int fd_cloexec(int fd, bool cloexec) {
1858 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1862 flags |= FD_CLOEXEC;
1864 flags &= ~FD_CLOEXEC;
1866 if (fcntl(fd, F_SETFD, flags) < 0)
1872 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1875 assert(n_fdset == 0 || fdset);
1877 for (i = 0; i < n_fdset; i++)
1884 int close_all_fds(const int except[], unsigned n_except) {
1889 assert(n_except == 0 || except);
1891 d = opendir("/proc/self/fd");
1896 /* When /proc isn't available (for example in chroots)
1897 * the fallback is brute forcing through the fd
1900 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1901 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1903 if (fd_in_set(fd, except, n_except))
1906 if (close_nointr(fd) < 0)
1907 if (errno != EBADF && r == 0)
1914 while ((de = readdir(d))) {
1917 if (ignore_file(de->d_name))
1920 if (safe_atoi(de->d_name, &fd) < 0)
1921 /* Let's better ignore this, just in case */
1930 if (fd_in_set(fd, except, n_except))
1933 if (close_nointr(fd) < 0) {
1934 /* Valgrind has its own FD and doesn't want to have it closed */
1935 if (errno != EBADF && r == 0)
1944 bool chars_intersect(const char *a, const char *b) {
1947 /* Returns true if any of the chars in a are in b. */
1948 for (p = a; *p; p++)
1955 char *format_timestamp(char *buf, size_t l, usec_t t) {
1965 sec = (time_t) (t / USEC_PER_SEC);
1967 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1973 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1976 n = now(CLOCK_REALTIME);
1978 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1983 if (d >= USEC_PER_YEAR)
1984 snprintf(buf, l, "%llu years and %llu months ago",
1985 (unsigned long long) (d / USEC_PER_YEAR),
1986 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1987 else if (d >= USEC_PER_MONTH)
1988 snprintf(buf, l, "%llu months and %llu days ago",
1989 (unsigned long long) (d / USEC_PER_MONTH),
1990 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1991 else if (d >= USEC_PER_WEEK)
1992 snprintf(buf, l, "%llu weeks and %llu days ago",
1993 (unsigned long long) (d / USEC_PER_WEEK),
1994 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1995 else if (d >= 2*USEC_PER_DAY)
1996 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1997 else if (d >= 25*USEC_PER_HOUR)
1998 snprintf(buf, l, "1 day and %lluh ago",
1999 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2000 else if (d >= 6*USEC_PER_HOUR)
2001 snprintf(buf, l, "%lluh ago",
2002 (unsigned long long) (d / USEC_PER_HOUR));
2003 else if (d >= USEC_PER_HOUR)
2004 snprintf(buf, l, "%lluh %llumin ago",
2005 (unsigned long long) (d / USEC_PER_HOUR),
2006 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2007 else if (d >= 5*USEC_PER_MINUTE)
2008 snprintf(buf, l, "%llumin ago",
2009 (unsigned long long) (d / USEC_PER_MINUTE));
2010 else if (d >= USEC_PER_MINUTE)
2011 snprintf(buf, l, "%llumin %llus ago",
2012 (unsigned long long) (d / USEC_PER_MINUTE),
2013 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2014 else if (d >= USEC_PER_SEC)
2015 snprintf(buf, l, "%llus ago",
2016 (unsigned long long) (d / USEC_PER_SEC));
2017 else if (d >= USEC_PER_MSEC)
2018 snprintf(buf, l, "%llums ago",
2019 (unsigned long long) (d / USEC_PER_MSEC));
2021 snprintf(buf, l, "%lluus ago",
2022 (unsigned long long) d);
2024 snprintf(buf, l, "now");
2030 char *format_timespan(char *buf, size_t l, usec_t t) {
2031 static const struct {
2035 { "w", USEC_PER_WEEK },
2036 { "d", USEC_PER_DAY },
2037 { "h", USEC_PER_HOUR },
2038 { "min", USEC_PER_MINUTE },
2039 { "s", USEC_PER_SEC },
2040 { "ms", USEC_PER_MSEC },
2050 if (t == (usec_t) -1)
2054 snprintf(p, l, "0");
2059 /* The result of this function can be parsed with parse_usec */
2061 for (i = 0; i < ELEMENTSOF(table); i++) {
2065 if (t < table[i].usec)
2071 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2072 n = MIN((size_t) k, l);
2085 bool fstype_is_network(const char *fstype) {
2086 static const char table[] =
2095 return nulstr_contains(table, fstype);
2099 _cleanup_close_ int fd;
2101 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2107 TIOCL_GETKMSGREDIRECT,
2111 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2114 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2117 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2123 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2124 struct termios old_termios, new_termios;
2126 char line[LINE_MAX];
2131 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2132 new_termios = old_termios;
2134 new_termios.c_lflag &= ~ICANON;
2135 new_termios.c_cc[VMIN] = 1;
2136 new_termios.c_cc[VTIME] = 0;
2138 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2141 if (t != (usec_t) -1) {
2142 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2143 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2148 k = fread(&c, 1, 1, f);
2150 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2156 *need_nl = c != '\n';
2163 if (t != (usec_t) -1)
2164 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2167 if (!fgets(line, sizeof(line), f))
2172 if (strlen(line) != 1)
2182 int ask(char *ret, const char *replies, const char *text, ...) {
2192 bool need_nl = true;
2195 fputs(ANSI_HIGHLIGHT_ON, stdout);
2202 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2206 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2209 if (r == -EBADMSG) {
2210 puts("Bad input, please try again.");
2221 if (strchr(replies, c)) {
2226 puts("Read unexpected character, please try again.");
2230 int reset_terminal_fd(int fd, bool switch_to_text) {
2231 struct termios termios;
2234 /* Set terminal to some sane defaults */
2238 /* We leave locked terminal attributes untouched, so that
2239 * Plymouth may set whatever it wants to set, and we don't
2240 * interfere with that. */
2242 /* Disable exclusive mode, just in case */
2243 ioctl(fd, TIOCNXCL);
2245 /* Switch to text mode */
2247 ioctl(fd, KDSETMODE, KD_TEXT);
2249 /* Enable console unicode mode */
2250 ioctl(fd, KDSKBMODE, K_UNICODE);
2252 if (tcgetattr(fd, &termios) < 0) {
2257 /* We only reset the stuff that matters to the software. How
2258 * hardware is set up we don't touch assuming that somebody
2259 * else will do that for us */
2261 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2262 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2263 termios.c_oflag |= ONLCR;
2264 termios.c_cflag |= CREAD;
2265 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2267 termios.c_cc[VINTR] = 03; /* ^C */
2268 termios.c_cc[VQUIT] = 034; /* ^\ */
2269 termios.c_cc[VERASE] = 0177;
2270 termios.c_cc[VKILL] = 025; /* ^X */
2271 termios.c_cc[VEOF] = 04; /* ^D */
2272 termios.c_cc[VSTART] = 021; /* ^Q */
2273 termios.c_cc[VSTOP] = 023; /* ^S */
2274 termios.c_cc[VSUSP] = 032; /* ^Z */
2275 termios.c_cc[VLNEXT] = 026; /* ^V */
2276 termios.c_cc[VWERASE] = 027; /* ^W */
2277 termios.c_cc[VREPRINT] = 022; /* ^R */
2278 termios.c_cc[VEOL] = 0;
2279 termios.c_cc[VEOL2] = 0;
2281 termios.c_cc[VTIME] = 0;
2282 termios.c_cc[VMIN] = 1;
2284 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2288 /* Just in case, flush all crap out */
2289 tcflush(fd, TCIOFLUSH);
2294 int reset_terminal(const char *name) {
2297 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2301 r = reset_terminal_fd(fd, true);
2302 close_nointr_nofail(fd);
2307 int open_terminal(const char *name, int mode) {
2312 * If a TTY is in the process of being closed opening it might
2313 * cause EIO. This is horribly awful, but unlikely to be
2314 * changed in the kernel. Hence we work around this problem by
2315 * retrying a couple of times.
2317 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2321 fd = open(name, mode);
2328 /* Max 1s in total */
2332 usleep(50 * USEC_PER_MSEC);
2341 close_nointr_nofail(fd);
2346 close_nointr_nofail(fd);
2353 int flush_fd(int fd) {
2354 struct pollfd pollfd;
2358 pollfd.events = POLLIN;
2365 if ((r = poll(&pollfd, 1, 0)) < 0) {
2376 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2381 if (errno == EAGAIN)
2392 int acquire_terminal(
2396 bool ignore_tiocstty_eperm,
2399 int fd = -1, notify = -1, r = 0, wd = -1;
2401 struct sigaction sa_old, sa_new;
2405 /* We use inotify to be notified when the tty is closed. We
2406 * create the watch before checking if we can actually acquire
2407 * it, so that we don't lose any event.
2409 * Note: strictly speaking this actually watches for the
2410 * device being closed, it does *not* really watch whether a
2411 * tty loses its controlling process. However, unless some
2412 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2413 * its tty otherwise this will not become a problem. As long
2414 * as the administrator makes sure not configure any service
2415 * on the same tty as an untrusted user this should not be a
2416 * problem. (Which he probably should not do anyway.) */
2418 if (timeout != (usec_t) -1)
2419 ts = now(CLOCK_MONOTONIC);
2421 if (!fail && !force) {
2422 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2428 wd = inotify_add_watch(notify, name, IN_CLOSE);
2437 r = flush_fd(notify);
2442 /* We pass here O_NOCTTY only so that we can check the return
2443 * value TIOCSCTTY and have a reliable way to figure out if we
2444 * successfully became the controlling process of the tty */
2445 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2449 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2450 * if we already own the tty. */
2452 sa_new.sa_handler = SIG_IGN;
2453 sa_new.sa_flags = SA_RESTART;
2454 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2456 /* First, try to get the tty */
2457 if (ioctl(fd, TIOCSCTTY, force) < 0)
2460 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2462 /* Sometimes it makes sense to ignore TIOCSCTTY
2463 * returning EPERM, i.e. when very likely we already
2464 * are have this controlling terminal. */
2465 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2468 if (r < 0 && (force || fail || r != -EPERM)) {
2477 assert(notify >= 0);
2480 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2482 struct inotify_event *e;
2484 if (timeout != (usec_t) -1) {
2487 n = now(CLOCK_MONOTONIC);
2488 if (ts + timeout < n) {
2493 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2503 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2506 if (errno == EINTR || errno == EAGAIN)
2513 e = (struct inotify_event*) inotify_buffer;
2518 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2523 step = sizeof(struct inotify_event) + e->len;
2524 assert(step <= (size_t) l);
2526 e = (struct inotify_event*) ((uint8_t*) e + step);
2533 /* We close the tty fd here since if the old session
2534 * ended our handle will be dead. It's important that
2535 * we do this after sleeping, so that we don't enter
2536 * an endless loop. */
2537 close_nointr_nofail(fd);
2541 close_nointr_nofail(notify);
2543 r = reset_terminal_fd(fd, true);
2545 log_warning("Failed to reset terminal: %s", strerror(-r));
2551 close_nointr_nofail(fd);
2554 close_nointr_nofail(notify);
2559 int release_terminal(void) {
2561 struct sigaction sa_old, sa_new;
2563 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2566 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2567 * by our own TIOCNOTTY */
2570 sa_new.sa_handler = SIG_IGN;
2571 sa_new.sa_flags = SA_RESTART;
2572 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2574 if (ioctl(fd, TIOCNOTTY) < 0)
2577 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2579 close_nointr_nofail(fd);
2583 int sigaction_many(const struct sigaction *sa, ...) {
2588 while ((sig = va_arg(ap, int)) > 0)
2589 if (sigaction(sig, sa, NULL) < 0)
2596 int ignore_signals(int sig, ...) {
2597 struct sigaction sa;
2602 sa.sa_handler = SIG_IGN;
2603 sa.sa_flags = SA_RESTART;
2605 if (sigaction(sig, &sa, NULL) < 0)
2609 while ((sig = va_arg(ap, int)) > 0)
2610 if (sigaction(sig, &sa, NULL) < 0)
2617 int default_signals(int sig, ...) {
2618 struct sigaction sa;
2623 sa.sa_handler = SIG_DFL;
2624 sa.sa_flags = SA_RESTART;
2626 if (sigaction(sig, &sa, NULL) < 0)
2630 while ((sig = va_arg(ap, int)) > 0)
2631 if (sigaction(sig, &sa, NULL) < 0)
2638 int close_pipe(int p[]) {
2644 a = close_nointr(p[0]);
2649 b = close_nointr(p[1]);
2653 return a < 0 ? a : b;
2656 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2665 while (nbytes > 0) {
2668 if ((k = read(fd, p, nbytes)) <= 0) {
2670 if (k < 0 && errno == EINTR)
2673 if (k < 0 && errno == EAGAIN && do_poll) {
2674 struct pollfd pollfd;
2678 pollfd.events = POLLIN;
2680 if (poll(&pollfd, 1, -1) < 0) {
2684 return n > 0 ? n : -errno;
2687 if (pollfd.revents != POLLIN)
2688 return n > 0 ? n : -EIO;
2693 return n > 0 ? n : (k < 0 ? -errno : 0);
2704 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2713 while (nbytes > 0) {
2716 k = write(fd, p, nbytes);
2719 if (k < 0 && errno == EINTR)
2722 if (k < 0 && errno == EAGAIN && do_poll) {
2723 struct pollfd pollfd;
2727 pollfd.events = POLLOUT;
2729 if (poll(&pollfd, 1, -1) < 0) {
2733 return n > 0 ? n : -errno;
2736 if (pollfd.revents != POLLOUT)
2737 return n > 0 ? n : -EIO;
2742 return n > 0 ? n : (k < 0 ? -errno : 0);
2753 int parse_usec(const char *t, usec_t *usec) {
2754 static const struct {
2758 { "seconds", USEC_PER_SEC },
2759 { "second", USEC_PER_SEC },
2760 { "sec", USEC_PER_SEC },
2761 { "s", USEC_PER_SEC },
2762 { "minutes", USEC_PER_MINUTE },
2763 { "minute", USEC_PER_MINUTE },
2764 { "min", USEC_PER_MINUTE },
2765 { "months", USEC_PER_MONTH },
2766 { "month", USEC_PER_MONTH },
2767 { "msec", USEC_PER_MSEC },
2768 { "ms", USEC_PER_MSEC },
2769 { "m", USEC_PER_MINUTE },
2770 { "hours", USEC_PER_HOUR },
2771 { "hour", USEC_PER_HOUR },
2772 { "hr", USEC_PER_HOUR },
2773 { "h", USEC_PER_HOUR },
2774 { "days", USEC_PER_DAY },
2775 { "day", USEC_PER_DAY },
2776 { "d", USEC_PER_DAY },
2777 { "weeks", USEC_PER_WEEK },
2778 { "week", USEC_PER_WEEK },
2779 { "w", USEC_PER_WEEK },
2780 { "years", USEC_PER_YEAR },
2781 { "year", USEC_PER_YEAR },
2782 { "y", USEC_PER_YEAR },
2785 { "", USEC_PER_SEC }, /* default is sec */
2801 l = strtoll(p, &e, 10);
2812 e += strspn(e, WHITESPACE);
2814 for (i = 0; i < ELEMENTSOF(table); i++)
2815 if (startswith(e, table[i].suffix)) {
2816 r += (usec_t) l * table[i].usec;
2817 p = e + strlen(table[i].suffix);
2821 if (i >= ELEMENTSOF(table))
2831 int parse_nsec(const char *t, nsec_t *nsec) {
2832 static const struct {
2836 { "seconds", NSEC_PER_SEC },
2837 { "second", NSEC_PER_SEC },
2838 { "sec", NSEC_PER_SEC },
2839 { "s", NSEC_PER_SEC },
2840 { "minutes", NSEC_PER_MINUTE },
2841 { "minute", NSEC_PER_MINUTE },
2842 { "min", NSEC_PER_MINUTE },
2843 { "months", NSEC_PER_MONTH },
2844 { "month", NSEC_PER_MONTH },
2845 { "msec", NSEC_PER_MSEC },
2846 { "ms", NSEC_PER_MSEC },
2847 { "m", NSEC_PER_MINUTE },
2848 { "hours", NSEC_PER_HOUR },
2849 { "hour", NSEC_PER_HOUR },
2850 { "hr", NSEC_PER_HOUR },
2851 { "h", NSEC_PER_HOUR },
2852 { "days", NSEC_PER_DAY },
2853 { "day", NSEC_PER_DAY },
2854 { "d", NSEC_PER_DAY },
2855 { "weeks", NSEC_PER_WEEK },
2856 { "week", NSEC_PER_WEEK },
2857 { "w", NSEC_PER_WEEK },
2858 { "years", NSEC_PER_YEAR },
2859 { "year", NSEC_PER_YEAR },
2860 { "y", NSEC_PER_YEAR },
2861 { "usec", NSEC_PER_USEC },
2862 { "us", NSEC_PER_USEC },
2865 { "", 1ULL }, /* default is nsec */
2881 l = strtoll(p, &e, 10);
2892 e += strspn(e, WHITESPACE);
2894 for (i = 0; i < ELEMENTSOF(table); i++)
2895 if (startswith(e, table[i].suffix)) {
2896 r += (nsec_t) l * table[i].nsec;
2897 p = e + strlen(table[i].suffix);
2901 if (i >= ELEMENTSOF(table))
2911 int parse_bytes(const char *t, off_t *bytes) {
2912 static const struct {
2918 { "M", 1024ULL*1024ULL },
2919 { "G", 1024ULL*1024ULL*1024ULL },
2920 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2921 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2922 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2939 l = strtoll(p, &e, 10);
2950 e += strspn(e, WHITESPACE);
2952 for (i = 0; i < ELEMENTSOF(table); i++)
2953 if (startswith(e, table[i].suffix)) {
2954 r += (off_t) l * table[i].factor;
2955 p = e + strlen(table[i].suffix);
2959 if (i >= ELEMENTSOF(table))
2969 int make_stdio(int fd) {
2974 r = dup3(fd, STDIN_FILENO, 0);
2975 s = dup3(fd, STDOUT_FILENO, 0);
2976 t = dup3(fd, STDERR_FILENO, 0);
2979 close_nointr_nofail(fd);
2981 if (r < 0 || s < 0 || t < 0)
2984 /* We rely here that the new fd has O_CLOEXEC not set */
2989 int make_null_stdio(void) {
2992 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2996 return make_stdio(null_fd);
2999 bool is_device_path(const char *path) {
3001 /* Returns true on paths that refer to a device, either in
3002 * sysfs or in /dev */
3005 path_startswith(path, "/dev/") ||
3006 path_startswith(path, "/sys/");
3009 int dir_is_empty(const char *path) {
3010 _cleanup_closedir_ DIR *d;
3019 union dirent_storage buf;
3021 r = readdir_r(d, &buf.de, &de);
3028 if (!ignore_file(de->d_name))
3033 unsigned long long random_ull(void) {
3034 _cleanup_close_ int fd;
3038 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3042 r = loop_read(fd, &ull, sizeof(ull), true);
3043 if (r != sizeof(ull))
3049 return random() * RAND_MAX + random();
3052 void rename_process(const char name[8]) {
3055 /* This is a like a poor man's setproctitle(). It changes the
3056 * comm field, argv[0], and also the glibc's internally used
3057 * name of the process. For the first one a limit of 16 chars
3058 * applies, to the second one usually one of 10 (i.e. length
3059 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3060 * "systemd"). If you pass a longer string it will be
3063 prctl(PR_SET_NAME, name);
3065 if (program_invocation_name)
3066 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3068 if (saved_argc > 0) {
3072 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3074 for (i = 1; i < saved_argc; i++) {
3078 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3083 void sigset_add_many(sigset_t *ss, ...) {
3090 while ((sig = va_arg(ap, int)) > 0)
3091 assert_se(sigaddset(ss, sig) == 0);
3095 char* gethostname_malloc(void) {
3098 assert_se(uname(&u) >= 0);
3100 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3101 return strdup(u.nodename);
3103 return strdup(u.sysname);
3106 bool hostname_is_set(void) {
3109 assert_se(uname(&u) >= 0);
3111 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3114 static char *lookup_uid(uid_t uid) {
3117 _cleanup_free_ char *buf = NULL;
3118 struct passwd pwbuf, *pw = NULL;
3120 /* Shortcut things to avoid NSS lookups */
3122 return strdup("root");
3124 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3128 buf = malloc(bufsize);
3132 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3133 return strdup(pw->pw_name);
3135 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3141 char* getlogname_malloc(void) {
3145 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3150 return lookup_uid(uid);
3153 char *getusername_malloc(void) {
3160 return lookup_uid(getuid());
3163 int getttyname_malloc(int fd, char **r) {
3164 char path[PATH_MAX], *c;
3169 k = ttyname_r(fd, path, sizeof(path));
3175 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3183 int getttyname_harder(int fd, char **r) {
3187 k = getttyname_malloc(fd, &s);
3191 if (streq(s, "tty")) {
3193 return get_ctty(0, NULL, r);
3200 int get_ctty_devnr(pid_t pid, dev_t *d) {
3202 char line[LINE_MAX], *p, *fn;
3203 unsigned long ttynr;
3206 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3209 f = fopen(fn, "re");
3214 if (!fgets(line, sizeof(line), f)) {
3215 k = feof(f) ? -EIO : -errno;
3222 p = strrchr(line, ')');
3232 "%*d " /* session */
3241 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3243 char fn[PATH_MAX], *s, *b, *p;
3248 k = get_ctty_devnr(pid, &devnr);
3252 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3255 if ((k = readlink_malloc(fn, &s)) < 0) {
3260 /* This is an ugly hack */
3261 if (major(devnr) == 136) {
3262 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3272 /* Probably something like the ptys which have no
3273 * symlink in /dev/char. Let's return something
3274 * vaguely useful. */
3276 if (!(b = strdup(fn + 5)))
3286 if (startswith(s, "/dev/"))
3288 else if (startswith(s, "../"))
3306 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3312 /* This returns the first error we run into, but nevertheless
3313 * tries to go on. This closes the passed fd. */
3317 close_nointr_nofail(fd);
3319 return errno == ENOENT ? 0 : -errno;
3324 union dirent_storage buf;
3325 bool is_dir, keep_around;
3329 r = readdir_r(d, &buf.de, &de);
3330 if (r != 0 && ret == 0) {
3338 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3341 if (de->d_type == DT_UNKNOWN ||
3343 (de->d_type == DT_DIR && root_dev)) {
3344 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3345 if (ret == 0 && errno != ENOENT)
3350 is_dir = S_ISDIR(st.st_mode);
3353 (st.st_uid == 0 || st.st_uid == getuid()) &&
3354 (st.st_mode & S_ISVTX);
3356 is_dir = de->d_type == DT_DIR;
3357 keep_around = false;
3363 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3364 if (root_dev && st.st_dev != root_dev->st_dev)
3367 subdir_fd = openat(fd, de->d_name,
3368 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3369 if (subdir_fd < 0) {
3370 if (ret == 0 && errno != ENOENT)
3375 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3376 if (r < 0 && ret == 0)
3380 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3381 if (ret == 0 && errno != ENOENT)
3385 } else if (!only_dirs && !keep_around) {
3387 if (unlinkat(fd, de->d_name, 0) < 0) {
3388 if (ret == 0 && errno != ENOENT)
3399 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3404 if (fstatfs(fd, &s) < 0) {
3405 close_nointr_nofail(fd);
3409 /* We refuse to clean disk file systems with this call. This
3410 * is extra paranoia just to be sure we never ever remove
3413 if (s.f_type != TMPFS_MAGIC &&
3414 s.f_type != RAMFS_MAGIC) {
3415 log_error("Attempted to remove disk file system, and we can't allow that.");
3416 close_nointr_nofail(fd);
3420 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3423 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3429 /* We refuse to clean the root file system with this
3430 * call. This is extra paranoia to never cause a really
3431 * seriously broken system. */
3432 if (path_equal(path, "/")) {
3433 log_error("Attempted to remove entire root file system, and we can't allow that.");
3437 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3440 if (errno != ENOTDIR)
3444 if (statfs(path, &s) < 0)
3447 if (s.f_type != TMPFS_MAGIC &&
3448 s.f_type != RAMFS_MAGIC) {
3449 log_error("Attempted to remove disk file system, and we can't allow that.");
3454 if (delete_root && !only_dirs)
3455 if (unlink(path) < 0 && errno != ENOENT)
3462 if (fstatfs(fd, &s) < 0) {
3463 close_nointr_nofail(fd);
3467 if (s.f_type != TMPFS_MAGIC &&
3468 s.f_type != RAMFS_MAGIC) {
3469 log_error("Attempted to remove disk file system, and we can't allow that.");
3470 close_nointr_nofail(fd);
3475 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3478 if (honour_sticky && file_is_priv_sticky(path) > 0)
3481 if (rmdir(path) < 0 && errno != ENOENT) {
3490 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3491 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3494 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3495 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3498 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3501 /* Under the assumption that we are running privileged we
3502 * first change the access mode and only then hand out
3503 * ownership to avoid a window where access is too open. */
3505 if (mode != (mode_t) -1)
3506 if (chmod(path, mode) < 0)
3509 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3510 if (chown(path, uid, gid) < 0)
3516 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3519 /* Under the assumption that we are running privileged we
3520 * first change the access mode and only then hand out
3521 * ownership to avoid a window where access is too open. */
3523 if (fchmod(fd, mode) < 0)
3526 if (fchown(fd, uid, gid) < 0)
3532 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3536 /* Allocates the cpuset in the right size */
3539 if (!(r = CPU_ALLOC(n)))
3542 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3543 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3553 if (errno != EINVAL)
3560 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3561 static const char status_indent[] = " "; /* "[" STATUS "] " */
3562 _cleanup_free_ char *s = NULL;
3563 _cleanup_close_ int fd = -1;
3564 struct iovec iovec[5];
3569 /* This is independent of logging, as status messages are
3570 * optional and go exclusively to the console. */
3572 if (vasprintf(&s, format, ap) < 0)
3575 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3588 sl = status ? sizeof(status_indent)-1 : 0;
3594 e = ellipsize(s, emax, 75);
3604 if (!isempty(status)) {
3605 IOVEC_SET_STRING(iovec[n++], "[");
3606 IOVEC_SET_STRING(iovec[n++], status);
3607 IOVEC_SET_STRING(iovec[n++], "] ");
3609 IOVEC_SET_STRING(iovec[n++], status_indent);
3612 IOVEC_SET_STRING(iovec[n++], s);
3613 IOVEC_SET_STRING(iovec[n++], "\n");
3615 if (writev(fd, iovec, n) < 0)
3621 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3627 va_start(ap, format);
3628 r = status_vprintf(status, ellipse, format, ap);
3634 int status_welcome(void) {
3636 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3638 r = parse_env_file("/etc/os-release", NEWLINE,
3639 "PRETTY_NAME", &pretty_name,
3640 "ANSI_COLOR", &ansi_color,
3642 if (r < 0 && r != -ENOENT)
3643 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3645 return status_printf(NULL, false,
3646 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3647 isempty(ansi_color) ? "1" : ansi_color,
3648 isempty(pretty_name) ? "Linux" : pretty_name);
3651 char *replace_env(const char *format, char **env) {
3658 const char *e, *word = format;
3663 for (e = format; *e; e ++) {
3674 if (!(k = strnappend(r, word, e-word-1)))
3683 } else if (*e == '$') {
3684 if (!(k = strnappend(r, word, e-word)))
3700 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3703 if (!(k = strappend(r, t)))
3716 if (!(k = strnappend(r, word, e-word)))
3727 char **replace_env_argv(char **argv, char **env) {
3729 unsigned k = 0, l = 0;
3731 l = strv_length(argv);
3733 if (!(r = new(char*, l+1)))
3736 STRV_FOREACH(i, argv) {
3738 /* If $FOO appears as single word, replace it by the split up variable */
3739 if ((*i)[0] == '$' && (*i)[1] != '{') {
3744 if ((e = strv_env_get(env, *i+1))) {
3746 if (!(m = strv_split_quoted(e))) {
3757 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3766 memcpy(r + k, m, q * sizeof(char*));
3774 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3775 if (!(r[k++] = replace_env(*i, env))) {
3785 int fd_columns(int fd) {
3789 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3798 unsigned columns(void) {
3802 if (_likely_(cached_columns > 0))
3803 return cached_columns;
3806 e = getenv("COLUMNS");
3811 c = fd_columns(STDOUT_FILENO);
3820 int fd_lines(int fd) {
3824 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3833 unsigned lines(void) {
3837 if (_likely_(cached_lines > 0))
3838 return cached_lines;
3841 e = getenv("LINES");
3846 l = fd_lines(STDOUT_FILENO);
3852 return cached_lines;
3855 /* intended to be used as a SIGWINCH sighandler */
3856 void columns_lines_cache_reset(int signum) {
3862 static int cached_on_tty = -1;
3864 if (_unlikely_(cached_on_tty < 0))
3865 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3867 return cached_on_tty;
3870 int running_in_chroot(void) {
3876 /* Only works as root */
3878 if (stat("/proc/1/root", &a) < 0)
3881 if (stat("/", &b) < 0)
3885 a.st_dev != b.st_dev ||
3886 a.st_ino != b.st_ino;
3889 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3894 assert(percent <= 100);
3895 assert(new_length >= 3);
3897 if (old_length <= 3 || old_length <= new_length)
3898 return strndup(s, old_length);
3900 r = new0(char, new_length+1);
3904 x = (new_length * percent) / 100;
3906 if (x > new_length - 3)
3914 s + old_length - (new_length - x - 3),
3915 new_length - x - 3);
3920 char *ellipsize(const char *s, size_t length, unsigned percent) {
3921 return ellipsize_mem(s, strlen(s), length, percent);
3924 int touch(const char *path) {
3929 /* This just opens the file for writing, ensuring it
3930 * exists. It doesn't call utimensat() the way /usr/bin/touch
3933 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3937 close_nointr_nofail(fd);
3941 char *unquote(const char *s, const char* quotes) {
3945 /* This is rather stupid, simply removes the heading and
3946 * trailing quotes if there is one. Doesn't care about
3947 * escaping or anything. We should make this smarter one
3954 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3955 return strndup(s+1, l-2);
3960 char *normalize_env_assignment(const char *s) {
3961 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3964 eq = strchr(s, '=');
3976 memmove(r, t, strlen(t) + 1);
3980 name = strndup(s, eq - s);
3988 value = unquote(strstrip(p), QUOTES);
3992 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3998 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4009 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4021 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4028 r = wait_for_terminate(pid, &status);
4030 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4034 if (status.si_code == CLD_EXITED) {
4035 if (status.si_status != 0) {
4036 log_warning("%s failed with error code %i.", name, status.si_status);
4037 return status.si_status;
4040 log_debug("%s succeeded.", name);
4043 } else if (status.si_code == CLD_KILLED ||
4044 status.si_code == CLD_DUMPED) {
4046 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4050 log_warning("%s failed due to unknown reason.", name);
4054 _noreturn_ void freeze(void) {
4056 /* Make sure nobody waits for us on a socket anymore */
4057 close_all_fds(NULL, 0);
4065 bool null_or_empty(struct stat *st) {
4068 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4071 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4077 int null_or_empty_path(const char *fn) {
4082 if (stat(fn, &st) < 0)
4085 return null_or_empty(&st);
4088 DIR *xopendirat(int fd, const char *name, int flags) {
4092 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4098 close_nointr_nofail(nfd);
4105 int signal_from_string_try_harder(const char *s) {
4109 signo = signal_from_string(s);
4111 if (startswith(s, "SIG"))
4112 return signal_from_string(s+3);
4117 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4123 if (!dual_timestamp_is_set(t))
4126 fprintf(f, "%s=%llu %llu\n",
4128 (unsigned long long) t->realtime,
4129 (unsigned long long) t->monotonic);
4132 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4133 unsigned long long a, b;
4138 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4139 log_debug("Failed to parse finish timestamp value %s", value);
4146 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4150 /* FIXME: to follow udev's logic 100% we need to leave valid
4151 * UTF8 chars unescaped */
4153 u = unquote(tagvalue, "\"\'");
4157 t = xescape(u, "/ ");
4163 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4172 char *fstab_node_to_udev_node(const char *p) {
4175 if (startswith(p, "LABEL="))
4176 return tag_to_udev_node(p+6, "label");
4178 if (startswith(p, "UUID="))
4179 return tag_to_udev_node(p+5, "uuid");
4181 if (startswith(p, "PARTUUID="))
4182 return tag_to_udev_node(p+9, "partuuid");
4184 if (startswith(p, "PARTLABEL="))
4185 return tag_to_udev_node(p+10, "partlabel");
4190 bool tty_is_vc(const char *tty) {
4193 if (startswith(tty, "/dev/"))
4196 return vtnr_from_tty(tty) >= 0;
4199 bool tty_is_console(const char *tty) {
4202 if (startswith(tty, "/dev/"))
4205 return streq(tty, "console");
4208 int vtnr_from_tty(const char *tty) {
4213 if (startswith(tty, "/dev/"))
4216 if (!startswith(tty, "tty") )
4219 if (tty[3] < '0' || tty[3] > '9')
4222 r = safe_atoi(tty+3, &i);
4226 if (i < 0 || i > 63)
4232 bool tty_is_vc_resolve(const char *tty) {
4233 char *active = NULL;
4238 if (startswith(tty, "/dev/"))
4241 /* Resolve where /dev/console is pointing to, if /sys is
4242 * actually ours (i.e. not read-only-mounted which is a sign
4243 * for container setups) */
4244 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4245 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4246 /* If multiple log outputs are configured the
4247 * last one is what /dev/console points to */
4248 tty = strrchr(active, ' ');
4261 const char *default_term_for_tty(const char *tty) {
4264 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4267 bool dirent_is_file(const struct dirent *de) {
4270 if (ignore_file(de->d_name))
4273 if (de->d_type != DT_REG &&
4274 de->d_type != DT_LNK &&
4275 de->d_type != DT_UNKNOWN)
4281 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4284 if (de->d_type != DT_REG &&
4285 de->d_type != DT_LNK &&
4286 de->d_type != DT_UNKNOWN)
4289 if (ignore_file_allow_backup(de->d_name))
4292 return endswith(de->d_name, suffix);
4295 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4298 Hashmap *pids = NULL;
4302 /* Executes all binaries in a directory in parallel and waits
4303 * until all they all finished. */
4306 if (!(_d = opendir(directory))) {
4308 if (errno == ENOENT)
4311 log_error("Failed to enumerate directory %s: %m", directory);
4318 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4319 log_error("Failed to allocate set.");
4323 while ((de = readdir(d))) {
4328 if (!dirent_is_file(de))
4331 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4336 if ((pid = fork()) < 0) {
4337 log_error("Failed to fork: %m");
4355 log_error("Failed to execute %s: %m", path);
4356 _exit(EXIT_FAILURE);
4359 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4361 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4362 log_error("Failed to add PID to set: %s", strerror(-k));
4367 while (!hashmap_isempty(pids)) {
4368 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4373 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4378 log_error("waitid() failed: %m");
4382 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4383 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4384 if (si.si_code == CLD_EXITED)
4385 log_error("%s exited with exit status %i.", path, si.si_status);
4387 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4389 log_debug("%s exited successfully.", path);
4400 hashmap_free_free(pids);
4403 int kill_and_sigcont(pid_t pid, int sig) {
4406 r = kill(pid, sig) < 0 ? -errno : 0;
4414 bool nulstr_contains(const char*nulstr, const char *needle) {
4420 NULSTR_FOREACH(i, nulstr)
4421 if (streq(i, needle))
4427 bool plymouth_running(void) {
4428 return access("/run/plymouth/pid", F_OK) >= 0;
4431 char* strshorten(char *s, size_t l) {
4440 static bool hostname_valid_char(char c) {
4442 (c >= 'a' && c <= 'z') ||
4443 (c >= 'A' && c <= 'Z') ||
4444 (c >= '0' && c <= '9') ||
4450 bool hostname_is_valid(const char *s) {
4456 for (p = s; *p; p++)
4457 if (!hostname_valid_char(*p))
4460 if (p-s > HOST_NAME_MAX)
4466 char* hostname_cleanup(char *s) {
4469 for (p = s, d = s; *p; p++)
4470 if ((*p >= 'a' && *p <= 'z') ||
4471 (*p >= 'A' && *p <= 'Z') ||
4472 (*p >= '0' && *p <= '9') ||
4480 strshorten(s, HOST_NAME_MAX);
4484 int pipe_eof(int fd) {
4485 struct pollfd pollfd;
4490 pollfd.events = POLLIN|POLLHUP;
4492 r = poll(&pollfd, 1, 0);
4499 return pollfd.revents & POLLHUP;
4502 int fd_wait_for_event(int fd, int event, usec_t t) {
4503 struct pollfd pollfd;
4508 pollfd.events = event;
4510 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4517 return pollfd.revents;
4520 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4531 t = new(char, strlen(path) + 1 + 6 + 1);
4535 fn = path_get_file_name(path);
4539 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4541 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4547 f = fdopen(fd, "we");
4560 int terminal_vhangup_fd(int fd) {
4563 if (ioctl(fd, TIOCVHANGUP) < 0)
4569 int terminal_vhangup(const char *name) {
4572 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4576 r = terminal_vhangup_fd(fd);
4577 close_nointr_nofail(fd);
4582 int vt_disallocate(const char *name) {
4586 /* Deallocate the VT if possible. If not possible
4587 * (i.e. because it is the active one), at least clear it
4588 * entirely (including the scrollback buffer) */
4590 if (!startswith(name, "/dev/"))
4593 if (!tty_is_vc(name)) {
4594 /* So this is not a VT. I guess we cannot deallocate
4595 * it then. But let's at least clear the screen */
4597 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4602 "\033[r" /* clear scrolling region */
4603 "\033[H" /* move home */
4604 "\033[2J", /* clear screen */
4606 close_nointr_nofail(fd);
4611 if (!startswith(name, "/dev/tty"))
4614 r = safe_atou(name+8, &u);
4621 /* Try to deallocate */
4622 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4626 r = ioctl(fd, VT_DISALLOCATE, u);
4627 close_nointr_nofail(fd);
4635 /* Couldn't deallocate, so let's clear it fully with
4637 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4642 "\033[r" /* clear scrolling region */
4643 "\033[H" /* move home */
4644 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4646 close_nointr_nofail(fd);
4651 int copy_file(const char *from, const char *to) {
4657 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4661 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4663 close_nointr_nofail(fdf);
4671 n = read(fdf, buf, sizeof(buf));
4675 close_nointr_nofail(fdf);
4686 k = loop_write(fdt, buf, n, false);
4688 r = k < 0 ? k : (errno ? -errno : -EIO);
4690 close_nointr_nofail(fdf);
4698 close_nointr_nofail(fdf);
4699 r = close_nointr(fdt);
4709 int symlink_atomic(const char *from, const char *to) {
4711 _cleanup_free_ char *t;
4714 unsigned long long ull;
4721 t = new(char, strlen(to) + 1 + 16 + 1);
4725 fn = path_get_file_name(to);
4729 x = stpcpy(t+k+1, fn);
4732 for (i = 0; i < 16; i++) {
4733 *(x++) = hexchar(ull & 0xF);
4739 if (symlink(from, t) < 0)
4742 if (rename(t, to) < 0) {
4751 bool display_is_local(const char *display) {
4755 display[0] == ':' &&
4756 display[1] >= '0' &&
4760 int socket_from_display(const char *display, char **path) {
4767 if (!display_is_local(display))
4770 k = strspn(display+1, "0123456789");
4772 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4776 c = stpcpy(f, "/tmp/.X11-unix/X");
4777 memcpy(c, display+1, k);
4786 const char **username,
4787 uid_t *uid, gid_t *gid,
4789 const char **shell) {
4797 /* We enforce some special rules for uid=0: in order to avoid
4798 * NSS lookups for root we hardcode its data. */
4800 if (streq(*username, "root") || streq(*username, "0")) {
4818 if (parse_uid(*username, &u) >= 0) {
4822 /* If there are multiple users with the same id, make
4823 * sure to leave $USER to the configured value instead
4824 * of the first occurrence in the database. However if
4825 * the uid was configured by a numeric uid, then let's
4826 * pick the real username from /etc/passwd. */
4828 *username = p->pw_name;
4831 p = getpwnam(*username);
4835 return errno != 0 ? -errno : -ESRCH;
4847 *shell = p->pw_shell;
4852 int get_group_creds(const char **groupname, gid_t *gid) {
4858 /* We enforce some special rules for gid=0: in order to avoid
4859 * NSS lookups for root we hardcode its data. */
4861 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4862 *groupname = "root";
4870 if (parse_gid(*groupname, &id) >= 0) {
4875 *groupname = g->gr_name;
4878 g = getgrnam(*groupname);
4882 return errno != 0 ? -errno : -ESRCH;
4890 int in_group(const char *name) {
4892 int ngroups_max, r, i;
4894 r = get_group_creds(&name, &gid);
4898 if (getgid() == gid)
4901 if (getegid() == gid)
4904 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4905 assert(ngroups_max > 0);
4907 gids = alloca(sizeof(gid_t) * ngroups_max);
4909 r = getgroups(ngroups_max, gids);
4913 for (i = 0; i < r; i++)
4920 int glob_exists(const char *path) {
4928 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4930 if (k == GLOB_NOMATCH)
4932 else if (k == GLOB_NOSPACE)
4935 r = !strv_isempty(g.gl_pathv);
4937 r = errno ? -errno : -EIO;
4944 int dirent_ensure_type(DIR *d, struct dirent *de) {
4950 if (de->d_type != DT_UNKNOWN)
4953 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4957 S_ISREG(st.st_mode) ? DT_REG :
4958 S_ISDIR(st.st_mode) ? DT_DIR :
4959 S_ISLNK(st.st_mode) ? DT_LNK :
4960 S_ISFIFO(st.st_mode) ? DT_FIFO :
4961 S_ISSOCK(st.st_mode) ? DT_SOCK :
4962 S_ISCHR(st.st_mode) ? DT_CHR :
4963 S_ISBLK(st.st_mode) ? DT_BLK :
4969 int in_search_path(const char *path, char **search) {
4973 r = path_get_parent(path, &parent);
4979 STRV_FOREACH(i, search) {
4980 if (path_equal(parent, *i)) {
4991 int get_files_in_directory(const char *path, char ***list) {
4999 /* Returns all files in a directory in *list, and the number
5000 * of files as return value. If list is NULL returns only the
5009 union dirent_storage buf;
5012 k = readdir_r(d, &buf.de, &de);
5021 dirent_ensure_type(d, de);
5023 if (!dirent_is_file(de))
5027 if ((unsigned) r >= n) {
5031 t = realloc(l, sizeof(char*) * n);
5040 assert((unsigned) r < n);
5042 l[r] = strdup(de->d_name);
5066 char *strjoin(const char *x, ...) {
5080 t = va_arg(ap, const char *);
5085 if (n > ((size_t) -1) - l) {
5109 t = va_arg(ap, const char *);
5123 bool is_main_thread(void) {
5124 static __thread int cached = 0;
5126 if (_unlikely_(cached == 0))
5127 cached = getpid() == gettid() ? 1 : -1;
5132 int block_get_whole_disk(dev_t d, dev_t *ret) {
5139 /* If it has a queue this is good enough for us */
5140 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5143 r = access(p, F_OK);
5151 /* If it is a partition find the originating device */
5152 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5155 r = access(p, F_OK);
5161 /* Get parent dev_t */
5162 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5165 r = read_one_line_file(p, &s);
5171 r = sscanf(s, "%u:%u", &m, &n);
5177 /* Only return this if it is really good enough for us. */
5178 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5181 r = access(p, F_OK);
5185 *ret = makedev(m, n);
5192 int file_is_priv_sticky(const char *p) {
5197 if (lstat(p, &st) < 0)
5201 (st.st_uid == 0 || st.st_uid == getuid()) &&
5202 (st.st_mode & S_ISVTX);
5205 static const char *const ioprio_class_table[] = {
5206 [IOPRIO_CLASS_NONE] = "none",
5207 [IOPRIO_CLASS_RT] = "realtime",
5208 [IOPRIO_CLASS_BE] = "best-effort",
5209 [IOPRIO_CLASS_IDLE] = "idle"
5212 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
5214 static const char *const sigchld_code_table[] = {
5215 [CLD_EXITED] = "exited",
5216 [CLD_KILLED] = "killed",
5217 [CLD_DUMPED] = "dumped",
5218 [CLD_TRAPPED] = "trapped",
5219 [CLD_STOPPED] = "stopped",
5220 [CLD_CONTINUED] = "continued",
5223 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5225 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5226 [LOG_FAC(LOG_KERN)] = "kern",
5227 [LOG_FAC(LOG_USER)] = "user",
5228 [LOG_FAC(LOG_MAIL)] = "mail",
5229 [LOG_FAC(LOG_DAEMON)] = "daemon",
5230 [LOG_FAC(LOG_AUTH)] = "auth",
5231 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5232 [LOG_FAC(LOG_LPR)] = "lpr",
5233 [LOG_FAC(LOG_NEWS)] = "news",
5234 [LOG_FAC(LOG_UUCP)] = "uucp",
5235 [LOG_FAC(LOG_CRON)] = "cron",
5236 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5237 [LOG_FAC(LOG_FTP)] = "ftp",
5238 [LOG_FAC(LOG_LOCAL0)] = "local0",
5239 [LOG_FAC(LOG_LOCAL1)] = "local1",
5240 [LOG_FAC(LOG_LOCAL2)] = "local2",
5241 [LOG_FAC(LOG_LOCAL3)] = "local3",
5242 [LOG_FAC(LOG_LOCAL4)] = "local4",
5243 [LOG_FAC(LOG_LOCAL5)] = "local5",
5244 [LOG_FAC(LOG_LOCAL6)] = "local6",
5245 [LOG_FAC(LOG_LOCAL7)] = "local7"
5248 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5250 static const char *const log_level_table[] = {
5251 [LOG_EMERG] = "emerg",
5252 [LOG_ALERT] = "alert",
5253 [LOG_CRIT] = "crit",
5255 [LOG_WARNING] = "warning",
5256 [LOG_NOTICE] = "notice",
5257 [LOG_INFO] = "info",
5258 [LOG_DEBUG] = "debug"
5261 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5263 static const char* const sched_policy_table[] = {
5264 [SCHED_OTHER] = "other",
5265 [SCHED_BATCH] = "batch",
5266 [SCHED_IDLE] = "idle",
5267 [SCHED_FIFO] = "fifo",
5271 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5273 static const char* const rlimit_table[] = {
5274 [RLIMIT_CPU] = "LimitCPU",
5275 [RLIMIT_FSIZE] = "LimitFSIZE",
5276 [RLIMIT_DATA] = "LimitDATA",
5277 [RLIMIT_STACK] = "LimitSTACK",
5278 [RLIMIT_CORE] = "LimitCORE",
5279 [RLIMIT_RSS] = "LimitRSS",
5280 [RLIMIT_NOFILE] = "LimitNOFILE",
5281 [RLIMIT_AS] = "LimitAS",
5282 [RLIMIT_NPROC] = "LimitNPROC",
5283 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5284 [RLIMIT_LOCKS] = "LimitLOCKS",
5285 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5286 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5287 [RLIMIT_NICE] = "LimitNICE",
5288 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5289 [RLIMIT_RTTIME] = "LimitRTTIME"
5292 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5294 static const char* const ip_tos_table[] = {
5295 [IPTOS_LOWDELAY] = "low-delay",
5296 [IPTOS_THROUGHPUT] = "throughput",
5297 [IPTOS_RELIABILITY] = "reliability",
5298 [IPTOS_LOWCOST] = "low-cost",
5301 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5303 static const char *const __signal_table[] = {
5320 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5331 [SIGVTALRM] = "VTALRM",
5333 [SIGWINCH] = "WINCH",
5339 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5341 const char *signal_to_string(int signo) {
5342 static __thread char buf[12];
5345 name = __signal_to_string(signo);
5349 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5350 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5352 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5357 int signal_from_string(const char *s) {
5362 signo = __signal_from_string(s);
5366 if (startswith(s, "RTMIN+")) {
5370 if (safe_atou(s, &u) >= 0) {
5371 signo = (int) u + offset;
5372 if (signo > 0 && signo < _NSIG)
5378 bool kexec_loaded(void) {
5379 bool loaded = false;
5382 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5390 int strdup_or_null(const char *a, char **b) {
5408 int prot_from_flags(int flags) {
5410 switch (flags & O_ACCMODE) {
5419 return PROT_READ|PROT_WRITE;
5426 char *format_bytes(char *buf, size_t l, off_t t) {
5429 static const struct {
5433 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5434 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5435 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5436 { "G", 1024ULL*1024ULL*1024ULL },
5437 { "M", 1024ULL*1024ULL },
5441 for (i = 0; i < ELEMENTSOF(table); i++) {
5443 if (t >= table[i].factor) {
5446 (unsigned long long) (t / table[i].factor),
5447 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5454 snprintf(buf, l, "%lluB", (unsigned long long) t);
5462 void* memdup(const void *p, size_t l) {
5475 int fd_inc_sndbuf(int fd, size_t n) {
5477 socklen_t l = sizeof(value);
5479 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5481 l == sizeof(value) &&
5482 (size_t) value >= n*2)
5486 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5493 int fd_inc_rcvbuf(int fd, size_t n) {
5495 socklen_t l = sizeof(value);
5497 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5499 l == sizeof(value) &&
5500 (size_t) value >= n*2)
5504 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5511 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5512 pid_t parent_pid, agent_pid;
5514 bool stdout_is_tty, stderr_is_tty;
5522 parent_pid = getpid();
5524 /* Spawns a temporary TTY agent, making sure it goes away when
5531 if (agent_pid != 0) {
5538 * Make sure the agent goes away when the parent dies */
5539 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5540 _exit(EXIT_FAILURE);
5542 /* Check whether our parent died before we were able
5543 * to set the death signal */
5544 if (getppid() != parent_pid)
5545 _exit(EXIT_SUCCESS);
5547 /* Don't leak fds to the agent */
5548 close_all_fds(except, n_except);
5550 stdout_is_tty = isatty(STDOUT_FILENO);
5551 stderr_is_tty = isatty(STDERR_FILENO);
5553 if (!stdout_is_tty || !stderr_is_tty) {
5554 /* Detach from stdout/stderr. and reopen
5555 * /dev/tty for them. This is important to
5556 * ensure that when systemctl is started via
5557 * popen() or a similar call that expects to
5558 * read EOF we actually do generate EOF and
5559 * not delay this indefinitely by because we
5560 * keep an unused copy of stdin around. */
5561 fd = open("/dev/tty", O_WRONLY);
5563 log_error("Failed to open /dev/tty: %m");
5564 _exit(EXIT_FAILURE);
5568 dup2(fd, STDOUT_FILENO);
5571 dup2(fd, STDERR_FILENO);
5577 /* Count arguments */
5579 for (n = 0; va_arg(ap, char*); n++)
5584 l = alloca(sizeof(char *) * (n + 1));
5586 /* Fill in arguments */
5588 for (i = 0; i <= n; i++)
5589 l[i] = va_arg(ap, char*);
5593 _exit(EXIT_FAILURE);
5596 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5597 struct rlimit highest, fixed;
5601 if (setrlimit(resource, rlim) >= 0)
5607 /* So we failed to set the desired setrlimit, then let's try
5608 * to get as close as we can */
5609 assert_se(getrlimit(resource, &highest) == 0);
5611 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5612 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5614 if (setrlimit(resource, &fixed) < 0)
5620 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5621 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5633 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5636 f = fopen(path, "re");
5644 char line[LINE_MAX];
5647 for (i = 0; i < sizeof(line)-1; i++) {
5651 if (_unlikely_(c == EOF)) {
5661 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5662 value = strdup(line + l + 1);
5682 int can_sleep(const char *type) {
5686 _cleanup_free_ char *p = NULL;
5690 r = read_one_line_file("/sys/power/state", &p);
5692 return r == -ENOENT ? 0 : r;
5695 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5696 if (l == k && memcmp(w, type, l) == 0)
5702 int can_sleep_disk(const char *type) {
5706 _cleanup_free_ char *p = NULL;
5710 r = read_one_line_file("/sys/power/disk", &p);
5712 return r == -ENOENT ? 0 : r;
5715 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5716 if (l == k && memcmp(w, type, l) == 0)
5719 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5726 bool is_valid_documentation_url(const char *url) {
5729 if (startswith(url, "http://") && url[7])
5732 if (startswith(url, "https://") && url[8])
5735 if (startswith(url, "file:") && url[5])
5738 if (startswith(url, "info:") && url[5])
5741 if (startswith(url, "man:") && url[4])
5747 bool in_initrd(void) {
5748 static __thread int saved = -1;
5754 /* We make two checks here:
5756 * 1. the flag file /etc/initrd-release must exist
5757 * 2. the root file system must be a memory file system
5759 * The second check is extra paranoia, since misdetecting an
5760 * initrd can have bad bad consequences due the initrd
5761 * emptying when transititioning to the main systemd.
5764 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5765 statfs("/", &s) >= 0 &&
5766 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5771 void warn_melody(void) {
5772 _cleanup_close_ int fd = -1;
5774 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5778 /* Yeah, this is synchronous. Kinda sucks. But well... */
5780 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5781 usleep(125*USEC_PER_MSEC);
5783 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5784 usleep(125*USEC_PER_MSEC);
5786 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5787 usleep(125*USEC_PER_MSEC);
5789 ioctl(fd, KIOCSOUND, 0);
5792 int make_console_stdio(void) {
5795 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5797 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5799 log_error("Failed to acquire terminal: %s", strerror(-fd));
5805 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5812 int get_home_dir(char **_h) {
5820 /* Take the user specified one */
5831 /* Hardcode home directory for root to avoid NSS */
5834 h = strdup("/root");
5842 /* Check the database... */
5846 return errno ? -errno : -ESRCH;
5848 if (!path_is_absolute(p->pw_dir))
5851 h = strdup(p->pw_dir);
5859 int get_shell(char **_sh) {
5867 /* Take the user specified one */
5868 e = getenv("SHELL");
5878 /* Hardcode home directory for root to avoid NSS */
5881 sh = strdup("/bin/sh");
5889 /* Check the database... */
5893 return errno ? -errno : -ESRCH;
5895 if (!path_is_absolute(p->pw_shell))
5898 sh = strdup(p->pw_shell);
5906 void freep(void *p) {
5910 void fclosep(FILE **f) {
5915 void closep(int *fd) {
5917 close_nointr_nofail(*fd);
5920 void closedirp(DIR **d) {
5925 void umaskp(mode_t *u) {
5929 bool filename_is_safe(const char *p) {
5943 if (strlen(p) > FILENAME_MAX)
5949 bool string_is_safe(const char *p) {
5954 for (t = p; *t; t++) {
5955 if (*t > 0 && *t < ' ')
5958 if (strchr("\\\"\'", *t))
5965 int parse_timestamp(const char *t, usec_t *usec) {
5969 usec_t plus = 0, minus = 0, ret;
5975 * 2012-09-22 16:34:22
5976 * 2012-09-22 16:34 (seconds will be set to 0)
5977 * 2012-09-22 (time will be set to 00:00:00)
5978 * 16:34:22 (date will be set to today)
5979 * 16:34 (date will be set to today, seconds to 0)
5981 * yesterday (time is set to 00:00:00)
5982 * today (time is set to 00:00:00)
5983 * tomorrow (time is set to 00:00:00)
5993 assert_se(localtime_r(&x, &tm));
5995 if (streq(t, "now"))
5998 else if (streq(t, "today")) {
5999 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6002 } else if (streq(t, "yesterday")) {
6004 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6007 } else if (streq(t, "tomorrow")) {
6009 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6012 } else if (t[0] == '+') {
6014 r = parse_usec(t+1, &plus);
6019 } else if (t[0] == '-') {
6021 r = parse_usec(t+1, &minus);
6029 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6034 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6039 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6046 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6053 k = strptime(t, "%y-%m-%d", &tm);
6055 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6060 k = strptime(t, "%Y-%m-%d", &tm);
6062 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6067 k = strptime(t, "%H:%M:%S", &tm);
6072 k = strptime(t, "%H:%M", &tm);
6082 if (x == (time_t) -1)
6085 ret = (usec_t) x * USEC_PER_SEC;
6098 /* hey glibc, APIs with callbacks without a user pointer are so useless */
6099 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
6100 int (*compar) (const void *, const void *, void *), void *arg) {
6109 p = (void *)(((const char *) base) + (idx * size));
6110 comparison = compar(key, p, arg);
6113 else if (comparison > 0)
6121 bool is_locale_utf8(void) {
6123 static int cached_answer = -1;
6125 if (cached_answer >= 0)
6128 if (!setlocale(LC_ALL, "")) {
6129 cached_answer = true;
6133 set = nl_langinfo(CODESET);
6135 cached_answer = true;
6139 cached_answer = streq(set, "UTF-8");
6141 return (bool)cached_answer;
6144 const char *draw_special_char(DrawSpecialChar ch) {
6145 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
6147 [DRAW_BOX_VERT] = "\342\224\202", /* │ */
6148 [DRAW_BOX_VERT_AND_RIGHT] = "\342\224\234", /* ├ */
6149 [DRAW_BOX_UP_AND_RIGHT] = "\342\224\224", /* └ */
6150 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
6152 /* ASCII fallback */ {
6153 [DRAW_BOX_VERT] = "|",
6154 [DRAW_BOX_VERT_AND_RIGHT] = "+",
6155 [DRAW_BOX_UP_AND_RIGHT] = "\\",
6156 [DRAW_TRIANGULAR_BULLET] = ">",
6160 return draw_table[!is_locale_utf8()][ch];