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>
68 #include "path-util.h"
69 #include "exit-status.h"
73 char **saved_argv = NULL;
75 static volatile unsigned cached_columns = 0;
76 static volatile unsigned cached_lines = 0;
78 size_t page_size(void) {
79 static __thread size_t pgsz = 0;
82 if (_likely_(pgsz > 0))
85 r = sysconf(_SC_PAGESIZE);
92 bool streq_ptr(const char *a, const char *b) {
94 /* Like streq(), but tries to make sense of NULL pointers */
105 usec_t now(clockid_t clock_id) {
108 assert_se(clock_gettime(clock_id, &ts) == 0);
110 return timespec_load(&ts);
113 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
116 ts->realtime = now(CLOCK_REALTIME);
117 ts->monotonic = now(CLOCK_MONOTONIC);
122 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
131 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
133 ts->monotonic = now(CLOCK_MONOTONIC);
135 if ((int64_t) ts->monotonic > delta)
136 ts->monotonic -= delta;
144 usec_t timespec_load(const struct timespec *ts) {
147 if (ts->tv_sec == (time_t) -1 &&
148 ts->tv_nsec == (long) -1)
151 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
155 (usec_t) ts->tv_sec * USEC_PER_SEC +
156 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
159 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
162 if (u == (usec_t) -1) {
163 ts->tv_sec = (time_t) -1;
164 ts->tv_nsec = (long) -1;
168 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
169 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
174 usec_t timeval_load(const struct timeval *tv) {
177 if (tv->tv_sec == (time_t) -1 &&
178 tv->tv_usec == (suseconds_t) -1)
181 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
185 (usec_t) tv->tv_sec * USEC_PER_SEC +
186 (usec_t) tv->tv_usec;
189 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
192 if (u == (usec_t) -1) {
193 tv->tv_sec = (time_t) -1;
194 tv->tv_usec = (suseconds_t) -1;
198 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
199 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
204 char* endswith(const char *s, const char *postfix) {
211 pl = strlen(postfix);
214 return (char*) s + sl;
219 if (memcmp(s + sl - pl, postfix, pl) != 0)
222 return (char*) s + sl - pl;
225 char* startswith(const char *s, const char *prefix) {
242 char* startswith_no_case(const char *s, const char *prefix) {
252 if (tolower(*a) != tolower(*b))
259 bool first_word(const char *s, const char *word) {
274 if (memcmp(s, word, wl) != 0)
278 strchr(WHITESPACE, s[wl]);
281 int close_nointr(int fd) {
296 void close_nointr_nofail(int fd) {
297 int saved_errno = errno;
299 /* like close_nointr() but cannot fail, and guarantees errno
302 assert_se(close_nointr(fd) == 0);
307 void close_many(const int fds[], unsigned n_fd) {
310 for (i = 0; i < n_fd; i++)
311 close_nointr_nofail(fds[i]);
314 int parse_boolean(const char *v) {
317 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
319 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
325 int parse_pid(const char *s, pid_t* ret_pid) {
326 unsigned long ul = 0;
333 r = safe_atolu(s, &ul);
339 if ((unsigned long) pid != ul)
349 int parse_uid(const char *s, uid_t* ret_uid) {
350 unsigned long ul = 0;
357 r = safe_atolu(s, &ul);
363 if ((unsigned long) uid != ul)
370 int safe_atou(const char *s, unsigned *ret_u) {
378 l = strtoul(s, &x, 0);
380 if (!x || *x || errno)
381 return errno ? -errno : -EINVAL;
383 if ((unsigned long) (unsigned) l != l)
386 *ret_u = (unsigned) l;
390 int safe_atoi(const char *s, int *ret_i) {
398 l = strtol(s, &x, 0);
400 if (!x || *x || errno)
401 return errno ? -errno : -EINVAL;
403 if ((long) (int) l != l)
410 int safe_atollu(const char *s, long long unsigned *ret_llu) {
412 unsigned long long l;
418 l = strtoull(s, &x, 0);
420 if (!x || *x || errno)
421 return errno ? -errno : -EINVAL;
427 int safe_atolli(const char *s, long long int *ret_lli) {
435 l = strtoll(s, &x, 0);
437 if (!x || *x || errno)
438 return errno ? -errno : -EINVAL;
444 /* Split a string into words. */
445 char *split(const char *c, size_t *l, const char *separator, char **state) {
448 current = *state ? *state : (char*) c;
450 if (!*current || *c == 0)
453 current += strspn(current, separator);
454 *l = strcspn(current, separator);
457 return (char*) current;
460 /* Split a string into words, but consider strings enclosed in '' and
461 * "" as words even if they include spaces. */
462 char *split_quoted(const char *c, size_t *l, char **state) {
464 bool escaped = false;
466 current = *state ? *state : (char*) c;
468 if (!*current || *c == 0)
471 current += strspn(current, WHITESPACE);
473 if (*current == '\'') {
476 for (e = current; *e; e++) {
486 *state = *e == 0 ? e : e+1;
487 } else if (*current == '\"') {
490 for (e = current; *e; e++) {
500 *state = *e == 0 ? e : e+1;
502 for (e = current; *e; e++) {
507 else if (strchr(WHITESPACE, *e))
514 return (char*) current;
517 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
519 _cleanup_fclose_ FILE *f = NULL;
520 char fn[PATH_MAX], line[LINE_MAX], *p;
526 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
533 if (!fgets(line, sizeof(line), f)) {
534 r = feof(f) ? -EIO : -errno;
539 /* Let's skip the pid and comm fields. The latter is enclosed
540 * in () but does not escape any () in its value, so let's
541 * skip over it manually */
543 p = strrchr(line, ')');
555 if ((long unsigned) (pid_t) ppid != ppid)
558 *_ppid = (pid_t) ppid;
563 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
564 _cleanup_fclose_ FILE *f = NULL;
565 char fn[PATH_MAX], line[LINE_MAX], *p;
570 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
577 if (!fgets(line, sizeof(line), f)) {
584 /* Let's skip the pid and comm fields. The latter is enclosed
585 * in () but does not escape any () in its value, so let's
586 * skip over it manually */
588 p = strrchr(line, ')');
610 "%*d " /* priority */
612 "%*d " /* num_threads */
613 "%*d " /* itrealvalue */
614 "%llu " /* starttime */,
621 int write_one_line_file(const char *fn, const char *line) {
622 _cleanup_fclose_ FILE *f = NULL;
632 if (fputs(line, f) < 0)
633 return errno ? -errno : -EIO;
635 if (!endswith(line, "\n"))
641 return errno ? -errno : -EIO;
646 int fchmod_umask(int fd, mode_t m) {
651 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
657 int write_one_line_file_atomic(const char *fn, const char *line) {
665 r = fopen_temporary(fn, &f, &p);
669 fchmod_umask(fileno(f), 0644);
672 if (fputs(line, f) < 0) {
677 if (!endswith(line, "\n"))
688 if (rename(p, fn) < 0)
704 int read_one_line_file(const char *fn, char **line) {
705 _cleanup_fclose_ FILE *f = NULL;
706 char t[LINE_MAX], *c;
715 if (!fgets(t, sizeof(t), f)) {
718 return errno ? -errno : -EIO;
732 int read_full_file(const char *fn, char **contents, size_t *size) {
733 _cleanup_fclose_ FILE *f = NULL;
735 _cleanup_free_ char *buf = NULL;
742 if (fstat(fileno(f), &st) < 0)
746 if (st.st_size > 4*1024*1024)
749 n = st.st_size > 0 ? st.st_size : LINE_MAX;
756 t = realloc(buf, n+1);
761 k = fread(buf + l, 1, n - l, f);
790 const char *separator, ...) {
793 char *contents = NULL, *p;
798 if ((r = read_full_file(fname, &contents, NULL)) < 0)
803 const char *key = NULL;
805 p += strspn(p, separator);
806 p += strspn(p, WHITESPACE);
811 if (!strchr(COMMENTS, *p)) {
815 va_start(ap, separator);
816 while ((key = va_arg(ap, char *))) {
820 value = va_arg(ap, char **);
823 if (strncmp(p, key, n) != 0 ||
828 n = strcspn(p, separator);
831 strchr(QUOTES, p[0]) &&
833 v = strndup(p+1, n-2);
844 /* return empty value strings as NULL */
861 p += strcspn(p, separator);
880 if (!(f = fopen(fname, "re")))
884 char l[LINE_MAX], *p, *u;
887 if (!fgets(l, sizeof(l), f)) {
900 if (strchr(COMMENTS, *p))
903 if (!(u = normalize_env_assignment(p))) {
908 t = strv_append(m, u);
934 int write_env_file(const char *fname, char **l) {
939 r = fopen_temporary(fname, &f, &p);
943 fchmod_umask(fileno(f), 0644);
959 if (rename(p, fname) < 0)
974 char *truncate_nl(char *s) {
977 s[strcspn(s, NEWLINE)] = 0;
981 int get_process_comm(pid_t pid, char **name) {
987 r = read_one_line_file("/proc/self/comm", name);
990 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
993 r = read_one_line_file(p, name);
1000 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1007 assert(max_length > 0);
1011 f = fopen("/proc/self/cmdline", "re");
1014 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1024 r = new(char, max_length);
1032 while ((c = getc(f)) != EOF) {
1054 size_t n = MIN(left-1, 3U);
1055 memcpy(k, "...", n);
1062 /* Kernel threads have no argv[] */
1072 h = get_process_comm(pid, &t);
1076 r = strjoin("[", t, "]", NULL);
1087 int is_kernel_thread(pid_t pid) {
1097 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1106 count = fread(&c, 1, 1, f);
1110 /* Kernel threads have an empty cmdline */
1113 return eof ? 1 : -errno;
1118 int get_process_exe(pid_t pid, char **name) {
1124 r = readlink_malloc("/proc/self/exe", name);
1127 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1130 r = readlink_malloc(p, name);
1137 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1147 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1157 char line[LINE_MAX], *l;
1159 if (!fgets(line, sizeof(line), f)) {
1169 if (startswith(l, field)) {
1171 l += strspn(l, WHITESPACE);
1173 l[strcspn(l, WHITESPACE)] = 0;
1175 r = parse_uid(l, uid);
1188 int get_process_uid(pid_t pid, uid_t *uid) {
1189 return get_process_id(pid, "Uid:", uid);
1192 int get_process_gid(pid_t pid, gid_t *gid) {
1193 return get_process_id(pid, "Gid:", gid);
1196 char *strnappend(const char *s, const char *suffix, size_t b) {
1204 return strndup(suffix, b);
1213 if (b > ((size_t) -1) - a)
1216 r = new(char, a+b+1);
1221 memcpy(r+a, suffix, b);
1227 char *strappend(const char *s, const char *suffix) {
1228 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1231 int readlink_malloc(const char *p, char **r) {
1241 if (!(c = new(char, l)))
1244 if ((n = readlink(p, c, l-1)) < 0) {
1250 if ((size_t) n < l-1) {
1261 int readlink_and_make_absolute(const char *p, char **r) {
1268 if ((j = readlink_malloc(p, &target)) < 0)
1271 k = file_in_same_dir(p, target);
1281 int readlink_and_canonicalize(const char *p, char **r) {
1288 j = readlink_and_make_absolute(p, &t);
1292 s = canonicalize_file_name(t);
1299 path_kill_slashes(*r);
1304 int reset_all_signal_handlers(void) {
1307 for (sig = 1; sig < _NSIG; sig++) {
1308 struct sigaction sa;
1310 if (sig == SIGKILL || sig == SIGSTOP)
1314 sa.sa_handler = SIG_DFL;
1315 sa.sa_flags = SA_RESTART;
1317 /* On Linux the first two RT signals are reserved by
1318 * glibc, and sigaction() will return EINVAL for them. */
1319 if ((sigaction(sig, &sa, NULL) < 0))
1320 if (errno != EINVAL)
1327 char *strstrip(char *s) {
1330 /* Drops trailing whitespace. Modifies the string in
1331 * place. Returns pointer to first non-space character */
1333 s += strspn(s, WHITESPACE);
1335 for (e = strchr(s, 0); e > s; e --)
1336 if (!strchr(WHITESPACE, e[-1]))
1344 char *delete_chars(char *s, const char *bad) {
1347 /* Drops all whitespace, regardless where in the string */
1349 for (f = s, t = s; *f; f++) {
1350 if (strchr(bad, *f))
1361 bool in_charset(const char *s, const char* charset) {
1367 for (i = s; *i; i++)
1368 if (!strchr(charset, *i))
1374 char *file_in_same_dir(const char *path, const char *filename) {
1381 /* This removes the last component of path and appends
1382 * filename, unless the latter is absolute anyway or the
1385 if (path_is_absolute(filename))
1386 return strdup(filename);
1388 if (!(e = strrchr(path, '/')))
1389 return strdup(filename);
1391 k = strlen(filename);
1392 if (!(r = new(char, e-path+1+k+1)))
1395 memcpy(r, path, e-path+1);
1396 memcpy(r+(e-path)+1, filename, k+1);
1401 int rmdir_parents(const char *path, const char *stop) {
1410 /* Skip trailing slashes */
1411 while (l > 0 && path[l-1] == '/')
1417 /* Skip last component */
1418 while (l > 0 && path[l-1] != '/')
1421 /* Skip trailing slashes */
1422 while (l > 0 && path[l-1] == '/')
1428 if (!(t = strndup(path, l)))
1431 if (path_startswith(stop, t)) {
1440 if (errno != ENOENT)
1448 char hexchar(int x) {
1449 static const char table[16] = "0123456789abcdef";
1451 return table[x & 15];
1454 int unhexchar(char c) {
1456 if (c >= '0' && c <= '9')
1459 if (c >= 'a' && c <= 'f')
1460 return c - 'a' + 10;
1462 if (c >= 'A' && c <= 'F')
1463 return c - 'A' + 10;
1468 char octchar(int x) {
1469 return '0' + (x & 7);
1472 int unoctchar(char c) {
1474 if (c >= '0' && c <= '7')
1480 char decchar(int x) {
1481 return '0' + (x % 10);
1484 int undecchar(char c) {
1486 if (c >= '0' && c <= '9')
1492 char *cescape(const char *s) {
1498 /* Does C style string escaping. */
1500 r = new(char, strlen(s)*4 + 1);
1504 for (f = s, t = r; *f; f++)
1550 /* For special chars we prefer octal over
1551 * hexadecimal encoding, simply because glib's
1552 * g_strescape() does the same */
1553 if ((*f < ' ') || (*f >= 127)) {
1555 *(t++) = octchar((unsigned char) *f >> 6);
1556 *(t++) = octchar((unsigned char) *f >> 3);
1557 *(t++) = octchar((unsigned char) *f);
1568 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1575 /* Undoes C style string escaping, and optionally prefixes it. */
1577 pl = prefix ? strlen(prefix) : 0;
1579 r = new(char, pl+length+1);
1584 memcpy(r, prefix, pl);
1586 for (f = s, t = r + pl; f < s + length; f++) {
1629 /* This is an extension of the XDG syntax files */
1634 /* hexadecimal encoding */
1637 a = unhexchar(f[1]);
1638 b = unhexchar(f[2]);
1640 if (a < 0 || b < 0) {
1641 /* Invalid escape code, let's take it literal then */
1645 *(t++) = (char) ((a << 4) | b);
1660 /* octal encoding */
1663 a = unoctchar(f[0]);
1664 b = unoctchar(f[1]);
1665 c = unoctchar(f[2]);
1667 if (a < 0 || b < 0 || c < 0) {
1668 /* Invalid escape code, let's take it literal then */
1672 *(t++) = (char) ((a << 6) | (b << 3) | c);
1680 /* premature end of string.*/
1685 /* Invalid escape code, let's take it literal then */
1697 char *cunescape_length(const char *s, size_t length) {
1698 return cunescape_length_with_prefix(s, length, NULL);
1701 char *cunescape(const char *s) {
1704 return cunescape_length(s, strlen(s));
1707 char *xescape(const char *s, const char *bad) {
1711 /* Escapes all chars in bad, in addition to \ and all special
1712 * chars, in \xFF style escaping. May be reversed with
1715 r = new(char, strlen(s) * 4 + 1);
1719 for (f = s, t = r; *f; f++) {
1721 if ((*f < ' ') || (*f >= 127) ||
1722 (*f == '\\') || strchr(bad, *f)) {
1725 *(t++) = hexchar(*f >> 4);
1726 *(t++) = hexchar(*f);
1736 char *bus_path_escape(const char *s) {
1742 /* Escapes all chars that D-Bus' object path cannot deal
1743 * with. Can be reverse with bus_path_unescape() */
1745 if (!(r = new(char, strlen(s)*3+1)))
1748 for (f = s, t = r; *f; f++) {
1750 if (!(*f >= 'A' && *f <= 'Z') &&
1751 !(*f >= 'a' && *f <= 'z') &&
1752 !(*f >= '0' && *f <= '9')) {
1754 *(t++) = hexchar(*f >> 4);
1755 *(t++) = hexchar(*f);
1765 char *bus_path_unescape(const char *f) {
1770 if (!(r = strdup(f)))
1773 for (t = r; *f; f++) {
1778 if ((a = unhexchar(f[1])) < 0 ||
1779 (b = unhexchar(f[2])) < 0) {
1780 /* Invalid escape code, let's take it literal then */
1783 *(t++) = (char) ((a << 4) | b);
1795 char *ascii_strlower(char *t) {
1800 for (p = t; *p; p++)
1801 if (*p >= 'A' && *p <= 'Z')
1802 *p = *p - 'A' + 'a';
1807 static bool ignore_file_allow_backup(const char *filename) {
1811 filename[0] == '.' ||
1812 streq(filename, "lost+found") ||
1813 streq(filename, "aquota.user") ||
1814 streq(filename, "aquota.group") ||
1815 endswith(filename, ".rpmnew") ||
1816 endswith(filename, ".rpmsave") ||
1817 endswith(filename, ".rpmorig") ||
1818 endswith(filename, ".dpkg-old") ||
1819 endswith(filename, ".dpkg-new") ||
1820 endswith(filename, ".swp");
1823 bool ignore_file(const char *filename) {
1826 if (endswith(filename, "~"))
1829 return ignore_file_allow_backup(filename);
1832 int fd_nonblock(int fd, bool nonblock) {
1837 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1841 flags |= O_NONBLOCK;
1843 flags &= ~O_NONBLOCK;
1845 if (fcntl(fd, F_SETFL, flags) < 0)
1851 int fd_cloexec(int fd, bool cloexec) {
1856 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1860 flags |= FD_CLOEXEC;
1862 flags &= ~FD_CLOEXEC;
1864 if (fcntl(fd, F_SETFD, flags) < 0)
1870 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1873 assert(n_fdset == 0 || fdset);
1875 for (i = 0; i < n_fdset; i++)
1882 int close_all_fds(const int except[], unsigned n_except) {
1887 assert(n_except == 0 || except);
1889 d = opendir("/proc/self/fd");
1894 /* When /proc isn't available (for example in chroots)
1895 * the fallback is brute forcing through the fd
1898 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1899 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1901 if (fd_in_set(fd, except, n_except))
1904 if (close_nointr(fd) < 0)
1905 if (errno != EBADF && r == 0)
1912 while ((de = readdir(d))) {
1915 if (ignore_file(de->d_name))
1918 if (safe_atoi(de->d_name, &fd) < 0)
1919 /* Let's better ignore this, just in case */
1928 if (fd_in_set(fd, except, n_except))
1931 if (close_nointr(fd) < 0) {
1932 /* Valgrind has its own FD and doesn't want to have it closed */
1933 if (errno != EBADF && r == 0)
1942 bool chars_intersect(const char *a, const char *b) {
1945 /* Returns true if any of the chars in a are in b. */
1946 for (p = a; *p; p++)
1953 char *format_timestamp(char *buf, size_t l, usec_t t) {
1963 sec = (time_t) (t / USEC_PER_SEC);
1965 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1971 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1974 n = now(CLOCK_REALTIME);
1976 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1981 if (d >= USEC_PER_YEAR)
1982 snprintf(buf, l, "%llu years and %llu months ago",
1983 (unsigned long long) (d / USEC_PER_YEAR),
1984 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1985 else if (d >= USEC_PER_MONTH)
1986 snprintf(buf, l, "%llu months and %llu days ago",
1987 (unsigned long long) (d / USEC_PER_MONTH),
1988 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1989 else if (d >= USEC_PER_WEEK)
1990 snprintf(buf, l, "%llu weeks and %llu days ago",
1991 (unsigned long long) (d / USEC_PER_WEEK),
1992 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1993 else if (d >= 2*USEC_PER_DAY)
1994 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1995 else if (d >= 25*USEC_PER_HOUR)
1996 snprintf(buf, l, "1 day and %lluh ago",
1997 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1998 else if (d >= 6*USEC_PER_HOUR)
1999 snprintf(buf, l, "%lluh ago",
2000 (unsigned long long) (d / USEC_PER_HOUR));
2001 else if (d >= USEC_PER_HOUR)
2002 snprintf(buf, l, "%lluh %llumin ago",
2003 (unsigned long long) (d / USEC_PER_HOUR),
2004 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2005 else if (d >= 5*USEC_PER_MINUTE)
2006 snprintf(buf, l, "%llumin ago",
2007 (unsigned long long) (d / USEC_PER_MINUTE));
2008 else if (d >= USEC_PER_MINUTE)
2009 snprintf(buf, l, "%llumin %llus ago",
2010 (unsigned long long) (d / USEC_PER_MINUTE),
2011 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2012 else if (d >= USEC_PER_SEC)
2013 snprintf(buf, l, "%llus ago",
2014 (unsigned long long) (d / USEC_PER_SEC));
2015 else if (d >= USEC_PER_MSEC)
2016 snprintf(buf, l, "%llums ago",
2017 (unsigned long long) (d / USEC_PER_MSEC));
2019 snprintf(buf, l, "%lluus ago",
2020 (unsigned long long) d);
2022 snprintf(buf, l, "now");
2028 char *format_timespan(char *buf, size_t l, usec_t t) {
2029 static const struct {
2033 { "w", USEC_PER_WEEK },
2034 { "d", USEC_PER_DAY },
2035 { "h", USEC_PER_HOUR },
2036 { "min", USEC_PER_MINUTE },
2037 { "s", USEC_PER_SEC },
2038 { "ms", USEC_PER_MSEC },
2048 if (t == (usec_t) -1)
2052 snprintf(p, l, "0");
2057 /* The result of this function can be parsed with parse_usec */
2059 for (i = 0; i < ELEMENTSOF(table); i++) {
2063 if (t < table[i].usec)
2069 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2070 n = MIN((size_t) k, l);
2083 bool fstype_is_network(const char *fstype) {
2084 static const char table[] =
2093 return nulstr_contains(table, fstype);
2097 _cleanup_close_ int fd;
2099 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2105 TIOCL_GETKMSGREDIRECT,
2109 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2112 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2115 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2121 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2122 struct termios old_termios, new_termios;
2124 char line[LINE_MAX];
2129 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2130 new_termios = old_termios;
2132 new_termios.c_lflag &= ~ICANON;
2133 new_termios.c_cc[VMIN] = 1;
2134 new_termios.c_cc[VTIME] = 0;
2136 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2139 if (t != (usec_t) -1) {
2140 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2141 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2146 k = fread(&c, 1, 1, f);
2148 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2154 *need_nl = c != '\n';
2161 if (t != (usec_t) -1)
2162 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2165 if (!fgets(line, sizeof(line), f))
2170 if (strlen(line) != 1)
2180 int ask(char *ret, const char *replies, const char *text, ...) {
2190 bool need_nl = true;
2193 fputs(ANSI_HIGHLIGHT_ON, stdout);
2200 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2204 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2207 if (r == -EBADMSG) {
2208 puts("Bad input, please try again.");
2219 if (strchr(replies, c)) {
2224 puts("Read unexpected character, please try again.");
2228 int reset_terminal_fd(int fd, bool switch_to_text) {
2229 struct termios termios;
2232 /* Set terminal to some sane defaults */
2236 /* We leave locked terminal attributes untouched, so that
2237 * Plymouth may set whatever it wants to set, and we don't
2238 * interfere with that. */
2240 /* Disable exclusive mode, just in case */
2241 ioctl(fd, TIOCNXCL);
2243 /* Switch to text mode */
2245 ioctl(fd, KDSETMODE, KD_TEXT);
2247 /* Enable console unicode mode */
2248 ioctl(fd, KDSKBMODE, K_UNICODE);
2250 if (tcgetattr(fd, &termios) < 0) {
2255 /* We only reset the stuff that matters to the software. How
2256 * hardware is set up we don't touch assuming that somebody
2257 * else will do that for us */
2259 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2260 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2261 termios.c_oflag |= ONLCR;
2262 termios.c_cflag |= CREAD;
2263 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2265 termios.c_cc[VINTR] = 03; /* ^C */
2266 termios.c_cc[VQUIT] = 034; /* ^\ */
2267 termios.c_cc[VERASE] = 0177;
2268 termios.c_cc[VKILL] = 025; /* ^X */
2269 termios.c_cc[VEOF] = 04; /* ^D */
2270 termios.c_cc[VSTART] = 021; /* ^Q */
2271 termios.c_cc[VSTOP] = 023; /* ^S */
2272 termios.c_cc[VSUSP] = 032; /* ^Z */
2273 termios.c_cc[VLNEXT] = 026; /* ^V */
2274 termios.c_cc[VWERASE] = 027; /* ^W */
2275 termios.c_cc[VREPRINT] = 022; /* ^R */
2276 termios.c_cc[VEOL] = 0;
2277 termios.c_cc[VEOL2] = 0;
2279 termios.c_cc[VTIME] = 0;
2280 termios.c_cc[VMIN] = 1;
2282 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2286 /* Just in case, flush all crap out */
2287 tcflush(fd, TCIOFLUSH);
2292 int reset_terminal(const char *name) {
2295 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2299 r = reset_terminal_fd(fd, true);
2300 close_nointr_nofail(fd);
2305 int open_terminal(const char *name, int mode) {
2310 * If a TTY is in the process of being closed opening it might
2311 * cause EIO. This is horribly awful, but unlikely to be
2312 * changed in the kernel. Hence we work around this problem by
2313 * retrying a couple of times.
2315 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2319 fd = open(name, mode);
2326 /* Max 1s in total */
2330 usleep(50 * USEC_PER_MSEC);
2339 close_nointr_nofail(fd);
2344 close_nointr_nofail(fd);
2351 int flush_fd(int fd) {
2352 struct pollfd pollfd;
2356 pollfd.events = POLLIN;
2363 if ((r = poll(&pollfd, 1, 0)) < 0) {
2374 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2379 if (errno == EAGAIN)
2390 int acquire_terminal(
2394 bool ignore_tiocstty_eperm,
2397 int fd = -1, notify = -1, r = 0, wd = -1;
2399 struct sigaction sa_old, sa_new;
2403 /* We use inotify to be notified when the tty is closed. We
2404 * create the watch before checking if we can actually acquire
2405 * it, so that we don't lose any event.
2407 * Note: strictly speaking this actually watches for the
2408 * device being closed, it does *not* really watch whether a
2409 * tty loses its controlling process. However, unless some
2410 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2411 * its tty otherwise this will not become a problem. As long
2412 * as the administrator makes sure not configure any service
2413 * on the same tty as an untrusted user this should not be a
2414 * problem. (Which he probably should not do anyway.) */
2416 if (timeout != (usec_t) -1)
2417 ts = now(CLOCK_MONOTONIC);
2419 if (!fail && !force) {
2420 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2426 wd = inotify_add_watch(notify, name, IN_CLOSE);
2435 r = flush_fd(notify);
2440 /* We pass here O_NOCTTY only so that we can check the return
2441 * value TIOCSCTTY and have a reliable way to figure out if we
2442 * successfully became the controlling process of the tty */
2443 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2447 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2448 * if we already own the tty. */
2450 sa_new.sa_handler = SIG_IGN;
2451 sa_new.sa_flags = SA_RESTART;
2452 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2454 /* First, try to get the tty */
2455 if (ioctl(fd, TIOCSCTTY, force) < 0)
2458 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2460 /* Sometimes it makes sense to ignore TIOCSCTTY
2461 * returning EPERM, i.e. when very likely we already
2462 * are have this controlling terminal. */
2463 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2466 if (r < 0 && (force || fail || r != -EPERM)) {
2475 assert(notify >= 0);
2478 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2480 struct inotify_event *e;
2482 if (timeout != (usec_t) -1) {
2485 n = now(CLOCK_MONOTONIC);
2486 if (ts + timeout < n) {
2491 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2501 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2504 if (errno == EINTR || errno == EAGAIN)
2511 e = (struct inotify_event*) inotify_buffer;
2516 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2521 step = sizeof(struct inotify_event) + e->len;
2522 assert(step <= (size_t) l);
2524 e = (struct inotify_event*) ((uint8_t*) e + step);
2531 /* We close the tty fd here since if the old session
2532 * ended our handle will be dead. It's important that
2533 * we do this after sleeping, so that we don't enter
2534 * an endless loop. */
2535 close_nointr_nofail(fd);
2539 close_nointr_nofail(notify);
2541 r = reset_terminal_fd(fd, true);
2543 log_warning("Failed to reset terminal: %s", strerror(-r));
2549 close_nointr_nofail(fd);
2552 close_nointr_nofail(notify);
2557 int release_terminal(void) {
2559 struct sigaction sa_old, sa_new;
2561 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2564 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2565 * by our own TIOCNOTTY */
2568 sa_new.sa_handler = SIG_IGN;
2569 sa_new.sa_flags = SA_RESTART;
2570 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2572 if (ioctl(fd, TIOCNOTTY) < 0)
2575 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2577 close_nointr_nofail(fd);
2581 int sigaction_many(const struct sigaction *sa, ...) {
2586 while ((sig = va_arg(ap, int)) > 0)
2587 if (sigaction(sig, sa, NULL) < 0)
2594 int ignore_signals(int sig, ...) {
2595 struct sigaction sa;
2600 sa.sa_handler = SIG_IGN;
2601 sa.sa_flags = SA_RESTART;
2603 if (sigaction(sig, &sa, NULL) < 0)
2607 while ((sig = va_arg(ap, int)) > 0)
2608 if (sigaction(sig, &sa, NULL) < 0)
2615 int default_signals(int sig, ...) {
2616 struct sigaction sa;
2621 sa.sa_handler = SIG_DFL;
2622 sa.sa_flags = SA_RESTART;
2624 if (sigaction(sig, &sa, NULL) < 0)
2628 while ((sig = va_arg(ap, int)) > 0)
2629 if (sigaction(sig, &sa, NULL) < 0)
2636 int close_pipe(int p[]) {
2642 a = close_nointr(p[0]);
2647 b = close_nointr(p[1]);
2651 return a < 0 ? a : b;
2654 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2663 while (nbytes > 0) {
2666 if ((k = read(fd, p, nbytes)) <= 0) {
2668 if (k < 0 && errno == EINTR)
2671 if (k < 0 && errno == EAGAIN && do_poll) {
2672 struct pollfd pollfd;
2676 pollfd.events = POLLIN;
2678 if (poll(&pollfd, 1, -1) < 0) {
2682 return n > 0 ? n : -errno;
2685 if (pollfd.revents != POLLIN)
2686 return n > 0 ? n : -EIO;
2691 return n > 0 ? n : (k < 0 ? -errno : 0);
2702 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2711 while (nbytes > 0) {
2714 k = write(fd, p, nbytes);
2717 if (k < 0 && errno == EINTR)
2720 if (k < 0 && errno == EAGAIN && do_poll) {
2721 struct pollfd pollfd;
2725 pollfd.events = POLLOUT;
2727 if (poll(&pollfd, 1, -1) < 0) {
2731 return n > 0 ? n : -errno;
2734 if (pollfd.revents != POLLOUT)
2735 return n > 0 ? n : -EIO;
2740 return n > 0 ? n : (k < 0 ? -errno : 0);
2751 int parse_usec(const char *t, usec_t *usec) {
2752 static const struct {
2756 { "seconds", USEC_PER_SEC },
2757 { "second", USEC_PER_SEC },
2758 { "sec", USEC_PER_SEC },
2759 { "s", USEC_PER_SEC },
2760 { "minutes", USEC_PER_MINUTE },
2761 { "minute", USEC_PER_MINUTE },
2762 { "min", USEC_PER_MINUTE },
2763 { "months", USEC_PER_MONTH },
2764 { "month", USEC_PER_MONTH },
2765 { "msec", USEC_PER_MSEC },
2766 { "ms", USEC_PER_MSEC },
2767 { "m", USEC_PER_MINUTE },
2768 { "hours", USEC_PER_HOUR },
2769 { "hour", USEC_PER_HOUR },
2770 { "hr", USEC_PER_HOUR },
2771 { "h", USEC_PER_HOUR },
2772 { "days", USEC_PER_DAY },
2773 { "day", USEC_PER_DAY },
2774 { "d", USEC_PER_DAY },
2775 { "weeks", USEC_PER_WEEK },
2776 { "week", USEC_PER_WEEK },
2777 { "w", USEC_PER_WEEK },
2778 { "years", USEC_PER_YEAR },
2779 { "year", USEC_PER_YEAR },
2780 { "y", USEC_PER_YEAR },
2783 { "", USEC_PER_SEC }, /* default is sec */
2799 l = strtoll(p, &e, 10);
2810 e += strspn(e, WHITESPACE);
2812 for (i = 0; i < ELEMENTSOF(table); i++)
2813 if (startswith(e, table[i].suffix)) {
2814 r += (usec_t) l * table[i].usec;
2815 p = e + strlen(table[i].suffix);
2819 if (i >= ELEMENTSOF(table))
2829 int parse_nsec(const char *t, nsec_t *nsec) {
2830 static const struct {
2834 { "seconds", NSEC_PER_SEC },
2835 { "second", NSEC_PER_SEC },
2836 { "sec", NSEC_PER_SEC },
2837 { "s", NSEC_PER_SEC },
2838 { "minutes", NSEC_PER_MINUTE },
2839 { "minute", NSEC_PER_MINUTE },
2840 { "min", NSEC_PER_MINUTE },
2841 { "months", NSEC_PER_MONTH },
2842 { "month", NSEC_PER_MONTH },
2843 { "msec", NSEC_PER_MSEC },
2844 { "ms", NSEC_PER_MSEC },
2845 { "m", NSEC_PER_MINUTE },
2846 { "hours", NSEC_PER_HOUR },
2847 { "hour", NSEC_PER_HOUR },
2848 { "hr", NSEC_PER_HOUR },
2849 { "h", NSEC_PER_HOUR },
2850 { "days", NSEC_PER_DAY },
2851 { "day", NSEC_PER_DAY },
2852 { "d", NSEC_PER_DAY },
2853 { "weeks", NSEC_PER_WEEK },
2854 { "week", NSEC_PER_WEEK },
2855 { "w", NSEC_PER_WEEK },
2856 { "years", NSEC_PER_YEAR },
2857 { "year", NSEC_PER_YEAR },
2858 { "y", NSEC_PER_YEAR },
2859 { "usec", NSEC_PER_USEC },
2860 { "us", NSEC_PER_USEC },
2863 { "", 1ULL }, /* default is nsec */
2879 l = strtoll(p, &e, 10);
2890 e += strspn(e, WHITESPACE);
2892 for (i = 0; i < ELEMENTSOF(table); i++)
2893 if (startswith(e, table[i].suffix)) {
2894 r += (nsec_t) l * table[i].nsec;
2895 p = e + strlen(table[i].suffix);
2899 if (i >= ELEMENTSOF(table))
2909 int parse_bytes(const char *t, off_t *bytes) {
2910 static const struct {
2916 { "M", 1024ULL*1024ULL },
2917 { "G", 1024ULL*1024ULL*1024ULL },
2918 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2919 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2920 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2937 l = strtoll(p, &e, 10);
2948 e += strspn(e, WHITESPACE);
2950 for (i = 0; i < ELEMENTSOF(table); i++)
2951 if (startswith(e, table[i].suffix)) {
2952 r += (off_t) l * table[i].factor;
2953 p = e + strlen(table[i].suffix);
2957 if (i >= ELEMENTSOF(table))
2967 int make_stdio(int fd) {
2972 r = dup3(fd, STDIN_FILENO, 0);
2973 s = dup3(fd, STDOUT_FILENO, 0);
2974 t = dup3(fd, STDERR_FILENO, 0);
2977 close_nointr_nofail(fd);
2979 if (r < 0 || s < 0 || t < 0)
2982 /* We rely here that the new fd has O_CLOEXEC not set */
2987 int make_null_stdio(void) {
2990 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2994 return make_stdio(null_fd);
2997 bool is_device_path(const char *path) {
2999 /* Returns true on paths that refer to a device, either in
3000 * sysfs or in /dev */
3003 path_startswith(path, "/dev/") ||
3004 path_startswith(path, "/sys/");
3007 int dir_is_empty(const char *path) {
3008 _cleanup_closedir_ DIR *d;
3017 union dirent_storage buf;
3019 r = readdir_r(d, &buf.de, &de);
3026 if (!ignore_file(de->d_name))
3031 unsigned long long random_ull(void) {
3032 _cleanup_close_ int fd;
3036 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3040 r = loop_read(fd, &ull, sizeof(ull), true);
3041 if (r != sizeof(ull))
3047 return random() * RAND_MAX + random();
3050 void rename_process(const char name[8]) {
3053 /* This is a like a poor man's setproctitle(). It changes the
3054 * comm field, argv[0], and also the glibc's internally used
3055 * name of the process. For the first one a limit of 16 chars
3056 * applies, to the second one usually one of 10 (i.e. length
3057 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3058 * "systemd"). If you pass a longer string it will be
3061 prctl(PR_SET_NAME, name);
3063 if (program_invocation_name)
3064 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3066 if (saved_argc > 0) {
3070 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3072 for (i = 1; i < saved_argc; i++) {
3076 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3081 void sigset_add_many(sigset_t *ss, ...) {
3088 while ((sig = va_arg(ap, int)) > 0)
3089 assert_se(sigaddset(ss, sig) == 0);
3093 char* gethostname_malloc(void) {
3096 assert_se(uname(&u) >= 0);
3098 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3099 return strdup(u.nodename);
3101 return strdup(u.sysname);
3104 bool hostname_is_set(void) {
3107 assert_se(uname(&u) >= 0);
3109 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3112 static char *lookup_uid(uid_t uid) {
3115 _cleanup_free_ char *buf = NULL;
3116 struct passwd pwbuf, *pw = NULL;
3118 /* Shortcut things to avoid NSS lookups */
3120 return strdup("root");
3122 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3126 buf = malloc(bufsize);
3130 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3131 return strdup(pw->pw_name);
3133 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3139 char* getlogname_malloc(void) {
3143 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3148 return lookup_uid(uid);
3151 char *getusername_malloc(void) {
3158 return lookup_uid(getuid());
3161 int getttyname_malloc(int fd, char **r) {
3162 char path[PATH_MAX], *c;
3167 k = ttyname_r(fd, path, sizeof(path));
3173 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3181 int getttyname_harder(int fd, char **r) {
3185 k = getttyname_malloc(fd, &s);
3189 if (streq(s, "tty")) {
3191 return get_ctty(0, NULL, r);
3198 int get_ctty_devnr(pid_t pid, dev_t *d) {
3200 char line[LINE_MAX], *p, *fn;
3201 unsigned long ttynr;
3204 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3207 f = fopen(fn, "re");
3212 if (!fgets(line, sizeof(line), f)) {
3213 k = feof(f) ? -EIO : -errno;
3220 p = strrchr(line, ')');
3230 "%*d " /* session */
3239 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3241 char fn[PATH_MAX], *s, *b, *p;
3246 k = get_ctty_devnr(pid, &devnr);
3250 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3253 if ((k = readlink_malloc(fn, &s)) < 0) {
3258 /* This is an ugly hack */
3259 if (major(devnr) == 136) {
3260 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3270 /* Probably something like the ptys which have no
3271 * symlink in /dev/char. Let's return something
3272 * vaguely useful. */
3274 if (!(b = strdup(fn + 5)))
3284 if (startswith(s, "/dev/"))
3286 else if (startswith(s, "../"))
3304 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3310 /* This returns the first error we run into, but nevertheless
3311 * tries to go on. This closes the passed fd. */
3315 close_nointr_nofail(fd);
3317 return errno == ENOENT ? 0 : -errno;
3322 union dirent_storage buf;
3323 bool is_dir, keep_around;
3327 r = readdir_r(d, &buf.de, &de);
3328 if (r != 0 && ret == 0) {
3336 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3339 if (de->d_type == DT_UNKNOWN ||
3341 (de->d_type == DT_DIR && root_dev)) {
3342 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3343 if (ret == 0 && errno != ENOENT)
3348 is_dir = S_ISDIR(st.st_mode);
3351 (st.st_uid == 0 || st.st_uid == getuid()) &&
3352 (st.st_mode & S_ISVTX);
3354 is_dir = de->d_type == DT_DIR;
3355 keep_around = false;
3361 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3362 if (root_dev && st.st_dev != root_dev->st_dev)
3365 subdir_fd = openat(fd, de->d_name,
3366 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3367 if (subdir_fd < 0) {
3368 if (ret == 0 && errno != ENOENT)
3373 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3374 if (r < 0 && ret == 0)
3378 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3379 if (ret == 0 && errno != ENOENT)
3383 } else if (!only_dirs && !keep_around) {
3385 if (unlinkat(fd, de->d_name, 0) < 0) {
3386 if (ret == 0 && errno != ENOENT)
3397 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3402 if (fstatfs(fd, &s) < 0) {
3403 close_nointr_nofail(fd);
3407 /* We refuse to clean disk file systems with this call. This
3408 * is extra paranoia just to be sure we never ever remove
3411 if (s.f_type != TMPFS_MAGIC &&
3412 s.f_type != RAMFS_MAGIC) {
3413 log_error("Attempted to remove disk file system, and we can't allow that.");
3414 close_nointr_nofail(fd);
3418 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3421 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3427 /* We refuse to clean the root file system with this
3428 * call. This is extra paranoia to never cause a really
3429 * seriously broken system. */
3430 if (path_equal(path, "/")) {
3431 log_error("Attempted to remove entire root file system, and we can't allow that.");
3435 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3438 if (errno != ENOTDIR)
3442 if (statfs(path, &s) < 0)
3445 if (s.f_type != TMPFS_MAGIC &&
3446 s.f_type != RAMFS_MAGIC) {
3447 log_error("Attempted to remove disk file system, and we can't allow that.");
3452 if (delete_root && !only_dirs)
3453 if (unlink(path) < 0 && errno != ENOENT)
3460 if (fstatfs(fd, &s) < 0) {
3461 close_nointr_nofail(fd);
3465 if (s.f_type != TMPFS_MAGIC &&
3466 s.f_type != RAMFS_MAGIC) {
3467 log_error("Attempted to remove disk file system, and we can't allow that.");
3468 close_nointr_nofail(fd);
3473 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3476 if (honour_sticky && file_is_priv_sticky(path) > 0)
3479 if (rmdir(path) < 0 && errno != ENOENT) {
3488 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3489 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3492 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3493 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3496 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3499 /* Under the assumption that we are running privileged we
3500 * first change the access mode and only then hand out
3501 * ownership to avoid a window where access is too open. */
3503 if (mode != (mode_t) -1)
3504 if (chmod(path, mode) < 0)
3507 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3508 if (chown(path, uid, gid) < 0)
3514 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3517 /* Under the assumption that we are running privileged we
3518 * first change the access mode and only then hand out
3519 * ownership to avoid a window where access is too open. */
3521 if (fchmod(fd, mode) < 0)
3524 if (fchown(fd, uid, gid) < 0)
3530 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3534 /* Allocates the cpuset in the right size */
3537 if (!(r = CPU_ALLOC(n)))
3540 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3541 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3551 if (errno != EINVAL)
3558 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3559 static const char status_indent[] = " "; /* "[" STATUS "] " */
3560 _cleanup_free_ char *s = NULL;
3561 _cleanup_close_ int fd = -1;
3562 struct iovec iovec[5];
3567 /* This is independent of logging, as status messages are
3568 * optional and go exclusively to the console. */
3570 if (vasprintf(&s, format, ap) < 0)
3573 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3586 sl = status ? sizeof(status_indent)-1 : 0;
3592 e = ellipsize(s, emax, 75);
3602 if (!isempty(status)) {
3603 IOVEC_SET_STRING(iovec[n++], "[");
3604 IOVEC_SET_STRING(iovec[n++], status);
3605 IOVEC_SET_STRING(iovec[n++], "] ");
3607 IOVEC_SET_STRING(iovec[n++], status_indent);
3610 IOVEC_SET_STRING(iovec[n++], s);
3611 IOVEC_SET_STRING(iovec[n++], "\n");
3613 if (writev(fd, iovec, n) < 0)
3619 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3625 va_start(ap, format);
3626 r = status_vprintf(status, ellipse, format, ap);
3632 int status_welcome(void) {
3634 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3636 r = parse_env_file("/etc/os-release", NEWLINE,
3637 "PRETTY_NAME", &pretty_name,
3638 "ANSI_COLOR", &ansi_color,
3640 if (r < 0 && r != -ENOENT)
3641 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3643 return status_printf(NULL, false,
3644 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3645 isempty(ansi_color) ? "1" : ansi_color,
3646 isempty(pretty_name) ? "Linux" : pretty_name);
3649 char *replace_env(const char *format, char **env) {
3656 const char *e, *word = format;
3661 for (e = format; *e; e ++) {
3672 if (!(k = strnappend(r, word, e-word-1)))
3681 } else if (*e == '$') {
3682 if (!(k = strnappend(r, word, e-word)))
3698 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3701 if (!(k = strappend(r, t)))
3714 if (!(k = strnappend(r, word, e-word)))
3725 char **replace_env_argv(char **argv, char **env) {
3727 unsigned k = 0, l = 0;
3729 l = strv_length(argv);
3731 if (!(r = new(char*, l+1)))
3734 STRV_FOREACH(i, argv) {
3736 /* If $FOO appears as single word, replace it by the split up variable */
3737 if ((*i)[0] == '$' && (*i)[1] != '{') {
3742 if ((e = strv_env_get(env, *i+1))) {
3744 if (!(m = strv_split_quoted(e))) {
3755 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3764 memcpy(r + k, m, q * sizeof(char*));
3772 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3773 if (!(r[k++] = replace_env(*i, env))) {
3783 int fd_columns(int fd) {
3787 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3796 unsigned columns(void) {
3800 if (_likely_(cached_columns > 0))
3801 return cached_columns;
3804 e = getenv("COLUMNS");
3809 c = fd_columns(STDOUT_FILENO);
3818 int fd_lines(int fd) {
3822 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3831 unsigned lines(void) {
3835 if (_likely_(cached_lines > 0))
3836 return cached_lines;
3839 e = getenv("LINES");
3844 l = fd_lines(STDOUT_FILENO);
3850 return cached_lines;
3853 /* intended to be used as a SIGWINCH sighandler */
3854 void columns_lines_cache_reset(int signum) {
3860 static int cached_on_tty = -1;
3862 if (_unlikely_(cached_on_tty < 0))
3863 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3865 return cached_on_tty;
3868 int running_in_chroot(void) {
3874 /* Only works as root */
3876 if (stat("/proc/1/root", &a) < 0)
3879 if (stat("/", &b) < 0)
3883 a.st_dev != b.st_dev ||
3884 a.st_ino != b.st_ino;
3887 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3892 assert(percent <= 100);
3893 assert(new_length >= 3);
3895 if (old_length <= 3 || old_length <= new_length)
3896 return strndup(s, old_length);
3898 r = new0(char, new_length+1);
3902 x = (new_length * percent) / 100;
3904 if (x > new_length - 3)
3912 s + old_length - (new_length - x - 3),
3913 new_length - x - 3);
3918 char *ellipsize(const char *s, size_t length, unsigned percent) {
3919 return ellipsize_mem(s, strlen(s), length, percent);
3922 int touch(const char *path) {
3927 /* This just opens the file for writing, ensuring it
3928 * exists. It doesn't call utimensat() the way /usr/bin/touch
3931 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3935 close_nointr_nofail(fd);
3939 char *unquote(const char *s, const char* quotes) {
3943 /* This is rather stupid, simply removes the heading and
3944 * trailing quotes if there is one. Doesn't care about
3945 * escaping or anything. We should make this smarter one
3952 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3953 return strndup(s+1, l-2);
3958 char *normalize_env_assignment(const char *s) {
3959 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3962 eq = strchr(s, '=');
3974 memmove(r, t, strlen(t) + 1);
3978 name = strndup(s, eq - s);
3986 value = unquote(strstrip(p), QUOTES);
3990 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3996 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4007 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4019 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4026 r = wait_for_terminate(pid, &status);
4028 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4032 if (status.si_code == CLD_EXITED) {
4033 if (status.si_status != 0) {
4034 log_warning("%s failed with error code %i.", name, status.si_status);
4035 return status.si_status;
4038 log_debug("%s succeeded.", name);
4041 } else if (status.si_code == CLD_KILLED ||
4042 status.si_code == CLD_DUMPED) {
4044 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4048 log_warning("%s failed due to unknown reason.", name);
4052 _noreturn_ void freeze(void) {
4054 /* Make sure nobody waits for us on a socket anymore */
4055 close_all_fds(NULL, 0);
4063 bool null_or_empty(struct stat *st) {
4066 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4069 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4075 int null_or_empty_path(const char *fn) {
4080 if (stat(fn, &st) < 0)
4083 return null_or_empty(&st);
4086 DIR *xopendirat(int fd, const char *name, int flags) {
4090 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4096 close_nointr_nofail(nfd);
4103 int signal_from_string_try_harder(const char *s) {
4107 signo = signal_from_string(s);
4109 if (startswith(s, "SIG"))
4110 return signal_from_string(s+3);
4115 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4121 if (!dual_timestamp_is_set(t))
4124 fprintf(f, "%s=%llu %llu\n",
4126 (unsigned long long) t->realtime,
4127 (unsigned long long) t->monotonic);
4130 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4131 unsigned long long a, b;
4136 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4137 log_debug("Failed to parse finish timestamp value %s", value);
4144 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4148 /* FIXME: to follow udev's logic 100% we need to leave valid
4149 * UTF8 chars unescaped */
4151 u = unquote(tagvalue, "\"\'");
4155 t = xescape(u, "/ ");
4161 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4170 char *fstab_node_to_udev_node(const char *p) {
4173 if (startswith(p, "LABEL="))
4174 return tag_to_udev_node(p+6, "label");
4176 if (startswith(p, "UUID="))
4177 return tag_to_udev_node(p+5, "uuid");
4179 if (startswith(p, "PARTUUID="))
4180 return tag_to_udev_node(p+9, "partuuid");
4182 if (startswith(p, "PARTLABEL="))
4183 return tag_to_udev_node(p+10, "partlabel");
4188 bool tty_is_vc(const char *tty) {
4191 if (startswith(tty, "/dev/"))
4194 return vtnr_from_tty(tty) >= 0;
4197 bool tty_is_console(const char *tty) {
4200 if (startswith(tty, "/dev/"))
4203 return streq(tty, "console");
4206 int vtnr_from_tty(const char *tty) {
4211 if (startswith(tty, "/dev/"))
4214 if (!startswith(tty, "tty") )
4217 if (tty[3] < '0' || tty[3] > '9')
4220 r = safe_atoi(tty+3, &i);
4224 if (i < 0 || i > 63)
4230 bool tty_is_vc_resolve(const char *tty) {
4231 char *active = NULL;
4236 if (startswith(tty, "/dev/"))
4239 /* Resolve where /dev/console is pointing to, if /sys is
4240 * actually ours (i.e. not read-only-mounted which is a sign
4241 * for container setups) */
4242 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4243 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4244 /* If multiple log outputs are configured the
4245 * last one is what /dev/console points to */
4246 tty = strrchr(active, ' ');
4259 const char *default_term_for_tty(const char *tty) {
4262 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4265 bool dirent_is_file(const struct dirent *de) {
4268 if (ignore_file(de->d_name))
4271 if (de->d_type != DT_REG &&
4272 de->d_type != DT_LNK &&
4273 de->d_type != DT_UNKNOWN)
4279 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4282 if (de->d_type != DT_REG &&
4283 de->d_type != DT_LNK &&
4284 de->d_type != DT_UNKNOWN)
4287 if (ignore_file_allow_backup(de->d_name))
4290 return endswith(de->d_name, suffix);
4293 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4296 Hashmap *pids = NULL;
4300 /* Executes all binaries in a directory in parallel and waits
4301 * until all they all finished. */
4304 if (!(_d = opendir(directory))) {
4306 if (errno == ENOENT)
4309 log_error("Failed to enumerate directory %s: %m", directory);
4316 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4317 log_error("Failed to allocate set.");
4321 while ((de = readdir(d))) {
4326 if (!dirent_is_file(de))
4329 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4334 if ((pid = fork()) < 0) {
4335 log_error("Failed to fork: %m");
4353 log_error("Failed to execute %s: %m", path);
4354 _exit(EXIT_FAILURE);
4357 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4359 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4360 log_error("Failed to add PID to set: %s", strerror(-k));
4365 while (!hashmap_isempty(pids)) {
4366 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4371 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4376 log_error("waitid() failed: %m");
4380 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4381 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4382 if (si.si_code == CLD_EXITED)
4383 log_error("%s exited with exit status %i.", path, si.si_status);
4385 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4387 log_debug("%s exited successfully.", path);
4398 hashmap_free_free(pids);
4401 int kill_and_sigcont(pid_t pid, int sig) {
4404 r = kill(pid, sig) < 0 ? -errno : 0;
4412 bool nulstr_contains(const char*nulstr, const char *needle) {
4418 NULSTR_FOREACH(i, nulstr)
4419 if (streq(i, needle))
4425 bool plymouth_running(void) {
4426 return access("/run/plymouth/pid", F_OK) >= 0;
4429 char* strshorten(char *s, size_t l) {
4438 static bool hostname_valid_char(char c) {
4440 (c >= 'a' && c <= 'z') ||
4441 (c >= 'A' && c <= 'Z') ||
4442 (c >= '0' && c <= '9') ||
4448 bool hostname_is_valid(const char *s) {
4454 for (p = s; *p; p++)
4455 if (!hostname_valid_char(*p))
4458 if (p-s > HOST_NAME_MAX)
4464 char* hostname_cleanup(char *s) {
4467 for (p = s, d = s; *p; p++)
4468 if ((*p >= 'a' && *p <= 'z') ||
4469 (*p >= 'A' && *p <= 'Z') ||
4470 (*p >= '0' && *p <= '9') ||
4478 strshorten(s, HOST_NAME_MAX);
4482 int pipe_eof(int fd) {
4483 struct pollfd pollfd;
4488 pollfd.events = POLLIN|POLLHUP;
4490 r = poll(&pollfd, 1, 0);
4497 return pollfd.revents & POLLHUP;
4500 int fd_wait_for_event(int fd, int event, usec_t t) {
4501 struct pollfd pollfd;
4506 pollfd.events = event;
4508 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4515 return pollfd.revents;
4518 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4529 t = new(char, strlen(path) + 1 + 6 + 1);
4533 fn = path_get_file_name(path);
4537 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4539 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4545 f = fdopen(fd, "we");
4558 int terminal_vhangup_fd(int fd) {
4561 if (ioctl(fd, TIOCVHANGUP) < 0)
4567 int terminal_vhangup(const char *name) {
4570 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4574 r = terminal_vhangup_fd(fd);
4575 close_nointr_nofail(fd);
4580 int vt_disallocate(const char *name) {
4584 /* Deallocate the VT if possible. If not possible
4585 * (i.e. because it is the active one), at least clear it
4586 * entirely (including the scrollback buffer) */
4588 if (!startswith(name, "/dev/"))
4591 if (!tty_is_vc(name)) {
4592 /* So this is not a VT. I guess we cannot deallocate
4593 * it then. But let's at least clear the screen */
4595 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4600 "\033[r" /* clear scrolling region */
4601 "\033[H" /* move home */
4602 "\033[2J", /* clear screen */
4604 close_nointr_nofail(fd);
4609 if (!startswith(name, "/dev/tty"))
4612 r = safe_atou(name+8, &u);
4619 /* Try to deallocate */
4620 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4624 r = ioctl(fd, VT_DISALLOCATE, u);
4625 close_nointr_nofail(fd);
4633 /* Couldn't deallocate, so let's clear it fully with
4635 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4640 "\033[r" /* clear scrolling region */
4641 "\033[H" /* move home */
4642 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4644 close_nointr_nofail(fd);
4649 int copy_file(const char *from, const char *to) {
4655 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4659 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4661 close_nointr_nofail(fdf);
4669 n = read(fdf, buf, sizeof(buf));
4673 close_nointr_nofail(fdf);
4684 k = loop_write(fdt, buf, n, false);
4686 r = k < 0 ? k : (errno ? -errno : -EIO);
4688 close_nointr_nofail(fdf);
4696 close_nointr_nofail(fdf);
4697 r = close_nointr(fdt);
4707 int symlink_atomic(const char *from, const char *to) {
4709 _cleanup_free_ char *t;
4712 unsigned long long ull;
4719 t = new(char, strlen(to) + 1 + 16 + 1);
4723 fn = path_get_file_name(to);
4727 x = stpcpy(t+k+1, fn);
4730 for (i = 0; i < 16; i++) {
4731 *(x++) = hexchar(ull & 0xF);
4737 if (symlink(from, t) < 0)
4740 if (rename(t, to) < 0) {
4749 bool display_is_local(const char *display) {
4753 display[0] == ':' &&
4754 display[1] >= '0' &&
4758 int socket_from_display(const char *display, char **path) {
4765 if (!display_is_local(display))
4768 k = strspn(display+1, "0123456789");
4770 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4774 c = stpcpy(f, "/tmp/.X11-unix/X");
4775 memcpy(c, display+1, k);
4784 const char **username,
4785 uid_t *uid, gid_t *gid,
4787 const char **shell) {
4795 /* We enforce some special rules for uid=0: in order to avoid
4796 * NSS lookups for root we hardcode its data. */
4798 if (streq(*username, "root") || streq(*username, "0")) {
4816 if (parse_uid(*username, &u) >= 0) {
4820 /* If there are multiple users with the same id, make
4821 * sure to leave $USER to the configured value instead
4822 * of the first occurrence in the database. However if
4823 * the uid was configured by a numeric uid, then let's
4824 * pick the real username from /etc/passwd. */
4826 *username = p->pw_name;
4829 p = getpwnam(*username);
4833 return errno != 0 ? -errno : -ESRCH;
4845 *shell = p->pw_shell;
4850 int get_group_creds(const char **groupname, gid_t *gid) {
4856 /* We enforce some special rules for gid=0: in order to avoid
4857 * NSS lookups for root we hardcode its data. */
4859 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4860 *groupname = "root";
4868 if (parse_gid(*groupname, &id) >= 0) {
4873 *groupname = g->gr_name;
4876 g = getgrnam(*groupname);
4880 return errno != 0 ? -errno : -ESRCH;
4888 int in_group(const char *name) {
4890 int ngroups_max, r, i;
4892 r = get_group_creds(&name, &gid);
4896 if (getgid() == gid)
4899 if (getegid() == gid)
4902 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4903 assert(ngroups_max > 0);
4905 gids = alloca(sizeof(gid_t) * ngroups_max);
4907 r = getgroups(ngroups_max, gids);
4911 for (i = 0; i < r; i++)
4918 int glob_exists(const char *path) {
4926 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4928 if (k == GLOB_NOMATCH)
4930 else if (k == GLOB_NOSPACE)
4933 r = !strv_isempty(g.gl_pathv);
4935 r = errno ? -errno : -EIO;
4942 int dirent_ensure_type(DIR *d, struct dirent *de) {
4948 if (de->d_type != DT_UNKNOWN)
4951 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4955 S_ISREG(st.st_mode) ? DT_REG :
4956 S_ISDIR(st.st_mode) ? DT_DIR :
4957 S_ISLNK(st.st_mode) ? DT_LNK :
4958 S_ISFIFO(st.st_mode) ? DT_FIFO :
4959 S_ISSOCK(st.st_mode) ? DT_SOCK :
4960 S_ISCHR(st.st_mode) ? DT_CHR :
4961 S_ISBLK(st.st_mode) ? DT_BLK :
4967 int in_search_path(const char *path, char **search) {
4971 r = path_get_parent(path, &parent);
4977 STRV_FOREACH(i, search) {
4978 if (path_equal(parent, *i)) {
4989 int get_files_in_directory(const char *path, char ***list) {
4997 /* Returns all files in a directory in *list, and the number
4998 * of files as return value. If list is NULL returns only the
5007 union dirent_storage buf;
5010 k = readdir_r(d, &buf.de, &de);
5019 dirent_ensure_type(d, de);
5021 if (!dirent_is_file(de))
5025 if ((unsigned) r >= n) {
5029 t = realloc(l, sizeof(char*) * n);
5038 assert((unsigned) r < n);
5040 l[r] = strdup(de->d_name);
5064 char *strjoin(const char *x, ...) {
5078 t = va_arg(ap, const char *);
5083 if (n > ((size_t) -1) - l) {
5107 t = va_arg(ap, const char *);
5121 bool is_main_thread(void) {
5122 static __thread int cached = 0;
5124 if (_unlikely_(cached == 0))
5125 cached = getpid() == gettid() ? 1 : -1;
5130 int block_get_whole_disk(dev_t d, dev_t *ret) {
5137 /* If it has a queue this is good enough for us */
5138 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5141 r = access(p, F_OK);
5149 /* If it is a partition find the originating device */
5150 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5153 r = access(p, F_OK);
5159 /* Get parent dev_t */
5160 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5163 r = read_one_line_file(p, &s);
5169 r = sscanf(s, "%u:%u", &m, &n);
5175 /* Only return this if it is really good enough for us. */
5176 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5179 r = access(p, F_OK);
5183 *ret = makedev(m, n);
5190 int file_is_priv_sticky(const char *p) {
5195 if (lstat(p, &st) < 0)
5199 (st.st_uid == 0 || st.st_uid == getuid()) &&
5200 (st.st_mode & S_ISVTX);
5203 static const char *const ioprio_class_table[] = {
5204 [IOPRIO_CLASS_NONE] = "none",
5205 [IOPRIO_CLASS_RT] = "realtime",
5206 [IOPRIO_CLASS_BE] = "best-effort",
5207 [IOPRIO_CLASS_IDLE] = "idle"
5210 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5212 static const char *const sigchld_code_table[] = {
5213 [CLD_EXITED] = "exited",
5214 [CLD_KILLED] = "killed",
5215 [CLD_DUMPED] = "dumped",
5216 [CLD_TRAPPED] = "trapped",
5217 [CLD_STOPPED] = "stopped",
5218 [CLD_CONTINUED] = "continued",
5221 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5223 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5224 [LOG_FAC(LOG_KERN)] = "kern",
5225 [LOG_FAC(LOG_USER)] = "user",
5226 [LOG_FAC(LOG_MAIL)] = "mail",
5227 [LOG_FAC(LOG_DAEMON)] = "daemon",
5228 [LOG_FAC(LOG_AUTH)] = "auth",
5229 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5230 [LOG_FAC(LOG_LPR)] = "lpr",
5231 [LOG_FAC(LOG_NEWS)] = "news",
5232 [LOG_FAC(LOG_UUCP)] = "uucp",
5233 [LOG_FAC(LOG_CRON)] = "cron",
5234 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5235 [LOG_FAC(LOG_FTP)] = "ftp",
5236 [LOG_FAC(LOG_LOCAL0)] = "local0",
5237 [LOG_FAC(LOG_LOCAL1)] = "local1",
5238 [LOG_FAC(LOG_LOCAL2)] = "local2",
5239 [LOG_FAC(LOG_LOCAL3)] = "local3",
5240 [LOG_FAC(LOG_LOCAL4)] = "local4",
5241 [LOG_FAC(LOG_LOCAL5)] = "local5",
5242 [LOG_FAC(LOG_LOCAL6)] = "local6",
5243 [LOG_FAC(LOG_LOCAL7)] = "local7"
5246 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5248 static const char *const log_level_table[] = {
5249 [LOG_EMERG] = "emerg",
5250 [LOG_ALERT] = "alert",
5251 [LOG_CRIT] = "crit",
5253 [LOG_WARNING] = "warning",
5254 [LOG_NOTICE] = "notice",
5255 [LOG_INFO] = "info",
5256 [LOG_DEBUG] = "debug"
5259 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5261 static const char* const sched_policy_table[] = {
5262 [SCHED_OTHER] = "other",
5263 [SCHED_BATCH] = "batch",
5264 [SCHED_IDLE] = "idle",
5265 [SCHED_FIFO] = "fifo",
5269 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5271 static const char* const rlimit_table[] = {
5272 [RLIMIT_CPU] = "LimitCPU",
5273 [RLIMIT_FSIZE] = "LimitFSIZE",
5274 [RLIMIT_DATA] = "LimitDATA",
5275 [RLIMIT_STACK] = "LimitSTACK",
5276 [RLIMIT_CORE] = "LimitCORE",
5277 [RLIMIT_RSS] = "LimitRSS",
5278 [RLIMIT_NOFILE] = "LimitNOFILE",
5279 [RLIMIT_AS] = "LimitAS",
5280 [RLIMIT_NPROC] = "LimitNPROC",
5281 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5282 [RLIMIT_LOCKS] = "LimitLOCKS",
5283 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5284 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5285 [RLIMIT_NICE] = "LimitNICE",
5286 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5287 [RLIMIT_RTTIME] = "LimitRTTIME"
5290 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5292 static const char* const ip_tos_table[] = {
5293 [IPTOS_LOWDELAY] = "low-delay",
5294 [IPTOS_THROUGHPUT] = "throughput",
5295 [IPTOS_RELIABILITY] = "reliability",
5296 [IPTOS_LOWCOST] = "low-cost",
5299 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5301 static const char *const __signal_table[] = {
5318 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5329 [SIGVTALRM] = "VTALRM",
5331 [SIGWINCH] = "WINCH",
5337 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5339 const char *signal_to_string(int signo) {
5340 static __thread char buf[12];
5343 name = __signal_to_string(signo);
5347 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5348 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5350 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5355 int signal_from_string(const char *s) {
5360 signo = __signal_from_string(s);
5364 if (startswith(s, "RTMIN+")) {
5368 if (safe_atou(s, &u) >= 0) {
5369 signo = (int) u + offset;
5370 if (signo > 0 && signo < _NSIG)
5376 bool kexec_loaded(void) {
5377 bool loaded = false;
5380 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5388 int strdup_or_null(const char *a, char **b) {
5406 int prot_from_flags(int flags) {
5408 switch (flags & O_ACCMODE) {
5417 return PROT_READ|PROT_WRITE;
5424 char *format_bytes(char *buf, size_t l, off_t t) {
5427 static const struct {
5431 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5432 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5433 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5434 { "G", 1024ULL*1024ULL*1024ULL },
5435 { "M", 1024ULL*1024ULL },
5439 for (i = 0; i < ELEMENTSOF(table); i++) {
5441 if (t >= table[i].factor) {
5444 (unsigned long long) (t / table[i].factor),
5445 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5452 snprintf(buf, l, "%lluB", (unsigned long long) t);
5460 void* memdup(const void *p, size_t l) {
5473 int fd_inc_sndbuf(int fd, size_t n) {
5475 socklen_t l = sizeof(value);
5477 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5479 l == sizeof(value) &&
5480 (size_t) value >= n*2)
5484 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5491 int fd_inc_rcvbuf(int fd, size_t n) {
5493 socklen_t l = sizeof(value);
5495 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5497 l == sizeof(value) &&
5498 (size_t) value >= n*2)
5502 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5509 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5510 pid_t parent_pid, agent_pid;
5512 bool stdout_is_tty, stderr_is_tty;
5520 parent_pid = getpid();
5522 /* Spawns a temporary TTY agent, making sure it goes away when
5529 if (agent_pid != 0) {
5536 * Make sure the agent goes away when the parent dies */
5537 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5538 _exit(EXIT_FAILURE);
5540 /* Check whether our parent died before we were able
5541 * to set the death signal */
5542 if (getppid() != parent_pid)
5543 _exit(EXIT_SUCCESS);
5545 /* Don't leak fds to the agent */
5546 close_all_fds(except, n_except);
5548 stdout_is_tty = isatty(STDOUT_FILENO);
5549 stderr_is_tty = isatty(STDERR_FILENO);
5551 if (!stdout_is_tty || !stderr_is_tty) {
5552 /* Detach from stdout/stderr. and reopen
5553 * /dev/tty for them. This is important to
5554 * ensure that when systemctl is started via
5555 * popen() or a similar call that expects to
5556 * read EOF we actually do generate EOF and
5557 * not delay this indefinitely by because we
5558 * keep an unused copy of stdin around. */
5559 fd = open("/dev/tty", O_WRONLY);
5561 log_error("Failed to open /dev/tty: %m");
5562 _exit(EXIT_FAILURE);
5566 dup2(fd, STDOUT_FILENO);
5569 dup2(fd, STDERR_FILENO);
5575 /* Count arguments */
5577 for (n = 0; va_arg(ap, char*); n++)
5582 l = alloca(sizeof(char *) * (n + 1));
5584 /* Fill in arguments */
5586 for (i = 0; i <= n; i++)
5587 l[i] = va_arg(ap, char*);
5591 _exit(EXIT_FAILURE);
5594 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5595 struct rlimit highest, fixed;
5599 if (setrlimit(resource, rlim) >= 0)
5605 /* So we failed to set the desired setrlimit, then let's try
5606 * to get as close as we can */
5607 assert_se(getrlimit(resource, &highest) == 0);
5609 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5610 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5612 if (setrlimit(resource, &fixed) < 0)
5618 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5619 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5631 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5634 f = fopen(path, "re");
5642 char line[LINE_MAX];
5645 for (i = 0; i < sizeof(line)-1; i++) {
5649 if (_unlikely_(c == EOF)) {
5659 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5660 value = strdup(line + l + 1);
5680 int can_sleep(const char *type) {
5684 _cleanup_free_ char *p = NULL;
5688 r = read_one_line_file("/sys/power/state", &p);
5690 return r == -ENOENT ? 0 : r;
5693 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5694 if (l == k && memcmp(w, type, l) == 0)
5700 int can_sleep_disk(const char *type) {
5704 _cleanup_free_ char *p = NULL;
5708 r = read_one_line_file("/sys/power/disk", &p);
5710 return r == -ENOENT ? 0 : r;
5713 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5714 if (l == k && memcmp(w, type, l) == 0)
5717 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5724 bool is_valid_documentation_url(const char *url) {
5727 if (startswith(url, "http://") && url[7])
5730 if (startswith(url, "https://") && url[8])
5733 if (startswith(url, "file:") && url[5])
5736 if (startswith(url, "info:") && url[5])
5739 if (startswith(url, "man:") && url[4])
5745 bool in_initrd(void) {
5746 static __thread int saved = -1;
5752 /* We make two checks here:
5754 * 1. the flag file /etc/initrd-release must exist
5755 * 2. the root file system must be a memory file system
5757 * The second check is extra paranoia, since misdetecting an
5758 * initrd can have bad bad consequences due the initrd
5759 * emptying when transititioning to the main systemd.
5762 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5763 statfs("/", &s) >= 0 &&
5764 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5769 void warn_melody(void) {
5770 _cleanup_close_ int fd = -1;
5772 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5776 /* Yeah, this is synchronous. Kinda sucks. But well... */
5778 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5779 usleep(125*USEC_PER_MSEC);
5781 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5782 usleep(125*USEC_PER_MSEC);
5784 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5785 usleep(125*USEC_PER_MSEC);
5787 ioctl(fd, KIOCSOUND, 0);
5790 int make_console_stdio(void) {
5793 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5795 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5797 log_error("Failed to acquire terminal: %s", strerror(-fd));
5803 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5810 int get_home_dir(char **_h) {
5818 /* Take the user specified one */
5829 /* Hardcode home directory for root to avoid NSS */
5832 h = strdup("/root");
5840 /* Check the database... */
5844 return errno ? -errno : -ESRCH;
5846 if (!path_is_absolute(p->pw_dir))
5849 h = strdup(p->pw_dir);
5857 int get_shell(char **_sh) {
5865 /* Take the user specified one */
5866 e = getenv("SHELL");
5876 /* Hardcode home directory for root to avoid NSS */
5879 sh = strdup("/bin/sh");
5887 /* Check the database... */
5891 return errno ? -errno : -ESRCH;
5893 if (!path_is_absolute(p->pw_shell))
5896 sh = strdup(p->pw_shell);
5904 void freep(void *p) {
5908 void fclosep(FILE **f) {
5913 void closep(int *fd) {
5915 close_nointr_nofail(*fd);
5918 void closedirp(DIR **d) {
5923 void umaskp(mode_t *u) {
5927 bool filename_is_safe(const char *p) {
5941 if (strlen(p) > FILENAME_MAX)
5947 bool string_is_safe(const char *p) {
5952 for (t = p; *t; t++) {
5953 if (*t > 0 && *t < ' ')
5956 if (strchr("\\\"\'", *t))
5963 int parse_timestamp(const char *t, usec_t *usec) {
5967 usec_t plus = 0, minus = 0, ret;
5973 * 2012-09-22 16:34:22
5974 * 2012-09-22 16:34 (seconds will be set to 0)
5975 * 2012-09-22 (time will be set to 00:00:00)
5976 * 16:34:22 (date will be set to today)
5977 * 16:34 (date will be set to today, seconds to 0)
5979 * yesterday (time is set to 00:00:00)
5980 * today (time is set to 00:00:00)
5981 * tomorrow (time is set to 00:00:00)
5991 assert_se(localtime_r(&x, &tm));
5993 if (streq(t, "now"))
5996 else if (streq(t, "today")) {
5997 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6000 } else if (streq(t, "yesterday")) {
6002 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6005 } else if (streq(t, "tomorrow")) {
6007 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6010 } else if (t[0] == '+') {
6012 r = parse_usec(t+1, &plus);
6017 } else if (t[0] == '-') {
6019 r = parse_usec(t+1, &minus);
6027 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6032 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6037 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6044 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6051 k = strptime(t, "%y-%m-%d", &tm);
6053 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6058 k = strptime(t, "%Y-%m-%d", &tm);
6060 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6065 k = strptime(t, "%H:%M:%S", &tm);
6070 k = strptime(t, "%H:%M", &tm);
6080 if (x == (time_t) -1)
6083 ret = (usec_t) x * USEC_PER_SEC;
6096 /* hey glibc, APIs with callbacks without a user pointer are so useless */
6097 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
6098 int (*compar) (const void *, const void *, void *), void *arg) {
6107 p = (void *)(((const char *) base) + (idx * size));
6108 comparison = compar(key, p, arg);
6111 else if (comparison > 0)