1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
75 char **saved_argv = NULL;
77 static volatile unsigned cached_columns = 0;
78 static volatile unsigned cached_lines = 0;
80 bool is_efiboot(void) {
81 return access("/sys/firmware/efi", F_OK) >= 0;
84 size_t page_size(void) {
85 static __thread size_t pgsz = 0;
88 if (_likely_(pgsz > 0))
91 r = sysconf(_SC_PAGESIZE);
98 bool streq_ptr(const char *a, const char *b) {
100 /* Like streq(), but tries to make sense of NULL pointers */
111 char* endswith(const char *s, const char *postfix) {
118 pl = strlen(postfix);
121 return (char*) s + sl;
126 if (memcmp(s + sl - pl, postfix, pl) != 0)
129 return (char*) s + sl - pl;
132 char* startswith(const char *s, const char *prefix) {
149 char* startswith_no_case(const char *s, const char *prefix) {
159 if (tolower(*a) != tolower(*b))
166 bool first_word(const char *s, const char *word) {
181 if (memcmp(s, word, wl) != 0)
185 strchr(WHITESPACE, s[wl]);
188 int close_nointr(int fd) {
203 void close_nointr_nofail(int fd) {
204 int saved_errno = errno;
206 /* like close_nointr() but cannot fail, and guarantees errno
209 assert_se(close_nointr(fd) == 0);
214 void close_many(const int fds[], unsigned n_fd) {
217 for (i = 0; i < n_fd; i++)
218 close_nointr_nofail(fds[i]);
221 int parse_boolean(const char *v) {
224 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
226 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
232 int parse_pid(const char *s, pid_t* ret_pid) {
233 unsigned long ul = 0;
240 r = safe_atolu(s, &ul);
246 if ((unsigned long) pid != ul)
256 int parse_uid(const char *s, uid_t* ret_uid) {
257 unsigned long ul = 0;
264 r = safe_atolu(s, &ul);
270 if ((unsigned long) uid != ul)
277 int safe_atou(const char *s, unsigned *ret_u) {
285 l = strtoul(s, &x, 0);
287 if (!x || x == s || *x || errno)
288 return errno ? -errno : -EINVAL;
290 if ((unsigned long) (unsigned) l != l)
293 *ret_u = (unsigned) l;
297 int safe_atoi(const char *s, int *ret_i) {
305 l = strtol(s, &x, 0);
307 if (!x || x == s || *x || errno)
308 return errno ? -errno : -EINVAL;
310 if ((long) (int) l != l)
317 int safe_atollu(const char *s, long long unsigned *ret_llu) {
319 unsigned long long l;
325 l = strtoull(s, &x, 0);
327 if (!x || x == s || *x || errno)
328 return errno ? -errno : -EINVAL;
334 int safe_atolli(const char *s, long long int *ret_lli) {
342 l = strtoll(s, &x, 0);
344 if (!x || x == s || *x || errno)
345 return errno ? -errno : -EINVAL;
351 /* Split a string into words. */
352 char *split(const char *c, size_t *l, const char *separator, char **state) {
355 current = *state ? *state : (char*) c;
357 if (!*current || *c == 0)
360 current += strspn(current, separator);
361 *l = strcspn(current, separator);
364 return (char*) current;
367 /* Split a string into words, but consider strings enclosed in '' and
368 * "" as words even if they include spaces. */
369 char *split_quoted(const char *c, size_t *l, char **state) {
371 bool escaped = false;
373 current = *state ? *state : (char*) c;
375 if (!*current || *c == 0)
378 current += strspn(current, WHITESPACE);
380 if (*current == '\'') {
383 for (e = current; *e; e++) {
393 *state = *e == 0 ? e : e+1;
394 } else if (*current == '\"') {
397 for (e = current; *e; e++) {
407 *state = *e == 0 ? e : e+1;
409 for (e = current; *e; e++) {
414 else if (strchr(WHITESPACE, *e))
421 return (char*) current;
424 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
426 _cleanup_fclose_ FILE *f = NULL;
427 char fn[PATH_MAX], line[LINE_MAX], *p;
433 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
440 if (!fgets(line, sizeof(line), f)) {
441 r = feof(f) ? -EIO : -errno;
445 /* Let's skip the pid and comm fields. The latter is enclosed
446 * in () but does not escape any () in its value, so let's
447 * skip over it manually */
449 p = strrchr(line, ')');
461 if ((long unsigned) (pid_t) ppid != ppid)
464 *_ppid = (pid_t) ppid;
469 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
470 _cleanup_fclose_ FILE *f = NULL;
471 char fn[PATH_MAX], line[LINE_MAX], *p;
476 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
483 if (!fgets(line, sizeof(line), f)) {
490 /* Let's skip the pid and comm fields. The latter is enclosed
491 * in () but does not escape any () in its value, so let's
492 * skip over it manually */
494 p = strrchr(line, ')');
516 "%*d " /* priority */
518 "%*d " /* num_threads */
519 "%*d " /* itrealvalue */
520 "%llu " /* starttime */,
527 int write_one_line_file(const char *fn, const char *line) {
528 _cleanup_fclose_ FILE *f = NULL;
538 if (fputs(line, f) < 0)
539 return errno ? -errno : -EIO;
541 if (!endswith(line, "\n"))
547 return errno ? -errno : -EIO;
552 int fchmod_umask(int fd, mode_t m) {
557 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
563 int write_one_line_file_atomic(const char *fn, const char *line) {
571 r = fopen_temporary(fn, &f, &p);
575 fchmod_umask(fileno(f), 0644);
578 if (fputs(line, f) < 0) {
583 if (!endswith(line, "\n"))
594 if (rename(p, fn) < 0)
610 int read_one_line_file(const char *fn, char **line) {
611 _cleanup_fclose_ FILE *f = NULL;
612 char t[LINE_MAX], *c;
621 if (!fgets(t, sizeof(t), f)) {
624 return errno ? -errno : -EIO;
638 int read_full_file(const char *fn, char **contents, size_t *size) {
639 _cleanup_fclose_ FILE *f = NULL;
641 _cleanup_free_ char *buf = NULL;
651 if (fstat(fileno(f), &st) < 0)
655 if (st.st_size > 4*1024*1024)
658 n = st.st_size > 0 ? st.st_size : LINE_MAX;
665 t = realloc(buf, n+1);
670 k = fread(buf + l, 1, n - l, f);
699 const char *separator, ...) {
702 char *contents = NULL, *p;
707 if ((r = read_full_file(fname, &contents, NULL)) < 0)
712 const char *key = NULL;
714 p += strspn(p, separator);
715 p += strspn(p, WHITESPACE);
720 if (!strchr(COMMENTS, *p)) {
724 va_start(ap, separator);
725 while ((key = va_arg(ap, char *))) {
729 value = va_arg(ap, char **);
732 if (strncmp(p, key, n) != 0 ||
737 n = strcspn(p, separator);
740 strchr(QUOTES, p[0]) &&
742 v = strndup(p+1, n-2);
753 /* return empty value strings as NULL */
770 p += strcspn(p, separator);
789 if (!(f = fopen(fname, "re")))
793 char l[LINE_MAX], *p, *u;
796 if (!fgets(l, sizeof(l), f)) {
809 if (strchr(COMMENTS, *p))
812 if (!(u = normalize_env_assignment(p))) {
817 t = strv_append(m, u);
843 int write_env_file(const char *fname, char **l) {
848 r = fopen_temporary(fname, &f, &p);
852 fchmod_umask(fileno(f), 0644);
868 if (rename(p, fname) < 0)
883 char *truncate_nl(char *s) {
886 s[strcspn(s, NEWLINE)] = 0;
890 int get_process_comm(pid_t pid, char **name) {
896 r = read_one_line_file("/proc/self/comm", name);
899 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
902 r = read_one_line_file(p, name);
909 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
917 f = fopen("/proc/self/cmdline", "re");
920 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
929 if (max_length == 0) {
931 while ((c = getc(f)) != EOF) {
932 k = realloc(r, len+1);
939 r[len-1] = isprint(c) ? c : ' ';
946 r = new(char, max_length);
954 while ((c = getc(f)) != EOF) {
976 size_t n = MIN(left-1, 3U);
985 /* Kernel threads have no argv[] */
986 if (r == NULL || r[0] == 0) {
995 h = get_process_comm(pid, &t);
999 r = strjoin("[", t, "]", NULL);
1010 int is_kernel_thread(pid_t pid) {
1020 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1029 count = fread(&c, 1, 1, f);
1033 /* Kernel threads have an empty cmdline */
1036 return eof ? 1 : -errno;
1041 int get_process_exe(pid_t pid, char **name) {
1047 r = readlink_malloc("/proc/self/exe", name);
1050 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1053 r = readlink_malloc(p, name);
1060 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1070 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1080 char line[LINE_MAX], *l;
1082 if (!fgets(line, sizeof(line), f)) {
1092 if (startswith(l, field)) {
1094 l += strspn(l, WHITESPACE);
1096 l[strcspn(l, WHITESPACE)] = 0;
1098 r = parse_uid(l, uid);
1111 int get_process_uid(pid_t pid, uid_t *uid) {
1112 return get_process_id(pid, "Uid:", uid);
1115 int get_process_gid(pid_t pid, gid_t *gid) {
1116 return get_process_id(pid, "Gid:", gid);
1119 char *strnappend(const char *s, const char *suffix, size_t b) {
1127 return strndup(suffix, b);
1136 if (b > ((size_t) -1) - a)
1139 r = new(char, a+b+1);
1144 memcpy(r+a, suffix, b);
1150 char *strappend(const char *s, const char *suffix) {
1151 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1154 int readlink_malloc(const char *p, char **r) {
1164 if (!(c = new(char, l)))
1167 if ((n = readlink(p, c, l-1)) < 0) {
1173 if ((size_t) n < l-1) {
1184 int readlink_and_make_absolute(const char *p, char **r) {
1191 if ((j = readlink_malloc(p, &target)) < 0)
1194 k = file_in_same_dir(p, target);
1204 int readlink_and_canonicalize(const char *p, char **r) {
1211 j = readlink_and_make_absolute(p, &t);
1215 s = canonicalize_file_name(t);
1222 path_kill_slashes(*r);
1227 int reset_all_signal_handlers(void) {
1230 for (sig = 1; sig < _NSIG; sig++) {
1231 struct sigaction sa;
1233 if (sig == SIGKILL || sig == SIGSTOP)
1237 sa.sa_handler = SIG_DFL;
1238 sa.sa_flags = SA_RESTART;
1240 /* On Linux the first two RT signals are reserved by
1241 * glibc, and sigaction() will return EINVAL for them. */
1242 if ((sigaction(sig, &sa, NULL) < 0))
1243 if (errno != EINVAL)
1250 char *strstrip(char *s) {
1253 /* Drops trailing whitespace. Modifies the string in
1254 * place. Returns pointer to first non-space character */
1256 s += strspn(s, WHITESPACE);
1258 for (e = strchr(s, 0); e > s; e --)
1259 if (!strchr(WHITESPACE, e[-1]))
1267 char *delete_chars(char *s, const char *bad) {
1270 /* Drops all whitespace, regardless where in the string */
1272 for (f = s, t = s; *f; f++) {
1273 if (strchr(bad, *f))
1284 bool in_charset(const char *s, const char* charset) {
1290 for (i = s; *i; i++)
1291 if (!strchr(charset, *i))
1297 char *file_in_same_dir(const char *path, const char *filename) {
1304 /* This removes the last component of path and appends
1305 * filename, unless the latter is absolute anyway or the
1308 if (path_is_absolute(filename))
1309 return strdup(filename);
1311 if (!(e = strrchr(path, '/')))
1312 return strdup(filename);
1314 k = strlen(filename);
1315 if (!(r = new(char, e-path+1+k+1)))
1318 memcpy(r, path, e-path+1);
1319 memcpy(r+(e-path)+1, filename, k+1);
1324 int rmdir_parents(const char *path, const char *stop) {
1333 /* Skip trailing slashes */
1334 while (l > 0 && path[l-1] == '/')
1340 /* Skip last component */
1341 while (l > 0 && path[l-1] != '/')
1344 /* Skip trailing slashes */
1345 while (l > 0 && path[l-1] == '/')
1351 if (!(t = strndup(path, l)))
1354 if (path_startswith(stop, t)) {
1363 if (errno != ENOENT)
1371 char hexchar(int x) {
1372 static const char table[16] = "0123456789abcdef";
1374 return table[x & 15];
1377 int unhexchar(char c) {
1379 if (c >= '0' && c <= '9')
1382 if (c >= 'a' && c <= 'f')
1383 return c - 'a' + 10;
1385 if (c >= 'A' && c <= 'F')
1386 return c - 'A' + 10;
1391 char octchar(int x) {
1392 return '0' + (x & 7);
1395 int unoctchar(char c) {
1397 if (c >= '0' && c <= '7')
1403 char decchar(int x) {
1404 return '0' + (x % 10);
1407 int undecchar(char c) {
1409 if (c >= '0' && c <= '9')
1415 char *cescape(const char *s) {
1421 /* Does C style string escaping. */
1423 r = new(char, strlen(s)*4 + 1);
1427 for (f = s, t = r; *f; f++)
1473 /* For special chars we prefer octal over
1474 * hexadecimal encoding, simply because glib's
1475 * g_strescape() does the same */
1476 if ((*f < ' ') || (*f >= 127)) {
1478 *(t++) = octchar((unsigned char) *f >> 6);
1479 *(t++) = octchar((unsigned char) *f >> 3);
1480 *(t++) = octchar((unsigned char) *f);
1491 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1498 /* Undoes C style string escaping, and optionally prefixes it. */
1500 pl = prefix ? strlen(prefix) : 0;
1502 r = new(char, pl+length+1);
1507 memcpy(r, prefix, pl);
1509 for (f = s, t = r + pl; f < s + length; f++) {
1552 /* This is an extension of the XDG syntax files */
1557 /* hexadecimal encoding */
1560 a = unhexchar(f[1]);
1561 b = unhexchar(f[2]);
1563 if (a < 0 || b < 0) {
1564 /* Invalid escape code, let's take it literal then */
1568 *(t++) = (char) ((a << 4) | b);
1583 /* octal encoding */
1586 a = unoctchar(f[0]);
1587 b = unoctchar(f[1]);
1588 c = unoctchar(f[2]);
1590 if (a < 0 || b < 0 || c < 0) {
1591 /* Invalid escape code, let's take it literal then */
1595 *(t++) = (char) ((a << 6) | (b << 3) | c);
1603 /* premature end of string.*/
1608 /* Invalid escape code, let's take it literal then */
1620 char *cunescape_length(const char *s, size_t length) {
1621 return cunescape_length_with_prefix(s, length, NULL);
1624 char *cunescape(const char *s) {
1627 return cunescape_length(s, strlen(s));
1630 char *xescape(const char *s, const char *bad) {
1634 /* Escapes all chars in bad, in addition to \ and all special
1635 * chars, in \xFF style escaping. May be reversed with
1638 r = new(char, strlen(s) * 4 + 1);
1642 for (f = s, t = r; *f; f++) {
1644 if ((*f < ' ') || (*f >= 127) ||
1645 (*f == '\\') || strchr(bad, *f)) {
1648 *(t++) = hexchar(*f >> 4);
1649 *(t++) = hexchar(*f);
1659 char *bus_path_escape(const char *s) {
1665 /* Escapes all chars that D-Bus' object path cannot deal
1666 * with. Can be reverse with bus_path_unescape() */
1668 if (!(r = new(char, strlen(s)*3+1)))
1671 for (f = s, t = r; *f; f++) {
1673 if (!(*f >= 'A' && *f <= 'Z') &&
1674 !(*f >= 'a' && *f <= 'z') &&
1675 !(*f >= '0' && *f <= '9')) {
1677 *(t++) = hexchar(*f >> 4);
1678 *(t++) = hexchar(*f);
1688 char *bus_path_unescape(const char *f) {
1693 if (!(r = strdup(f)))
1696 for (t = r; *f; f++) {
1701 if ((a = unhexchar(f[1])) < 0 ||
1702 (b = unhexchar(f[2])) < 0) {
1703 /* Invalid escape code, let's take it literal then */
1706 *(t++) = (char) ((a << 4) | b);
1718 char *ascii_strlower(char *t) {
1723 for (p = t; *p; p++)
1724 if (*p >= 'A' && *p <= 'Z')
1725 *p = *p - 'A' + 'a';
1730 static bool ignore_file_allow_backup(const char *filename) {
1734 filename[0] == '.' ||
1735 streq(filename, "lost+found") ||
1736 streq(filename, "aquota.user") ||
1737 streq(filename, "aquota.group") ||
1738 endswith(filename, ".rpmnew") ||
1739 endswith(filename, ".rpmsave") ||
1740 endswith(filename, ".rpmorig") ||
1741 endswith(filename, ".dpkg-old") ||
1742 endswith(filename, ".dpkg-new") ||
1743 endswith(filename, ".swp");
1746 bool ignore_file(const char *filename) {
1749 if (endswith(filename, "~"))
1752 return ignore_file_allow_backup(filename);
1755 int fd_nonblock(int fd, bool nonblock) {
1760 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1764 flags |= O_NONBLOCK;
1766 flags &= ~O_NONBLOCK;
1768 if (fcntl(fd, F_SETFL, flags) < 0)
1774 int fd_cloexec(int fd, bool cloexec) {
1779 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1783 flags |= FD_CLOEXEC;
1785 flags &= ~FD_CLOEXEC;
1787 if (fcntl(fd, F_SETFD, flags) < 0)
1793 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1796 assert(n_fdset == 0 || fdset);
1798 for (i = 0; i < n_fdset; i++)
1805 int close_all_fds(const int except[], unsigned n_except) {
1810 assert(n_except == 0 || except);
1812 d = opendir("/proc/self/fd");
1817 /* When /proc isn't available (for example in chroots)
1818 * the fallback is brute forcing through the fd
1821 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1822 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1824 if (fd_in_set(fd, except, n_except))
1827 if (close_nointr(fd) < 0)
1828 if (errno != EBADF && r == 0)
1835 while ((de = readdir(d))) {
1838 if (ignore_file(de->d_name))
1841 if (safe_atoi(de->d_name, &fd) < 0)
1842 /* Let's better ignore this, just in case */
1851 if (fd_in_set(fd, except, n_except))
1854 if (close_nointr(fd) < 0) {
1855 /* Valgrind has its own FD and doesn't want to have it closed */
1856 if (errno != EBADF && r == 0)
1865 bool chars_intersect(const char *a, const char *b) {
1868 /* Returns true if any of the chars in a are in b. */
1869 for (p = a; *p; p++)
1876 bool fstype_is_network(const char *fstype) {
1877 static const char table[] =
1886 return nulstr_contains(table, fstype);
1890 _cleanup_close_ int fd;
1892 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1898 TIOCL_GETKMSGREDIRECT,
1902 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1905 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1908 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1914 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1915 struct termios old_termios, new_termios;
1917 char line[LINE_MAX];
1922 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1923 new_termios = old_termios;
1925 new_termios.c_lflag &= ~ICANON;
1926 new_termios.c_cc[VMIN] = 1;
1927 new_termios.c_cc[VTIME] = 0;
1929 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1932 if (t != (usec_t) -1) {
1933 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1934 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1939 k = fread(&c, 1, 1, f);
1941 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1947 *need_nl = c != '\n';
1954 if (t != (usec_t) -1)
1955 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1958 if (!fgets(line, sizeof(line), f))
1963 if (strlen(line) != 1)
1973 int ask(char *ret, const char *replies, const char *text, ...) {
1983 bool need_nl = true;
1986 fputs(ANSI_HIGHLIGHT_ON, stdout);
1993 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1997 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2000 if (r == -EBADMSG) {
2001 puts("Bad input, please try again.");
2012 if (strchr(replies, c)) {
2017 puts("Read unexpected character, please try again.");
2021 int reset_terminal_fd(int fd, bool switch_to_text) {
2022 struct termios termios;
2025 /* Set terminal to some sane defaults */
2029 /* We leave locked terminal attributes untouched, so that
2030 * Plymouth may set whatever it wants to set, and we don't
2031 * interfere with that. */
2033 /* Disable exclusive mode, just in case */
2034 ioctl(fd, TIOCNXCL);
2036 /* Switch to text mode */
2038 ioctl(fd, KDSETMODE, KD_TEXT);
2040 /* Enable console unicode mode */
2041 ioctl(fd, KDSKBMODE, K_UNICODE);
2043 if (tcgetattr(fd, &termios) < 0) {
2048 /* We only reset the stuff that matters to the software. How
2049 * hardware is set up we don't touch assuming that somebody
2050 * else will do that for us */
2052 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2053 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2054 termios.c_oflag |= ONLCR;
2055 termios.c_cflag |= CREAD;
2056 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2058 termios.c_cc[VINTR] = 03; /* ^C */
2059 termios.c_cc[VQUIT] = 034; /* ^\ */
2060 termios.c_cc[VERASE] = 0177;
2061 termios.c_cc[VKILL] = 025; /* ^X */
2062 termios.c_cc[VEOF] = 04; /* ^D */
2063 termios.c_cc[VSTART] = 021; /* ^Q */
2064 termios.c_cc[VSTOP] = 023; /* ^S */
2065 termios.c_cc[VSUSP] = 032; /* ^Z */
2066 termios.c_cc[VLNEXT] = 026; /* ^V */
2067 termios.c_cc[VWERASE] = 027; /* ^W */
2068 termios.c_cc[VREPRINT] = 022; /* ^R */
2069 termios.c_cc[VEOL] = 0;
2070 termios.c_cc[VEOL2] = 0;
2072 termios.c_cc[VTIME] = 0;
2073 termios.c_cc[VMIN] = 1;
2075 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2079 /* Just in case, flush all crap out */
2080 tcflush(fd, TCIOFLUSH);
2085 int reset_terminal(const char *name) {
2088 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2092 r = reset_terminal_fd(fd, true);
2093 close_nointr_nofail(fd);
2098 int open_terminal(const char *name, int mode) {
2103 * If a TTY is in the process of being closed opening it might
2104 * cause EIO. This is horribly awful, but unlikely to be
2105 * changed in the kernel. Hence we work around this problem by
2106 * retrying a couple of times.
2108 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2112 fd = open(name, mode);
2119 /* Max 1s in total */
2123 usleep(50 * USEC_PER_MSEC);
2132 close_nointr_nofail(fd);
2137 close_nointr_nofail(fd);
2144 int flush_fd(int fd) {
2145 struct pollfd pollfd;
2149 pollfd.events = POLLIN;
2156 if ((r = poll(&pollfd, 1, 0)) < 0) {
2167 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2172 if (errno == EAGAIN)
2183 int acquire_terminal(
2187 bool ignore_tiocstty_eperm,
2190 int fd = -1, notify = -1, r = 0, wd = -1;
2192 struct sigaction sa_old, sa_new;
2196 /* We use inotify to be notified when the tty is closed. We
2197 * create the watch before checking if we can actually acquire
2198 * it, so that we don't lose any event.
2200 * Note: strictly speaking this actually watches for the
2201 * device being closed, it does *not* really watch whether a
2202 * tty loses its controlling process. However, unless some
2203 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2204 * its tty otherwise this will not become a problem. As long
2205 * as the administrator makes sure not configure any service
2206 * on the same tty as an untrusted user this should not be a
2207 * problem. (Which he probably should not do anyway.) */
2209 if (timeout != (usec_t) -1)
2210 ts = now(CLOCK_MONOTONIC);
2212 if (!fail && !force) {
2213 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2219 wd = inotify_add_watch(notify, name, IN_CLOSE);
2228 r = flush_fd(notify);
2233 /* We pass here O_NOCTTY only so that we can check the return
2234 * value TIOCSCTTY and have a reliable way to figure out if we
2235 * successfully became the controlling process of the tty */
2236 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2240 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2241 * if we already own the tty. */
2243 sa_new.sa_handler = SIG_IGN;
2244 sa_new.sa_flags = SA_RESTART;
2245 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2247 /* First, try to get the tty */
2248 if (ioctl(fd, TIOCSCTTY, force) < 0)
2251 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2253 /* Sometimes it makes sense to ignore TIOCSCTTY
2254 * returning EPERM, i.e. when very likely we already
2255 * are have this controlling terminal. */
2256 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2259 if (r < 0 && (force || fail || r != -EPERM)) {
2268 assert(notify >= 0);
2271 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2273 struct inotify_event *e;
2275 if (timeout != (usec_t) -1) {
2278 n = now(CLOCK_MONOTONIC);
2279 if (ts + timeout < n) {
2284 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2294 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2297 if (errno == EINTR || errno == EAGAIN)
2304 e = (struct inotify_event*) inotify_buffer;
2309 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2314 step = sizeof(struct inotify_event) + e->len;
2315 assert(step <= (size_t) l);
2317 e = (struct inotify_event*) ((uint8_t*) e + step);
2324 /* We close the tty fd here since if the old session
2325 * ended our handle will be dead. It's important that
2326 * we do this after sleeping, so that we don't enter
2327 * an endless loop. */
2328 close_nointr_nofail(fd);
2332 close_nointr_nofail(notify);
2334 r = reset_terminal_fd(fd, true);
2336 log_warning("Failed to reset terminal: %s", strerror(-r));
2342 close_nointr_nofail(fd);
2345 close_nointr_nofail(notify);
2350 int release_terminal(void) {
2352 struct sigaction sa_old, sa_new;
2354 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2357 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2358 * by our own TIOCNOTTY */
2361 sa_new.sa_handler = SIG_IGN;
2362 sa_new.sa_flags = SA_RESTART;
2363 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2365 if (ioctl(fd, TIOCNOTTY) < 0)
2368 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2370 close_nointr_nofail(fd);
2374 int sigaction_many(const struct sigaction *sa, ...) {
2379 while ((sig = va_arg(ap, int)) > 0)
2380 if (sigaction(sig, sa, NULL) < 0)
2387 int ignore_signals(int sig, ...) {
2388 struct sigaction sa;
2393 sa.sa_handler = SIG_IGN;
2394 sa.sa_flags = SA_RESTART;
2396 if (sigaction(sig, &sa, NULL) < 0)
2400 while ((sig = va_arg(ap, int)) > 0)
2401 if (sigaction(sig, &sa, NULL) < 0)
2408 int default_signals(int sig, ...) {
2409 struct sigaction sa;
2414 sa.sa_handler = SIG_DFL;
2415 sa.sa_flags = SA_RESTART;
2417 if (sigaction(sig, &sa, NULL) < 0)
2421 while ((sig = va_arg(ap, int)) > 0)
2422 if (sigaction(sig, &sa, NULL) < 0)
2429 int close_pipe(int p[]) {
2435 a = close_nointr(p[0]);
2440 b = close_nointr(p[1]);
2444 return a < 0 ? a : b;
2447 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2456 while (nbytes > 0) {
2459 if ((k = read(fd, p, nbytes)) <= 0) {
2461 if (k < 0 && errno == EINTR)
2464 if (k < 0 && errno == EAGAIN && do_poll) {
2465 struct pollfd pollfd;
2469 pollfd.events = POLLIN;
2471 if (poll(&pollfd, 1, -1) < 0) {
2475 return n > 0 ? n : -errno;
2478 if (pollfd.revents != POLLIN)
2479 return n > 0 ? n : -EIO;
2484 return n > 0 ? n : (k < 0 ? -errno : 0);
2495 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2504 while (nbytes > 0) {
2507 k = write(fd, p, nbytes);
2510 if (k < 0 && errno == EINTR)
2513 if (k < 0 && errno == EAGAIN && do_poll) {
2514 struct pollfd pollfd;
2518 pollfd.events = POLLOUT;
2520 if (poll(&pollfd, 1, -1) < 0) {
2524 return n > 0 ? n : -errno;
2527 if (pollfd.revents != POLLOUT)
2528 return n > 0 ? n : -EIO;
2533 return n > 0 ? n : (k < 0 ? -errno : 0);
2544 int parse_bytes(const char *t, off_t *bytes) {
2545 static const struct {
2551 { "M", 1024ULL*1024ULL },
2552 { "G", 1024ULL*1024ULL*1024ULL },
2553 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2554 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2555 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2572 l = strtoll(p, &e, 10);
2583 e += strspn(e, WHITESPACE);
2585 for (i = 0; i < ELEMENTSOF(table); i++)
2586 if (startswith(e, table[i].suffix)) {
2587 r += (off_t) l * table[i].factor;
2588 p = e + strlen(table[i].suffix);
2592 if (i >= ELEMENTSOF(table))
2602 int make_stdio(int fd) {
2607 r = dup3(fd, STDIN_FILENO, 0);
2608 s = dup3(fd, STDOUT_FILENO, 0);
2609 t = dup3(fd, STDERR_FILENO, 0);
2612 close_nointr_nofail(fd);
2614 if (r < 0 || s < 0 || t < 0)
2617 /* We rely here that the new fd has O_CLOEXEC not set */
2622 int make_null_stdio(void) {
2625 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2629 return make_stdio(null_fd);
2632 bool is_device_path(const char *path) {
2634 /* Returns true on paths that refer to a device, either in
2635 * sysfs or in /dev */
2638 path_startswith(path, "/dev/") ||
2639 path_startswith(path, "/sys/");
2642 int dir_is_empty(const char *path) {
2643 _cleanup_closedir_ DIR *d;
2652 union dirent_storage buf;
2654 r = readdir_r(d, &buf.de, &de);
2661 if (!ignore_file(de->d_name))
2666 unsigned long long random_ull(void) {
2667 _cleanup_close_ int fd;
2671 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2675 r = loop_read(fd, &ull, sizeof(ull), true);
2676 if (r != sizeof(ull))
2682 return random() * RAND_MAX + random();
2685 void rename_process(const char name[8]) {
2688 /* This is a like a poor man's setproctitle(). It changes the
2689 * comm field, argv[0], and also the glibc's internally used
2690 * name of the process. For the first one a limit of 16 chars
2691 * applies, to the second one usually one of 10 (i.e. length
2692 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2693 * "systemd"). If you pass a longer string it will be
2696 prctl(PR_SET_NAME, name);
2698 if (program_invocation_name)
2699 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2701 if (saved_argc > 0) {
2705 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2707 for (i = 1; i < saved_argc; i++) {
2711 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2716 void sigset_add_many(sigset_t *ss, ...) {
2723 while ((sig = va_arg(ap, int)) > 0)
2724 assert_se(sigaddset(ss, sig) == 0);
2728 char* gethostname_malloc(void) {
2731 assert_se(uname(&u) >= 0);
2733 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2734 return strdup(u.nodename);
2736 return strdup(u.sysname);
2739 bool hostname_is_set(void) {
2742 assert_se(uname(&u) >= 0);
2744 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2747 static char *lookup_uid(uid_t uid) {
2750 _cleanup_free_ char *buf = NULL;
2751 struct passwd pwbuf, *pw = NULL;
2753 /* Shortcut things to avoid NSS lookups */
2755 return strdup("root");
2757 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2761 buf = malloc(bufsize);
2765 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2766 return strdup(pw->pw_name);
2768 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2774 char* getlogname_malloc(void) {
2778 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2783 return lookup_uid(uid);
2786 char *getusername_malloc(void) {
2793 return lookup_uid(getuid());
2796 int getttyname_malloc(int fd, char **r) {
2797 char path[PATH_MAX], *c;
2802 k = ttyname_r(fd, path, sizeof(path));
2808 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2816 int getttyname_harder(int fd, char **r) {
2820 k = getttyname_malloc(fd, &s);
2824 if (streq(s, "tty")) {
2826 return get_ctty(0, NULL, r);
2833 int get_ctty_devnr(pid_t pid, dev_t *d) {
2835 char line[LINE_MAX], *p, *fn;
2836 unsigned long ttynr;
2839 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2842 f = fopen(fn, "re");
2847 if (!fgets(line, sizeof(line), f)) {
2848 k = feof(f) ? -EIO : -errno;
2855 p = strrchr(line, ')');
2865 "%*d " /* session */
2870 if (major(ttynr) == 0 && minor(ttynr) == 0)
2877 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2879 char fn[PATH_MAX], *s, *b, *p;
2884 k = get_ctty_devnr(pid, &devnr);
2888 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2891 k = readlink_malloc(fn, &s);
2897 /* This is an ugly hack */
2898 if (major(devnr) == 136) {
2899 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2909 /* Probably something like the ptys which have no
2910 * symlink in /dev/char. Let's return something
2911 * vaguely useful. */
2924 if (startswith(s, "/dev/"))
2926 else if (startswith(s, "../"))
2944 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2950 /* This returns the first error we run into, but nevertheless
2951 * tries to go on. This closes the passed fd. */
2955 close_nointr_nofail(fd);
2957 return errno == ENOENT ? 0 : -errno;
2962 union dirent_storage buf;
2963 bool is_dir, keep_around;
2967 r = readdir_r(d, &buf.de, &de);
2968 if (r != 0 && ret == 0) {
2976 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2979 if (de->d_type == DT_UNKNOWN ||
2981 (de->d_type == DT_DIR && root_dev)) {
2982 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2983 if (ret == 0 && errno != ENOENT)
2988 is_dir = S_ISDIR(st.st_mode);
2991 (st.st_uid == 0 || st.st_uid == getuid()) &&
2992 (st.st_mode & S_ISVTX);
2994 is_dir = de->d_type == DT_DIR;
2995 keep_around = false;
3001 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3002 if (root_dev && st.st_dev != root_dev->st_dev)
3005 subdir_fd = openat(fd, de->d_name,
3006 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3007 if (subdir_fd < 0) {
3008 if (ret == 0 && errno != ENOENT)
3013 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3014 if (r < 0 && ret == 0)
3018 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3019 if (ret == 0 && errno != ENOENT)
3023 } else if (!only_dirs && !keep_around) {
3025 if (unlinkat(fd, de->d_name, 0) < 0) {
3026 if (ret == 0 && errno != ENOENT)
3037 static int is_temporary_fs(struct statfs *s) {
3039 return s->f_type == TMPFS_MAGIC ||
3040 (long)s->f_type == (long)RAMFS_MAGIC;
3043 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3048 if (fstatfs(fd, &s) < 0) {
3049 close_nointr_nofail(fd);
3053 /* We refuse to clean disk file systems with this call. This
3054 * is extra paranoia just to be sure we never ever remove
3056 if (!is_temporary_fs(&s)) {
3057 log_error("Attempted to remove disk file system, and we can't allow that.");
3058 close_nointr_nofail(fd);
3062 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3065 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3071 /* We refuse to clean the root file system with this
3072 * call. This is extra paranoia to never cause a really
3073 * seriously broken system. */
3074 if (path_equal(path, "/")) {
3075 log_error("Attempted to remove entire root file system, and we can't allow that.");
3079 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3082 if (errno != ENOTDIR)
3086 if (statfs(path, &s) < 0)
3089 if (!is_temporary_fs(&s)) {
3090 log_error("Attempted to remove disk file system, and we can't allow that.");
3095 if (delete_root && !only_dirs)
3096 if (unlink(path) < 0 && errno != ENOENT)
3103 if (fstatfs(fd, &s) < 0) {
3104 close_nointr_nofail(fd);
3108 if (!is_temporary_fs(&s)) {
3109 log_error("Attempted to remove disk file system, and we can't allow that.");
3110 close_nointr_nofail(fd);
3115 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3118 if (honour_sticky && file_is_priv_sticky(path) > 0)
3121 if (rmdir(path) < 0 && errno != ENOENT) {
3130 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3131 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3134 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3135 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3138 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3141 /* Under the assumption that we are running privileged we
3142 * first change the access mode and only then hand out
3143 * ownership to avoid a window where access is too open. */
3145 if (mode != (mode_t) -1)
3146 if (chmod(path, mode) < 0)
3149 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3150 if (chown(path, uid, gid) < 0)
3156 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3159 /* Under the assumption that we are running privileged we
3160 * first change the access mode and only then hand out
3161 * ownership to avoid a window where access is too open. */
3163 if (fchmod(fd, mode) < 0)
3166 if (fchown(fd, uid, gid) < 0)
3172 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3176 /* Allocates the cpuset in the right size */
3179 if (!(r = CPU_ALLOC(n)))
3182 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3183 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3193 if (errno != EINVAL)
3200 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3201 static const char status_indent[] = " "; /* "[" STATUS "] " */
3202 _cleanup_free_ char *s = NULL;
3203 _cleanup_close_ int fd = -1;
3204 struct iovec iovec[5];
3209 /* This is independent of logging, as status messages are
3210 * optional and go exclusively to the console. */
3212 if (vasprintf(&s, format, ap) < 0)
3215 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3228 sl = status ? sizeof(status_indent)-1 : 0;
3234 e = ellipsize(s, emax, 75);
3244 if (!isempty(status)) {
3245 IOVEC_SET_STRING(iovec[n++], "[");
3246 IOVEC_SET_STRING(iovec[n++], status);
3247 IOVEC_SET_STRING(iovec[n++], "] ");
3249 IOVEC_SET_STRING(iovec[n++], status_indent);
3252 IOVEC_SET_STRING(iovec[n++], s);
3253 IOVEC_SET_STRING(iovec[n++], "\n");
3255 if (writev(fd, iovec, n) < 0)
3261 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3267 va_start(ap, format);
3268 r = status_vprintf(status, ellipse, format, ap);
3274 int status_welcome(void) {
3276 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3278 r = parse_env_file("/etc/os-release", NEWLINE,
3279 "PRETTY_NAME", &pretty_name,
3280 "ANSI_COLOR", &ansi_color,
3282 if (r < 0 && r != -ENOENT)
3283 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3285 return status_printf(NULL, false,
3286 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3287 isempty(ansi_color) ? "1" : ansi_color,
3288 isempty(pretty_name) ? "Linux" : pretty_name);
3291 char *replace_env(const char *format, char **env) {
3298 const char *e, *word = format;
3303 for (e = format; *e; e ++) {
3314 if (!(k = strnappend(r, word, e-word-1)))
3323 } else if (*e == '$') {
3324 if (!(k = strnappend(r, word, e-word)))
3340 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3343 if (!(k = strappend(r, t)))
3356 if (!(k = strnappend(r, word, e-word)))
3367 char **replace_env_argv(char **argv, char **env) {
3369 unsigned k = 0, l = 0;
3371 l = strv_length(argv);
3373 if (!(r = new(char*, l+1)))
3376 STRV_FOREACH(i, argv) {
3378 /* If $FOO appears as single word, replace it by the split up variable */
3379 if ((*i)[0] == '$' && (*i)[1] != '{') {
3384 if ((e = strv_env_get(env, *i+1))) {
3386 if (!(m = strv_split_quoted(e))) {
3397 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3406 memcpy(r + k, m, q * sizeof(char*));
3414 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3415 if (!(r[k++] = replace_env(*i, env))) {
3425 int fd_columns(int fd) {
3429 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3438 unsigned columns(void) {
3442 if (_likely_(cached_columns > 0))
3443 return cached_columns;
3446 e = getenv("COLUMNS");
3451 c = fd_columns(STDOUT_FILENO);
3460 int fd_lines(int fd) {
3464 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3473 unsigned lines(void) {
3477 if (_likely_(cached_lines > 0))
3478 return cached_lines;
3481 e = getenv("LINES");
3486 l = fd_lines(STDOUT_FILENO);
3492 return cached_lines;
3495 /* intended to be used as a SIGWINCH sighandler */
3496 void columns_lines_cache_reset(int signum) {
3502 static int cached_on_tty = -1;
3504 if (_unlikely_(cached_on_tty < 0))
3505 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3507 return cached_on_tty;
3510 int running_in_chroot(void) {
3516 /* Only works as root */
3518 if (stat("/proc/1/root", &a) < 0)
3521 if (stat("/", &b) < 0)
3525 a.st_dev != b.st_dev ||
3526 a.st_ino != b.st_ino;
3529 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3534 assert(percent <= 100);
3535 assert(new_length >= 3);
3537 if (old_length <= 3 || old_length <= new_length)
3538 return strndup(s, old_length);
3540 r = new0(char, new_length+1);
3544 x = (new_length * percent) / 100;
3546 if (x > new_length - 3)
3554 s + old_length - (new_length - x - 3),
3555 new_length - x - 3);
3560 char *ellipsize(const char *s, size_t length, unsigned percent) {
3561 return ellipsize_mem(s, strlen(s), length, percent);
3564 int touch(const char *path) {
3569 /* This just opens the file for writing, ensuring it
3570 * exists. It doesn't call utimensat() the way /usr/bin/touch
3573 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3577 close_nointr_nofail(fd);
3581 char *unquote(const char *s, const char* quotes) {
3585 /* This is rather stupid, simply removes the heading and
3586 * trailing quotes if there is one. Doesn't care about
3587 * escaping or anything. We should make this smarter one
3594 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3595 return strndup(s+1, l-2);
3600 char *normalize_env_assignment(const char *s) {
3601 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3604 eq = strchr(s, '=');
3616 memmove(r, t, strlen(t) + 1);
3620 name = strndup(s, eq - s);
3628 value = unquote(strstrip(p), QUOTES);
3632 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3638 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3649 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3661 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3668 r = wait_for_terminate(pid, &status);
3670 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3674 if (status.si_code == CLD_EXITED) {
3675 if (status.si_status != 0) {
3676 log_warning("%s failed with error code %i.", name, status.si_status);
3677 return status.si_status;
3680 log_debug("%s succeeded.", name);
3683 } else if (status.si_code == CLD_KILLED ||
3684 status.si_code == CLD_DUMPED) {
3686 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3690 log_warning("%s failed due to unknown reason.", name);
3694 _noreturn_ void freeze(void) {
3696 /* Make sure nobody waits for us on a socket anymore */
3697 close_all_fds(NULL, 0);
3705 bool null_or_empty(struct stat *st) {
3708 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3711 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3717 int null_or_empty_path(const char *fn) {
3722 if (stat(fn, &st) < 0)
3725 return null_or_empty(&st);
3728 DIR *xopendirat(int fd, const char *name, int flags) {
3732 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3738 close_nointr_nofail(nfd);
3745 int signal_from_string_try_harder(const char *s) {
3749 signo = signal_from_string(s);
3751 if (startswith(s, "SIG"))
3752 return signal_from_string(s+3);
3757 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3761 /* FIXME: to follow udev's logic 100% we need to leave valid
3762 * UTF8 chars unescaped */
3764 u = unquote(tagvalue, "\"\'");
3768 t = xescape(u, "/ ");
3774 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3783 char *fstab_node_to_udev_node(const char *p) {
3786 if (startswith(p, "LABEL="))
3787 return tag_to_udev_node(p+6, "label");
3789 if (startswith(p, "UUID="))
3790 return tag_to_udev_node(p+5, "uuid");
3792 if (startswith(p, "PARTUUID="))
3793 return tag_to_udev_node(p+9, "partuuid");
3795 if (startswith(p, "PARTLABEL="))
3796 return tag_to_udev_node(p+10, "partlabel");
3801 bool tty_is_vc(const char *tty) {
3804 if (startswith(tty, "/dev/"))
3807 return vtnr_from_tty(tty) >= 0;
3810 bool tty_is_console(const char *tty) {
3813 if (startswith(tty, "/dev/"))
3816 return streq(tty, "console");
3819 int vtnr_from_tty(const char *tty) {
3824 if (startswith(tty, "/dev/"))
3827 if (!startswith(tty, "tty") )
3830 if (tty[3] < '0' || tty[3] > '9')
3833 r = safe_atoi(tty+3, &i);
3837 if (i < 0 || i > 63)
3843 bool tty_is_vc_resolve(const char *tty) {
3844 char *active = NULL;
3849 if (startswith(tty, "/dev/"))
3852 /* Resolve where /dev/console is pointing to, if /sys is
3853 * actually ours (i.e. not read-only-mounted which is a sign
3854 * for container setups) */
3855 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3856 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3857 /* If multiple log outputs are configured the
3858 * last one is what /dev/console points to */
3859 tty = strrchr(active, ' ');
3872 const char *default_term_for_tty(const char *tty) {
3875 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3878 bool dirent_is_file(const struct dirent *de) {
3881 if (ignore_file(de->d_name))
3884 if (de->d_type != DT_REG &&
3885 de->d_type != DT_LNK &&
3886 de->d_type != DT_UNKNOWN)
3892 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3895 if (de->d_type != DT_REG &&
3896 de->d_type != DT_LNK &&
3897 de->d_type != DT_UNKNOWN)
3900 if (ignore_file_allow_backup(de->d_name))
3903 return endswith(de->d_name, suffix);
3906 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3909 Hashmap *pids = NULL;
3913 /* Executes all binaries in a directory in parallel and waits
3914 * until all they all finished. */
3917 if (!(_d = opendir(directory))) {
3919 if (errno == ENOENT)
3922 log_error("Failed to enumerate directory %s: %m", directory);
3929 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3930 log_error("Failed to allocate set.");
3934 while ((de = readdir(d))) {
3939 if (!dirent_is_file(de))
3942 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3947 if ((pid = fork()) < 0) {
3948 log_error("Failed to fork: %m");
3966 log_error("Failed to execute %s: %m", path);
3967 _exit(EXIT_FAILURE);
3970 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3972 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3973 log_error("Failed to add PID to set: %s", strerror(-k));
3978 while (!hashmap_isempty(pids)) {
3979 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3984 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3989 log_error("waitid() failed: %m");
3993 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3994 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3995 if (si.si_code == CLD_EXITED)
3996 log_error("%s exited with exit status %i.", path, si.si_status);
3998 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4000 log_debug("%s exited successfully.", path);
4011 hashmap_free_free(pids);
4014 int kill_and_sigcont(pid_t pid, int sig) {
4017 r = kill(pid, sig) < 0 ? -errno : 0;
4025 bool nulstr_contains(const char*nulstr, const char *needle) {
4031 NULSTR_FOREACH(i, nulstr)
4032 if (streq(i, needle))
4038 bool plymouth_running(void) {
4039 return access("/run/plymouth/pid", F_OK) >= 0;
4042 char* strshorten(char *s, size_t l) {
4051 static bool hostname_valid_char(char c) {
4053 (c >= 'a' && c <= 'z') ||
4054 (c >= 'A' && c <= 'Z') ||
4055 (c >= '0' && c <= '9') ||
4061 bool hostname_is_valid(const char *s) {
4067 for (p = s; *p; p++)
4068 if (!hostname_valid_char(*p))
4071 if (p-s > HOST_NAME_MAX)
4077 char* hostname_cleanup(char *s) {
4080 for (p = s, d = s; *p; p++)
4081 if ((*p >= 'a' && *p <= 'z') ||
4082 (*p >= 'A' && *p <= 'Z') ||
4083 (*p >= '0' && *p <= '9') ||
4091 strshorten(s, HOST_NAME_MAX);
4095 int pipe_eof(int fd) {
4096 struct pollfd pollfd;
4101 pollfd.events = POLLIN|POLLHUP;
4103 r = poll(&pollfd, 1, 0);
4110 return pollfd.revents & POLLHUP;
4113 int fd_wait_for_event(int fd, int event, usec_t t) {
4114 struct pollfd pollfd;
4119 pollfd.events = event;
4121 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4128 return pollfd.revents;
4131 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4142 t = new(char, strlen(path) + 1 + 6 + 1);
4146 fn = path_get_file_name(path);
4150 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4152 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4158 f = fdopen(fd, "we");
4171 int terminal_vhangup_fd(int fd) {
4174 if (ioctl(fd, TIOCVHANGUP) < 0)
4180 int terminal_vhangup(const char *name) {
4183 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4187 r = terminal_vhangup_fd(fd);
4188 close_nointr_nofail(fd);
4193 int vt_disallocate(const char *name) {
4197 /* Deallocate the VT if possible. If not possible
4198 * (i.e. because it is the active one), at least clear it
4199 * entirely (including the scrollback buffer) */
4201 if (!startswith(name, "/dev/"))
4204 if (!tty_is_vc(name)) {
4205 /* So this is not a VT. I guess we cannot deallocate
4206 * it then. But let's at least clear the screen */
4208 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4213 "\033[r" /* clear scrolling region */
4214 "\033[H" /* move home */
4215 "\033[2J", /* clear screen */
4217 close_nointr_nofail(fd);
4222 if (!startswith(name, "/dev/tty"))
4225 r = safe_atou(name+8, &u);
4232 /* Try to deallocate */
4233 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4237 r = ioctl(fd, VT_DISALLOCATE, u);
4238 close_nointr_nofail(fd);
4246 /* Couldn't deallocate, so let's clear it fully with
4248 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4253 "\033[r" /* clear scrolling region */
4254 "\033[H" /* move home */
4255 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4257 close_nointr_nofail(fd);
4262 int copy_file(const char *from, const char *to) {
4268 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4272 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4274 close_nointr_nofail(fdf);
4282 n = read(fdf, buf, sizeof(buf));
4286 close_nointr_nofail(fdf);
4297 k = loop_write(fdt, buf, n, false);
4299 r = k < 0 ? k : (errno ? -errno : -EIO);
4301 close_nointr_nofail(fdf);
4309 close_nointr_nofail(fdf);
4310 r = close_nointr(fdt);
4320 int symlink_atomic(const char *from, const char *to) {
4322 _cleanup_free_ char *t;
4325 unsigned long long ull;
4332 t = new(char, strlen(to) + 1 + 16 + 1);
4336 fn = path_get_file_name(to);
4340 x = stpcpy(t+k+1, fn);
4343 for (i = 0; i < 16; i++) {
4344 *(x++) = hexchar(ull & 0xF);
4350 if (symlink(from, t) < 0)
4353 if (rename(t, to) < 0) {
4362 bool display_is_local(const char *display) {
4366 display[0] == ':' &&
4367 display[1] >= '0' &&
4371 int socket_from_display(const char *display, char **path) {
4378 if (!display_is_local(display))
4381 k = strspn(display+1, "0123456789");
4383 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4387 c = stpcpy(f, "/tmp/.X11-unix/X");
4388 memcpy(c, display+1, k);
4397 const char **username,
4398 uid_t *uid, gid_t *gid,
4400 const char **shell) {
4408 /* We enforce some special rules for uid=0: in order to avoid
4409 * NSS lookups for root we hardcode its data. */
4411 if (streq(*username, "root") || streq(*username, "0")) {
4429 if (parse_uid(*username, &u) >= 0) {
4433 /* If there are multiple users with the same id, make
4434 * sure to leave $USER to the configured value instead
4435 * of the first occurrence in the database. However if
4436 * the uid was configured by a numeric uid, then let's
4437 * pick the real username from /etc/passwd. */
4439 *username = p->pw_name;
4442 p = getpwnam(*username);
4446 return errno != 0 ? -errno : -ESRCH;
4458 *shell = p->pw_shell;
4463 char* uid_to_name(uid_t uid) {
4468 return strdup("root");
4472 return strdup(p->pw_name);
4474 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4480 int get_group_creds(const char **groupname, gid_t *gid) {
4486 /* We enforce some special rules for gid=0: in order to avoid
4487 * NSS lookups for root we hardcode its data. */
4489 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4490 *groupname = "root";
4498 if (parse_gid(*groupname, &id) >= 0) {
4503 *groupname = g->gr_name;
4506 g = getgrnam(*groupname);
4510 return errno != 0 ? -errno : -ESRCH;
4518 int in_group(const char *name) {
4520 int ngroups_max, r, i;
4522 r = get_group_creds(&name, &gid);
4526 if (getgid() == gid)
4529 if (getegid() == gid)
4532 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4533 assert(ngroups_max > 0);
4535 gids = alloca(sizeof(gid_t) * ngroups_max);
4537 r = getgroups(ngroups_max, gids);
4541 for (i = 0; i < r; i++)
4548 int glob_exists(const char *path) {
4556 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4558 if (k == GLOB_NOMATCH)
4560 else if (k == GLOB_NOSPACE)
4563 r = !strv_isempty(g.gl_pathv);
4565 r = errno ? -errno : -EIO;
4572 int dirent_ensure_type(DIR *d, struct dirent *de) {
4578 if (de->d_type != DT_UNKNOWN)
4581 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4585 S_ISREG(st.st_mode) ? DT_REG :
4586 S_ISDIR(st.st_mode) ? DT_DIR :
4587 S_ISLNK(st.st_mode) ? DT_LNK :
4588 S_ISFIFO(st.st_mode) ? DT_FIFO :
4589 S_ISSOCK(st.st_mode) ? DT_SOCK :
4590 S_ISCHR(st.st_mode) ? DT_CHR :
4591 S_ISBLK(st.st_mode) ? DT_BLK :
4597 int in_search_path(const char *path, char **search) {
4601 r = path_get_parent(path, &parent);
4607 STRV_FOREACH(i, search) {
4608 if (path_equal(parent, *i)) {
4619 int get_files_in_directory(const char *path, char ***list) {
4627 /* Returns all files in a directory in *list, and the number
4628 * of files as return value. If list is NULL returns only the
4637 union dirent_storage buf;
4640 k = readdir_r(d, &buf.de, &de);
4649 dirent_ensure_type(d, de);
4651 if (!dirent_is_file(de))
4655 if ((unsigned) r >= n) {
4659 t = realloc(l, sizeof(char*) * n);
4668 assert((unsigned) r < n);
4670 l[r] = strdup(de->d_name);
4694 char *strjoin(const char *x, ...) {
4708 t = va_arg(ap, const char *);
4713 if (n > ((size_t) -1) - l) {
4737 t = va_arg(ap, const char *);
4751 bool is_main_thread(void) {
4752 static __thread int cached = 0;
4754 if (_unlikely_(cached == 0))
4755 cached = getpid() == gettid() ? 1 : -1;
4760 int block_get_whole_disk(dev_t d, dev_t *ret) {
4767 /* If it has a queue this is good enough for us */
4768 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4771 r = access(p, F_OK);
4779 /* If it is a partition find the originating device */
4780 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4783 r = access(p, F_OK);
4789 /* Get parent dev_t */
4790 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4793 r = read_one_line_file(p, &s);
4799 r = sscanf(s, "%u:%u", &m, &n);
4805 /* Only return this if it is really good enough for us. */
4806 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4809 r = access(p, F_OK);
4813 *ret = makedev(m, n);
4820 int file_is_priv_sticky(const char *p) {
4825 if (lstat(p, &st) < 0)
4829 (st.st_uid == 0 || st.st_uid == getuid()) &&
4830 (st.st_mode & S_ISVTX);
4833 static const char *const ioprio_class_table[] = {
4834 [IOPRIO_CLASS_NONE] = "none",
4835 [IOPRIO_CLASS_RT] = "realtime",
4836 [IOPRIO_CLASS_BE] = "best-effort",
4837 [IOPRIO_CLASS_IDLE] = "idle"
4840 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4842 static const char *const sigchld_code_table[] = {
4843 [CLD_EXITED] = "exited",
4844 [CLD_KILLED] = "killed",
4845 [CLD_DUMPED] = "dumped",
4846 [CLD_TRAPPED] = "trapped",
4847 [CLD_STOPPED] = "stopped",
4848 [CLD_CONTINUED] = "continued",
4851 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4853 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4854 [LOG_FAC(LOG_KERN)] = "kern",
4855 [LOG_FAC(LOG_USER)] = "user",
4856 [LOG_FAC(LOG_MAIL)] = "mail",
4857 [LOG_FAC(LOG_DAEMON)] = "daemon",
4858 [LOG_FAC(LOG_AUTH)] = "auth",
4859 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4860 [LOG_FAC(LOG_LPR)] = "lpr",
4861 [LOG_FAC(LOG_NEWS)] = "news",
4862 [LOG_FAC(LOG_UUCP)] = "uucp",
4863 [LOG_FAC(LOG_CRON)] = "cron",
4864 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4865 [LOG_FAC(LOG_FTP)] = "ftp",
4866 [LOG_FAC(LOG_LOCAL0)] = "local0",
4867 [LOG_FAC(LOG_LOCAL1)] = "local1",
4868 [LOG_FAC(LOG_LOCAL2)] = "local2",
4869 [LOG_FAC(LOG_LOCAL3)] = "local3",
4870 [LOG_FAC(LOG_LOCAL4)] = "local4",
4871 [LOG_FAC(LOG_LOCAL5)] = "local5",
4872 [LOG_FAC(LOG_LOCAL6)] = "local6",
4873 [LOG_FAC(LOG_LOCAL7)] = "local7"
4876 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4878 static const char *const log_level_table[] = {
4879 [LOG_EMERG] = "emerg",
4880 [LOG_ALERT] = "alert",
4881 [LOG_CRIT] = "crit",
4883 [LOG_WARNING] = "warning",
4884 [LOG_NOTICE] = "notice",
4885 [LOG_INFO] = "info",
4886 [LOG_DEBUG] = "debug"
4889 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4891 static const char* const sched_policy_table[] = {
4892 [SCHED_OTHER] = "other",
4893 [SCHED_BATCH] = "batch",
4894 [SCHED_IDLE] = "idle",
4895 [SCHED_FIFO] = "fifo",
4899 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4901 static const char* const rlimit_table[] = {
4902 [RLIMIT_CPU] = "LimitCPU",
4903 [RLIMIT_FSIZE] = "LimitFSIZE",
4904 [RLIMIT_DATA] = "LimitDATA",
4905 [RLIMIT_STACK] = "LimitSTACK",
4906 [RLIMIT_CORE] = "LimitCORE",
4907 [RLIMIT_RSS] = "LimitRSS",
4908 [RLIMIT_NOFILE] = "LimitNOFILE",
4909 [RLIMIT_AS] = "LimitAS",
4910 [RLIMIT_NPROC] = "LimitNPROC",
4911 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4912 [RLIMIT_LOCKS] = "LimitLOCKS",
4913 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4914 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4915 [RLIMIT_NICE] = "LimitNICE",
4916 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4917 [RLIMIT_RTTIME] = "LimitRTTIME"
4920 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4922 static const char* const ip_tos_table[] = {
4923 [IPTOS_LOWDELAY] = "low-delay",
4924 [IPTOS_THROUGHPUT] = "throughput",
4925 [IPTOS_RELIABILITY] = "reliability",
4926 [IPTOS_LOWCOST] = "low-cost",
4929 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4931 static const char *const __signal_table[] = {
4948 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4959 [SIGVTALRM] = "VTALRM",
4961 [SIGWINCH] = "WINCH",
4967 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4969 const char *signal_to_string(int signo) {
4970 static __thread char buf[12];
4973 name = __signal_to_string(signo);
4977 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4978 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4980 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4985 int signal_from_string(const char *s) {
4990 signo = __signal_from_string(s);
4994 if (startswith(s, "RTMIN+")) {
4998 if (safe_atou(s, &u) >= 0) {
4999 signo = (int) u + offset;
5000 if (signo > 0 && signo < _NSIG)
5006 bool kexec_loaded(void) {
5007 bool loaded = false;
5010 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5018 int strdup_or_null(const char *a, char **b) {
5036 int prot_from_flags(int flags) {
5038 switch (flags & O_ACCMODE) {
5047 return PROT_READ|PROT_WRITE;
5054 char *format_bytes(char *buf, size_t l, off_t t) {
5057 static const struct {
5061 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5062 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5063 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5064 { "G", 1024ULL*1024ULL*1024ULL },
5065 { "M", 1024ULL*1024ULL },
5069 for (i = 0; i < ELEMENTSOF(table); i++) {
5071 if (t >= table[i].factor) {
5074 (unsigned long long) (t / table[i].factor),
5075 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5082 snprintf(buf, l, "%lluB", (unsigned long long) t);
5090 void* memdup(const void *p, size_t l) {
5103 int fd_inc_sndbuf(int fd, size_t n) {
5105 socklen_t l = sizeof(value);
5107 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5109 l == sizeof(value) &&
5110 (size_t) value >= n*2)
5114 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5121 int fd_inc_rcvbuf(int fd, size_t n) {
5123 socklen_t l = sizeof(value);
5125 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5127 l == sizeof(value) &&
5128 (size_t) value >= n*2)
5132 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5139 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5140 pid_t parent_pid, agent_pid;
5142 bool stdout_is_tty, stderr_is_tty;
5150 parent_pid = getpid();
5152 /* Spawns a temporary TTY agent, making sure it goes away when
5159 if (agent_pid != 0) {
5166 * Make sure the agent goes away when the parent dies */
5167 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5168 _exit(EXIT_FAILURE);
5170 /* Check whether our parent died before we were able
5171 * to set the death signal */
5172 if (getppid() != parent_pid)
5173 _exit(EXIT_SUCCESS);
5175 /* Don't leak fds to the agent */
5176 close_all_fds(except, n_except);
5178 stdout_is_tty = isatty(STDOUT_FILENO);
5179 stderr_is_tty = isatty(STDERR_FILENO);
5181 if (!stdout_is_tty || !stderr_is_tty) {
5182 /* Detach from stdout/stderr. and reopen
5183 * /dev/tty for them. This is important to
5184 * ensure that when systemctl is started via
5185 * popen() or a similar call that expects to
5186 * read EOF we actually do generate EOF and
5187 * not delay this indefinitely by because we
5188 * keep an unused copy of stdin around. */
5189 fd = open("/dev/tty", O_WRONLY);
5191 log_error("Failed to open /dev/tty: %m");
5192 _exit(EXIT_FAILURE);
5196 dup2(fd, STDOUT_FILENO);
5199 dup2(fd, STDERR_FILENO);
5205 /* Count arguments */
5207 for (n = 0; va_arg(ap, char*); n++)
5212 l = alloca(sizeof(char *) * (n + 1));
5214 /* Fill in arguments */
5216 for (i = 0; i <= n; i++)
5217 l[i] = va_arg(ap, char*);
5221 _exit(EXIT_FAILURE);
5224 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5225 struct rlimit highest, fixed;
5229 if (setrlimit(resource, rlim) >= 0)
5235 /* So we failed to set the desired setrlimit, then let's try
5236 * to get as close as we can */
5237 assert_se(getrlimit(resource, &highest) == 0);
5239 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5240 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5242 if (setrlimit(resource, &fixed) < 0)
5248 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5249 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5261 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5264 f = fopen(path, "re");
5272 char line[LINE_MAX];
5275 for (i = 0; i < sizeof(line)-1; i++) {
5279 if (_unlikely_(c == EOF)) {
5289 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5290 value = strdup(line + l + 1);
5310 int can_sleep(const char *type) {
5314 _cleanup_free_ char *p = NULL;
5318 /* If /sys is read-only we cannot sleep */
5319 if (access("/sys/power/state", W_OK) < 0)
5322 r = read_one_line_file("/sys/power/state", &p);
5327 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5328 if (l == k && memcmp(w, type, l) == 0)
5334 int can_sleep_disk(const char *type) {
5338 _cleanup_free_ char *p = NULL;
5342 /* If /sys is read-only we cannot sleep */
5343 if (access("/sys/power/state", W_OK) < 0 ||
5344 access("/sys/power/disk", W_OK) < 0)
5347 r = read_one_line_file("/sys/power/disk", &p);
5352 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5353 if (l == k && memcmp(w, type, l) == 0)
5356 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5363 bool is_valid_documentation_url(const char *url) {
5366 if (startswith(url, "http://") && url[7])
5369 if (startswith(url, "https://") && url[8])
5372 if (startswith(url, "file:") && url[5])
5375 if (startswith(url, "info:") && url[5])
5378 if (startswith(url, "man:") && url[4])
5384 bool in_initrd(void) {
5385 static __thread int saved = -1;
5391 /* We make two checks here:
5393 * 1. the flag file /etc/initrd-release must exist
5394 * 2. the root file system must be a memory file system
5396 * The second check is extra paranoia, since misdetecting an
5397 * initrd can have bad bad consequences due the initrd
5398 * emptying when transititioning to the main systemd.
5401 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5402 statfs("/", &s) >= 0 &&
5403 is_temporary_fs(&s);
5408 void warn_melody(void) {
5409 _cleanup_close_ int fd = -1;
5411 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5415 /* Yeah, this is synchronous. Kinda sucks. But well... */
5417 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5418 usleep(125*USEC_PER_MSEC);
5420 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5421 usleep(125*USEC_PER_MSEC);
5423 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5424 usleep(125*USEC_PER_MSEC);
5426 ioctl(fd, KIOCSOUND, 0);
5429 int make_console_stdio(void) {
5432 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5434 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5436 log_error("Failed to acquire terminal: %s", strerror(-fd));
5442 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5449 int get_home_dir(char **_h) {
5457 /* Take the user specified one */
5468 /* Hardcode home directory for root to avoid NSS */
5471 h = strdup("/root");
5479 /* Check the database... */
5483 return errno ? -errno : -ESRCH;
5485 if (!path_is_absolute(p->pw_dir))
5488 h = strdup(p->pw_dir);
5496 int get_shell(char **_sh) {
5504 /* Take the user specified one */
5505 e = getenv("SHELL");
5515 /* Hardcode home directory for root to avoid NSS */
5518 sh = strdup("/bin/sh");
5526 /* Check the database... */
5530 return errno ? -errno : -ESRCH;
5532 if (!path_is_absolute(p->pw_shell))
5535 sh = strdup(p->pw_shell);
5543 void freep(void *p) {
5547 void fclosep(FILE **f) {
5552 void closep(int *fd) {
5554 close_nointr_nofail(*fd);
5557 void closedirp(DIR **d) {
5562 void umaskp(mode_t *u) {
5566 bool filename_is_safe(const char *p) {
5580 if (strlen(p) > FILENAME_MAX)
5586 bool string_is_safe(const char *p) {
5591 for (t = p; *t; t++) {
5592 if (*t > 0 && *t < ' ')
5595 if (strchr("\\\"\'", *t))
5602 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5603 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5604 int (*compar) (const void *, const void *, void *), void *arg) {
5613 p = (void *)(((const char *) base) + (idx * size));
5614 comparison = compar(key, p, arg);
5617 else if (comparison > 0)
5625 bool is_locale_utf8(void) {
5627 static int cached_answer = -1;
5629 if (cached_answer >= 0)
5632 if (!setlocale(LC_ALL, "")) {
5633 cached_answer = true;
5637 set = nl_langinfo(CODESET);
5639 cached_answer = true;
5643 cached_answer = streq(set, "UTF-8");
5645 return (bool)cached_answer;
5648 const char *draw_special_char(DrawSpecialChar ch) {
5649 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5651 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5652 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5653 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5654 [DRAW_TREE_SPACE] = " ", /* */
5655 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5657 /* ASCII fallback */ {
5658 [DRAW_TREE_VERT] = "| ",
5659 [DRAW_TREE_BRANCH] = "|-",
5660 [DRAW_TREE_RIGHT] = "`-",
5661 [DRAW_TREE_SPACE] = " ",
5662 [DRAW_TRIANGULAR_BULLET] = "> ",
5666 return draw_table[!is_locale_utf8()][ch];
5669 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5672 size_t l, old_len, new_len;
5678 old_len = strlen(old_string);
5679 new_len = strlen(new_string);
5692 if (!startswith(f, old_string)) {
5698 nl = l - old_len + new_len;
5699 a = realloc(r, nl + 1);
5707 t = stpcpy(t, new_string);
5719 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5720 const char *i, *begin = NULL;
5725 } state = STATE_OTHER;
5727 size_t osz = 0, isz;
5733 /* Strips ANSI color and replaces TABs by 8 spaces */
5735 isz = _isz ? *_isz : strlen(*ibuf);
5737 f = open_memstream(&obuf, &osz);
5741 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5746 if (i >= *ibuf + isz) /* EOT */
5748 else if (*i == '\x1B')
5749 state = STATE_ESCAPE;
5750 else if (*i == '\t')
5757 if (i >= *ibuf + isz) { /* EOT */
5760 } else if (*i == '[') {
5761 state = STATE_BRACKET;
5766 state = STATE_OTHER;
5773 if (i >= *ibuf + isz || /* EOT */
5774 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5777 state = STATE_OTHER;
5779 } else if (*i == 'm')
5780 state = STATE_OTHER;
5802 int on_ac_power(void) {
5803 bool found_offline = false, found_online = false;
5804 _cleanup_closedir_ DIR *d = NULL;
5806 d = opendir("/sys/class/power_supply");
5812 union dirent_storage buf;
5813 _cleanup_free_ char *p = NULL;
5814 _cleanup_close_ int fd = -1, device = -1;
5819 k = readdir_r(d, &buf.de, &de);
5826 if (ignore_file(de->d_name))
5829 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5831 if (errno == ENOENT || errno == ENOTDIR)
5837 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5839 if (errno == ENOENT)
5845 n = read(fd, contents, sizeof(contents));
5849 if (n != 6 || memcmp(contents, "Mains\n", 6))
5852 close_nointr_nofail(fd);
5853 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5855 if (errno == ENOENT)
5861 n = read(fd, contents, sizeof(contents));
5865 if (n != 2 || contents[1] != '\n')
5868 if (contents[0] == '1') {
5869 found_online = true;
5871 } else if (contents[0] == '0')
5872 found_offline = true;
5877 return found_online || !found_offline;