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)
152 (usec_t) ts->tv_sec * USEC_PER_SEC +
153 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
156 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
159 if (u == (usec_t) -1) {
160 ts->tv_sec = (time_t) -1;
161 ts->tv_nsec = (long) -1;
165 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
166 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
171 usec_t timeval_load(const struct timeval *tv) {
174 if (tv->tv_sec == (time_t) -1 &&
175 tv->tv_usec == (suseconds_t) -1)
179 (usec_t) tv->tv_sec * USEC_PER_SEC +
180 (usec_t) tv->tv_usec;
183 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
186 if (u == (usec_t) -1) {
187 tv->tv_sec = (time_t) -1;
188 tv->tv_usec = (suseconds_t) -1;
192 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
193 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
198 char* endswith(const char *s, const char *postfix) {
205 pl = strlen(postfix);
208 return (char*) s + sl;
213 if (memcmp(s + sl - pl, postfix, pl) != 0)
216 return (char*) s + sl - pl;
219 bool startswith(const char *s, const char *prefix) {
234 return memcmp(s, prefix, pl) == 0;
237 bool startswith_no_case(const char *s, const char *prefix) {
253 for(i = 0; i < pl; ++i)
254 if (tolower(s[i]) != tolower(prefix[i]))
260 bool first_word(const char *s, const char *word) {
275 if (memcmp(s, word, wl) != 0)
279 strchr(WHITESPACE, s[wl]);
282 int close_nointr(int fd) {
297 void close_nointr_nofail(int fd) {
298 int saved_errno = errno;
300 /* like close_nointr() but cannot fail, and guarantees errno
303 assert_se(close_nointr(fd) == 0);
308 void close_many(const int fds[], unsigned n_fd) {
311 for (i = 0; i < n_fd; i++)
312 close_nointr_nofail(fds[i]);
315 int parse_boolean(const char *v) {
318 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
320 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
326 int parse_pid(const char *s, pid_t* ret_pid) {
327 unsigned long ul = 0;
334 r = safe_atolu(s, &ul);
340 if ((unsigned long) pid != ul)
350 int parse_uid(const char *s, uid_t* ret_uid) {
351 unsigned long ul = 0;
358 r = safe_atolu(s, &ul);
364 if ((unsigned long) uid != ul)
371 int safe_atou(const char *s, unsigned *ret_u) {
379 l = strtoul(s, &x, 0);
381 if (!x || *x || errno)
382 return errno ? -errno : -EINVAL;
384 if ((unsigned long) (unsigned) l != l)
387 *ret_u = (unsigned) l;
391 int safe_atoi(const char *s, int *ret_i) {
399 l = strtol(s, &x, 0);
401 if (!x || *x || errno)
402 return errno ? -errno : -EINVAL;
404 if ((long) (int) l != l)
411 int safe_atollu(const char *s, long long unsigned *ret_llu) {
413 unsigned long long l;
419 l = strtoull(s, &x, 0);
421 if (!x || *x || errno)
422 return errno ? -errno : -EINVAL;
428 int safe_atolli(const char *s, long long int *ret_lli) {
436 l = strtoll(s, &x, 0);
438 if (!x || *x || errno)
439 return errno ? -errno : -EINVAL;
445 /* Split a string into words. */
446 char *split(const char *c, size_t *l, const char *separator, char **state) {
449 current = *state ? *state : (char*) c;
451 if (!*current || *c == 0)
454 current += strspn(current, separator);
455 *l = strcspn(current, separator);
458 return (char*) current;
461 /* Split a string into words, but consider strings enclosed in '' and
462 * "" as words even if they include spaces. */
463 char *split_quoted(const char *c, size_t *l, char **state) {
465 bool escaped = false;
467 current = *state ? *state : (char*) c;
469 if (!*current || *c == 0)
472 current += strspn(current, WHITESPACE);
474 if (*current == '\'') {
477 for (e = current; *e; e++) {
487 *state = *e == 0 ? e : e+1;
488 } else if (*current == '\"') {
491 for (e = current; *e; e++) {
501 *state = *e == 0 ? e : e+1;
503 for (e = current; *e; e++) {
508 else if (strchr(WHITESPACE, *e))
515 return (char*) current;
518 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
520 _cleanup_fclose_ FILE *f = NULL;
521 char fn[PATH_MAX], line[LINE_MAX], *p;
527 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
534 if (!fgets(line, sizeof(line), f)) {
535 r = feof(f) ? -EIO : -errno;
540 /* Let's skip the pid and comm fields. The latter is enclosed
541 * in () but does not escape any () in its value, so let's
542 * skip over it manually */
544 p = strrchr(line, ')');
556 if ((long unsigned) (pid_t) ppid != ppid)
559 *_ppid = (pid_t) ppid;
564 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
565 _cleanup_fclose_ FILE *f = NULL;
566 char fn[PATH_MAX], line[LINE_MAX], *p;
571 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
578 if (!fgets(line, sizeof(line), f)) {
585 /* Let's skip the pid and comm fields. The latter is enclosed
586 * in () but does not escape any () in its value, so let's
587 * skip over it manually */
589 p = strrchr(line, ')');
611 "%*d " /* priority */
613 "%*d " /* num_threads */
614 "%*d " /* itrealvalue */
615 "%llu " /* starttime */,
622 int write_one_line_file(const char *fn, const char *line) {
623 _cleanup_fclose_ FILE *f = NULL;
633 if (fputs(line, f) < 0)
634 return errno ? -errno : -EIO;
636 if (!endswith(line, "\n"))
642 return errno ? -errno : -EIO;
647 int fchmod_umask(int fd, mode_t m) {
652 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
658 int write_one_line_file_atomic(const char *fn, const char *line) {
666 r = fopen_temporary(fn, &f, &p);
670 fchmod_umask(fileno(f), 0644);
673 if (fputs(line, f) < 0) {
678 if (!endswith(line, "\n"))
689 if (rename(p, fn) < 0)
705 int read_one_line_file(const char *fn, char **line) {
706 _cleanup_fclose_ FILE *f = NULL;
707 char t[LINE_MAX], *c;
716 if (!fgets(t, sizeof(t), f)) {
719 return errno ? -errno : -EIO;
733 int read_full_file(const char *fn, char **contents, size_t *size) {
734 _cleanup_fclose_ FILE *f = NULL;
736 _cleanup_free_ char *buf = NULL;
743 if (fstat(fileno(f), &st) < 0)
747 if (st.st_size > 4*1024*1024)
750 n = st.st_size > 0 ? st.st_size : LINE_MAX;
757 t = realloc(buf, n+1);
762 k = fread(buf + l, 1, n - l, f);
791 const char *separator, ...) {
794 char *contents = NULL, *p;
799 if ((r = read_full_file(fname, &contents, NULL)) < 0)
804 const char *key = NULL;
806 p += strspn(p, separator);
807 p += strspn(p, WHITESPACE);
812 if (!strchr(COMMENTS, *p)) {
816 va_start(ap, separator);
817 while ((key = va_arg(ap, char *))) {
821 value = va_arg(ap, char **);
824 if (strncmp(p, key, n) != 0 ||
829 n = strcspn(p, separator);
832 strchr(QUOTES, p[0]) &&
834 v = strndup(p+1, n-2);
845 /* return empty value strings as NULL */
862 p += strcspn(p, separator);
881 if (!(f = fopen(fname, "re")))
885 char l[LINE_MAX], *p, *u;
888 if (!fgets(l, sizeof(l), f)) {
901 if (strchr(COMMENTS, *p))
904 if (!(u = normalize_env_assignment(p))) {
909 t = strv_append(m, u);
935 int write_env_file(const char *fname, char **l) {
940 r = fopen_temporary(fname, &f, &p);
944 fchmod_umask(fileno(f), 0644);
960 if (rename(p, fname) < 0)
975 char *truncate_nl(char *s) {
978 s[strcspn(s, NEWLINE)] = 0;
982 int get_process_comm(pid_t pid, char **name) {
988 r = read_one_line_file("/proc/self/comm", name);
991 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
994 r = read_one_line_file(p, name);
1001 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1008 assert(max_length > 0);
1012 f = fopen("/proc/self/cmdline", "re");
1015 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1025 r = new(char, max_length);
1033 while ((c = getc(f)) != EOF) {
1055 size_t n = MIN(left-1, 3U);
1056 memcpy(k, "...", n);
1063 /* Kernel threads have no argv[] */
1073 h = get_process_comm(pid, &t);
1077 r = strjoin("[", t, "]", NULL);
1088 int is_kernel_thread(pid_t pid) {
1098 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1107 count = fread(&c, 1, 1, f);
1111 /* Kernel threads have an empty cmdline */
1114 return eof ? 1 : -errno;
1119 int get_process_exe(pid_t pid, char **name) {
1125 r = readlink_malloc("/proc/self/exe", name);
1128 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1131 r = readlink_malloc(p, name);
1138 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1148 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1158 char line[LINE_MAX], *l;
1160 if (!fgets(line, sizeof(line), f)) {
1170 if (startswith(l, field)) {
1172 l += strspn(l, WHITESPACE);
1174 l[strcspn(l, WHITESPACE)] = 0;
1176 r = parse_uid(l, uid);
1189 int get_process_uid(pid_t pid, uid_t *uid) {
1190 return get_process_id(pid, "Uid:", uid);
1193 int get_process_gid(pid_t pid, gid_t *gid) {
1194 return get_process_id(pid, "Gid:", gid);
1197 char *strnappend(const char *s, const char *suffix, size_t b) {
1205 return strndup(suffix, b);
1214 if (b > ((size_t) -1) - a)
1217 r = new(char, a+b+1);
1222 memcpy(r+a, suffix, b);
1228 char *strappend(const char *s, const char *suffix) {
1229 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1232 int readlink_malloc(const char *p, char **r) {
1242 if (!(c = new(char, l)))
1245 if ((n = readlink(p, c, l-1)) < 0) {
1251 if ((size_t) n < l-1) {
1262 int readlink_and_make_absolute(const char *p, char **r) {
1269 if ((j = readlink_malloc(p, &target)) < 0)
1272 k = file_in_same_dir(p, target);
1282 int readlink_and_canonicalize(const char *p, char **r) {
1289 j = readlink_and_make_absolute(p, &t);
1293 s = canonicalize_file_name(t);
1300 path_kill_slashes(*r);
1305 int reset_all_signal_handlers(void) {
1308 for (sig = 1; sig < _NSIG; sig++) {
1309 struct sigaction sa;
1311 if (sig == SIGKILL || sig == SIGSTOP)
1315 sa.sa_handler = SIG_DFL;
1316 sa.sa_flags = SA_RESTART;
1318 /* On Linux the first two RT signals are reserved by
1319 * glibc, and sigaction() will return EINVAL for them. */
1320 if ((sigaction(sig, &sa, NULL) < 0))
1321 if (errno != EINVAL)
1328 char *strstrip(char *s) {
1331 /* Drops trailing whitespace. Modifies the string in
1332 * place. Returns pointer to first non-space character */
1334 s += strspn(s, WHITESPACE);
1336 for (e = strchr(s, 0); e > s; e --)
1337 if (!strchr(WHITESPACE, e[-1]))
1345 char *delete_chars(char *s, const char *bad) {
1348 /* Drops all whitespace, regardless where in the string */
1350 for (f = s, t = s; *f; f++) {
1351 if (strchr(bad, *f))
1362 bool in_charset(const char *s, const char* charset) {
1368 for (i = s; *i; i++)
1369 if (!strchr(charset, *i))
1375 char *file_in_same_dir(const char *path, const char *filename) {
1382 /* This removes the last component of path and appends
1383 * filename, unless the latter is absolute anyway or the
1386 if (path_is_absolute(filename))
1387 return strdup(filename);
1389 if (!(e = strrchr(path, '/')))
1390 return strdup(filename);
1392 k = strlen(filename);
1393 if (!(r = new(char, e-path+1+k+1)))
1396 memcpy(r, path, e-path+1);
1397 memcpy(r+(e-path)+1, filename, k+1);
1402 int rmdir_parents(const char *path, const char *stop) {
1411 /* Skip trailing slashes */
1412 while (l > 0 && path[l-1] == '/')
1418 /* Skip last component */
1419 while (l > 0 && path[l-1] != '/')
1422 /* Skip trailing slashes */
1423 while (l > 0 && path[l-1] == '/')
1429 if (!(t = strndup(path, l)))
1432 if (path_startswith(stop, t)) {
1441 if (errno != ENOENT)
1449 char hexchar(int x) {
1450 static const char table[16] = "0123456789abcdef";
1452 return table[x & 15];
1455 int unhexchar(char c) {
1457 if (c >= '0' && c <= '9')
1460 if (c >= 'a' && c <= 'f')
1461 return c - 'a' + 10;
1463 if (c >= 'A' && c <= 'F')
1464 return c - 'A' + 10;
1469 char octchar(int x) {
1470 return '0' + (x & 7);
1473 int unoctchar(char c) {
1475 if (c >= '0' && c <= '7')
1481 char decchar(int x) {
1482 return '0' + (x % 10);
1485 int undecchar(char c) {
1487 if (c >= '0' && c <= '9')
1493 char *cescape(const char *s) {
1499 /* Does C style string escaping. */
1501 r = new(char, strlen(s)*4 + 1);
1505 for (f = s, t = r; *f; f++)
1551 /* For special chars we prefer octal over
1552 * hexadecimal encoding, simply because glib's
1553 * g_strescape() does the same */
1554 if ((*f < ' ') || (*f >= 127)) {
1556 *(t++) = octchar((unsigned char) *f >> 6);
1557 *(t++) = octchar((unsigned char) *f >> 3);
1558 *(t++) = octchar((unsigned char) *f);
1569 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1576 /* Undoes C style string escaping, and optionally prefixes it. */
1578 pl = prefix ? strlen(prefix) : 0;
1580 r = new(char, pl+length+1);
1585 memcpy(r, prefix, pl);
1587 for (f = s, t = r + pl; f < s + length; f++) {
1630 /* This is an extension of the XDG syntax files */
1635 /* hexadecimal encoding */
1638 a = unhexchar(f[1]);
1639 b = unhexchar(f[2]);
1641 if (a < 0 || b < 0) {
1642 /* Invalid escape code, let's take it literal then */
1646 *(t++) = (char) ((a << 4) | b);
1661 /* octal encoding */
1664 a = unoctchar(f[0]);
1665 b = unoctchar(f[1]);
1666 c = unoctchar(f[2]);
1668 if (a < 0 || b < 0 || c < 0) {
1669 /* Invalid escape code, let's take it literal then */
1673 *(t++) = (char) ((a << 6) | (b << 3) | c);
1681 /* premature end of string.*/
1686 /* Invalid escape code, let's take it literal then */
1698 char *cunescape_length(const char *s, size_t length) {
1699 return cunescape_length_with_prefix(s, length, NULL);
1702 char *cunescape(const char *s) {
1705 return cunescape_length(s, strlen(s));
1708 char *xescape(const char *s, const char *bad) {
1712 /* Escapes all chars in bad, in addition to \ and all special
1713 * chars, in \xFF style escaping. May be reversed with
1716 r = new(char, strlen(s) * 4 + 1);
1720 for (f = s, t = r; *f; f++) {
1722 if ((*f < ' ') || (*f >= 127) ||
1723 (*f == '\\') || strchr(bad, *f)) {
1726 *(t++) = hexchar(*f >> 4);
1727 *(t++) = hexchar(*f);
1737 char *bus_path_escape(const char *s) {
1743 /* Escapes all chars that D-Bus' object path cannot deal
1744 * with. Can be reverse with bus_path_unescape() */
1746 if (!(r = new(char, strlen(s)*3+1)))
1749 for (f = s, t = r; *f; f++) {
1751 if (!(*f >= 'A' && *f <= 'Z') &&
1752 !(*f >= 'a' && *f <= 'z') &&
1753 !(*f >= '0' && *f <= '9')) {
1755 *(t++) = hexchar(*f >> 4);
1756 *(t++) = hexchar(*f);
1766 char *bus_path_unescape(const char *f) {
1771 if (!(r = strdup(f)))
1774 for (t = r; *f; f++) {
1779 if ((a = unhexchar(f[1])) < 0 ||
1780 (b = unhexchar(f[2])) < 0) {
1781 /* Invalid escape code, let's take it literal then */
1784 *(t++) = (char) ((a << 4) | b);
1796 char *ascii_strlower(char *t) {
1801 for (p = t; *p; p++)
1802 if (*p >= 'A' && *p <= 'Z')
1803 *p = *p - 'A' + 'a';
1808 static bool ignore_file_allow_backup(const char *filename) {
1812 filename[0] == '.' ||
1813 streq(filename, "lost+found") ||
1814 streq(filename, "aquota.user") ||
1815 streq(filename, "aquota.group") ||
1816 endswith(filename, ".rpmnew") ||
1817 endswith(filename, ".rpmsave") ||
1818 endswith(filename, ".rpmorig") ||
1819 endswith(filename, ".dpkg-old") ||
1820 endswith(filename, ".dpkg-new") ||
1821 endswith(filename, ".swp");
1824 bool ignore_file(const char *filename) {
1827 if (endswith(filename, "~"))
1830 return ignore_file_allow_backup(filename);
1833 int fd_nonblock(int fd, bool nonblock) {
1838 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1842 flags |= O_NONBLOCK;
1844 flags &= ~O_NONBLOCK;
1846 if (fcntl(fd, F_SETFL, flags) < 0)
1852 int fd_cloexec(int fd, bool cloexec) {
1857 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1861 flags |= FD_CLOEXEC;
1863 flags &= ~FD_CLOEXEC;
1865 if (fcntl(fd, F_SETFD, flags) < 0)
1871 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1874 assert(n_fdset == 0 || fdset);
1876 for (i = 0; i < n_fdset; i++)
1883 int close_all_fds(const int except[], unsigned n_except) {
1888 assert(n_except == 0 || except);
1890 d = opendir("/proc/self/fd");
1895 /* When /proc isn't available (for example in chroots)
1896 * the fallback is brute forcing through the fd
1899 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1900 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1902 if (fd_in_set(fd, except, n_except))
1905 if (close_nointr(fd) < 0)
1906 if (errno != EBADF && r == 0)
1913 while ((de = readdir(d))) {
1916 if (ignore_file(de->d_name))
1919 if (safe_atoi(de->d_name, &fd) < 0)
1920 /* Let's better ignore this, just in case */
1929 if (fd_in_set(fd, except, n_except))
1932 if (close_nointr(fd) < 0) {
1933 /* Valgrind has its own FD and doesn't want to have it closed */
1934 if (errno != EBADF && r == 0)
1943 bool chars_intersect(const char *a, const char *b) {
1946 /* Returns true if any of the chars in a are in b. */
1947 for (p = a; *p; p++)
1954 char *format_timestamp(char *buf, size_t l, usec_t t) {
1964 sec = (time_t) (t / USEC_PER_SEC);
1966 if (strftime(buf, l, "%a, %Y-%m-%d %H:%M:%S %Z", localtime_r(&sec, &tm)) <= 0)
1972 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1975 n = now(CLOCK_REALTIME);
1977 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1982 if (d >= USEC_PER_YEAR)
1983 snprintf(buf, l, "%llu years and %llu months ago",
1984 (unsigned long long) (d / USEC_PER_YEAR),
1985 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1986 else if (d >= USEC_PER_MONTH)
1987 snprintf(buf, l, "%llu months and %llu days ago",
1988 (unsigned long long) (d / USEC_PER_MONTH),
1989 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1990 else if (d >= USEC_PER_WEEK)
1991 snprintf(buf, l, "%llu weeks and %llu days ago",
1992 (unsigned long long) (d / USEC_PER_WEEK),
1993 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1994 else if (d >= 2*USEC_PER_DAY)
1995 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1996 else if (d >= 25*USEC_PER_HOUR)
1997 snprintf(buf, l, "1 day and %lluh ago",
1998 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1999 else if (d >= 6*USEC_PER_HOUR)
2000 snprintf(buf, l, "%lluh ago",
2001 (unsigned long long) (d / USEC_PER_HOUR));
2002 else if (d >= USEC_PER_HOUR)
2003 snprintf(buf, l, "%lluh %llumin ago",
2004 (unsigned long long) (d / USEC_PER_HOUR),
2005 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2006 else if (d >= 5*USEC_PER_MINUTE)
2007 snprintf(buf, l, "%llumin ago",
2008 (unsigned long long) (d / USEC_PER_MINUTE));
2009 else if (d >= USEC_PER_MINUTE)
2010 snprintf(buf, l, "%llumin %llus ago",
2011 (unsigned long long) (d / USEC_PER_MINUTE),
2012 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2013 else if (d >= USEC_PER_SEC)
2014 snprintf(buf, l, "%llus ago",
2015 (unsigned long long) (d / USEC_PER_SEC));
2016 else if (d >= USEC_PER_MSEC)
2017 snprintf(buf, l, "%llums ago",
2018 (unsigned long long) (d / USEC_PER_MSEC));
2020 snprintf(buf, l, "%lluus ago",
2021 (unsigned long long) d);
2023 snprintf(buf, l, "now");
2029 char *format_timespan(char *buf, size_t l, usec_t t) {
2030 static const struct {
2034 { "w", USEC_PER_WEEK },
2035 { "d", USEC_PER_DAY },
2036 { "h", USEC_PER_HOUR },
2037 { "min", USEC_PER_MINUTE },
2038 { "s", USEC_PER_SEC },
2039 { "ms", USEC_PER_MSEC },
2049 if (t == (usec_t) -1)
2053 snprintf(p, l, "0");
2058 /* The result of this function can be parsed with parse_usec */
2060 for (i = 0; i < ELEMENTSOF(table); i++) {
2064 if (t < table[i].usec)
2070 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2071 n = MIN((size_t) k, l);
2084 bool fstype_is_network(const char *fstype) {
2085 static const char table[] =
2094 return nulstr_contains(table, fstype);
2098 _cleanup_close_ int fd;
2100 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
2106 TIOCL_GETKMSGREDIRECT,
2110 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2113 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2116 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2122 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2123 struct termios old_termios, new_termios;
2125 char line[LINE_MAX];
2130 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2131 new_termios = old_termios;
2133 new_termios.c_lflag &= ~ICANON;
2134 new_termios.c_cc[VMIN] = 1;
2135 new_termios.c_cc[VTIME] = 0;
2137 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2140 if (t != (usec_t) -1) {
2141 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2142 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2147 k = fread(&c, 1, 1, f);
2149 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2155 *need_nl = c != '\n';
2162 if (t != (usec_t) -1)
2163 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2166 if (!fgets(line, sizeof(line), f))
2171 if (strlen(line) != 1)
2181 int ask(char *ret, const char *replies, const char *text, ...) {
2191 bool need_nl = true;
2194 fputs(ANSI_HIGHLIGHT_ON, stdout);
2201 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2205 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2208 if (r == -EBADMSG) {
2209 puts("Bad input, please try again.");
2220 if (strchr(replies, c)) {
2225 puts("Read unexpected character, please try again.");
2229 int reset_terminal_fd(int fd, bool switch_to_text) {
2230 struct termios termios;
2233 /* Set terminal to some sane defaults */
2237 /* We leave locked terminal attributes untouched, so that
2238 * Plymouth may set whatever it wants to set, and we don't
2239 * interfere with that. */
2241 /* Disable exclusive mode, just in case */
2242 ioctl(fd, TIOCNXCL);
2244 /* Switch to text mode */
2246 ioctl(fd, KDSETMODE, KD_TEXT);
2248 /* Enable console unicode mode */
2249 ioctl(fd, KDSKBMODE, K_UNICODE);
2251 if (tcgetattr(fd, &termios) < 0) {
2256 /* We only reset the stuff that matters to the software. How
2257 * hardware is set up we don't touch assuming that somebody
2258 * else will do that for us */
2260 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2261 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2262 termios.c_oflag |= ONLCR;
2263 termios.c_cflag |= CREAD;
2264 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2266 termios.c_cc[VINTR] = 03; /* ^C */
2267 termios.c_cc[VQUIT] = 034; /* ^\ */
2268 termios.c_cc[VERASE] = 0177;
2269 termios.c_cc[VKILL] = 025; /* ^X */
2270 termios.c_cc[VEOF] = 04; /* ^D */
2271 termios.c_cc[VSTART] = 021; /* ^Q */
2272 termios.c_cc[VSTOP] = 023; /* ^S */
2273 termios.c_cc[VSUSP] = 032; /* ^Z */
2274 termios.c_cc[VLNEXT] = 026; /* ^V */
2275 termios.c_cc[VWERASE] = 027; /* ^W */
2276 termios.c_cc[VREPRINT] = 022; /* ^R */
2277 termios.c_cc[VEOL] = 0;
2278 termios.c_cc[VEOL2] = 0;
2280 termios.c_cc[VTIME] = 0;
2281 termios.c_cc[VMIN] = 1;
2283 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2287 /* Just in case, flush all crap out */
2288 tcflush(fd, TCIOFLUSH);
2293 int reset_terminal(const char *name) {
2296 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2300 r = reset_terminal_fd(fd, true);
2301 close_nointr_nofail(fd);
2306 int open_terminal(const char *name, int mode) {
2311 * If a TTY is in the process of being closed opening it might
2312 * cause EIO. This is horribly awful, but unlikely to be
2313 * changed in the kernel. Hence we work around this problem by
2314 * retrying a couple of times.
2316 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2320 fd = open(name, mode);
2327 /* Max 1s in total */
2331 usleep(50 * USEC_PER_MSEC);
2340 close_nointr_nofail(fd);
2345 close_nointr_nofail(fd);
2352 int flush_fd(int fd) {
2353 struct pollfd pollfd;
2357 pollfd.events = POLLIN;
2364 if ((r = poll(&pollfd, 1, 0)) < 0) {
2375 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2380 if (errno == EAGAIN)
2391 int acquire_terminal(
2395 bool ignore_tiocstty_eperm,
2398 int fd = -1, notify = -1, r = 0, wd = -1;
2400 struct sigaction sa_old, sa_new;
2404 /* We use inotify to be notified when the tty is closed. We
2405 * create the watch before checking if we can actually acquire
2406 * it, so that we don't lose any event.
2408 * Note: strictly speaking this actually watches for the
2409 * device being closed, it does *not* really watch whether a
2410 * tty loses its controlling process. However, unless some
2411 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2412 * its tty otherwise this will not become a problem. As long
2413 * as the administrator makes sure not configure any service
2414 * on the same tty as an untrusted user this should not be a
2415 * problem. (Which he probably should not do anyway.) */
2417 if (timeout != (usec_t) -1)
2418 ts = now(CLOCK_MONOTONIC);
2420 if (!fail && !force) {
2421 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2427 wd = inotify_add_watch(notify, name, IN_CLOSE);
2436 r = flush_fd(notify);
2441 /* We pass here O_NOCTTY only so that we can check the return
2442 * value TIOCSCTTY and have a reliable way to figure out if we
2443 * successfully became the controlling process of the tty */
2444 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2448 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2449 * if we already own the tty. */
2451 sa_new.sa_handler = SIG_IGN;
2452 sa_new.sa_flags = SA_RESTART;
2453 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2455 /* First, try to get the tty */
2456 if (ioctl(fd, TIOCSCTTY, force) < 0)
2459 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2461 /* Sometimes it makes sense to ignore TIOCSCTTY
2462 * returning EPERM, i.e. when very likely we already
2463 * are have this controlling terminal. */
2464 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2467 if (r < 0 && (force || fail || r != -EPERM)) {
2476 assert(notify >= 0);
2479 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2481 struct inotify_event *e;
2483 if (timeout != (usec_t) -1) {
2486 n = now(CLOCK_MONOTONIC);
2487 if (ts + timeout < n) {
2492 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2502 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2505 if (errno == EINTR || errno == EAGAIN)
2512 e = (struct inotify_event*) inotify_buffer;
2517 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2522 step = sizeof(struct inotify_event) + e->len;
2523 assert(step <= (size_t) l);
2525 e = (struct inotify_event*) ((uint8_t*) e + step);
2532 /* We close the tty fd here since if the old session
2533 * ended our handle will be dead. It's important that
2534 * we do this after sleeping, so that we don't enter
2535 * an endless loop. */
2536 close_nointr_nofail(fd);
2540 close_nointr_nofail(notify);
2542 r = reset_terminal_fd(fd, true);
2544 log_warning("Failed to reset terminal: %s", strerror(-r));
2550 close_nointr_nofail(fd);
2553 close_nointr_nofail(notify);
2558 int release_terminal(void) {
2560 struct sigaction sa_old, sa_new;
2562 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2565 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2566 * by our own TIOCNOTTY */
2569 sa_new.sa_handler = SIG_IGN;
2570 sa_new.sa_flags = SA_RESTART;
2571 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2573 if (ioctl(fd, TIOCNOTTY) < 0)
2576 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2578 close_nointr_nofail(fd);
2582 int sigaction_many(const struct sigaction *sa, ...) {
2587 while ((sig = va_arg(ap, int)) > 0)
2588 if (sigaction(sig, sa, NULL) < 0)
2595 int ignore_signals(int sig, ...) {
2596 struct sigaction sa;
2601 sa.sa_handler = SIG_IGN;
2602 sa.sa_flags = SA_RESTART;
2604 if (sigaction(sig, &sa, NULL) < 0)
2608 while ((sig = va_arg(ap, int)) > 0)
2609 if (sigaction(sig, &sa, NULL) < 0)
2616 int default_signals(int sig, ...) {
2617 struct sigaction sa;
2622 sa.sa_handler = SIG_DFL;
2623 sa.sa_flags = SA_RESTART;
2625 if (sigaction(sig, &sa, NULL) < 0)
2629 while ((sig = va_arg(ap, int)) > 0)
2630 if (sigaction(sig, &sa, NULL) < 0)
2637 int close_pipe(int p[]) {
2643 a = close_nointr(p[0]);
2648 b = close_nointr(p[1]);
2652 return a < 0 ? a : b;
2655 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2664 while (nbytes > 0) {
2667 if ((k = read(fd, p, nbytes)) <= 0) {
2669 if (k < 0 && errno == EINTR)
2672 if (k < 0 && errno == EAGAIN && do_poll) {
2673 struct pollfd pollfd;
2677 pollfd.events = POLLIN;
2679 if (poll(&pollfd, 1, -1) < 0) {
2683 return n > 0 ? n : -errno;
2686 if (pollfd.revents != POLLIN)
2687 return n > 0 ? n : -EIO;
2692 return n > 0 ? n : (k < 0 ? -errno : 0);
2703 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2712 while (nbytes > 0) {
2715 k = write(fd, p, nbytes);
2718 if (k < 0 && errno == EINTR)
2721 if (k < 0 && errno == EAGAIN && do_poll) {
2722 struct pollfd pollfd;
2726 pollfd.events = POLLOUT;
2728 if (poll(&pollfd, 1, -1) < 0) {
2732 return n > 0 ? n : -errno;
2735 if (pollfd.revents != POLLOUT)
2736 return n > 0 ? n : -EIO;
2741 return n > 0 ? n : (k < 0 ? -errno : 0);
2752 int parse_usec(const char *t, usec_t *usec) {
2753 static const struct {
2757 { "seconds", USEC_PER_SEC },
2758 { "second", USEC_PER_SEC },
2759 { "sec", USEC_PER_SEC },
2760 { "s", USEC_PER_SEC },
2761 { "minutes", USEC_PER_MINUTE },
2762 { "minute", USEC_PER_MINUTE },
2763 { "min", USEC_PER_MINUTE },
2764 { "months", USEC_PER_MONTH },
2765 { "month", USEC_PER_MONTH },
2766 { "msec", USEC_PER_MSEC },
2767 { "ms", USEC_PER_MSEC },
2768 { "m", USEC_PER_MINUTE },
2769 { "hours", USEC_PER_HOUR },
2770 { "hour", USEC_PER_HOUR },
2771 { "hr", USEC_PER_HOUR },
2772 { "h", USEC_PER_HOUR },
2773 { "days", USEC_PER_DAY },
2774 { "day", USEC_PER_DAY },
2775 { "d", USEC_PER_DAY },
2776 { "weeks", USEC_PER_WEEK },
2777 { "week", USEC_PER_WEEK },
2778 { "w", USEC_PER_WEEK },
2779 { "years", USEC_PER_YEAR },
2780 { "year", USEC_PER_YEAR },
2781 { "y", USEC_PER_YEAR },
2784 { "", USEC_PER_SEC }, /* default is sec */
2800 l = strtoll(p, &e, 10);
2811 e += strspn(e, WHITESPACE);
2813 for (i = 0; i < ELEMENTSOF(table); i++)
2814 if (startswith(e, table[i].suffix)) {
2815 r += (usec_t) l * table[i].usec;
2816 p = e + strlen(table[i].suffix);
2820 if (i >= ELEMENTSOF(table))
2830 int parse_nsec(const char *t, nsec_t *nsec) {
2831 static const struct {
2835 { "seconds", NSEC_PER_SEC },
2836 { "second", NSEC_PER_SEC },
2837 { "sec", NSEC_PER_SEC },
2838 { "s", NSEC_PER_SEC },
2839 { "minutes", NSEC_PER_MINUTE },
2840 { "minute", NSEC_PER_MINUTE },
2841 { "min", NSEC_PER_MINUTE },
2842 { "months", NSEC_PER_MONTH },
2843 { "month", NSEC_PER_MONTH },
2844 { "msec", NSEC_PER_MSEC },
2845 { "ms", NSEC_PER_MSEC },
2846 { "m", NSEC_PER_MINUTE },
2847 { "hours", NSEC_PER_HOUR },
2848 { "hour", NSEC_PER_HOUR },
2849 { "hr", NSEC_PER_HOUR },
2850 { "h", NSEC_PER_HOUR },
2851 { "days", NSEC_PER_DAY },
2852 { "day", NSEC_PER_DAY },
2853 { "d", NSEC_PER_DAY },
2854 { "weeks", NSEC_PER_WEEK },
2855 { "week", NSEC_PER_WEEK },
2856 { "w", NSEC_PER_WEEK },
2857 { "years", NSEC_PER_YEAR },
2858 { "year", NSEC_PER_YEAR },
2859 { "y", NSEC_PER_YEAR },
2860 { "usec", NSEC_PER_USEC },
2861 { "us", NSEC_PER_USEC },
2864 { "", 1ULL }, /* default is nsec */
2880 l = strtoll(p, &e, 10);
2891 e += strspn(e, WHITESPACE);
2893 for (i = 0; i < ELEMENTSOF(table); i++)
2894 if (startswith(e, table[i].suffix)) {
2895 r += (nsec_t) l * table[i].nsec;
2896 p = e + strlen(table[i].suffix);
2900 if (i >= ELEMENTSOF(table))
2910 int parse_bytes(const char *t, off_t *bytes) {
2911 static const struct {
2917 { "M", 1024ULL*1024ULL },
2918 { "G", 1024ULL*1024ULL*1024ULL },
2919 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2920 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2921 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2938 l = strtoll(p, &e, 10);
2949 e += strspn(e, WHITESPACE);
2951 for (i = 0; i < ELEMENTSOF(table); i++)
2952 if (startswith(e, table[i].suffix)) {
2953 r += (off_t) l * table[i].factor;
2954 p = e + strlen(table[i].suffix);
2958 if (i >= ELEMENTSOF(table))
2968 int make_stdio(int fd) {
2973 r = dup3(fd, STDIN_FILENO, 0);
2974 s = dup3(fd, STDOUT_FILENO, 0);
2975 t = dup3(fd, STDERR_FILENO, 0);
2978 close_nointr_nofail(fd);
2980 if (r < 0 || s < 0 || t < 0)
2983 /* We rely here that the new fd has O_CLOEXEC not set */
2988 int make_null_stdio(void) {
2991 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2995 return make_stdio(null_fd);
2998 bool is_device_path(const char *path) {
3000 /* Returns true on paths that refer to a device, either in
3001 * sysfs or in /dev */
3004 path_startswith(path, "/dev/") ||
3005 path_startswith(path, "/sys/");
3008 int dir_is_empty(const char *path) {
3009 _cleanup_closedir_ DIR *d;
3018 union dirent_storage buf;
3020 r = readdir_r(d, &buf.de, &de);
3027 if (!ignore_file(de->d_name))
3032 unsigned long long random_ull(void) {
3033 _cleanup_close_ int fd;
3037 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3041 r = loop_read(fd, &ull, sizeof(ull), true);
3042 if (r != sizeof(ull))
3048 return random() * RAND_MAX + random();
3051 void rename_process(const char name[8]) {
3054 /* This is a like a poor man's setproctitle(). It changes the
3055 * comm field, argv[0], and also the glibc's internally used
3056 * name of the process. For the first one a limit of 16 chars
3057 * applies, to the second one usually one of 10 (i.e. length
3058 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3059 * "systemd"). If you pass a longer string it will be
3062 prctl(PR_SET_NAME, name);
3064 if (program_invocation_name)
3065 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3067 if (saved_argc > 0) {
3071 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3073 for (i = 1; i < saved_argc; i++) {
3077 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3082 void sigset_add_many(sigset_t *ss, ...) {
3089 while ((sig = va_arg(ap, int)) > 0)
3090 assert_se(sigaddset(ss, sig) == 0);
3094 char* gethostname_malloc(void) {
3097 assert_se(uname(&u) >= 0);
3099 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3100 return strdup(u.nodename);
3102 return strdup(u.sysname);
3105 bool hostname_is_set(void) {
3108 assert_se(uname(&u) >= 0);
3110 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3113 static char *lookup_uid(uid_t uid) {
3116 _cleanup_free_ char *buf = NULL;
3117 struct passwd pwbuf, *pw = NULL;
3119 /* Shortcut things to avoid NSS lookups */
3121 return strdup("root");
3123 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3127 buf = malloc(bufsize);
3131 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
3132 return strdup(pw->pw_name);
3134 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3140 char* getlogname_malloc(void) {
3144 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3149 return lookup_uid(uid);
3152 char *getusername_malloc(void) {
3159 return lookup_uid(getuid());
3162 int getttyname_malloc(int fd, char **r) {
3163 char path[PATH_MAX], *c;
3168 k = ttyname_r(fd, path, sizeof(path));
3174 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
3182 int getttyname_harder(int fd, char **r) {
3186 k = getttyname_malloc(fd, &s);
3190 if (streq(s, "tty")) {
3192 return get_ctty(0, NULL, r);
3199 int get_ctty_devnr(pid_t pid, dev_t *d) {
3201 char line[LINE_MAX], *p, *fn;
3202 unsigned long ttynr;
3205 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3208 f = fopen(fn, "re");
3213 if (!fgets(line, sizeof(line), f)) {
3214 k = feof(f) ? -EIO : -errno;
3221 p = strrchr(line, ')');
3231 "%*d " /* session */
3240 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3242 char fn[PATH_MAX], *s, *b, *p;
3247 k = get_ctty_devnr(pid, &devnr);
3251 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3254 if ((k = readlink_malloc(fn, &s)) < 0) {
3259 /* This is an ugly hack */
3260 if (major(devnr) == 136) {
3261 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3271 /* Probably something like the ptys which have no
3272 * symlink in /dev/char. Let's return something
3273 * vaguely useful. */
3275 if (!(b = strdup(fn + 5)))
3285 if (startswith(s, "/dev/"))
3287 else if (startswith(s, "../"))
3305 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3311 /* This returns the first error we run into, but nevertheless
3312 * tries to go on. This closes the passed fd. */
3316 close_nointr_nofail(fd);
3318 return errno == ENOENT ? 0 : -errno;
3323 union dirent_storage buf;
3324 bool is_dir, keep_around;
3328 r = readdir_r(d, &buf.de, &de);
3329 if (r != 0 && ret == 0) {
3337 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3340 if (de->d_type == DT_UNKNOWN ||
3342 (de->d_type == DT_DIR && root_dev)) {
3343 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3344 if (ret == 0 && errno != ENOENT)
3349 is_dir = S_ISDIR(st.st_mode);
3352 (st.st_uid == 0 || st.st_uid == getuid()) &&
3353 (st.st_mode & S_ISVTX);
3355 is_dir = de->d_type == DT_DIR;
3356 keep_around = false;
3362 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3363 if (root_dev && st.st_dev != root_dev->st_dev)
3366 subdir_fd = openat(fd, de->d_name,
3367 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3368 if (subdir_fd < 0) {
3369 if (ret == 0 && errno != ENOENT)
3374 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3375 if (r < 0 && ret == 0)
3379 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3380 if (ret == 0 && errno != ENOENT)
3384 } else if (!only_dirs && !keep_around) {
3386 if (unlinkat(fd, de->d_name, 0) < 0) {
3387 if (ret == 0 && errno != ENOENT)
3398 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3403 if (fstatfs(fd, &s) < 0) {
3404 close_nointr_nofail(fd);
3408 /* We refuse to clean disk file systems with this call. This
3409 * is extra paranoia just to be sure we never ever remove
3412 if (s.f_type != TMPFS_MAGIC &&
3413 s.f_type != RAMFS_MAGIC) {
3414 log_error("Attempted to remove disk file system, and we can't allow that.");
3415 close_nointr_nofail(fd);
3419 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3422 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3428 /* We refuse to clean the root file system with this
3429 * call. This is extra paranoia to never cause a really
3430 * seriously broken system. */
3431 if (path_equal(path, "/")) {
3432 log_error("Attempted to remove entire root file system, and we can't allow that.");
3436 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3439 if (errno != ENOTDIR)
3443 if (statfs(path, &s) < 0)
3446 if (s.f_type != TMPFS_MAGIC &&
3447 s.f_type != RAMFS_MAGIC) {
3448 log_error("Attempted to remove disk file system, and we can't allow that.");
3453 if (delete_root && !only_dirs)
3454 if (unlink(path) < 0 && errno != ENOENT)
3461 if (fstatfs(fd, &s) < 0) {
3462 close_nointr_nofail(fd);
3466 if (s.f_type != TMPFS_MAGIC &&
3467 s.f_type != RAMFS_MAGIC) {
3468 log_error("Attempted to remove disk file system, and we can't allow that.");
3469 close_nointr_nofail(fd);
3474 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3477 if (honour_sticky && file_is_priv_sticky(path) > 0)
3480 if (rmdir(path) < 0 && errno != ENOENT) {
3489 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3490 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3493 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3494 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3497 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3500 /* Under the assumption that we are running privileged we
3501 * first change the access mode and only then hand out
3502 * ownership to avoid a window where access is too open. */
3504 if (mode != (mode_t) -1)
3505 if (chmod(path, mode) < 0)
3508 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3509 if (chown(path, uid, gid) < 0)
3515 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3518 /* Under the assumption that we are running privileged we
3519 * first change the access mode and only then hand out
3520 * ownership to avoid a window where access is too open. */
3522 if (fchmod(fd, mode) < 0)
3525 if (fchown(fd, uid, gid) < 0)
3531 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3535 /* Allocates the cpuset in the right size */
3538 if (!(r = CPU_ALLOC(n)))
3541 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3542 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3552 if (errno != EINVAL)
3559 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3560 static const char status_indent[] = " "; /* "[" STATUS "] " */
3561 _cleanup_free_ char *s = NULL;
3562 _cleanup_close_ int fd = -1;
3563 struct iovec iovec[5];
3568 /* This is independent of logging, as status messages are
3569 * optional and go exclusively to the console. */
3571 if (vasprintf(&s, format, ap) < 0)
3574 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3587 sl = status ? sizeof(status_indent)-1 : 0;
3593 e = ellipsize(s, emax, 75);
3603 if (!isempty(status)) {
3604 IOVEC_SET_STRING(iovec[n++], "[");
3605 IOVEC_SET_STRING(iovec[n++], status);
3606 IOVEC_SET_STRING(iovec[n++], "] ");
3608 IOVEC_SET_STRING(iovec[n++], status_indent);
3611 IOVEC_SET_STRING(iovec[n++], s);
3612 IOVEC_SET_STRING(iovec[n++], "\n");
3614 if (writev(fd, iovec, n) < 0)
3620 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3626 va_start(ap, format);
3627 r = status_vprintf(status, ellipse, format, ap);
3633 int status_welcome(void) {
3635 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3637 r = parse_env_file("/etc/os-release", NEWLINE,
3638 "PRETTY_NAME", &pretty_name,
3639 "ANSI_COLOR", &ansi_color,
3641 if (r < 0 && r != -ENOENT)
3642 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3644 return status_printf(NULL, false,
3645 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3646 isempty(ansi_color) ? "1" : ansi_color,
3647 isempty(pretty_name) ? "Linux" : pretty_name);
3650 char *replace_env(const char *format, char **env) {
3657 const char *e, *word = format;
3662 for (e = format; *e; e ++) {
3673 if (!(k = strnappend(r, word, e-word-1)))
3682 } else if (*e == '$') {
3683 if (!(k = strnappend(r, word, e-word)))
3699 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3702 if (!(k = strappend(r, t)))
3715 if (!(k = strnappend(r, word, e-word)))
3726 char **replace_env_argv(char **argv, char **env) {
3728 unsigned k = 0, l = 0;
3730 l = strv_length(argv);
3732 if (!(r = new(char*, l+1)))
3735 STRV_FOREACH(i, argv) {
3737 /* If $FOO appears as single word, replace it by the split up variable */
3738 if ((*i)[0] == '$' && (*i)[1] != '{') {
3743 if ((e = strv_env_get(env, *i+1))) {
3745 if (!(m = strv_split_quoted(e))) {
3756 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3765 memcpy(r + k, m, q * sizeof(char*));
3773 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3774 if (!(r[k++] = replace_env(*i, env))) {
3784 int fd_columns(int fd) {
3788 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3797 unsigned columns(void) {
3801 if (_likely_(cached_columns > 0))
3802 return cached_columns;
3805 e = getenv("COLUMNS");
3810 c = fd_columns(STDOUT_FILENO);
3819 int fd_lines(int fd) {
3823 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3832 unsigned lines(void) {
3836 if (_likely_(cached_lines > 0))
3837 return cached_lines;
3840 e = getenv("LINES");
3845 l = fd_lines(STDOUT_FILENO);
3851 return cached_lines;
3854 /* intended to be used as a SIGWINCH sighandler */
3855 void columns_lines_cache_reset(int signum) {
3861 static int cached_on_tty = -1;
3863 if (_unlikely_(cached_on_tty < 0))
3864 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3866 return cached_on_tty;
3869 int running_in_chroot(void) {
3875 /* Only works as root */
3877 if (stat("/proc/1/root", &a) < 0)
3880 if (stat("/", &b) < 0)
3884 a.st_dev != b.st_dev ||
3885 a.st_ino != b.st_ino;
3888 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3893 assert(percent <= 100);
3894 assert(new_length >= 3);
3896 if (old_length <= 3 || old_length <= new_length)
3897 return strndup(s, old_length);
3899 r = new0(char, new_length+1);
3903 x = (new_length * percent) / 100;
3905 if (x > new_length - 3)
3913 s + old_length - (new_length - x - 3),
3914 new_length - x - 3);
3919 char *ellipsize(const char *s, size_t length, unsigned percent) {
3920 return ellipsize_mem(s, strlen(s), length, percent);
3923 int touch(const char *path) {
3928 /* This just opens the file for writing, ensuring it
3929 * exists. It doesn't call utimensat() the way /usr/bin/touch
3932 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3936 close_nointr_nofail(fd);
3940 char *unquote(const char *s, const char* quotes) {
3944 /* This is rather stupid, simply removes the heading and
3945 * trailing quotes if there is one. Doesn't care about
3946 * escaping or anything. We should make this smarter one
3953 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3954 return strndup(s+1, l-2);
3959 char *normalize_env_assignment(const char *s) {
3960 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3963 eq = strchr(s, '=');
3975 memmove(r, t, strlen(t) + 1);
3979 name = strndup(s, eq - s);
3987 value = unquote(strstrip(p), QUOTES);
3991 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3997 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4008 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4020 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4027 r = wait_for_terminate(pid, &status);
4029 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4033 if (status.si_code == CLD_EXITED) {
4034 if (status.si_status != 0) {
4035 log_warning("%s failed with error code %i.", name, status.si_status);
4036 return status.si_status;
4039 log_debug("%s succeeded.", name);
4042 } else if (status.si_code == CLD_KILLED ||
4043 status.si_code == CLD_DUMPED) {
4045 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4049 log_warning("%s failed due to unknown reason.", name);
4053 _noreturn_ void freeze(void) {
4055 /* Make sure nobody waits for us on a socket anymore */
4056 close_all_fds(NULL, 0);
4064 bool null_or_empty(struct stat *st) {
4067 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4070 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4076 int null_or_empty_path(const char *fn) {
4081 if (stat(fn, &st) < 0)
4084 return null_or_empty(&st);
4087 DIR *xopendirat(int fd, const char *name, int flags) {
4091 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
4097 close_nointr_nofail(nfd);
4104 int signal_from_string_try_harder(const char *s) {
4108 signo = signal_from_string(s);
4110 if (startswith(s, "SIG"))
4111 return signal_from_string(s+3);
4116 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4122 if (!dual_timestamp_is_set(t))
4125 fprintf(f, "%s=%llu %llu\n",
4127 (unsigned long long) t->realtime,
4128 (unsigned long long) t->monotonic);
4131 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4132 unsigned long long a, b;
4137 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4138 log_debug("Failed to parse finish timestamp value %s", value);
4145 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
4149 /* FIXME: to follow udev's logic 100% we need to leave valid
4150 * UTF8 chars unescaped */
4152 u = unquote(tagvalue, "\"\'");
4156 t = xescape(u, "/ ");
4162 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
4171 char *fstab_node_to_udev_node(const char *p) {
4174 if (startswith(p, "LABEL="))
4175 return tag_to_udev_node(p+6, "label");
4177 if (startswith(p, "UUID="))
4178 return tag_to_udev_node(p+5, "uuid");
4180 if (startswith(p, "PARTUUID="))
4181 return tag_to_udev_node(p+9, "partuuid");
4183 if (startswith(p, "PARTLABEL="))
4184 return tag_to_udev_node(p+10, "partlabel");
4189 bool tty_is_vc(const char *tty) {
4192 if (startswith(tty, "/dev/"))
4195 return vtnr_from_tty(tty) >= 0;
4198 bool tty_is_console(const char *tty) {
4201 if (startswith(tty, "/dev/"))
4204 return streq(tty, "console");
4207 int vtnr_from_tty(const char *tty) {
4212 if (startswith(tty, "/dev/"))
4215 if (!startswith(tty, "tty") )
4218 if (tty[3] < '0' || tty[3] > '9')
4221 r = safe_atoi(tty+3, &i);
4225 if (i < 0 || i > 63)
4231 bool tty_is_vc_resolve(const char *tty) {
4232 char *active = NULL;
4237 if (startswith(tty, "/dev/"))
4240 /* Resolve where /dev/console is pointing to, if /sys is
4241 * actually ours (i.e. not read-only-mounted which is a sign
4242 * for container setups) */
4243 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4244 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4245 /* If multiple log outputs are configured the
4246 * last one is what /dev/console points to */
4247 tty = strrchr(active, ' ');
4260 const char *default_term_for_tty(const char *tty) {
4263 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4266 bool dirent_is_file(const struct dirent *de) {
4269 if (ignore_file(de->d_name))
4272 if (de->d_type != DT_REG &&
4273 de->d_type != DT_LNK &&
4274 de->d_type != DT_UNKNOWN)
4280 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4283 if (de->d_type != DT_REG &&
4284 de->d_type != DT_LNK &&
4285 de->d_type != DT_UNKNOWN)
4288 if (ignore_file_allow_backup(de->d_name))
4291 return endswith(de->d_name, suffix);
4294 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4297 Hashmap *pids = NULL;
4301 /* Executes all binaries in a directory in parallel and waits
4302 * until all they all finished. */
4305 if (!(_d = opendir(directory))) {
4307 if (errno == ENOENT)
4310 log_error("Failed to enumerate directory %s: %m", directory);
4317 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4318 log_error("Failed to allocate set.");
4322 while ((de = readdir(d))) {
4327 if (!dirent_is_file(de))
4330 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4335 if ((pid = fork()) < 0) {
4336 log_error("Failed to fork: %m");
4354 log_error("Failed to execute %s: %m", path);
4355 _exit(EXIT_FAILURE);
4358 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4360 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4361 log_error("Failed to add PID to set: %s", strerror(-k));
4366 while (!hashmap_isempty(pids)) {
4367 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4372 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4377 log_error("waitid() failed: %m");
4381 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4382 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
4383 if (si.si_code == CLD_EXITED)
4384 log_error("%s exited with exit status %i.", path, si.si_status);
4386 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4388 log_debug("%s exited successfully.", path);
4399 hashmap_free_free(pids);
4402 int kill_and_sigcont(pid_t pid, int sig) {
4405 r = kill(pid, sig) < 0 ? -errno : 0;
4413 bool nulstr_contains(const char*nulstr, const char *needle) {
4419 NULSTR_FOREACH(i, nulstr)
4420 if (streq(i, needle))
4426 bool plymouth_running(void) {
4427 return access("/run/plymouth/pid", F_OK) >= 0;
4430 char* strshorten(char *s, size_t l) {
4439 static bool hostname_valid_char(char c) {
4441 (c >= 'a' && c <= 'z') ||
4442 (c >= 'A' && c <= 'Z') ||
4443 (c >= '0' && c <= '9') ||
4449 bool hostname_is_valid(const char *s) {
4455 for (p = s; *p; p++)
4456 if (!hostname_valid_char(*p))
4459 if (p-s > HOST_NAME_MAX)
4465 char* hostname_cleanup(char *s) {
4468 for (p = s, d = s; *p; p++)
4469 if ((*p >= 'a' && *p <= 'z') ||
4470 (*p >= 'A' && *p <= 'Z') ||
4471 (*p >= '0' && *p <= '9') ||
4479 strshorten(s, HOST_NAME_MAX);
4483 int pipe_eof(int fd) {
4484 struct pollfd pollfd;
4489 pollfd.events = POLLIN|POLLHUP;
4491 r = poll(&pollfd, 1, 0);
4498 return pollfd.revents & POLLHUP;
4501 int fd_wait_for_event(int fd, int event, usec_t t) {
4502 struct pollfd pollfd;
4507 pollfd.events = event;
4509 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4516 return pollfd.revents;
4519 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4530 t = new(char, strlen(path) + 1 + 6 + 1);
4534 fn = path_get_file_name(path);
4538 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4540 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4546 f = fdopen(fd, "we");
4559 int terminal_vhangup_fd(int fd) {
4562 if (ioctl(fd, TIOCVHANGUP) < 0)
4568 int terminal_vhangup(const char *name) {
4571 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4575 r = terminal_vhangup_fd(fd);
4576 close_nointr_nofail(fd);
4581 int vt_disallocate(const char *name) {
4585 /* Deallocate the VT if possible. If not possible
4586 * (i.e. because it is the active one), at least clear it
4587 * entirely (including the scrollback buffer) */
4589 if (!startswith(name, "/dev/"))
4592 if (!tty_is_vc(name)) {
4593 /* So this is not a VT. I guess we cannot deallocate
4594 * it then. But let's at least clear the screen */
4596 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4601 "\033[r" /* clear scrolling region */
4602 "\033[H" /* move home */
4603 "\033[2J", /* clear screen */
4605 close_nointr_nofail(fd);
4610 if (!startswith(name, "/dev/tty"))
4613 r = safe_atou(name+8, &u);
4620 /* Try to deallocate */
4621 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4625 r = ioctl(fd, VT_DISALLOCATE, u);
4626 close_nointr_nofail(fd);
4634 /* Couldn't deallocate, so let's clear it fully with
4636 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4641 "\033[r" /* clear scrolling region */
4642 "\033[H" /* move home */
4643 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4645 close_nointr_nofail(fd);
4650 int copy_file(const char *from, const char *to) {
4656 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4660 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4662 close_nointr_nofail(fdf);
4670 n = read(fdf, buf, sizeof(buf));
4674 close_nointr_nofail(fdf);
4685 k = loop_write(fdt, buf, n, false);
4687 r = k < 0 ? k : (errno ? -errno : -EIO);
4689 close_nointr_nofail(fdf);
4697 close_nointr_nofail(fdf);
4698 r = close_nointr(fdt);
4708 int symlink_atomic(const char *from, const char *to) {
4710 _cleanup_free_ char *t;
4713 unsigned long long ull;
4720 t = new(char, strlen(to) + 1 + 16 + 1);
4724 fn = path_get_file_name(to);
4728 x = stpcpy(t+k+1, fn);
4731 for (i = 0; i < 16; i++) {
4732 *(x++) = hexchar(ull & 0xF);
4738 if (symlink(from, t) < 0)
4741 if (rename(t, to) < 0) {
4750 bool display_is_local(const char *display) {
4754 display[0] == ':' &&
4755 display[1] >= '0' &&
4759 int socket_from_display(const char *display, char **path) {
4766 if (!display_is_local(display))
4769 k = strspn(display+1, "0123456789");
4771 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4775 c = stpcpy(f, "/tmp/.X11-unix/X");
4776 memcpy(c, display+1, k);
4785 const char **username,
4786 uid_t *uid, gid_t *gid,
4788 const char **shell) {
4796 /* We enforce some special rules for uid=0: in order to avoid
4797 * NSS lookups for root we hardcode its data. */
4799 if (streq(*username, "root") || streq(*username, "0")) {
4817 if (parse_uid(*username, &u) >= 0) {
4821 /* If there are multiple users with the same id, make
4822 * sure to leave $USER to the configured value instead
4823 * of the first occurrence in the database. However if
4824 * the uid was configured by a numeric uid, then let's
4825 * pick the real username from /etc/passwd. */
4827 *username = p->pw_name;
4830 p = getpwnam(*username);
4834 return errno != 0 ? -errno : -ESRCH;
4846 *shell = p->pw_shell;
4851 int get_group_creds(const char **groupname, gid_t *gid) {
4857 /* We enforce some special rules for gid=0: in order to avoid
4858 * NSS lookups for root we hardcode its data. */
4860 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4861 *groupname = "root";
4869 if (parse_gid(*groupname, &id) >= 0) {
4874 *groupname = g->gr_name;
4877 g = getgrnam(*groupname);
4881 return errno != 0 ? -errno : -ESRCH;
4889 int in_group(const char *name) {
4891 int ngroups_max, r, i;
4893 r = get_group_creds(&name, &gid);
4897 if (getgid() == gid)
4900 if (getegid() == gid)
4903 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4904 assert(ngroups_max > 0);
4906 gids = alloca(sizeof(gid_t) * ngroups_max);
4908 r = getgroups(ngroups_max, gids);
4912 for (i = 0; i < r; i++)
4919 int glob_exists(const char *path) {
4927 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4929 if (k == GLOB_NOMATCH)
4931 else if (k == GLOB_NOSPACE)
4934 r = !strv_isempty(g.gl_pathv);
4936 r = errno ? -errno : -EIO;
4943 int dirent_ensure_type(DIR *d, struct dirent *de) {
4949 if (de->d_type != DT_UNKNOWN)
4952 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4956 S_ISREG(st.st_mode) ? DT_REG :
4957 S_ISDIR(st.st_mode) ? DT_DIR :
4958 S_ISLNK(st.st_mode) ? DT_LNK :
4959 S_ISFIFO(st.st_mode) ? DT_FIFO :
4960 S_ISSOCK(st.st_mode) ? DT_SOCK :
4961 S_ISCHR(st.st_mode) ? DT_CHR :
4962 S_ISBLK(st.st_mode) ? DT_BLK :
4968 int in_search_path(const char *path, char **search) {
4972 r = path_get_parent(path, &parent);
4978 STRV_FOREACH(i, search) {
4979 if (path_equal(parent, *i)) {
4990 int get_files_in_directory(const char *path, char ***list) {
4998 /* Returns all files in a directory in *list, and the number
4999 * of files as return value. If list is NULL returns only the
5008 union dirent_storage buf;
5011 k = readdir_r(d, &buf.de, &de);
5020 dirent_ensure_type(d, de);
5022 if (!dirent_is_file(de))
5026 if ((unsigned) r >= n) {
5030 t = realloc(l, sizeof(char*) * n);
5039 assert((unsigned) r < n);
5041 l[r] = strdup(de->d_name);
5065 char *strjoin(const char *x, ...) {
5079 t = va_arg(ap, const char *);
5084 if (n > ((size_t) -1) - l) {
5108 t = va_arg(ap, const char *);
5122 bool is_main_thread(void) {
5123 static __thread int cached = 0;
5125 if (_unlikely_(cached == 0))
5126 cached = getpid() == gettid() ? 1 : -1;
5131 int block_get_whole_disk(dev_t d, dev_t *ret) {
5138 /* If it has a queue this is good enough for us */
5139 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5142 r = access(p, F_OK);
5150 /* If it is a partition find the originating device */
5151 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5154 r = access(p, F_OK);
5160 /* Get parent dev_t */
5161 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5164 r = read_one_line_file(p, &s);
5170 r = sscanf(s, "%u:%u", &m, &n);
5176 /* Only return this if it is really good enough for us. */
5177 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5180 r = access(p, F_OK);
5184 *ret = makedev(m, n);
5191 int file_is_priv_sticky(const char *p) {
5196 if (lstat(p, &st) < 0)
5200 (st.st_uid == 0 || st.st_uid == getuid()) &&
5201 (st.st_mode & S_ISVTX);
5204 static const char *const ioprio_class_table[] = {
5205 [IOPRIO_CLASS_NONE] = "none",
5206 [IOPRIO_CLASS_RT] = "realtime",
5207 [IOPRIO_CLASS_BE] = "best-effort",
5208 [IOPRIO_CLASS_IDLE] = "idle"
5211 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5213 static const char *const sigchld_code_table[] = {
5214 [CLD_EXITED] = "exited",
5215 [CLD_KILLED] = "killed",
5216 [CLD_DUMPED] = "dumped",
5217 [CLD_TRAPPED] = "trapped",
5218 [CLD_STOPPED] = "stopped",
5219 [CLD_CONTINUED] = "continued",
5222 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5224 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5225 [LOG_FAC(LOG_KERN)] = "kern",
5226 [LOG_FAC(LOG_USER)] = "user",
5227 [LOG_FAC(LOG_MAIL)] = "mail",
5228 [LOG_FAC(LOG_DAEMON)] = "daemon",
5229 [LOG_FAC(LOG_AUTH)] = "auth",
5230 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5231 [LOG_FAC(LOG_LPR)] = "lpr",
5232 [LOG_FAC(LOG_NEWS)] = "news",
5233 [LOG_FAC(LOG_UUCP)] = "uucp",
5234 [LOG_FAC(LOG_CRON)] = "cron",
5235 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5236 [LOG_FAC(LOG_FTP)] = "ftp",
5237 [LOG_FAC(LOG_LOCAL0)] = "local0",
5238 [LOG_FAC(LOG_LOCAL1)] = "local1",
5239 [LOG_FAC(LOG_LOCAL2)] = "local2",
5240 [LOG_FAC(LOG_LOCAL3)] = "local3",
5241 [LOG_FAC(LOG_LOCAL4)] = "local4",
5242 [LOG_FAC(LOG_LOCAL5)] = "local5",
5243 [LOG_FAC(LOG_LOCAL6)] = "local6",
5244 [LOG_FAC(LOG_LOCAL7)] = "local7"
5247 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5249 static const char *const log_level_table[] = {
5250 [LOG_EMERG] = "emerg",
5251 [LOG_ALERT] = "alert",
5252 [LOG_CRIT] = "crit",
5254 [LOG_WARNING] = "warning",
5255 [LOG_NOTICE] = "notice",
5256 [LOG_INFO] = "info",
5257 [LOG_DEBUG] = "debug"
5260 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5262 static const char* const sched_policy_table[] = {
5263 [SCHED_OTHER] = "other",
5264 [SCHED_BATCH] = "batch",
5265 [SCHED_IDLE] = "idle",
5266 [SCHED_FIFO] = "fifo",
5270 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5272 static const char* const rlimit_table[] = {
5273 [RLIMIT_CPU] = "LimitCPU",
5274 [RLIMIT_FSIZE] = "LimitFSIZE",
5275 [RLIMIT_DATA] = "LimitDATA",
5276 [RLIMIT_STACK] = "LimitSTACK",
5277 [RLIMIT_CORE] = "LimitCORE",
5278 [RLIMIT_RSS] = "LimitRSS",
5279 [RLIMIT_NOFILE] = "LimitNOFILE",
5280 [RLIMIT_AS] = "LimitAS",
5281 [RLIMIT_NPROC] = "LimitNPROC",
5282 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5283 [RLIMIT_LOCKS] = "LimitLOCKS",
5284 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5285 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5286 [RLIMIT_NICE] = "LimitNICE",
5287 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5288 [RLIMIT_RTTIME] = "LimitRTTIME"
5291 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5293 static const char* const ip_tos_table[] = {
5294 [IPTOS_LOWDELAY] = "low-delay",
5295 [IPTOS_THROUGHPUT] = "throughput",
5296 [IPTOS_RELIABILITY] = "reliability",
5297 [IPTOS_LOWCOST] = "low-cost",
5300 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5302 static const char *const __signal_table[] = {
5319 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5330 [SIGVTALRM] = "VTALRM",
5332 [SIGWINCH] = "WINCH",
5338 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5340 const char *signal_to_string(int signo) {
5341 static __thread char buf[12];
5344 name = __signal_to_string(signo);
5348 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5349 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5351 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5356 int signal_from_string(const char *s) {
5361 signo = __signal_from_string(s);
5365 if (startswith(s, "RTMIN+")) {
5369 if (safe_atou(s, &u) >= 0) {
5370 signo = (int) u + offset;
5371 if (signo > 0 && signo < _NSIG)
5377 bool kexec_loaded(void) {
5378 bool loaded = false;
5381 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5389 int strdup_or_null(const char *a, char **b) {
5407 int prot_from_flags(int flags) {
5409 switch (flags & O_ACCMODE) {
5418 return PROT_READ|PROT_WRITE;
5425 char *format_bytes(char *buf, size_t l, off_t t) {
5428 static const struct {
5432 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5433 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5434 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5435 { "G", 1024ULL*1024ULL*1024ULL },
5436 { "M", 1024ULL*1024ULL },
5440 for (i = 0; i < ELEMENTSOF(table); i++) {
5442 if (t >= table[i].factor) {
5445 (unsigned long long) (t / table[i].factor),
5446 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5453 snprintf(buf, l, "%lluB", (unsigned long long) t);
5461 void* memdup(const void *p, size_t l) {
5474 int fd_inc_sndbuf(int fd, size_t n) {
5476 socklen_t l = sizeof(value);
5478 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5480 l == sizeof(value) &&
5481 (size_t) value >= n*2)
5485 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5492 int fd_inc_rcvbuf(int fd, size_t n) {
5494 socklen_t l = sizeof(value);
5496 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5498 l == sizeof(value) &&
5499 (size_t) value >= n*2)
5503 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5510 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5511 pid_t parent_pid, agent_pid;
5513 bool stdout_is_tty, stderr_is_tty;
5521 parent_pid = getpid();
5523 /* Spawns a temporary TTY agent, making sure it goes away when
5530 if (agent_pid != 0) {
5537 * Make sure the agent goes away when the parent dies */
5538 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5539 _exit(EXIT_FAILURE);
5541 /* Check whether our parent died before we were able
5542 * to set the death signal */
5543 if (getppid() != parent_pid)
5544 _exit(EXIT_SUCCESS);
5546 /* Don't leak fds to the agent */
5547 close_all_fds(except, n_except);
5549 stdout_is_tty = isatty(STDOUT_FILENO);
5550 stderr_is_tty = isatty(STDERR_FILENO);
5552 if (!stdout_is_tty || !stderr_is_tty) {
5553 /* Detach from stdout/stderr. and reopen
5554 * /dev/tty for them. This is important to
5555 * ensure that when systemctl is started via
5556 * popen() or a similar call that expects to
5557 * read EOF we actually do generate EOF and
5558 * not delay this indefinitely by because we
5559 * keep an unused copy of stdin around. */
5560 fd = open("/dev/tty", O_WRONLY);
5562 log_error("Failed to open /dev/tty: %m");
5563 _exit(EXIT_FAILURE);
5567 dup2(fd, STDOUT_FILENO);
5570 dup2(fd, STDERR_FILENO);
5576 /* Count arguments */
5578 for (n = 0; va_arg(ap, char*); n++)
5583 l = alloca(sizeof(char *) * (n + 1));
5585 /* Fill in arguments */
5587 for (i = 0; i <= n; i++)
5588 l[i] = va_arg(ap, char*);
5592 _exit(EXIT_FAILURE);
5595 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5596 struct rlimit highest, fixed;
5600 if (setrlimit(resource, rlim) >= 0)
5606 /* So we failed to set the desired setrlimit, then let's try
5607 * to get as close as we can */
5608 assert_se(getrlimit(resource, &highest) == 0);
5610 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5611 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5613 if (setrlimit(resource, &fixed) < 0)
5619 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5620 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5632 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5635 f = fopen(path, "re");
5643 char line[LINE_MAX];
5646 for (i = 0; i < sizeof(line)-1; i++) {
5650 if (_unlikely_(c == EOF)) {
5660 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5661 value = strdup(line + l + 1);
5681 int can_sleep(const char *type) {
5685 _cleanup_free_ char *p = NULL;
5689 r = read_one_line_file("/sys/power/state", &p);
5691 return r == -ENOENT ? 0 : r;
5694 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5695 if (l == k && memcmp(w, type, l) == 0)
5701 bool is_valid_documentation_url(const char *url) {
5704 if (startswith(url, "http://") && url[7])
5707 if (startswith(url, "https://") && url[8])
5710 if (startswith(url, "file:") && url[5])
5713 if (startswith(url, "info:") && url[5])
5716 if (startswith(url, "man:") && url[4])
5722 bool in_initrd(void) {
5723 static __thread int saved = -1;
5729 /* We make two checks here:
5731 * 1. the flag file /etc/initrd-release must exist
5732 * 2. the root file system must be a memory file system
5734 * The second check is extra paranoia, since misdetecting an
5735 * initrd can have bad bad consequences due the initrd
5736 * emptying when transititioning to the main systemd.
5739 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5740 statfs("/", &s) >= 0 &&
5741 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5746 void warn_melody(void) {
5747 _cleanup_close_ int fd = -1;
5749 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5753 /* Yeah, this is synchronous. Kinda sucks. But well... */
5755 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5756 usleep(125*USEC_PER_MSEC);
5758 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5759 usleep(125*USEC_PER_MSEC);
5761 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5762 usleep(125*USEC_PER_MSEC);
5764 ioctl(fd, KIOCSOUND, 0);
5767 int make_console_stdio(void) {
5770 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5772 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5774 log_error("Failed to acquire terminal: %s", strerror(-fd));
5780 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5787 int get_home_dir(char **_h) {
5795 /* Take the user specified one */
5806 /* Hardcode home directory for root to avoid NSS */
5809 h = strdup("/root");
5817 /* Check the database... */
5821 return errno ? -errno : -ESRCH;
5823 if (!path_is_absolute(p->pw_dir))
5826 h = strdup(p->pw_dir);
5834 int get_shell(char **_sh) {
5842 /* Take the user specified one */
5843 e = getenv("SHELL");
5853 /* Hardcode home directory for root to avoid NSS */
5856 sh = strdup("/bin/sh");
5864 /* Check the database... */
5868 return errno ? -errno : -ESRCH;
5870 if (!path_is_absolute(p->pw_shell))
5873 sh = strdup(p->pw_shell);
5881 void freep(void *p) {
5885 void fclosep(FILE **f) {
5890 void closep(int *fd) {
5892 close_nointr_nofail(*fd);
5895 void closedirp(DIR **d) {
5900 void umaskp(mode_t *u) {
5904 bool filename_is_safe(const char *p) {
5918 if (strlen(p) > FILENAME_MAX)
5924 bool string_is_safe(const char *p) {
5929 for (t = p; *t; t++) {
5930 if (*t > 0 && *t < ' ')
5933 if (strchr("\\\"\'", *t))
5940 int parse_timestamp(const char *t, usec_t *usec) {
5944 usec_t plus = 0, minus = 0, ret;
5950 * 2012-09-22 16:34:22
5951 * 2012-09-22 16:34 (seconds will be set to 0)
5952 * 2012-09-22 (time will be set to 00:00:00)
5953 * 16:34:22 (date will be set to today)
5954 * 16:34 (date will be set to today, seconds to 0)
5956 * yesterday (time is set to 00:00:00)
5957 * today (time is set to 00:00:00)
5958 * tomorrow (time is set to 00:00:00)
5968 assert_se(localtime_r(&x, &tm));
5970 if (streq(t, "now"))
5973 else if (streq(t, "today")) {
5974 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5977 } else if (streq(t, "yesterday")) {
5979 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5982 } else if (streq(t, "tomorrow")) {
5984 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
5987 } else if (t[0] == '+') {
5989 r = parse_usec(t+1, &plus);
5994 } else if (t[0] == '-') {
5996 r = parse_usec(t+1, &minus);
6004 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
6009 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
6014 k = strptime(t, "%y-%m-%d %H:%M", &tm);
6021 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
6028 k = strptime(t, "%y-%m-%d", &tm);
6030 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6035 k = strptime(t, "%Y-%m-%d", &tm);
6037 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
6042 k = strptime(t, "%H:%M:%S", &tm);
6047 k = strptime(t, "%H:%M", &tm);
6057 if (x == (time_t) -1)
6060 ret = (usec_t) x * USEC_PER_SEC;
6073 /* hey glibc, APIs with callbacks without a user pointer are so useless */
6074 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
6075 int (*compar) (const void *, const void *, void *),
6085 p = (void *)(((const char *) base) + (idx * size));
6086 comparison = compar(key, p, arg);
6089 else if (comparison > 0)