1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
76 char **saved_argv = NULL;
78 static volatile unsigned cached_columns = 0;
79 static volatile unsigned cached_lines = 0;
81 size_t page_size(void) {
82 static __thread size_t pgsz = 0;
85 if (_likely_(pgsz > 0))
88 r = sysconf(_SC_PAGESIZE);
95 bool streq_ptr(const char *a, const char *b) {
97 /* Like streq(), but tries to make sense of NULL pointers */
108 char* endswith(const char *s, const char *postfix) {
115 pl = strlen(postfix);
118 return (char*) s + sl;
123 if (memcmp(s + sl - pl, postfix, pl) != 0)
126 return (char*) s + sl - pl;
129 char* startswith(const char *s, const char *prefix) {
146 char* startswith_no_case(const char *s, const char *prefix) {
156 if (tolower(*a) != tolower(*b))
163 bool first_word(const char *s, const char *word) {
178 if (memcmp(s, word, wl) != 0)
182 strchr(WHITESPACE, s[wl]);
185 int close_nointr(int fd) {
200 void close_nointr_nofail(int fd) {
201 int saved_errno = errno;
203 /* like close_nointr() but cannot fail, and guarantees errno
206 assert_se(close_nointr(fd) == 0);
211 void close_many(const int fds[], unsigned n_fd) {
214 for (i = 0; i < n_fd; i++)
215 close_nointr_nofail(fds[i]);
218 int parse_boolean(const char *v) {
221 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
223 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
229 int parse_pid(const char *s, pid_t* ret_pid) {
230 unsigned long ul = 0;
237 r = safe_atolu(s, &ul);
243 if ((unsigned long) pid != ul)
253 int parse_uid(const char *s, uid_t* ret_uid) {
254 unsigned long ul = 0;
261 r = safe_atolu(s, &ul);
267 if ((unsigned long) uid != ul)
274 int safe_atou(const char *s, unsigned *ret_u) {
282 l = strtoul(s, &x, 0);
284 if (!x || x == s || *x || errno)
285 return errno ? -errno : -EINVAL;
287 if ((unsigned long) (unsigned) l != l)
290 *ret_u = (unsigned) l;
294 int safe_atoi(const char *s, int *ret_i) {
302 l = strtol(s, &x, 0);
304 if (!x || x == s || *x || errno)
305 return errno ? -errno : -EINVAL;
307 if ((long) (int) l != l)
314 int safe_atollu(const char *s, long long unsigned *ret_llu) {
316 unsigned long long l;
322 l = strtoull(s, &x, 0);
324 if (!x || x == s || *x || errno)
325 return errno ? -errno : -EINVAL;
331 int safe_atolli(const char *s, long long int *ret_lli) {
339 l = strtoll(s, &x, 0);
341 if (!x || x == s || *x || errno)
342 return errno ? -errno : -EINVAL;
348 /* Split a string into words. */
349 char *split(const char *c, size_t *l, const char *separator, char **state) {
352 current = *state ? *state : (char*) c;
354 if (!*current || *c == 0)
357 current += strspn(current, separator);
358 *l = strcspn(current, separator);
361 return (char*) current;
364 /* Split a string into words, but consider strings enclosed in '' and
365 * "" as words even if they include spaces. */
366 char *split_quoted(const char *c, size_t *l, char **state) {
368 bool escaped = false;
370 current = *state ? *state : (char*) c;
372 if (!*current || *c == 0)
375 current += strspn(current, WHITESPACE);
377 if (*current == '\'') {
380 for (e = current; *e; e++) {
390 *state = *e == 0 ? e : e+1;
391 } else if (*current == '\"') {
394 for (e = current; *e; e++) {
404 *state = *e == 0 ? e : e+1;
406 for (e = current; *e; e++) {
411 else if (strchr(WHITESPACE, *e))
418 return (char*) current;
421 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
423 _cleanup_fclose_ FILE *f = NULL;
424 char fn[PATH_MAX], line[LINE_MAX], *p;
430 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
437 if (!fgets(line, sizeof(line), f)) {
438 r = feof(f) ? -EIO : -errno;
442 /* Let's skip the pid and comm fields. The latter is enclosed
443 * in () but does not escape any () in its value, so let's
444 * skip over it manually */
446 p = strrchr(line, ')');
458 if ((long unsigned) (pid_t) ppid != ppid)
461 *_ppid = (pid_t) ppid;
466 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
467 _cleanup_fclose_ FILE *f = NULL;
468 char fn[PATH_MAX], line[LINE_MAX], *p;
473 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
480 if (!fgets(line, sizeof(line), f)) {
487 /* Let's skip the pid and comm fields. The latter is enclosed
488 * in () but does not escape any () in its value, so let's
489 * skip over it manually */
491 p = strrchr(line, ')');
513 "%*d " /* priority */
515 "%*d " /* num_threads */
516 "%*d " /* itrealvalue */
517 "%llu " /* starttime */,
524 int write_one_line_file(const char *fn, const char *line) {
525 _cleanup_fclose_ FILE *f = NULL;
535 if (fputs(line, f) < 0)
536 return errno ? -errno : -EIO;
538 if (!endswith(line, "\n"))
544 return errno ? -errno : -EIO;
549 int fchmod_umask(int fd, mode_t m) {
554 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
560 int write_one_line_file_atomic(const char *fn, const char *line) {
561 _cleanup_fclose_ FILE *f = NULL;
562 _cleanup_free_ char *p = NULL;
568 r = fopen_temporary(fn, &f, &p);
572 fchmod_umask(fileno(f), 0644);
575 if (fputs(line, f) < 0) {
580 if (!endswith(line, "\n"))
586 r = errno ? -errno : -EIO;
588 if (rename(p, fn) < 0)
601 int read_one_line_file(const char *fn, char **line) {
602 _cleanup_fclose_ FILE *f = NULL;
603 char t[LINE_MAX], *c;
612 if (!fgets(t, sizeof(t), f)) {
615 return errno ? -errno : -EIO;
629 int read_full_file(const char *fn, char **contents, size_t *size) {
630 _cleanup_fclose_ FILE *f = NULL;
632 _cleanup_free_ char *buf = NULL;
642 if (fstat(fileno(f), &st) < 0)
646 if (st.st_size > 4*1024*1024)
649 n = st.st_size > 0 ? st.st_size : LINE_MAX;
656 t = realloc(buf, n+1);
661 k = fread(buf + l, 1, n - l, f);
690 const char *separator, ...) {
693 char *contents = NULL, *p;
698 if ((r = read_full_file(fname, &contents, NULL)) < 0)
703 const char *key = NULL;
705 p += strspn(p, separator);
706 p += strspn(p, WHITESPACE);
711 if (!strchr(COMMENTS, *p)) {
715 va_start(ap, separator);
716 while ((key = va_arg(ap, char *))) {
720 value = va_arg(ap, char **);
723 if (strncmp(p, key, n) != 0 ||
728 n = strcspn(p, separator);
731 strchr(QUOTES, p[0]) &&
733 v = strndup(p+1, n-2);
744 /* return empty value strings as NULL */
761 p += strcspn(p, separator);
769 int load_env_file(const char *fname,
772 FILE _cleanup_fclose_ *f;
774 char _cleanup_free_ *c = NULL;
775 char _cleanup_strv_free_ **m = NULL;
780 f = fopen(fname, "re");
785 char l[LINE_MAX], *p, *u, *cs;
788 if (!fgets(l, sizeof(l), f)) {
795 cs = endswith(l, "\\\n");
817 p = strstrip(c ? c : l);
822 if (strchr(COMMENTS, *p))
825 u = normalize_env_assignment(p);
832 t = strv_append(m, u);
848 int write_env_file(const char *fname, char **l) {
853 r = fopen_temporary(fname, &f, &p);
857 fchmod_umask(fileno(f), 0644);
873 if (rename(p, fname) < 0)
888 char *truncate_nl(char *s) {
891 s[strcspn(s, NEWLINE)] = 0;
895 int get_process_comm(pid_t pid, char **name) {
901 r = read_one_line_file("/proc/self/comm", name);
904 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
907 r = read_one_line_file(p, name);
914 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
922 f = fopen("/proc/self/cmdline", "re");
925 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
934 if (max_length == 0) {
936 while ((c = getc(f)) != EOF) {
937 k = realloc(r, len+1);
944 r[len-1] = isprint(c) ? c : ' ';
951 r = new(char, max_length);
959 while ((c = getc(f)) != EOF) {
981 size_t n = MIN(left-1, 3U);
990 /* Kernel threads have no argv[] */
991 if (r == NULL || r[0] == 0) {
1000 h = get_process_comm(pid, &t);
1004 r = strjoin("[", t, "]", NULL);
1015 int is_kernel_thread(pid_t pid) {
1025 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1034 count = fread(&c, 1, 1, f);
1038 /* Kernel threads have an empty cmdline */
1041 return eof ? 1 : -errno;
1046 int get_process_exe(pid_t pid, char **name) {
1052 r = readlink_malloc("/proc/self/exe", name);
1055 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1058 r = readlink_malloc(p, name);
1065 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1066 _cleanup_fclose_ FILE *f = NULL;
1067 _cleanup_free_ char *p = NULL;
1075 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1082 FOREACH_LINE(f, line, return -errno) {
1087 if (startswith(l, field)) {
1089 l += strspn(l, WHITESPACE);
1091 l[strcspn(l, WHITESPACE)] = 0;
1093 return parse_uid(l, uid);
1100 int get_process_uid(pid_t pid, uid_t *uid) {
1101 return get_process_id(pid, "Uid:", uid);
1104 int get_process_gid(pid_t pid, gid_t *gid) {
1105 return get_process_id(pid, "Gid:", gid);
1108 char *strnappend(const char *s, const char *suffix, size_t b) {
1116 return strndup(suffix, b);
1125 if (b > ((size_t) -1) - a)
1128 r = new(char, a+b+1);
1133 memcpy(r+a, suffix, b);
1139 char *strappend(const char *s, const char *suffix) {
1140 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1143 int readlink_malloc(const char *p, char **r) {
1153 if (!(c = new(char, l)))
1156 if ((n = readlink(p, c, l-1)) < 0) {
1162 if ((size_t) n < l-1) {
1173 int readlink_and_make_absolute(const char *p, char **r) {
1180 if ((j = readlink_malloc(p, &target)) < 0)
1183 k = file_in_same_dir(p, target);
1193 int readlink_and_canonicalize(const char *p, char **r) {
1200 j = readlink_and_make_absolute(p, &t);
1204 s = canonicalize_file_name(t);
1211 path_kill_slashes(*r);
1216 int reset_all_signal_handlers(void) {
1219 for (sig = 1; sig < _NSIG; sig++) {
1220 struct sigaction sa;
1222 if (sig == SIGKILL || sig == SIGSTOP)
1226 sa.sa_handler = SIG_DFL;
1227 sa.sa_flags = SA_RESTART;
1229 /* On Linux the first two RT signals are reserved by
1230 * glibc, and sigaction() will return EINVAL for them. */
1231 if ((sigaction(sig, &sa, NULL) < 0))
1232 if (errno != EINVAL)
1239 char *strstrip(char *s) {
1242 /* Drops trailing whitespace. Modifies the string in
1243 * place. Returns pointer to first non-space character */
1245 s += strspn(s, WHITESPACE);
1247 for (e = strchr(s, 0); e > s; e --)
1248 if (!strchr(WHITESPACE, e[-1]))
1256 char *delete_chars(char *s, const char *bad) {
1259 /* Drops all whitespace, regardless where in the string */
1261 for (f = s, t = s; *f; f++) {
1262 if (strchr(bad, *f))
1273 bool in_charset(const char *s, const char* charset) {
1279 for (i = s; *i; i++)
1280 if (!strchr(charset, *i))
1286 char *file_in_same_dir(const char *path, const char *filename) {
1293 /* This removes the last component of path and appends
1294 * filename, unless the latter is absolute anyway or the
1297 if (path_is_absolute(filename))
1298 return strdup(filename);
1300 if (!(e = strrchr(path, '/')))
1301 return strdup(filename);
1303 k = strlen(filename);
1304 if (!(r = new(char, e-path+1+k+1)))
1307 memcpy(r, path, e-path+1);
1308 memcpy(r+(e-path)+1, filename, k+1);
1313 int rmdir_parents(const char *path, const char *stop) {
1322 /* Skip trailing slashes */
1323 while (l > 0 && path[l-1] == '/')
1329 /* Skip last component */
1330 while (l > 0 && path[l-1] != '/')
1333 /* Skip trailing slashes */
1334 while (l > 0 && path[l-1] == '/')
1340 if (!(t = strndup(path, l)))
1343 if (path_startswith(stop, t)) {
1352 if (errno != ENOENT)
1360 char hexchar(int x) {
1361 static const char table[16] = "0123456789abcdef";
1363 return table[x & 15];
1366 int unhexchar(char c) {
1368 if (c >= '0' && c <= '9')
1371 if (c >= 'a' && c <= 'f')
1372 return c - 'a' + 10;
1374 if (c >= 'A' && c <= 'F')
1375 return c - 'A' + 10;
1380 char octchar(int x) {
1381 return '0' + (x & 7);
1384 int unoctchar(char c) {
1386 if (c >= '0' && c <= '7')
1392 char decchar(int x) {
1393 return '0' + (x % 10);
1396 int undecchar(char c) {
1398 if (c >= '0' && c <= '9')
1404 char *cescape(const char *s) {
1410 /* Does C style string escaping. */
1412 r = new(char, strlen(s)*4 + 1);
1416 for (f = s, t = r; *f; f++)
1462 /* For special chars we prefer octal over
1463 * hexadecimal encoding, simply because glib's
1464 * g_strescape() does the same */
1465 if ((*f < ' ') || (*f >= 127)) {
1467 *(t++) = octchar((unsigned char) *f >> 6);
1468 *(t++) = octchar((unsigned char) *f >> 3);
1469 *(t++) = octchar((unsigned char) *f);
1480 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1487 /* Undoes C style string escaping, and optionally prefixes it. */
1489 pl = prefix ? strlen(prefix) : 0;
1491 r = new(char, pl+length+1);
1496 memcpy(r, prefix, pl);
1498 for (f = s, t = r + pl; f < s + length; f++) {
1541 /* This is an extension of the XDG syntax files */
1546 /* hexadecimal encoding */
1549 a = unhexchar(f[1]);
1550 b = unhexchar(f[2]);
1552 if (a < 0 || b < 0) {
1553 /* Invalid escape code, let's take it literal then */
1557 *(t++) = (char) ((a << 4) | b);
1572 /* octal encoding */
1575 a = unoctchar(f[0]);
1576 b = unoctchar(f[1]);
1577 c = unoctchar(f[2]);
1579 if (a < 0 || b < 0 || c < 0) {
1580 /* Invalid escape code, let's take it literal then */
1584 *(t++) = (char) ((a << 6) | (b << 3) | c);
1592 /* premature end of string.*/
1597 /* Invalid escape code, let's take it literal then */
1609 char *cunescape_length(const char *s, size_t length) {
1610 return cunescape_length_with_prefix(s, length, NULL);
1613 char *cunescape(const char *s) {
1616 return cunescape_length(s, strlen(s));
1619 char *xescape(const char *s, const char *bad) {
1623 /* Escapes all chars in bad, in addition to \ and all special
1624 * chars, in \xFF style escaping. May be reversed with
1627 r = new(char, strlen(s) * 4 + 1);
1631 for (f = s, t = r; *f; f++) {
1633 if ((*f < ' ') || (*f >= 127) ||
1634 (*f == '\\') || strchr(bad, *f)) {
1637 *(t++) = hexchar(*f >> 4);
1638 *(t++) = hexchar(*f);
1648 char *bus_path_escape(const char *s) {
1654 /* Escapes all chars that D-Bus' object path cannot deal
1655 * with. Can be reverse with bus_path_unescape() */
1657 if (!(r = new(char, strlen(s)*3+1)))
1660 for (f = s, t = r; *f; f++) {
1662 if (!(*f >= 'A' && *f <= 'Z') &&
1663 !(*f >= 'a' && *f <= 'z') &&
1664 !(*f >= '0' && *f <= '9')) {
1666 *(t++) = hexchar(*f >> 4);
1667 *(t++) = hexchar(*f);
1677 char *bus_path_unescape(const char *f) {
1682 if (!(r = strdup(f)))
1685 for (t = r; *f; f++) {
1690 if ((a = unhexchar(f[1])) < 0 ||
1691 (b = unhexchar(f[2])) < 0) {
1692 /* Invalid escape code, let's take it literal then */
1695 *(t++) = (char) ((a << 4) | b);
1707 char *ascii_strlower(char *t) {
1712 for (p = t; *p; p++)
1713 if (*p >= 'A' && *p <= 'Z')
1714 *p = *p - 'A' + 'a';
1719 static bool ignore_file_allow_backup(const char *filename) {
1723 filename[0] == '.' ||
1724 streq(filename, "lost+found") ||
1725 streq(filename, "aquota.user") ||
1726 streq(filename, "aquota.group") ||
1727 endswith(filename, ".rpmnew") ||
1728 endswith(filename, ".rpmsave") ||
1729 endswith(filename, ".rpmorig") ||
1730 endswith(filename, ".dpkg-old") ||
1731 endswith(filename, ".dpkg-new") ||
1732 endswith(filename, ".swp");
1735 bool ignore_file(const char *filename) {
1738 if (endswith(filename, "~"))
1741 return ignore_file_allow_backup(filename);
1744 int fd_nonblock(int fd, bool nonblock) {
1749 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1753 flags |= O_NONBLOCK;
1755 flags &= ~O_NONBLOCK;
1757 if (fcntl(fd, F_SETFL, flags) < 0)
1763 int fd_cloexec(int fd, bool cloexec) {
1768 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1772 flags |= FD_CLOEXEC;
1774 flags &= ~FD_CLOEXEC;
1776 if (fcntl(fd, F_SETFD, flags) < 0)
1782 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1785 assert(n_fdset == 0 || fdset);
1787 for (i = 0; i < n_fdset; i++)
1794 int close_all_fds(const int except[], unsigned n_except) {
1799 assert(n_except == 0 || except);
1801 d = opendir("/proc/self/fd");
1806 /* When /proc isn't available (for example in chroots)
1807 * the fallback is brute forcing through the fd
1810 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1811 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1813 if (fd_in_set(fd, except, n_except))
1816 if (close_nointr(fd) < 0)
1817 if (errno != EBADF && r == 0)
1824 while ((de = readdir(d))) {
1827 if (ignore_file(de->d_name))
1830 if (safe_atoi(de->d_name, &fd) < 0)
1831 /* Let's better ignore this, just in case */
1840 if (fd_in_set(fd, except, n_except))
1843 if (close_nointr(fd) < 0) {
1844 /* Valgrind has its own FD and doesn't want to have it closed */
1845 if (errno != EBADF && r == 0)
1854 bool chars_intersect(const char *a, const char *b) {
1857 /* Returns true if any of the chars in a are in b. */
1858 for (p = a; *p; p++)
1865 bool fstype_is_network(const char *fstype) {
1866 static const char table[] =
1875 return nulstr_contains(table, fstype);
1879 _cleanup_close_ int fd;
1881 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1887 TIOCL_GETKMSGREDIRECT,
1891 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1894 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1897 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1903 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1904 struct termios old_termios, new_termios;
1906 char line[LINE_MAX];
1911 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1912 new_termios = old_termios;
1914 new_termios.c_lflag &= ~ICANON;
1915 new_termios.c_cc[VMIN] = 1;
1916 new_termios.c_cc[VTIME] = 0;
1918 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1921 if (t != (usec_t) -1) {
1922 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1923 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1928 k = fread(&c, 1, 1, f);
1930 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1936 *need_nl = c != '\n';
1943 if (t != (usec_t) -1)
1944 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1947 if (!fgets(line, sizeof(line), f))
1952 if (strlen(line) != 1)
1962 int ask(char *ret, const char *replies, const char *text, ...) {
1972 bool need_nl = true;
1975 fputs(ANSI_HIGHLIGHT_ON, stdout);
1982 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1986 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1989 if (r == -EBADMSG) {
1990 puts("Bad input, please try again.");
2001 if (strchr(replies, c)) {
2006 puts("Read unexpected character, please try again.");
2010 int reset_terminal_fd(int fd, bool switch_to_text) {
2011 struct termios termios;
2014 /* Set terminal to some sane defaults */
2018 /* We leave locked terminal attributes untouched, so that
2019 * Plymouth may set whatever it wants to set, and we don't
2020 * interfere with that. */
2022 /* Disable exclusive mode, just in case */
2023 ioctl(fd, TIOCNXCL);
2025 /* Switch to text mode */
2027 ioctl(fd, KDSETMODE, KD_TEXT);
2029 /* Enable console unicode mode */
2030 ioctl(fd, KDSKBMODE, K_UNICODE);
2032 if (tcgetattr(fd, &termios) < 0) {
2037 /* We only reset the stuff that matters to the software. How
2038 * hardware is set up we don't touch assuming that somebody
2039 * else will do that for us */
2041 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2042 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2043 termios.c_oflag |= ONLCR;
2044 termios.c_cflag |= CREAD;
2045 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2047 termios.c_cc[VINTR] = 03; /* ^C */
2048 termios.c_cc[VQUIT] = 034; /* ^\ */
2049 termios.c_cc[VERASE] = 0177;
2050 termios.c_cc[VKILL] = 025; /* ^X */
2051 termios.c_cc[VEOF] = 04; /* ^D */
2052 termios.c_cc[VSTART] = 021; /* ^Q */
2053 termios.c_cc[VSTOP] = 023; /* ^S */
2054 termios.c_cc[VSUSP] = 032; /* ^Z */
2055 termios.c_cc[VLNEXT] = 026; /* ^V */
2056 termios.c_cc[VWERASE] = 027; /* ^W */
2057 termios.c_cc[VREPRINT] = 022; /* ^R */
2058 termios.c_cc[VEOL] = 0;
2059 termios.c_cc[VEOL2] = 0;
2061 termios.c_cc[VTIME] = 0;
2062 termios.c_cc[VMIN] = 1;
2064 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2068 /* Just in case, flush all crap out */
2069 tcflush(fd, TCIOFLUSH);
2074 int reset_terminal(const char *name) {
2077 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2081 r = reset_terminal_fd(fd, true);
2082 close_nointr_nofail(fd);
2087 int open_terminal(const char *name, int mode) {
2092 * If a TTY is in the process of being closed opening it might
2093 * cause EIO. This is horribly awful, but unlikely to be
2094 * changed in the kernel. Hence we work around this problem by
2095 * retrying a couple of times.
2097 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2101 fd = open(name, mode);
2108 /* Max 1s in total */
2112 usleep(50 * USEC_PER_MSEC);
2121 close_nointr_nofail(fd);
2126 close_nointr_nofail(fd);
2133 int flush_fd(int fd) {
2134 struct pollfd pollfd;
2138 pollfd.events = POLLIN;
2145 if ((r = poll(&pollfd, 1, 0)) < 0) {
2156 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2161 if (errno == EAGAIN)
2172 int acquire_terminal(
2176 bool ignore_tiocstty_eperm,
2179 int fd = -1, notify = -1, r = 0, wd = -1;
2181 struct sigaction sa_old, sa_new;
2185 /* We use inotify to be notified when the tty is closed. We
2186 * create the watch before checking if we can actually acquire
2187 * it, so that we don't lose any event.
2189 * Note: strictly speaking this actually watches for the
2190 * device being closed, it does *not* really watch whether a
2191 * tty loses its controlling process. However, unless some
2192 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2193 * its tty otherwise this will not become a problem. As long
2194 * as the administrator makes sure not configure any service
2195 * on the same tty as an untrusted user this should not be a
2196 * problem. (Which he probably should not do anyway.) */
2198 if (timeout != (usec_t) -1)
2199 ts = now(CLOCK_MONOTONIC);
2201 if (!fail && !force) {
2202 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2208 wd = inotify_add_watch(notify, name, IN_CLOSE);
2217 r = flush_fd(notify);
2222 /* We pass here O_NOCTTY only so that we can check the return
2223 * value TIOCSCTTY and have a reliable way to figure out if we
2224 * successfully became the controlling process of the tty */
2225 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2229 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2230 * if we already own the tty. */
2232 sa_new.sa_handler = SIG_IGN;
2233 sa_new.sa_flags = SA_RESTART;
2234 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2236 /* First, try to get the tty */
2237 if (ioctl(fd, TIOCSCTTY, force) < 0)
2240 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2242 /* Sometimes it makes sense to ignore TIOCSCTTY
2243 * returning EPERM, i.e. when very likely we already
2244 * are have this controlling terminal. */
2245 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2248 if (r < 0 && (force || fail || r != -EPERM)) {
2257 assert(notify >= 0);
2260 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2262 struct inotify_event *e;
2264 if (timeout != (usec_t) -1) {
2267 n = now(CLOCK_MONOTONIC);
2268 if (ts + timeout < n) {
2273 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2283 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2286 if (errno == EINTR || errno == EAGAIN)
2293 e = (struct inotify_event*) inotify_buffer;
2298 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2303 step = sizeof(struct inotify_event) + e->len;
2304 assert(step <= (size_t) l);
2306 e = (struct inotify_event*) ((uint8_t*) e + step);
2313 /* We close the tty fd here since if the old session
2314 * ended our handle will be dead. It's important that
2315 * we do this after sleeping, so that we don't enter
2316 * an endless loop. */
2317 close_nointr_nofail(fd);
2321 close_nointr_nofail(notify);
2323 r = reset_terminal_fd(fd, true);
2325 log_warning("Failed to reset terminal: %s", strerror(-r));
2331 close_nointr_nofail(fd);
2334 close_nointr_nofail(notify);
2339 int release_terminal(void) {
2341 struct sigaction sa_old, sa_new;
2343 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2346 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2347 * by our own TIOCNOTTY */
2350 sa_new.sa_handler = SIG_IGN;
2351 sa_new.sa_flags = SA_RESTART;
2352 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2354 if (ioctl(fd, TIOCNOTTY) < 0)
2357 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2359 close_nointr_nofail(fd);
2363 int sigaction_many(const struct sigaction *sa, ...) {
2368 while ((sig = va_arg(ap, int)) > 0)
2369 if (sigaction(sig, sa, NULL) < 0)
2376 int ignore_signals(int sig, ...) {
2377 struct sigaction sa;
2382 sa.sa_handler = SIG_IGN;
2383 sa.sa_flags = SA_RESTART;
2385 if (sigaction(sig, &sa, NULL) < 0)
2389 while ((sig = va_arg(ap, int)) > 0)
2390 if (sigaction(sig, &sa, NULL) < 0)
2397 int default_signals(int sig, ...) {
2398 struct sigaction sa;
2403 sa.sa_handler = SIG_DFL;
2404 sa.sa_flags = SA_RESTART;
2406 if (sigaction(sig, &sa, NULL) < 0)
2410 while ((sig = va_arg(ap, int)) > 0)
2411 if (sigaction(sig, &sa, NULL) < 0)
2418 int close_pipe(int p[]) {
2424 a = close_nointr(p[0]);
2429 b = close_nointr(p[1]);
2433 return a < 0 ? a : b;
2436 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2445 while (nbytes > 0) {
2448 if ((k = read(fd, p, nbytes)) <= 0) {
2450 if (k < 0 && errno == EINTR)
2453 if (k < 0 && errno == EAGAIN && do_poll) {
2454 struct pollfd pollfd;
2458 pollfd.events = POLLIN;
2460 if (poll(&pollfd, 1, -1) < 0) {
2464 return n > 0 ? n : -errno;
2467 if (pollfd.revents != POLLIN)
2468 return n > 0 ? n : -EIO;
2473 return n > 0 ? n : (k < 0 ? -errno : 0);
2484 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2493 while (nbytes > 0) {
2496 k = write(fd, p, nbytes);
2499 if (k < 0 && errno == EINTR)
2502 if (k < 0 && errno == EAGAIN && do_poll) {
2503 struct pollfd pollfd;
2507 pollfd.events = POLLOUT;
2509 if (poll(&pollfd, 1, -1) < 0) {
2513 return n > 0 ? n : -errno;
2516 if (pollfd.revents != POLLOUT)
2517 return n > 0 ? n : -EIO;
2522 return n > 0 ? n : (k < 0 ? -errno : 0);
2533 int parse_bytes(const char *t, off_t *bytes) {
2534 static const struct {
2540 { "M", 1024ULL*1024ULL },
2541 { "G", 1024ULL*1024ULL*1024ULL },
2542 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2543 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2544 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2561 l = strtoll(p, &e, 10);
2572 e += strspn(e, WHITESPACE);
2574 for (i = 0; i < ELEMENTSOF(table); i++)
2575 if (startswith(e, table[i].suffix)) {
2576 r += (off_t) l * table[i].factor;
2577 p = e + strlen(table[i].suffix);
2581 if (i >= ELEMENTSOF(table))
2591 int make_stdio(int fd) {
2596 r = dup3(fd, STDIN_FILENO, 0);
2597 s = dup3(fd, STDOUT_FILENO, 0);
2598 t = dup3(fd, STDERR_FILENO, 0);
2601 close_nointr_nofail(fd);
2603 if (r < 0 || s < 0 || t < 0)
2606 /* We rely here that the new fd has O_CLOEXEC not set */
2611 int make_null_stdio(void) {
2614 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2618 return make_stdio(null_fd);
2621 bool is_device_path(const char *path) {
2623 /* Returns true on paths that refer to a device, either in
2624 * sysfs or in /dev */
2627 path_startswith(path, "/dev/") ||
2628 path_startswith(path, "/sys/");
2631 int dir_is_empty(const char *path) {
2632 _cleanup_closedir_ DIR *d;
2641 union dirent_storage buf;
2643 r = readdir_r(d, &buf.de, &de);
2650 if (!ignore_file(de->d_name))
2655 unsigned long long random_ull(void) {
2656 _cleanup_close_ int fd;
2660 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2664 r = loop_read(fd, &ull, sizeof(ull), true);
2665 if (r != sizeof(ull))
2671 return random() * RAND_MAX + random();
2674 void rename_process(const char name[8]) {
2677 /* This is a like a poor man's setproctitle(). It changes the
2678 * comm field, argv[0], and also the glibc's internally used
2679 * name of the process. For the first one a limit of 16 chars
2680 * applies, to the second one usually one of 10 (i.e. length
2681 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2682 * "systemd"). If you pass a longer string it will be
2685 prctl(PR_SET_NAME, name);
2687 if (program_invocation_name)
2688 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2690 if (saved_argc > 0) {
2694 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2696 for (i = 1; i < saved_argc; i++) {
2700 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2705 void sigset_add_many(sigset_t *ss, ...) {
2712 while ((sig = va_arg(ap, int)) > 0)
2713 assert_se(sigaddset(ss, sig) == 0);
2717 char* gethostname_malloc(void) {
2720 assert_se(uname(&u) >= 0);
2722 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2723 return strdup(u.nodename);
2725 return strdup(u.sysname);
2728 bool hostname_is_set(void) {
2731 assert_se(uname(&u) >= 0);
2733 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2736 static char *lookup_uid(uid_t uid) {
2739 _cleanup_free_ char *buf = NULL;
2740 struct passwd pwbuf, *pw = NULL;
2742 /* Shortcut things to avoid NSS lookups */
2744 return strdup("root");
2746 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2750 buf = malloc(bufsize);
2754 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2755 return strdup(pw->pw_name);
2757 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2763 char* getlogname_malloc(void) {
2767 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2772 return lookup_uid(uid);
2775 char *getusername_malloc(void) {
2782 return lookup_uid(getuid());
2785 int getttyname_malloc(int fd, char **r) {
2786 char path[PATH_MAX], *c;
2791 k = ttyname_r(fd, path, sizeof(path));
2797 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2805 int getttyname_harder(int fd, char **r) {
2809 k = getttyname_malloc(fd, &s);
2813 if (streq(s, "tty")) {
2815 return get_ctty(0, NULL, r);
2822 int get_ctty_devnr(pid_t pid, dev_t *d) {
2824 char line[LINE_MAX], *p, *fn;
2825 unsigned long ttynr;
2828 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2831 f = fopen(fn, "re");
2836 if (!fgets(line, sizeof(line), f)) {
2837 k = feof(f) ? -EIO : -errno;
2844 p = strrchr(line, ')');
2854 "%*d " /* session */
2859 if (major(ttynr) == 0 && minor(ttynr) == 0)
2866 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2868 char fn[PATH_MAX], *s, *b, *p;
2873 k = get_ctty_devnr(pid, &devnr);
2877 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2880 k = readlink_malloc(fn, &s);
2886 /* This is an ugly hack */
2887 if (major(devnr) == 136) {
2888 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2898 /* Probably something like the ptys which have no
2899 * symlink in /dev/char. Let's return something
2900 * vaguely useful. */
2913 if (startswith(s, "/dev/"))
2915 else if (startswith(s, "../"))
2933 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2939 /* This returns the first error we run into, but nevertheless
2940 * tries to go on. This closes the passed fd. */
2944 close_nointr_nofail(fd);
2946 return errno == ENOENT ? 0 : -errno;
2951 union dirent_storage buf;
2952 bool is_dir, keep_around;
2956 r = readdir_r(d, &buf.de, &de);
2957 if (r != 0 && ret == 0) {
2965 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2968 if (de->d_type == DT_UNKNOWN ||
2970 (de->d_type == DT_DIR && root_dev)) {
2971 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2972 if (ret == 0 && errno != ENOENT)
2977 is_dir = S_ISDIR(st.st_mode);
2980 (st.st_uid == 0 || st.st_uid == getuid()) &&
2981 (st.st_mode & S_ISVTX);
2983 is_dir = de->d_type == DT_DIR;
2984 keep_around = false;
2990 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2991 if (root_dev && st.st_dev != root_dev->st_dev)
2994 subdir_fd = openat(fd, de->d_name,
2995 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2996 if (subdir_fd < 0) {
2997 if (ret == 0 && errno != ENOENT)
3002 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3003 if (r < 0 && ret == 0)
3007 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3008 if (ret == 0 && errno != ENOENT)
3012 } else if (!only_dirs && !keep_around) {
3014 if (unlinkat(fd, de->d_name, 0) < 0) {
3015 if (ret == 0 && errno != ENOENT)
3026 static int is_temporary_fs(struct statfs *s) {
3028 return s->f_type == TMPFS_MAGIC ||
3029 (long)s->f_type == (long)RAMFS_MAGIC;
3032 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3037 if (fstatfs(fd, &s) < 0) {
3038 close_nointr_nofail(fd);
3042 /* We refuse to clean disk file systems with this call. This
3043 * is extra paranoia just to be sure we never ever remove
3045 if (!is_temporary_fs(&s)) {
3046 log_error("Attempted to remove disk file system, and we can't allow that.");
3047 close_nointr_nofail(fd);
3051 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3054 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3060 /* We refuse to clean the root file system with this
3061 * call. This is extra paranoia to never cause a really
3062 * seriously broken system. */
3063 if (path_equal(path, "/")) {
3064 log_error("Attempted to remove entire root file system, and we can't allow that.");
3068 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3071 if (errno != ENOTDIR)
3075 if (statfs(path, &s) < 0)
3078 if (!is_temporary_fs(&s)) {
3079 log_error("Attempted to remove disk file system, and we can't allow that.");
3084 if (delete_root && !only_dirs)
3085 if (unlink(path) < 0 && errno != ENOENT)
3092 if (fstatfs(fd, &s) < 0) {
3093 close_nointr_nofail(fd);
3097 if (!is_temporary_fs(&s)) {
3098 log_error("Attempted to remove disk file system, and we can't allow that.");
3099 close_nointr_nofail(fd);
3104 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3107 if (honour_sticky && file_is_priv_sticky(path) > 0)
3110 if (rmdir(path) < 0 && errno != ENOENT) {
3119 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3120 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3123 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3124 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3127 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3130 /* Under the assumption that we are running privileged we
3131 * first change the access mode and only then hand out
3132 * ownership to avoid a window where access is too open. */
3134 if (mode != (mode_t) -1)
3135 if (chmod(path, mode) < 0)
3138 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3139 if (chown(path, uid, gid) < 0)
3145 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3148 /* Under the assumption that we are running privileged we
3149 * first change the access mode and only then hand out
3150 * ownership to avoid a window where access is too open. */
3152 if (fchmod(fd, mode) < 0)
3155 if (fchown(fd, uid, gid) < 0)
3161 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3165 /* Allocates the cpuset in the right size */
3168 if (!(r = CPU_ALLOC(n)))
3171 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3172 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3182 if (errno != EINVAL)
3189 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3190 static const char status_indent[] = " "; /* "[" STATUS "] " */
3191 _cleanup_free_ char *s = NULL;
3192 _cleanup_close_ int fd = -1;
3193 struct iovec iovec[5];
3198 /* This is independent of logging, as status messages are
3199 * optional and go exclusively to the console. */
3201 if (vasprintf(&s, format, ap) < 0)
3204 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3217 sl = status ? sizeof(status_indent)-1 : 0;
3223 e = ellipsize(s, emax, 75);
3233 if (!isempty(status)) {
3234 IOVEC_SET_STRING(iovec[n++], "[");
3235 IOVEC_SET_STRING(iovec[n++], status);
3236 IOVEC_SET_STRING(iovec[n++], "] ");
3238 IOVEC_SET_STRING(iovec[n++], status_indent);
3241 IOVEC_SET_STRING(iovec[n++], s);
3242 IOVEC_SET_STRING(iovec[n++], "\n");
3244 if (writev(fd, iovec, n) < 0)
3250 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3256 va_start(ap, format);
3257 r = status_vprintf(status, ellipse, format, ap);
3263 int status_welcome(void) {
3265 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3267 r = parse_env_file("/etc/os-release", NEWLINE,
3268 "PRETTY_NAME", &pretty_name,
3269 "ANSI_COLOR", &ansi_color,
3271 if (r < 0 && r != -ENOENT)
3272 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3274 return status_printf(NULL, false,
3275 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3276 isempty(ansi_color) ? "1" : ansi_color,
3277 isempty(pretty_name) ? "Linux" : pretty_name);
3280 char *replace_env(const char *format, char **env) {
3287 const char *e, *word = format;
3292 for (e = format; *e; e ++) {
3303 if (!(k = strnappend(r, word, e-word-1)))
3312 } else if (*e == '$') {
3313 if (!(k = strnappend(r, word, e-word)))
3329 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3331 k = strappend(r, t);
3345 if (!(k = strnappend(r, word, e-word)))
3356 char **replace_env_argv(char **argv, char **env) {
3358 unsigned k = 0, l = 0;
3360 l = strv_length(argv);
3362 if (!(r = new(char*, l+1)))
3365 STRV_FOREACH(i, argv) {
3367 /* If $FOO appears as single word, replace it by the split up variable */
3368 if ((*i)[0] == '$' && (*i)[1] != '{') {
3373 e = strv_env_get(env, *i+1);
3376 if (!(m = strv_split_quoted(e))) {
3387 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3396 memcpy(r + k, m, q * sizeof(char*));
3404 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3405 if (!(r[k++] = replace_env(*i, env))) {
3415 int fd_columns(int fd) {
3419 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3428 unsigned columns(void) {
3432 if (_likely_(cached_columns > 0))
3433 return cached_columns;
3436 e = getenv("COLUMNS");
3441 c = fd_columns(STDOUT_FILENO);
3450 int fd_lines(int fd) {
3454 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3463 unsigned lines(void) {
3467 if (_likely_(cached_lines > 0))
3468 return cached_lines;
3471 e = getenv("LINES");
3476 l = fd_lines(STDOUT_FILENO);
3482 return cached_lines;
3485 /* intended to be used as a SIGWINCH sighandler */
3486 void columns_lines_cache_reset(int signum) {
3492 static int cached_on_tty = -1;
3494 if (_unlikely_(cached_on_tty < 0))
3495 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3497 return cached_on_tty;
3500 int running_in_chroot(void) {
3506 /* Only works as root */
3508 if (stat("/proc/1/root", &a) < 0)
3511 if (stat("/", &b) < 0)
3515 a.st_dev != b.st_dev ||
3516 a.st_ino != b.st_ino;
3519 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3524 assert(percent <= 100);
3525 assert(new_length >= 3);
3527 if (old_length <= 3 || old_length <= new_length)
3528 return strndup(s, old_length);
3530 r = new0(char, new_length+1);
3534 x = (new_length * percent) / 100;
3536 if (x > new_length - 3)
3544 s + old_length - (new_length - x - 3),
3545 new_length - x - 3);
3550 char *ellipsize(const char *s, size_t length, unsigned percent) {
3551 return ellipsize_mem(s, strlen(s), length, percent);
3554 int touch(const char *path) {
3559 /* This just opens the file for writing, ensuring it
3560 * exists. It doesn't call utimensat() the way /usr/bin/touch
3563 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3567 close_nointr_nofail(fd);
3571 char *unquote(const char *s, const char* quotes) {
3575 /* This is rather stupid, simply removes the heading and
3576 * trailing quotes if there is one. Doesn't care about
3577 * escaping or anything. We should make this smarter one
3584 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3585 return strndup(s+1, l-2);
3590 char *normalize_env_assignment(const char *s) {
3591 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3594 eq = strchr(s, '=');
3606 memmove(r, t, strlen(t) + 1);
3610 name = strndup(s, eq - s);
3618 value = unquote(strstrip(p), QUOTES);
3622 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3628 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3639 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3651 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3658 r = wait_for_terminate(pid, &status);
3660 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3664 if (status.si_code == CLD_EXITED) {
3665 if (status.si_status != 0) {
3666 log_warning("%s failed with error code %i.", name, status.si_status);
3667 return status.si_status;
3670 log_debug("%s succeeded.", name);
3673 } else if (status.si_code == CLD_KILLED ||
3674 status.si_code == CLD_DUMPED) {
3676 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3680 log_warning("%s failed due to unknown reason.", name);
3684 _noreturn_ void freeze(void) {
3686 /* Make sure nobody waits for us on a socket anymore */
3687 close_all_fds(NULL, 0);
3695 bool null_or_empty(struct stat *st) {
3698 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3701 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3707 int null_or_empty_path(const char *fn) {
3712 if (stat(fn, &st) < 0)
3715 return null_or_empty(&st);
3718 DIR *xopendirat(int fd, const char *name, int flags) {
3722 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3728 close_nointr_nofail(nfd);
3735 int signal_from_string_try_harder(const char *s) {
3739 signo = signal_from_string(s);
3741 if (startswith(s, "SIG"))
3742 return signal_from_string(s+3);
3747 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3751 /* FIXME: to follow udev's logic 100% we need to leave valid
3752 * UTF8 chars unescaped */
3754 u = unquote(tagvalue, "\"\'");
3758 t = xescape(u, "/ ");
3764 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3773 char *fstab_node_to_udev_node(const char *p) {
3776 if (startswith(p, "LABEL="))
3777 return tag_to_udev_node(p+6, "label");
3779 if (startswith(p, "UUID="))
3780 return tag_to_udev_node(p+5, "uuid");
3782 if (startswith(p, "PARTUUID="))
3783 return tag_to_udev_node(p+9, "partuuid");
3785 if (startswith(p, "PARTLABEL="))
3786 return tag_to_udev_node(p+10, "partlabel");
3791 bool tty_is_vc(const char *tty) {
3794 if (startswith(tty, "/dev/"))
3797 return vtnr_from_tty(tty) >= 0;
3800 bool tty_is_console(const char *tty) {
3803 if (startswith(tty, "/dev/"))
3806 return streq(tty, "console");
3809 int vtnr_from_tty(const char *tty) {
3814 if (startswith(tty, "/dev/"))
3817 if (!startswith(tty, "tty") )
3820 if (tty[3] < '0' || tty[3] > '9')
3823 r = safe_atoi(tty+3, &i);
3827 if (i < 0 || i > 63)
3833 bool tty_is_vc_resolve(const char *tty) {
3834 char *active = NULL;
3839 if (startswith(tty, "/dev/"))
3842 /* Resolve where /dev/console is pointing to, if /sys is
3843 * actually ours (i.e. not read-only-mounted which is a sign
3844 * for container setups) */
3845 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3846 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3847 /* If multiple log outputs are configured the
3848 * last one is what /dev/console points to */
3849 tty = strrchr(active, ' ');
3862 const char *default_term_for_tty(const char *tty) {
3865 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3868 bool dirent_is_file(const struct dirent *de) {
3871 if (ignore_file(de->d_name))
3874 if (de->d_type != DT_REG &&
3875 de->d_type != DT_LNK &&
3876 de->d_type != DT_UNKNOWN)
3882 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3885 if (de->d_type != DT_REG &&
3886 de->d_type != DT_LNK &&
3887 de->d_type != DT_UNKNOWN)
3890 if (ignore_file_allow_backup(de->d_name))
3893 return endswith(de->d_name, suffix);
3896 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3899 Hashmap *pids = NULL;
3903 /* Executes all binaries in a directory in parallel and waits
3904 * until all they all finished. */
3907 if (!(_d = opendir(directory))) {
3909 if (errno == ENOENT)
3912 log_error("Failed to enumerate directory %s: %m", directory);
3919 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3920 log_error("Failed to allocate set.");
3924 while ((de = readdir(d))) {
3929 if (!dirent_is_file(de))
3932 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3937 if ((pid = fork()) < 0) {
3938 log_error("Failed to fork: %m");
3956 log_error("Failed to execute %s: %m", path);
3957 _exit(EXIT_FAILURE);
3960 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3962 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3963 log_error("Failed to add PID to set: %s", strerror(-k));
3968 while (!hashmap_isempty(pids)) {
3969 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3974 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3979 log_error("waitid() failed: %m");
3983 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3984 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3985 if (si.si_code == CLD_EXITED)
3986 log_error("%s exited with exit status %i.", path, si.si_status);
3988 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3990 log_debug("%s exited successfully.", path);
4001 hashmap_free_free(pids);
4004 int kill_and_sigcont(pid_t pid, int sig) {
4007 r = kill(pid, sig) < 0 ? -errno : 0;
4015 bool nulstr_contains(const char*nulstr, const char *needle) {
4021 NULSTR_FOREACH(i, nulstr)
4022 if (streq(i, needle))
4028 bool plymouth_running(void) {
4029 return access("/run/plymouth/pid", F_OK) >= 0;
4032 char* strshorten(char *s, size_t l) {
4041 static bool hostname_valid_char(char c) {
4043 (c >= 'a' && c <= 'z') ||
4044 (c >= 'A' && c <= 'Z') ||
4045 (c >= '0' && c <= '9') ||
4051 bool hostname_is_valid(const char *s) {
4057 for (p = s; *p; p++)
4058 if (!hostname_valid_char(*p))
4061 if (p-s > HOST_NAME_MAX)
4067 char* hostname_cleanup(char *s) {
4070 for (p = s, d = s; *p; p++)
4071 if ((*p >= 'a' && *p <= 'z') ||
4072 (*p >= 'A' && *p <= 'Z') ||
4073 (*p >= '0' && *p <= '9') ||
4081 strshorten(s, HOST_NAME_MAX);
4085 int pipe_eof(int fd) {
4086 struct pollfd pollfd;
4091 pollfd.events = POLLIN|POLLHUP;
4093 r = poll(&pollfd, 1, 0);
4100 return pollfd.revents & POLLHUP;
4103 int fd_wait_for_event(int fd, int event, usec_t t) {
4104 struct pollfd pollfd;
4109 pollfd.events = event;
4111 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4118 return pollfd.revents;
4121 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4132 t = new(char, strlen(path) + 1 + 6 + 1);
4136 fn = path_get_file_name(path);
4140 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4142 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4148 f = fdopen(fd, "we");
4161 int terminal_vhangup_fd(int fd) {
4164 if (ioctl(fd, TIOCVHANGUP) < 0)
4170 int terminal_vhangup(const char *name) {
4173 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4177 r = terminal_vhangup_fd(fd);
4178 close_nointr_nofail(fd);
4183 int vt_disallocate(const char *name) {
4187 /* Deallocate the VT if possible. If not possible
4188 * (i.e. because it is the active one), at least clear it
4189 * entirely (including the scrollback buffer) */
4191 if (!startswith(name, "/dev/"))
4194 if (!tty_is_vc(name)) {
4195 /* So this is not a VT. I guess we cannot deallocate
4196 * it then. But let's at least clear the screen */
4198 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4203 "\033[r" /* clear scrolling region */
4204 "\033[H" /* move home */
4205 "\033[2J", /* clear screen */
4207 close_nointr_nofail(fd);
4212 if (!startswith(name, "/dev/tty"))
4215 r = safe_atou(name+8, &u);
4222 /* Try to deallocate */
4223 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4227 r = ioctl(fd, VT_DISALLOCATE, u);
4228 close_nointr_nofail(fd);
4236 /* Couldn't deallocate, so let's clear it fully with
4238 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4243 "\033[r" /* clear scrolling region */
4244 "\033[H" /* move home */
4245 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4247 close_nointr_nofail(fd);
4252 int copy_file(const char *from, const char *to) {
4258 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4262 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4264 close_nointr_nofail(fdf);
4272 n = read(fdf, buf, sizeof(buf));
4276 close_nointr_nofail(fdf);
4287 k = loop_write(fdt, buf, n, false);
4289 r = k < 0 ? k : (errno ? -errno : -EIO);
4291 close_nointr_nofail(fdf);
4299 close_nointr_nofail(fdf);
4300 r = close_nointr(fdt);
4310 int symlink_atomic(const char *from, const char *to) {
4312 _cleanup_free_ char *t;
4315 unsigned long long ull;
4322 t = new(char, strlen(to) + 1 + 16 + 1);
4326 fn = path_get_file_name(to);
4330 x = stpcpy(t+k+1, fn);
4333 for (i = 0; i < 16; i++) {
4334 *(x++) = hexchar(ull & 0xF);
4340 if (symlink(from, t) < 0)
4343 if (rename(t, to) < 0) {
4352 bool display_is_local(const char *display) {
4356 display[0] == ':' &&
4357 display[1] >= '0' &&
4361 int socket_from_display(const char *display, char **path) {
4368 if (!display_is_local(display))
4371 k = strspn(display+1, "0123456789");
4373 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4377 c = stpcpy(f, "/tmp/.X11-unix/X");
4378 memcpy(c, display+1, k);
4387 const char **username,
4388 uid_t *uid, gid_t *gid,
4390 const char **shell) {
4398 /* We enforce some special rules for uid=0: in order to avoid
4399 * NSS lookups for root we hardcode its data. */
4401 if (streq(*username, "root") || streq(*username, "0")) {
4419 if (parse_uid(*username, &u) >= 0) {
4423 /* If there are multiple users with the same id, make
4424 * sure to leave $USER to the configured value instead
4425 * of the first occurrence in the database. However if
4426 * the uid was configured by a numeric uid, then let's
4427 * pick the real username from /etc/passwd. */
4429 *username = p->pw_name;
4432 p = getpwnam(*username);
4436 return errno != 0 ? -errno : -ESRCH;
4448 *shell = p->pw_shell;
4453 char* uid_to_name(uid_t uid) {
4458 return strdup("root");
4462 return strdup(p->pw_name);
4464 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4470 int get_group_creds(const char **groupname, gid_t *gid) {
4476 /* We enforce some special rules for gid=0: in order to avoid
4477 * NSS lookups for root we hardcode its data. */
4479 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4480 *groupname = "root";
4488 if (parse_gid(*groupname, &id) >= 0) {
4493 *groupname = g->gr_name;
4496 g = getgrnam(*groupname);
4500 return errno != 0 ? -errno : -ESRCH;
4508 int in_group(const char *name) {
4510 int ngroups_max, r, i;
4512 r = get_group_creds(&name, &gid);
4516 if (getgid() == gid)
4519 if (getegid() == gid)
4522 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4523 assert(ngroups_max > 0);
4525 gids = alloca(sizeof(gid_t) * ngroups_max);
4527 r = getgroups(ngroups_max, gids);
4531 for (i = 0; i < r; i++)
4538 int glob_exists(const char *path) {
4546 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4548 if (k == GLOB_NOMATCH)
4550 else if (k == GLOB_NOSPACE)
4553 r = !strv_isempty(g.gl_pathv);
4555 r = errno ? -errno : -EIO;
4562 int dirent_ensure_type(DIR *d, struct dirent *de) {
4568 if (de->d_type != DT_UNKNOWN)
4571 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4575 S_ISREG(st.st_mode) ? DT_REG :
4576 S_ISDIR(st.st_mode) ? DT_DIR :
4577 S_ISLNK(st.st_mode) ? DT_LNK :
4578 S_ISFIFO(st.st_mode) ? DT_FIFO :
4579 S_ISSOCK(st.st_mode) ? DT_SOCK :
4580 S_ISCHR(st.st_mode) ? DT_CHR :
4581 S_ISBLK(st.st_mode) ? DT_BLK :
4587 int in_search_path(const char *path, char **search) {
4591 r = path_get_parent(path, &parent);
4597 STRV_FOREACH(i, search) {
4598 if (path_equal(parent, *i)) {
4609 int get_files_in_directory(const char *path, char ***list) {
4617 /* Returns all files in a directory in *list, and the number
4618 * of files as return value. If list is NULL returns only the
4627 union dirent_storage buf;
4630 k = readdir_r(d, &buf.de, &de);
4639 dirent_ensure_type(d, de);
4641 if (!dirent_is_file(de))
4645 if ((unsigned) r >= n) {
4649 t = realloc(l, sizeof(char*) * n);
4658 assert((unsigned) r < n);
4660 l[r] = strdup(de->d_name);
4684 char *strjoin(const char *x, ...) {
4698 t = va_arg(ap, const char *);
4703 if (n > ((size_t) -1) - l) {
4727 t = va_arg(ap, const char *);
4741 bool is_main_thread(void) {
4742 static __thread int cached = 0;
4744 if (_unlikely_(cached == 0))
4745 cached = getpid() == gettid() ? 1 : -1;
4750 int block_get_whole_disk(dev_t d, dev_t *ret) {
4757 /* If it has a queue this is good enough for us */
4758 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4761 r = access(p, F_OK);
4769 /* If it is a partition find the originating device */
4770 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4773 r = access(p, F_OK);
4779 /* Get parent dev_t */
4780 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4783 r = read_one_line_file(p, &s);
4789 r = sscanf(s, "%u:%u", &m, &n);
4795 /* Only return this if it is really good enough for us. */
4796 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4799 r = access(p, F_OK);
4803 *ret = makedev(m, n);
4810 int file_is_priv_sticky(const char *p) {
4815 if (lstat(p, &st) < 0)
4819 (st.st_uid == 0 || st.st_uid == getuid()) &&
4820 (st.st_mode & S_ISVTX);
4823 static const char *const ioprio_class_table[] = {
4824 [IOPRIO_CLASS_NONE] = "none",
4825 [IOPRIO_CLASS_RT] = "realtime",
4826 [IOPRIO_CLASS_BE] = "best-effort",
4827 [IOPRIO_CLASS_IDLE] = "idle"
4830 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4832 static const char *const sigchld_code_table[] = {
4833 [CLD_EXITED] = "exited",
4834 [CLD_KILLED] = "killed",
4835 [CLD_DUMPED] = "dumped",
4836 [CLD_TRAPPED] = "trapped",
4837 [CLD_STOPPED] = "stopped",
4838 [CLD_CONTINUED] = "continued",
4841 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4843 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4844 [LOG_FAC(LOG_KERN)] = "kern",
4845 [LOG_FAC(LOG_USER)] = "user",
4846 [LOG_FAC(LOG_MAIL)] = "mail",
4847 [LOG_FAC(LOG_DAEMON)] = "daemon",
4848 [LOG_FAC(LOG_AUTH)] = "auth",
4849 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4850 [LOG_FAC(LOG_LPR)] = "lpr",
4851 [LOG_FAC(LOG_NEWS)] = "news",
4852 [LOG_FAC(LOG_UUCP)] = "uucp",
4853 [LOG_FAC(LOG_CRON)] = "cron",
4854 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4855 [LOG_FAC(LOG_FTP)] = "ftp",
4856 [LOG_FAC(LOG_LOCAL0)] = "local0",
4857 [LOG_FAC(LOG_LOCAL1)] = "local1",
4858 [LOG_FAC(LOG_LOCAL2)] = "local2",
4859 [LOG_FAC(LOG_LOCAL3)] = "local3",
4860 [LOG_FAC(LOG_LOCAL4)] = "local4",
4861 [LOG_FAC(LOG_LOCAL5)] = "local5",
4862 [LOG_FAC(LOG_LOCAL6)] = "local6",
4863 [LOG_FAC(LOG_LOCAL7)] = "local7"
4866 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4868 static const char *const log_level_table[] = {
4869 [LOG_EMERG] = "emerg",
4870 [LOG_ALERT] = "alert",
4871 [LOG_CRIT] = "crit",
4873 [LOG_WARNING] = "warning",
4874 [LOG_NOTICE] = "notice",
4875 [LOG_INFO] = "info",
4876 [LOG_DEBUG] = "debug"
4879 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4881 static const char* const sched_policy_table[] = {
4882 [SCHED_OTHER] = "other",
4883 [SCHED_BATCH] = "batch",
4884 [SCHED_IDLE] = "idle",
4885 [SCHED_FIFO] = "fifo",
4889 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4891 static const char* const rlimit_table[] = {
4892 [RLIMIT_CPU] = "LimitCPU",
4893 [RLIMIT_FSIZE] = "LimitFSIZE",
4894 [RLIMIT_DATA] = "LimitDATA",
4895 [RLIMIT_STACK] = "LimitSTACK",
4896 [RLIMIT_CORE] = "LimitCORE",
4897 [RLIMIT_RSS] = "LimitRSS",
4898 [RLIMIT_NOFILE] = "LimitNOFILE",
4899 [RLIMIT_AS] = "LimitAS",
4900 [RLIMIT_NPROC] = "LimitNPROC",
4901 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4902 [RLIMIT_LOCKS] = "LimitLOCKS",
4903 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4904 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4905 [RLIMIT_NICE] = "LimitNICE",
4906 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4907 [RLIMIT_RTTIME] = "LimitRTTIME"
4910 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4912 static const char* const ip_tos_table[] = {
4913 [IPTOS_LOWDELAY] = "low-delay",
4914 [IPTOS_THROUGHPUT] = "throughput",
4915 [IPTOS_RELIABILITY] = "reliability",
4916 [IPTOS_LOWCOST] = "low-cost",
4919 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4921 static const char *const __signal_table[] = {
4938 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4949 [SIGVTALRM] = "VTALRM",
4951 [SIGWINCH] = "WINCH",
4957 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4959 const char *signal_to_string(int signo) {
4960 static __thread char buf[12];
4963 name = __signal_to_string(signo);
4967 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4968 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4970 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4975 int signal_from_string(const char *s) {
4980 signo = __signal_from_string(s);
4984 if (startswith(s, "RTMIN+")) {
4988 if (safe_atou(s, &u) >= 0) {
4989 signo = (int) u + offset;
4990 if (signo > 0 && signo < _NSIG)
4996 bool kexec_loaded(void) {
4997 bool loaded = false;
5000 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5008 int strdup_or_null(const char *a, char **b) {
5026 int prot_from_flags(int flags) {
5028 switch (flags & O_ACCMODE) {
5037 return PROT_READ|PROT_WRITE;
5044 char *format_bytes(char *buf, size_t l, off_t t) {
5047 static const struct {
5051 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5052 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5053 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5054 { "G", 1024ULL*1024ULL*1024ULL },
5055 { "M", 1024ULL*1024ULL },
5059 for (i = 0; i < ELEMENTSOF(table); i++) {
5061 if (t >= table[i].factor) {
5064 (unsigned long long) (t / table[i].factor),
5065 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5072 snprintf(buf, l, "%lluB", (unsigned long long) t);
5080 void* memdup(const void *p, size_t l) {
5093 int fd_inc_sndbuf(int fd, size_t n) {
5095 socklen_t l = sizeof(value);
5097 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5099 l == sizeof(value) &&
5100 (size_t) value >= n*2)
5104 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5111 int fd_inc_rcvbuf(int fd, size_t n) {
5113 socklen_t l = sizeof(value);
5115 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5117 l == sizeof(value) &&
5118 (size_t) value >= n*2)
5122 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5129 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5130 pid_t parent_pid, agent_pid;
5132 bool stdout_is_tty, stderr_is_tty;
5140 parent_pid = getpid();
5142 /* Spawns a temporary TTY agent, making sure it goes away when
5149 if (agent_pid != 0) {
5156 * Make sure the agent goes away when the parent dies */
5157 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5158 _exit(EXIT_FAILURE);
5160 /* Check whether our parent died before we were able
5161 * to set the death signal */
5162 if (getppid() != parent_pid)
5163 _exit(EXIT_SUCCESS);
5165 /* Don't leak fds to the agent */
5166 close_all_fds(except, n_except);
5168 stdout_is_tty = isatty(STDOUT_FILENO);
5169 stderr_is_tty = isatty(STDERR_FILENO);
5171 if (!stdout_is_tty || !stderr_is_tty) {
5172 /* Detach from stdout/stderr. and reopen
5173 * /dev/tty for them. This is important to
5174 * ensure that when systemctl is started via
5175 * popen() or a similar call that expects to
5176 * read EOF we actually do generate EOF and
5177 * not delay this indefinitely by because we
5178 * keep an unused copy of stdin around. */
5179 fd = open("/dev/tty", O_WRONLY);
5181 log_error("Failed to open /dev/tty: %m");
5182 _exit(EXIT_FAILURE);
5186 dup2(fd, STDOUT_FILENO);
5189 dup2(fd, STDERR_FILENO);
5195 /* Count arguments */
5197 for (n = 0; va_arg(ap, char*); n++)
5202 l = alloca(sizeof(char *) * (n + 1));
5204 /* Fill in arguments */
5206 for (i = 0; i <= n; i++)
5207 l[i] = va_arg(ap, char*);
5211 _exit(EXIT_FAILURE);
5214 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5215 struct rlimit highest, fixed;
5219 if (setrlimit(resource, rlim) >= 0)
5225 /* So we failed to set the desired setrlimit, then let's try
5226 * to get as close as we can */
5227 assert_se(getrlimit(resource, &highest) == 0);
5229 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5230 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5232 if (setrlimit(resource, &fixed) < 0)
5238 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5239 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5251 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5254 f = fopen(path, "re");
5262 char line[LINE_MAX];
5265 for (i = 0; i < sizeof(line)-1; i++) {
5269 if (_unlikely_(c == EOF)) {
5279 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5280 value = strdup(line + l + 1);
5300 int can_sleep(const char *type) {
5304 _cleanup_free_ char *p = NULL;
5308 /* If /sys is read-only we cannot sleep */
5309 if (access("/sys/power/state", W_OK) < 0)
5312 r = read_one_line_file("/sys/power/state", &p);
5317 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5318 if (l == k && memcmp(w, type, l) == 0)
5324 int can_sleep_disk(const char *type) {
5328 _cleanup_free_ char *p = NULL;
5332 /* If /sys is read-only we cannot sleep */
5333 if (access("/sys/power/state", W_OK) < 0 ||
5334 access("/sys/power/disk", W_OK) < 0)
5337 r = read_one_line_file("/sys/power/disk", &p);
5342 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5343 if (l == k && memcmp(w, type, l) == 0)
5346 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5353 bool is_valid_documentation_url(const char *url) {
5356 if (startswith(url, "http://") && url[7])
5359 if (startswith(url, "https://") && url[8])
5362 if (startswith(url, "file:") && url[5])
5365 if (startswith(url, "info:") && url[5])
5368 if (startswith(url, "man:") && url[4])
5374 bool in_initrd(void) {
5375 static __thread int saved = -1;
5381 /* We make two checks here:
5383 * 1. the flag file /etc/initrd-release must exist
5384 * 2. the root file system must be a memory file system
5386 * The second check is extra paranoia, since misdetecting an
5387 * initrd can have bad bad consequences due the initrd
5388 * emptying when transititioning to the main systemd.
5391 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5392 statfs("/", &s) >= 0 &&
5393 is_temporary_fs(&s);
5398 void warn_melody(void) {
5399 _cleanup_close_ int fd = -1;
5401 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5405 /* Yeah, this is synchronous. Kinda sucks. But well... */
5407 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5408 usleep(125*USEC_PER_MSEC);
5410 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5411 usleep(125*USEC_PER_MSEC);
5413 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5414 usleep(125*USEC_PER_MSEC);
5416 ioctl(fd, KIOCSOUND, 0);
5419 int make_console_stdio(void) {
5422 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5424 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5426 log_error("Failed to acquire terminal: %s", strerror(-fd));
5432 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5439 int get_home_dir(char **_h) {
5447 /* Take the user specified one */
5458 /* Hardcode home directory for root to avoid NSS */
5461 h = strdup("/root");
5469 /* Check the database... */
5473 return errno ? -errno : -ESRCH;
5475 if (!path_is_absolute(p->pw_dir))
5478 h = strdup(p->pw_dir);
5486 int get_shell(char **_sh) {
5494 /* Take the user specified one */
5495 e = getenv("SHELL");
5505 /* Hardcode home directory for root to avoid NSS */
5508 sh = strdup("/bin/sh");
5516 /* Check the database... */
5520 return errno ? -errno : -ESRCH;
5522 if (!path_is_absolute(p->pw_shell))
5525 sh = strdup(p->pw_shell);
5533 void freep(void *p) {
5537 void fclosep(FILE **f) {
5542 void pclosep(FILE **f) {
5547 void closep(int *fd) {
5549 close_nointr_nofail(*fd);
5552 void closedirp(DIR **d) {
5557 void umaskp(mode_t *u) {
5561 bool filename_is_safe(const char *p) {
5575 if (strlen(p) > FILENAME_MAX)
5581 bool string_is_safe(const char *p) {
5586 for (t = p; *t; t++) {
5587 if (*t > 0 && *t < ' ')
5590 if (strchr("\\\"\'", *t))
5597 bool string_has_cc(const char *p) {
5602 for (t = p; *t; t++)
5603 if (*t > 0 && *t < ' ')
5609 bool path_is_safe(const char *p) {
5614 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5617 if (strlen(p) > PATH_MAX)
5620 /* The following two checks are not really dangerous, but hey, they still are confusing */
5621 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5624 if (strstr(p, "//"))
5630 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5631 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5632 int (*compar) (const void *, const void *, void *), void *arg) {
5641 p = (void *)(((const char *) base) + (idx * size));
5642 comparison = compar(key, p, arg);
5645 else if (comparison > 0)
5653 bool is_locale_utf8(void) {
5655 static int cached_answer = -1;
5657 if (cached_answer >= 0)
5660 if (!setlocale(LC_ALL, "")) {
5661 cached_answer = true;
5665 set = nl_langinfo(CODESET);
5667 cached_answer = true;
5671 cached_answer = streq(set, "UTF-8");
5673 return (bool)cached_answer;
5676 const char *draw_special_char(DrawSpecialChar ch) {
5677 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5679 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5680 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5681 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5682 [DRAW_TREE_SPACE] = " ", /* */
5683 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5685 /* ASCII fallback */ {
5686 [DRAW_TREE_VERT] = "| ",
5687 [DRAW_TREE_BRANCH] = "|-",
5688 [DRAW_TREE_RIGHT] = "`-",
5689 [DRAW_TREE_SPACE] = " ",
5690 [DRAW_TRIANGULAR_BULLET] = "> ",
5694 return draw_table[!is_locale_utf8()][ch];
5697 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5700 size_t l, old_len, new_len;
5706 old_len = strlen(old_string);
5707 new_len = strlen(new_string);
5720 if (!startswith(f, old_string)) {
5726 nl = l - old_len + new_len;
5727 a = realloc(r, nl + 1);
5735 t = stpcpy(t, new_string);
5747 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5748 const char *i, *begin = NULL;
5753 } state = STATE_OTHER;
5755 size_t osz = 0, isz;
5761 /* Strips ANSI color and replaces TABs by 8 spaces */
5763 isz = _isz ? *_isz : strlen(*ibuf);
5765 f = open_memstream(&obuf, &osz);
5769 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5774 if (i >= *ibuf + isz) /* EOT */
5776 else if (*i == '\x1B')
5777 state = STATE_ESCAPE;
5778 else if (*i == '\t')
5785 if (i >= *ibuf + isz) { /* EOT */
5788 } else if (*i == '[') {
5789 state = STATE_BRACKET;
5794 state = STATE_OTHER;
5801 if (i >= *ibuf + isz || /* EOT */
5802 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5805 state = STATE_OTHER;
5807 } else if (*i == 'm')
5808 state = STATE_OTHER;
5830 int on_ac_power(void) {
5831 bool found_offline = false, found_online = false;
5832 _cleanup_closedir_ DIR *d = NULL;
5834 d = opendir("/sys/class/power_supply");
5840 union dirent_storage buf;
5841 _cleanup_free_ char *p = NULL;
5842 _cleanup_close_ int fd = -1, device = -1;
5847 k = readdir_r(d, &buf.de, &de);
5854 if (ignore_file(de->d_name))
5857 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5859 if (errno == ENOENT || errno == ENOTDIR)
5865 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5867 if (errno == ENOENT)
5873 n = read(fd, contents, sizeof(contents));
5877 if (n != 6 || memcmp(contents, "Mains\n", 6))
5880 close_nointr_nofail(fd);
5881 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5883 if (errno == ENOENT)
5889 n = read(fd, contents, sizeof(contents));
5893 if (n != 2 || contents[1] != '\n')
5896 if (contents[0] == '1') {
5897 found_online = true;
5899 } else if (contents[0] == '0')
5900 found_offline = true;
5905 return found_online || !found_offline;