1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
75 char **saved_argv = NULL;
77 static volatile unsigned cached_columns = 0;
78 static volatile unsigned cached_lines = 0;
80 size_t page_size(void) {
81 static __thread size_t pgsz = 0;
84 if (_likely_(pgsz > 0))
87 r = sysconf(_SC_PAGESIZE);
94 bool streq_ptr(const char *a, const char *b) {
96 /* Like streq(), but tries to make sense of NULL pointers */
107 char* endswith(const char *s, const char *postfix) {
114 pl = strlen(postfix);
117 return (char*) s + sl;
122 if (memcmp(s + sl - pl, postfix, pl) != 0)
125 return (char*) s + sl - pl;
128 char* startswith(const char *s, const char *prefix) {
145 char* startswith_no_case(const char *s, const char *prefix) {
155 if (tolower(*a) != tolower(*b))
162 bool first_word(const char *s, const char *word) {
177 if (memcmp(s, word, wl) != 0)
181 strchr(WHITESPACE, s[wl]);
184 int close_nointr(int fd) {
199 void close_nointr_nofail(int fd) {
200 int saved_errno = errno;
202 /* like close_nointr() but cannot fail, and guarantees errno
205 assert_se(close_nointr(fd) == 0);
210 void close_many(const int fds[], unsigned n_fd) {
213 for (i = 0; i < n_fd; i++)
214 close_nointr_nofail(fds[i]);
217 int parse_boolean(const char *v) {
220 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
222 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
228 int parse_pid(const char *s, pid_t* ret_pid) {
229 unsigned long ul = 0;
236 r = safe_atolu(s, &ul);
242 if ((unsigned long) pid != ul)
252 int parse_uid(const char *s, uid_t* ret_uid) {
253 unsigned long ul = 0;
260 r = safe_atolu(s, &ul);
266 if ((unsigned long) uid != ul)
273 int safe_atou(const char *s, unsigned *ret_u) {
281 l = strtoul(s, &x, 0);
283 if (!x || x == s || *x || errno)
284 return errno ? -errno : -EINVAL;
286 if ((unsigned long) (unsigned) l != l)
289 *ret_u = (unsigned) l;
293 int safe_atoi(const char *s, int *ret_i) {
301 l = strtol(s, &x, 0);
303 if (!x || x == s || *x || errno)
304 return errno ? -errno : -EINVAL;
306 if ((long) (int) l != l)
313 int safe_atollu(const char *s, long long unsigned *ret_llu) {
315 unsigned long long l;
321 l = strtoull(s, &x, 0);
323 if (!x || x == s || *x || errno)
324 return errno ? -errno : -EINVAL;
330 int safe_atolli(const char *s, long long int *ret_lli) {
338 l = strtoll(s, &x, 0);
340 if (!x || x == s || *x || errno)
341 return errno ? -errno : -EINVAL;
347 /* Split a string into words. */
348 char *split(const char *c, size_t *l, const char *separator, char **state) {
351 current = *state ? *state : (char*) c;
353 if (!*current || *c == 0)
356 current += strspn(current, separator);
357 *l = strcspn(current, separator);
360 return (char*) current;
363 /* Split a string into words, but consider strings enclosed in '' and
364 * "" as words even if they include spaces. */
365 char *split_quoted(const char *c, size_t *l, char **state) {
367 bool escaped = false;
369 current = *state ? *state : (char*) c;
371 if (!*current || *c == 0)
374 current += strspn(current, WHITESPACE);
376 if (*current == '\'') {
379 for (e = current; *e; e++) {
389 *state = *e == 0 ? e : e+1;
390 } else if (*current == '\"') {
393 for (e = current; *e; e++) {
403 *state = *e == 0 ? e : e+1;
405 for (e = current; *e; e++) {
410 else if (strchr(WHITESPACE, *e))
417 return (char*) current;
420 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
422 _cleanup_fclose_ FILE *f = NULL;
423 char fn[PATH_MAX], line[LINE_MAX], *p;
429 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
436 if (!fgets(line, sizeof(line), f)) {
437 r = feof(f) ? -EIO : -errno;
441 /* Let's skip the pid and comm fields. The latter is enclosed
442 * in () but does not escape any () in its value, so let's
443 * skip over it manually */
445 p = strrchr(line, ')');
457 if ((long unsigned) (pid_t) ppid != ppid)
460 *_ppid = (pid_t) ppid;
465 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
466 _cleanup_fclose_ FILE *f = NULL;
467 char fn[PATH_MAX], line[LINE_MAX], *p;
472 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
479 if (!fgets(line, sizeof(line), f)) {
486 /* Let's skip the pid and comm fields. The latter is enclosed
487 * in () but does not escape any () in its value, so let's
488 * skip over it manually */
490 p = strrchr(line, ')');
512 "%*d " /* priority */
514 "%*d " /* num_threads */
515 "%*d " /* itrealvalue */
516 "%llu " /* starttime */,
523 int write_one_line_file(const char *fn, const char *line) {
524 _cleanup_fclose_ FILE *f = NULL;
534 if (fputs(line, f) < 0)
535 return errno ? -errno : -EIO;
537 if (!endswith(line, "\n"))
543 return errno ? -errno : -EIO;
548 int fchmod_umask(int fd, mode_t m) {
553 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
559 int write_one_line_file_atomic(const char *fn, const char *line) {
560 _cleanup_fclose_ FILE *f = NULL;
561 _cleanup_free_ char *p = NULL;
567 r = fopen_temporary(fn, &f, &p);
571 fchmod_umask(fileno(f), 0644);
574 if (fputs(line, f) < 0) {
579 if (!endswith(line, "\n"))
585 r = errno ? -errno : -EIO;
587 if (rename(p, fn) < 0)
600 int read_one_line_file(const char *fn, char **line) {
601 _cleanup_fclose_ FILE *f = NULL;
602 char t[LINE_MAX], *c;
611 if (!fgets(t, sizeof(t), f)) {
614 return errno ? -errno : -EIO;
628 int read_full_file(const char *fn, char **contents, size_t *size) {
629 _cleanup_fclose_ FILE *f = NULL;
631 _cleanup_free_ char *buf = NULL;
641 if (fstat(fileno(f), &st) < 0)
645 if (st.st_size > 4*1024*1024)
648 n = st.st_size > 0 ? st.st_size : LINE_MAX;
655 t = realloc(buf, n+1);
660 k = fread(buf + l, 1, n - l, f);
689 const char *separator, ...) {
692 char *contents = NULL, *p;
697 if ((r = read_full_file(fname, &contents, NULL)) < 0)
702 const char *key = NULL;
704 p += strspn(p, separator);
705 p += strspn(p, WHITESPACE);
710 if (!strchr(COMMENTS, *p)) {
714 va_start(ap, separator);
715 while ((key = va_arg(ap, char *))) {
719 value = va_arg(ap, char **);
722 if (strncmp(p, key, n) != 0 ||
727 n = strcspn(p, separator);
730 strchr(QUOTES, p[0]) &&
732 v = strndup(p+1, n-2);
743 /* return empty value strings as NULL */
760 p += strcspn(p, separator);
768 int load_env_file(const char *fname,
771 FILE _cleanup_fclose_ *f;
773 char _cleanup_free_ *c = NULL;
774 char _cleanup_strv_free_ **m = NULL;
779 f = fopen(fname, "re");
784 char l[LINE_MAX], *p, *u, *cs;
787 if (!fgets(l, sizeof(l), f)) {
794 cs = endswith(l, "\\\n");
816 p = strstrip(c ? c : l);
821 if (strchr(COMMENTS, *p))
824 u = normalize_env_assignment(p);
831 t = strv_append(m, u);
847 int write_env_file(const char *fname, char **l) {
852 r = fopen_temporary(fname, &f, &p);
856 fchmod_umask(fileno(f), 0644);
872 if (rename(p, fname) < 0)
887 char *truncate_nl(char *s) {
890 s[strcspn(s, NEWLINE)] = 0;
894 int get_process_comm(pid_t pid, char **name) {
900 r = read_one_line_file("/proc/self/comm", name);
903 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
906 r = read_one_line_file(p, name);
913 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
921 f = fopen("/proc/self/cmdline", "re");
924 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
933 if (max_length == 0) {
935 while ((c = getc(f)) != EOF) {
936 k = realloc(r, len+1);
943 r[len-1] = isprint(c) ? c : ' ';
950 r = new(char, max_length);
958 while ((c = getc(f)) != EOF) {
980 size_t n = MIN(left-1, 3U);
989 /* Kernel threads have no argv[] */
990 if (r == NULL || r[0] == 0) {
999 h = get_process_comm(pid, &t);
1003 r = strjoin("[", t, "]", NULL);
1014 int is_kernel_thread(pid_t pid) {
1024 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1033 count = fread(&c, 1, 1, f);
1037 /* Kernel threads have an empty cmdline */
1040 return eof ? 1 : -errno;
1045 int get_process_exe(pid_t pid, char **name) {
1051 r = readlink_malloc("/proc/self/exe", name);
1054 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1057 r = readlink_malloc(p, name);
1064 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1074 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1084 char line[LINE_MAX], *l;
1086 if (!fgets(line, sizeof(line), f)) {
1096 if (startswith(l, field)) {
1098 l += strspn(l, WHITESPACE);
1100 l[strcspn(l, WHITESPACE)] = 0;
1102 r = parse_uid(l, uid);
1115 int get_process_uid(pid_t pid, uid_t *uid) {
1116 return get_process_id(pid, "Uid:", uid);
1119 int get_process_gid(pid_t pid, gid_t *gid) {
1120 return get_process_id(pid, "Gid:", gid);
1123 char *strnappend(const char *s, const char *suffix, size_t b) {
1131 return strndup(suffix, b);
1140 if (b > ((size_t) -1) - a)
1143 r = new(char, a+b+1);
1148 memcpy(r+a, suffix, b);
1154 char *strappend(const char *s, const char *suffix) {
1155 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1158 int readlink_malloc(const char *p, char **r) {
1168 if (!(c = new(char, l)))
1171 if ((n = readlink(p, c, l-1)) < 0) {
1177 if ((size_t) n < l-1) {
1188 int readlink_and_make_absolute(const char *p, char **r) {
1195 if ((j = readlink_malloc(p, &target)) < 0)
1198 k = file_in_same_dir(p, target);
1208 int readlink_and_canonicalize(const char *p, char **r) {
1215 j = readlink_and_make_absolute(p, &t);
1219 s = canonicalize_file_name(t);
1226 path_kill_slashes(*r);
1231 int reset_all_signal_handlers(void) {
1234 for (sig = 1; sig < _NSIG; sig++) {
1235 struct sigaction sa;
1237 if (sig == SIGKILL || sig == SIGSTOP)
1241 sa.sa_handler = SIG_DFL;
1242 sa.sa_flags = SA_RESTART;
1244 /* On Linux the first two RT signals are reserved by
1245 * glibc, and sigaction() will return EINVAL for them. */
1246 if ((sigaction(sig, &sa, NULL) < 0))
1247 if (errno != EINVAL)
1254 char *strstrip(char *s) {
1257 /* Drops trailing whitespace. Modifies the string in
1258 * place. Returns pointer to first non-space character */
1260 s += strspn(s, WHITESPACE);
1262 for (e = strchr(s, 0); e > s; e --)
1263 if (!strchr(WHITESPACE, e[-1]))
1271 char *delete_chars(char *s, const char *bad) {
1274 /* Drops all whitespace, regardless where in the string */
1276 for (f = s, t = s; *f; f++) {
1277 if (strchr(bad, *f))
1288 bool in_charset(const char *s, const char* charset) {
1294 for (i = s; *i; i++)
1295 if (!strchr(charset, *i))
1301 char *file_in_same_dir(const char *path, const char *filename) {
1308 /* This removes the last component of path and appends
1309 * filename, unless the latter is absolute anyway or the
1312 if (path_is_absolute(filename))
1313 return strdup(filename);
1315 if (!(e = strrchr(path, '/')))
1316 return strdup(filename);
1318 k = strlen(filename);
1319 if (!(r = new(char, e-path+1+k+1)))
1322 memcpy(r, path, e-path+1);
1323 memcpy(r+(e-path)+1, filename, k+1);
1328 int rmdir_parents(const char *path, const char *stop) {
1337 /* Skip trailing slashes */
1338 while (l > 0 && path[l-1] == '/')
1344 /* Skip last component */
1345 while (l > 0 && path[l-1] != '/')
1348 /* Skip trailing slashes */
1349 while (l > 0 && path[l-1] == '/')
1355 if (!(t = strndup(path, l)))
1358 if (path_startswith(stop, t)) {
1367 if (errno != ENOENT)
1375 char hexchar(int x) {
1376 static const char table[16] = "0123456789abcdef";
1378 return table[x & 15];
1381 int unhexchar(char c) {
1383 if (c >= '0' && c <= '9')
1386 if (c >= 'a' && c <= 'f')
1387 return c - 'a' + 10;
1389 if (c >= 'A' && c <= 'F')
1390 return c - 'A' + 10;
1395 char octchar(int x) {
1396 return '0' + (x & 7);
1399 int unoctchar(char c) {
1401 if (c >= '0' && c <= '7')
1407 char decchar(int x) {
1408 return '0' + (x % 10);
1411 int undecchar(char c) {
1413 if (c >= '0' && c <= '9')
1419 char *cescape(const char *s) {
1425 /* Does C style string escaping. */
1427 r = new(char, strlen(s)*4 + 1);
1431 for (f = s, t = r; *f; f++)
1477 /* For special chars we prefer octal over
1478 * hexadecimal encoding, simply because glib's
1479 * g_strescape() does the same */
1480 if ((*f < ' ') || (*f >= 127)) {
1482 *(t++) = octchar((unsigned char) *f >> 6);
1483 *(t++) = octchar((unsigned char) *f >> 3);
1484 *(t++) = octchar((unsigned char) *f);
1495 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1502 /* Undoes C style string escaping, and optionally prefixes it. */
1504 pl = prefix ? strlen(prefix) : 0;
1506 r = new(char, pl+length+1);
1511 memcpy(r, prefix, pl);
1513 for (f = s, t = r + pl; f < s + length; f++) {
1556 /* This is an extension of the XDG syntax files */
1561 /* hexadecimal encoding */
1564 a = unhexchar(f[1]);
1565 b = unhexchar(f[2]);
1567 if (a < 0 || b < 0) {
1568 /* Invalid escape code, let's take it literal then */
1572 *(t++) = (char) ((a << 4) | b);
1587 /* octal encoding */
1590 a = unoctchar(f[0]);
1591 b = unoctchar(f[1]);
1592 c = unoctchar(f[2]);
1594 if (a < 0 || b < 0 || c < 0) {
1595 /* Invalid escape code, let's take it literal then */
1599 *(t++) = (char) ((a << 6) | (b << 3) | c);
1607 /* premature end of string.*/
1612 /* Invalid escape code, let's take it literal then */
1624 char *cunescape_length(const char *s, size_t length) {
1625 return cunescape_length_with_prefix(s, length, NULL);
1628 char *cunescape(const char *s) {
1631 return cunescape_length(s, strlen(s));
1634 char *xescape(const char *s, const char *bad) {
1638 /* Escapes all chars in bad, in addition to \ and all special
1639 * chars, in \xFF style escaping. May be reversed with
1642 r = new(char, strlen(s) * 4 + 1);
1646 for (f = s, t = r; *f; f++) {
1648 if ((*f < ' ') || (*f >= 127) ||
1649 (*f == '\\') || strchr(bad, *f)) {
1652 *(t++) = hexchar(*f >> 4);
1653 *(t++) = hexchar(*f);
1663 char *bus_path_escape(const char *s) {
1669 /* Escapes all chars that D-Bus' object path cannot deal
1670 * with. Can be reverse with bus_path_unescape() */
1672 if (!(r = new(char, strlen(s)*3+1)))
1675 for (f = s, t = r; *f; f++) {
1677 if (!(*f >= 'A' && *f <= 'Z') &&
1678 !(*f >= 'a' && *f <= 'z') &&
1679 !(*f >= '0' && *f <= '9')) {
1681 *(t++) = hexchar(*f >> 4);
1682 *(t++) = hexchar(*f);
1692 char *bus_path_unescape(const char *f) {
1697 if (!(r = strdup(f)))
1700 for (t = r; *f; f++) {
1705 if ((a = unhexchar(f[1])) < 0 ||
1706 (b = unhexchar(f[2])) < 0) {
1707 /* Invalid escape code, let's take it literal then */
1710 *(t++) = (char) ((a << 4) | b);
1722 char *ascii_strlower(char *t) {
1727 for (p = t; *p; p++)
1728 if (*p >= 'A' && *p <= 'Z')
1729 *p = *p - 'A' + 'a';
1734 static bool ignore_file_allow_backup(const char *filename) {
1738 filename[0] == '.' ||
1739 streq(filename, "lost+found") ||
1740 streq(filename, "aquota.user") ||
1741 streq(filename, "aquota.group") ||
1742 endswith(filename, ".rpmnew") ||
1743 endswith(filename, ".rpmsave") ||
1744 endswith(filename, ".rpmorig") ||
1745 endswith(filename, ".dpkg-old") ||
1746 endswith(filename, ".dpkg-new") ||
1747 endswith(filename, ".swp");
1750 bool ignore_file(const char *filename) {
1753 if (endswith(filename, "~"))
1756 return ignore_file_allow_backup(filename);
1759 int fd_nonblock(int fd, bool nonblock) {
1764 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1768 flags |= O_NONBLOCK;
1770 flags &= ~O_NONBLOCK;
1772 if (fcntl(fd, F_SETFL, flags) < 0)
1778 int fd_cloexec(int fd, bool cloexec) {
1783 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1787 flags |= FD_CLOEXEC;
1789 flags &= ~FD_CLOEXEC;
1791 if (fcntl(fd, F_SETFD, flags) < 0)
1797 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1800 assert(n_fdset == 0 || fdset);
1802 for (i = 0; i < n_fdset; i++)
1809 int close_all_fds(const int except[], unsigned n_except) {
1814 assert(n_except == 0 || except);
1816 d = opendir("/proc/self/fd");
1821 /* When /proc isn't available (for example in chroots)
1822 * the fallback is brute forcing through the fd
1825 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1826 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1828 if (fd_in_set(fd, except, n_except))
1831 if (close_nointr(fd) < 0)
1832 if (errno != EBADF && r == 0)
1839 while ((de = readdir(d))) {
1842 if (ignore_file(de->d_name))
1845 if (safe_atoi(de->d_name, &fd) < 0)
1846 /* Let's better ignore this, just in case */
1855 if (fd_in_set(fd, except, n_except))
1858 if (close_nointr(fd) < 0) {
1859 /* Valgrind has its own FD and doesn't want to have it closed */
1860 if (errno != EBADF && r == 0)
1869 bool chars_intersect(const char *a, const char *b) {
1872 /* Returns true if any of the chars in a are in b. */
1873 for (p = a; *p; p++)
1880 bool fstype_is_network(const char *fstype) {
1881 static const char table[] =
1890 return nulstr_contains(table, fstype);
1894 _cleanup_close_ int fd;
1896 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1902 TIOCL_GETKMSGREDIRECT,
1906 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1909 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1912 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1918 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1919 struct termios old_termios, new_termios;
1921 char line[LINE_MAX];
1926 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1927 new_termios = old_termios;
1929 new_termios.c_lflag &= ~ICANON;
1930 new_termios.c_cc[VMIN] = 1;
1931 new_termios.c_cc[VTIME] = 0;
1933 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1936 if (t != (usec_t) -1) {
1937 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1938 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1943 k = fread(&c, 1, 1, f);
1945 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1951 *need_nl = c != '\n';
1958 if (t != (usec_t) -1)
1959 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1962 if (!fgets(line, sizeof(line), f))
1967 if (strlen(line) != 1)
1977 int ask(char *ret, const char *replies, const char *text, ...) {
1987 bool need_nl = true;
1990 fputs(ANSI_HIGHLIGHT_ON, stdout);
1997 fputs(ANSI_HIGHLIGHT_OFF, stdout);
2001 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2004 if (r == -EBADMSG) {
2005 puts("Bad input, please try again.");
2016 if (strchr(replies, c)) {
2021 puts("Read unexpected character, please try again.");
2025 int reset_terminal_fd(int fd, bool switch_to_text) {
2026 struct termios termios;
2029 /* Set terminal to some sane defaults */
2033 /* We leave locked terminal attributes untouched, so that
2034 * Plymouth may set whatever it wants to set, and we don't
2035 * interfere with that. */
2037 /* Disable exclusive mode, just in case */
2038 ioctl(fd, TIOCNXCL);
2040 /* Switch to text mode */
2042 ioctl(fd, KDSETMODE, KD_TEXT);
2044 /* Enable console unicode mode */
2045 ioctl(fd, KDSKBMODE, K_UNICODE);
2047 if (tcgetattr(fd, &termios) < 0) {
2052 /* We only reset the stuff that matters to the software. How
2053 * hardware is set up we don't touch assuming that somebody
2054 * else will do that for us */
2056 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2057 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2058 termios.c_oflag |= ONLCR;
2059 termios.c_cflag |= CREAD;
2060 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2062 termios.c_cc[VINTR] = 03; /* ^C */
2063 termios.c_cc[VQUIT] = 034; /* ^\ */
2064 termios.c_cc[VERASE] = 0177;
2065 termios.c_cc[VKILL] = 025; /* ^X */
2066 termios.c_cc[VEOF] = 04; /* ^D */
2067 termios.c_cc[VSTART] = 021; /* ^Q */
2068 termios.c_cc[VSTOP] = 023; /* ^S */
2069 termios.c_cc[VSUSP] = 032; /* ^Z */
2070 termios.c_cc[VLNEXT] = 026; /* ^V */
2071 termios.c_cc[VWERASE] = 027; /* ^W */
2072 termios.c_cc[VREPRINT] = 022; /* ^R */
2073 termios.c_cc[VEOL] = 0;
2074 termios.c_cc[VEOL2] = 0;
2076 termios.c_cc[VTIME] = 0;
2077 termios.c_cc[VMIN] = 1;
2079 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2083 /* Just in case, flush all crap out */
2084 tcflush(fd, TCIOFLUSH);
2089 int reset_terminal(const char *name) {
2092 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2096 r = reset_terminal_fd(fd, true);
2097 close_nointr_nofail(fd);
2102 int open_terminal(const char *name, int mode) {
2107 * If a TTY is in the process of being closed opening it might
2108 * cause EIO. This is horribly awful, but unlikely to be
2109 * changed in the kernel. Hence we work around this problem by
2110 * retrying a couple of times.
2112 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2116 fd = open(name, mode);
2123 /* Max 1s in total */
2127 usleep(50 * USEC_PER_MSEC);
2136 close_nointr_nofail(fd);
2141 close_nointr_nofail(fd);
2148 int flush_fd(int fd) {
2149 struct pollfd pollfd;
2153 pollfd.events = POLLIN;
2160 if ((r = poll(&pollfd, 1, 0)) < 0) {
2171 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2176 if (errno == EAGAIN)
2187 int acquire_terminal(
2191 bool ignore_tiocstty_eperm,
2194 int fd = -1, notify = -1, r = 0, wd = -1;
2196 struct sigaction sa_old, sa_new;
2200 /* We use inotify to be notified when the tty is closed. We
2201 * create the watch before checking if we can actually acquire
2202 * it, so that we don't lose any event.
2204 * Note: strictly speaking this actually watches for the
2205 * device being closed, it does *not* really watch whether a
2206 * tty loses its controlling process. However, unless some
2207 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2208 * its tty otherwise this will not become a problem. As long
2209 * as the administrator makes sure not configure any service
2210 * on the same tty as an untrusted user this should not be a
2211 * problem. (Which he probably should not do anyway.) */
2213 if (timeout != (usec_t) -1)
2214 ts = now(CLOCK_MONOTONIC);
2216 if (!fail && !force) {
2217 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2223 wd = inotify_add_watch(notify, name, IN_CLOSE);
2232 r = flush_fd(notify);
2237 /* We pass here O_NOCTTY only so that we can check the return
2238 * value TIOCSCTTY and have a reliable way to figure out if we
2239 * successfully became the controlling process of the tty */
2240 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2244 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2245 * if we already own the tty. */
2247 sa_new.sa_handler = SIG_IGN;
2248 sa_new.sa_flags = SA_RESTART;
2249 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2251 /* First, try to get the tty */
2252 if (ioctl(fd, TIOCSCTTY, force) < 0)
2255 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2257 /* Sometimes it makes sense to ignore TIOCSCTTY
2258 * returning EPERM, i.e. when very likely we already
2259 * are have this controlling terminal. */
2260 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2263 if (r < 0 && (force || fail || r != -EPERM)) {
2272 assert(notify >= 0);
2275 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2277 struct inotify_event *e;
2279 if (timeout != (usec_t) -1) {
2282 n = now(CLOCK_MONOTONIC);
2283 if (ts + timeout < n) {
2288 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2298 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2301 if (errno == EINTR || errno == EAGAIN)
2308 e = (struct inotify_event*) inotify_buffer;
2313 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2318 step = sizeof(struct inotify_event) + e->len;
2319 assert(step <= (size_t) l);
2321 e = (struct inotify_event*) ((uint8_t*) e + step);
2328 /* We close the tty fd here since if the old session
2329 * ended our handle will be dead. It's important that
2330 * we do this after sleeping, so that we don't enter
2331 * an endless loop. */
2332 close_nointr_nofail(fd);
2336 close_nointr_nofail(notify);
2338 r = reset_terminal_fd(fd, true);
2340 log_warning("Failed to reset terminal: %s", strerror(-r));
2346 close_nointr_nofail(fd);
2349 close_nointr_nofail(notify);
2354 int release_terminal(void) {
2356 struct sigaction sa_old, sa_new;
2358 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2361 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2362 * by our own TIOCNOTTY */
2365 sa_new.sa_handler = SIG_IGN;
2366 sa_new.sa_flags = SA_RESTART;
2367 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2369 if (ioctl(fd, TIOCNOTTY) < 0)
2372 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2374 close_nointr_nofail(fd);
2378 int sigaction_many(const struct sigaction *sa, ...) {
2383 while ((sig = va_arg(ap, int)) > 0)
2384 if (sigaction(sig, sa, NULL) < 0)
2391 int ignore_signals(int sig, ...) {
2392 struct sigaction sa;
2397 sa.sa_handler = SIG_IGN;
2398 sa.sa_flags = SA_RESTART;
2400 if (sigaction(sig, &sa, NULL) < 0)
2404 while ((sig = va_arg(ap, int)) > 0)
2405 if (sigaction(sig, &sa, NULL) < 0)
2412 int default_signals(int sig, ...) {
2413 struct sigaction sa;
2418 sa.sa_handler = SIG_DFL;
2419 sa.sa_flags = SA_RESTART;
2421 if (sigaction(sig, &sa, NULL) < 0)
2425 while ((sig = va_arg(ap, int)) > 0)
2426 if (sigaction(sig, &sa, NULL) < 0)
2433 int close_pipe(int p[]) {
2439 a = close_nointr(p[0]);
2444 b = close_nointr(p[1]);
2448 return a < 0 ? a : b;
2451 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2460 while (nbytes > 0) {
2463 if ((k = read(fd, p, nbytes)) <= 0) {
2465 if (k < 0 && errno == EINTR)
2468 if (k < 0 && errno == EAGAIN && do_poll) {
2469 struct pollfd pollfd;
2473 pollfd.events = POLLIN;
2475 if (poll(&pollfd, 1, -1) < 0) {
2479 return n > 0 ? n : -errno;
2482 if (pollfd.revents != POLLIN)
2483 return n > 0 ? n : -EIO;
2488 return n > 0 ? n : (k < 0 ? -errno : 0);
2499 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2508 while (nbytes > 0) {
2511 k = write(fd, p, nbytes);
2514 if (k < 0 && errno == EINTR)
2517 if (k < 0 && errno == EAGAIN && do_poll) {
2518 struct pollfd pollfd;
2522 pollfd.events = POLLOUT;
2524 if (poll(&pollfd, 1, -1) < 0) {
2528 return n > 0 ? n : -errno;
2531 if (pollfd.revents != POLLOUT)
2532 return n > 0 ? n : -EIO;
2537 return n > 0 ? n : (k < 0 ? -errno : 0);
2548 int parse_bytes(const char *t, off_t *bytes) {
2549 static const struct {
2555 { "M", 1024ULL*1024ULL },
2556 { "G", 1024ULL*1024ULL*1024ULL },
2557 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2558 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2559 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2576 l = strtoll(p, &e, 10);
2587 e += strspn(e, WHITESPACE);
2589 for (i = 0; i < ELEMENTSOF(table); i++)
2590 if (startswith(e, table[i].suffix)) {
2591 r += (off_t) l * table[i].factor;
2592 p = e + strlen(table[i].suffix);
2596 if (i >= ELEMENTSOF(table))
2606 int make_stdio(int fd) {
2611 r = dup3(fd, STDIN_FILENO, 0);
2612 s = dup3(fd, STDOUT_FILENO, 0);
2613 t = dup3(fd, STDERR_FILENO, 0);
2616 close_nointr_nofail(fd);
2618 if (r < 0 || s < 0 || t < 0)
2621 /* We rely here that the new fd has O_CLOEXEC not set */
2626 int make_null_stdio(void) {
2629 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2633 return make_stdio(null_fd);
2636 bool is_device_path(const char *path) {
2638 /* Returns true on paths that refer to a device, either in
2639 * sysfs or in /dev */
2642 path_startswith(path, "/dev/") ||
2643 path_startswith(path, "/sys/");
2646 int dir_is_empty(const char *path) {
2647 _cleanup_closedir_ DIR *d;
2656 union dirent_storage buf;
2658 r = readdir_r(d, &buf.de, &de);
2665 if (!ignore_file(de->d_name))
2670 unsigned long long random_ull(void) {
2671 _cleanup_close_ int fd;
2675 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2679 r = loop_read(fd, &ull, sizeof(ull), true);
2680 if (r != sizeof(ull))
2686 return random() * RAND_MAX + random();
2689 void rename_process(const char name[8]) {
2692 /* This is a like a poor man's setproctitle(). It changes the
2693 * comm field, argv[0], and also the glibc's internally used
2694 * name of the process. For the first one a limit of 16 chars
2695 * applies, to the second one usually one of 10 (i.e. length
2696 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2697 * "systemd"). If you pass a longer string it will be
2700 prctl(PR_SET_NAME, name);
2702 if (program_invocation_name)
2703 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2705 if (saved_argc > 0) {
2709 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2711 for (i = 1; i < saved_argc; i++) {
2715 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2720 void sigset_add_many(sigset_t *ss, ...) {
2727 while ((sig = va_arg(ap, int)) > 0)
2728 assert_se(sigaddset(ss, sig) == 0);
2732 char* gethostname_malloc(void) {
2735 assert_se(uname(&u) >= 0);
2737 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2738 return strdup(u.nodename);
2740 return strdup(u.sysname);
2743 bool hostname_is_set(void) {
2746 assert_se(uname(&u) >= 0);
2748 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2751 static char *lookup_uid(uid_t uid) {
2754 _cleanup_free_ char *buf = NULL;
2755 struct passwd pwbuf, *pw = NULL;
2757 /* Shortcut things to avoid NSS lookups */
2759 return strdup("root");
2761 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2765 buf = malloc(bufsize);
2769 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2770 return strdup(pw->pw_name);
2772 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2778 char* getlogname_malloc(void) {
2782 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2787 return lookup_uid(uid);
2790 char *getusername_malloc(void) {
2797 return lookup_uid(getuid());
2800 int getttyname_malloc(int fd, char **r) {
2801 char path[PATH_MAX], *c;
2806 k = ttyname_r(fd, path, sizeof(path));
2812 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2820 int getttyname_harder(int fd, char **r) {
2824 k = getttyname_malloc(fd, &s);
2828 if (streq(s, "tty")) {
2830 return get_ctty(0, NULL, r);
2837 int get_ctty_devnr(pid_t pid, dev_t *d) {
2839 char line[LINE_MAX], *p, *fn;
2840 unsigned long ttynr;
2843 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2846 f = fopen(fn, "re");
2851 if (!fgets(line, sizeof(line), f)) {
2852 k = feof(f) ? -EIO : -errno;
2859 p = strrchr(line, ')');
2869 "%*d " /* session */
2874 if (major(ttynr) == 0 && minor(ttynr) == 0)
2881 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2883 char fn[PATH_MAX], *s, *b, *p;
2888 k = get_ctty_devnr(pid, &devnr);
2892 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2895 k = readlink_malloc(fn, &s);
2901 /* This is an ugly hack */
2902 if (major(devnr) == 136) {
2903 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2913 /* Probably something like the ptys which have no
2914 * symlink in /dev/char. Let's return something
2915 * vaguely useful. */
2928 if (startswith(s, "/dev/"))
2930 else if (startswith(s, "../"))
2948 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2954 /* This returns the first error we run into, but nevertheless
2955 * tries to go on. This closes the passed fd. */
2959 close_nointr_nofail(fd);
2961 return errno == ENOENT ? 0 : -errno;
2966 union dirent_storage buf;
2967 bool is_dir, keep_around;
2971 r = readdir_r(d, &buf.de, &de);
2972 if (r != 0 && ret == 0) {
2980 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2983 if (de->d_type == DT_UNKNOWN ||
2985 (de->d_type == DT_DIR && root_dev)) {
2986 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2987 if (ret == 0 && errno != ENOENT)
2992 is_dir = S_ISDIR(st.st_mode);
2995 (st.st_uid == 0 || st.st_uid == getuid()) &&
2996 (st.st_mode & S_ISVTX);
2998 is_dir = de->d_type == DT_DIR;
2999 keep_around = false;
3005 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3006 if (root_dev && st.st_dev != root_dev->st_dev)
3009 subdir_fd = openat(fd, de->d_name,
3010 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3011 if (subdir_fd < 0) {
3012 if (ret == 0 && errno != ENOENT)
3017 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3018 if (r < 0 && ret == 0)
3022 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3023 if (ret == 0 && errno != ENOENT)
3027 } else if (!only_dirs && !keep_around) {
3029 if (unlinkat(fd, de->d_name, 0) < 0) {
3030 if (ret == 0 && errno != ENOENT)
3041 static int is_temporary_fs(struct statfs *s) {
3043 return s->f_type == TMPFS_MAGIC ||
3044 (long)s->f_type == (long)RAMFS_MAGIC;
3047 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3052 if (fstatfs(fd, &s) < 0) {
3053 close_nointr_nofail(fd);
3057 /* We refuse to clean disk file systems with this call. This
3058 * is extra paranoia just to be sure we never ever remove
3060 if (!is_temporary_fs(&s)) {
3061 log_error("Attempted to remove disk file system, and we can't allow that.");
3062 close_nointr_nofail(fd);
3066 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3069 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3075 /* We refuse to clean the root file system with this
3076 * call. This is extra paranoia to never cause a really
3077 * seriously broken system. */
3078 if (path_equal(path, "/")) {
3079 log_error("Attempted to remove entire root file system, and we can't allow that.");
3083 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3086 if (errno != ENOTDIR)
3090 if (statfs(path, &s) < 0)
3093 if (!is_temporary_fs(&s)) {
3094 log_error("Attempted to remove disk file system, and we can't allow that.");
3099 if (delete_root && !only_dirs)
3100 if (unlink(path) < 0 && errno != ENOENT)
3107 if (fstatfs(fd, &s) < 0) {
3108 close_nointr_nofail(fd);
3112 if (!is_temporary_fs(&s)) {
3113 log_error("Attempted to remove disk file system, and we can't allow that.");
3114 close_nointr_nofail(fd);
3119 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3122 if (honour_sticky && file_is_priv_sticky(path) > 0)
3125 if (rmdir(path) < 0 && errno != ENOENT) {
3134 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3135 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3138 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3139 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3142 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3145 /* Under the assumption that we are running privileged we
3146 * first change the access mode and only then hand out
3147 * ownership to avoid a window where access is too open. */
3149 if (mode != (mode_t) -1)
3150 if (chmod(path, mode) < 0)
3153 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3154 if (chown(path, uid, gid) < 0)
3160 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3163 /* Under the assumption that we are running privileged we
3164 * first change the access mode and only then hand out
3165 * ownership to avoid a window where access is too open. */
3167 if (fchmod(fd, mode) < 0)
3170 if (fchown(fd, uid, gid) < 0)
3176 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3180 /* Allocates the cpuset in the right size */
3183 if (!(r = CPU_ALLOC(n)))
3186 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3187 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3197 if (errno != EINVAL)
3204 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3205 static const char status_indent[] = " "; /* "[" STATUS "] " */
3206 _cleanup_free_ char *s = NULL;
3207 _cleanup_close_ int fd = -1;
3208 struct iovec iovec[5];
3213 /* This is independent of logging, as status messages are
3214 * optional and go exclusively to the console. */
3216 if (vasprintf(&s, format, ap) < 0)
3219 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3232 sl = status ? sizeof(status_indent)-1 : 0;
3238 e = ellipsize(s, emax, 75);
3248 if (!isempty(status)) {
3249 IOVEC_SET_STRING(iovec[n++], "[");
3250 IOVEC_SET_STRING(iovec[n++], status);
3251 IOVEC_SET_STRING(iovec[n++], "] ");
3253 IOVEC_SET_STRING(iovec[n++], status_indent);
3256 IOVEC_SET_STRING(iovec[n++], s);
3257 IOVEC_SET_STRING(iovec[n++], "\n");
3259 if (writev(fd, iovec, n) < 0)
3265 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3271 va_start(ap, format);
3272 r = status_vprintf(status, ellipse, format, ap);
3278 int status_welcome(void) {
3280 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3282 r = parse_env_file("/etc/os-release", NEWLINE,
3283 "PRETTY_NAME", &pretty_name,
3284 "ANSI_COLOR", &ansi_color,
3286 if (r < 0 && r != -ENOENT)
3287 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3289 return status_printf(NULL, false,
3290 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3291 isempty(ansi_color) ? "1" : ansi_color,
3292 isempty(pretty_name) ? "Linux" : pretty_name);
3295 char *replace_env(const char *format, char **env) {
3302 const char *e, *word = format;
3307 for (e = format; *e; e ++) {
3318 if (!(k = strnappend(r, word, e-word-1)))
3327 } else if (*e == '$') {
3328 if (!(k = strnappend(r, word, e-word)))
3344 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3347 if (!(k = strappend(r, t)))
3360 if (!(k = strnappend(r, word, e-word)))
3371 char **replace_env_argv(char **argv, char **env) {
3373 unsigned k = 0, l = 0;
3375 l = strv_length(argv);
3377 if (!(r = new(char*, l+1)))
3380 STRV_FOREACH(i, argv) {
3382 /* If $FOO appears as single word, replace it by the split up variable */
3383 if ((*i)[0] == '$' && (*i)[1] != '{') {
3388 if ((e = strv_env_get(env, *i+1))) {
3390 if (!(m = strv_split_quoted(e))) {
3401 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3410 memcpy(r + k, m, q * sizeof(char*));
3418 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3419 if (!(r[k++] = replace_env(*i, env))) {
3429 int fd_columns(int fd) {
3433 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3442 unsigned columns(void) {
3446 if (_likely_(cached_columns > 0))
3447 return cached_columns;
3450 e = getenv("COLUMNS");
3455 c = fd_columns(STDOUT_FILENO);
3464 int fd_lines(int fd) {
3468 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3477 unsigned lines(void) {
3481 if (_likely_(cached_lines > 0))
3482 return cached_lines;
3485 e = getenv("LINES");
3490 l = fd_lines(STDOUT_FILENO);
3496 return cached_lines;
3499 /* intended to be used as a SIGWINCH sighandler */
3500 void columns_lines_cache_reset(int signum) {
3506 static int cached_on_tty = -1;
3508 if (_unlikely_(cached_on_tty < 0))
3509 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3511 return cached_on_tty;
3514 int running_in_chroot(void) {
3520 /* Only works as root */
3522 if (stat("/proc/1/root", &a) < 0)
3525 if (stat("/", &b) < 0)
3529 a.st_dev != b.st_dev ||
3530 a.st_ino != b.st_ino;
3533 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3538 assert(percent <= 100);
3539 assert(new_length >= 3);
3541 if (old_length <= 3 || old_length <= new_length)
3542 return strndup(s, old_length);
3544 r = new0(char, new_length+1);
3548 x = (new_length * percent) / 100;
3550 if (x > new_length - 3)
3558 s + old_length - (new_length - x - 3),
3559 new_length - x - 3);
3564 char *ellipsize(const char *s, size_t length, unsigned percent) {
3565 return ellipsize_mem(s, strlen(s), length, percent);
3568 int touch(const char *path) {
3573 /* This just opens the file for writing, ensuring it
3574 * exists. It doesn't call utimensat() the way /usr/bin/touch
3577 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3581 close_nointr_nofail(fd);
3585 char *unquote(const char *s, const char* quotes) {
3589 /* This is rather stupid, simply removes the heading and
3590 * trailing quotes if there is one. Doesn't care about
3591 * escaping or anything. We should make this smarter one
3598 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3599 return strndup(s+1, l-2);
3604 char *normalize_env_assignment(const char *s) {
3605 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3608 eq = strchr(s, '=');
3620 memmove(r, t, strlen(t) + 1);
3624 name = strndup(s, eq - s);
3632 value = unquote(strstrip(p), QUOTES);
3636 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3642 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3653 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3665 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3672 r = wait_for_terminate(pid, &status);
3674 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3678 if (status.si_code == CLD_EXITED) {
3679 if (status.si_status != 0) {
3680 log_warning("%s failed with error code %i.", name, status.si_status);
3681 return status.si_status;
3684 log_debug("%s succeeded.", name);
3687 } else if (status.si_code == CLD_KILLED ||
3688 status.si_code == CLD_DUMPED) {
3690 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3694 log_warning("%s failed due to unknown reason.", name);
3698 _noreturn_ void freeze(void) {
3700 /* Make sure nobody waits for us on a socket anymore */
3701 close_all_fds(NULL, 0);
3709 bool null_or_empty(struct stat *st) {
3712 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3715 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3721 int null_or_empty_path(const char *fn) {
3726 if (stat(fn, &st) < 0)
3729 return null_or_empty(&st);
3732 DIR *xopendirat(int fd, const char *name, int flags) {
3736 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3742 close_nointr_nofail(nfd);
3749 int signal_from_string_try_harder(const char *s) {
3753 signo = signal_from_string(s);
3755 if (startswith(s, "SIG"))
3756 return signal_from_string(s+3);
3761 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3765 /* FIXME: to follow udev's logic 100% we need to leave valid
3766 * UTF8 chars unescaped */
3768 u = unquote(tagvalue, "\"\'");
3772 t = xescape(u, "/ ");
3778 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3787 char *fstab_node_to_udev_node(const char *p) {
3790 if (startswith(p, "LABEL="))
3791 return tag_to_udev_node(p+6, "label");
3793 if (startswith(p, "UUID="))
3794 return tag_to_udev_node(p+5, "uuid");
3796 if (startswith(p, "PARTUUID="))
3797 return tag_to_udev_node(p+9, "partuuid");
3799 if (startswith(p, "PARTLABEL="))
3800 return tag_to_udev_node(p+10, "partlabel");
3805 bool tty_is_vc(const char *tty) {
3808 if (startswith(tty, "/dev/"))
3811 return vtnr_from_tty(tty) >= 0;
3814 bool tty_is_console(const char *tty) {
3817 if (startswith(tty, "/dev/"))
3820 return streq(tty, "console");
3823 int vtnr_from_tty(const char *tty) {
3828 if (startswith(tty, "/dev/"))
3831 if (!startswith(tty, "tty") )
3834 if (tty[3] < '0' || tty[3] > '9')
3837 r = safe_atoi(tty+3, &i);
3841 if (i < 0 || i > 63)
3847 bool tty_is_vc_resolve(const char *tty) {
3848 char *active = NULL;
3853 if (startswith(tty, "/dev/"))
3856 /* Resolve where /dev/console is pointing to, if /sys is
3857 * actually ours (i.e. not read-only-mounted which is a sign
3858 * for container setups) */
3859 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3860 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3861 /* If multiple log outputs are configured the
3862 * last one is what /dev/console points to */
3863 tty = strrchr(active, ' ');
3876 const char *default_term_for_tty(const char *tty) {
3879 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3882 bool dirent_is_file(const struct dirent *de) {
3885 if (ignore_file(de->d_name))
3888 if (de->d_type != DT_REG &&
3889 de->d_type != DT_LNK &&
3890 de->d_type != DT_UNKNOWN)
3896 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3899 if (de->d_type != DT_REG &&
3900 de->d_type != DT_LNK &&
3901 de->d_type != DT_UNKNOWN)
3904 if (ignore_file_allow_backup(de->d_name))
3907 return endswith(de->d_name, suffix);
3910 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3913 Hashmap *pids = NULL;
3917 /* Executes all binaries in a directory in parallel and waits
3918 * until all they all finished. */
3921 if (!(_d = opendir(directory))) {
3923 if (errno == ENOENT)
3926 log_error("Failed to enumerate directory %s: %m", directory);
3933 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3934 log_error("Failed to allocate set.");
3938 while ((de = readdir(d))) {
3943 if (!dirent_is_file(de))
3946 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3951 if ((pid = fork()) < 0) {
3952 log_error("Failed to fork: %m");
3970 log_error("Failed to execute %s: %m", path);
3971 _exit(EXIT_FAILURE);
3974 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3976 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3977 log_error("Failed to add PID to set: %s", strerror(-k));
3982 while (!hashmap_isempty(pids)) {
3983 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3988 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3993 log_error("waitid() failed: %m");
3997 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3998 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3999 if (si.si_code == CLD_EXITED)
4000 log_error("%s exited with exit status %i.", path, si.si_status);
4002 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4004 log_debug("%s exited successfully.", path);
4015 hashmap_free_free(pids);
4018 int kill_and_sigcont(pid_t pid, int sig) {
4021 r = kill(pid, sig) < 0 ? -errno : 0;
4029 bool nulstr_contains(const char*nulstr, const char *needle) {
4035 NULSTR_FOREACH(i, nulstr)
4036 if (streq(i, needle))
4042 bool plymouth_running(void) {
4043 return access("/run/plymouth/pid", F_OK) >= 0;
4046 char* strshorten(char *s, size_t l) {
4055 static bool hostname_valid_char(char c) {
4057 (c >= 'a' && c <= 'z') ||
4058 (c >= 'A' && c <= 'Z') ||
4059 (c >= '0' && c <= '9') ||
4065 bool hostname_is_valid(const char *s) {
4071 for (p = s; *p; p++)
4072 if (!hostname_valid_char(*p))
4075 if (p-s > HOST_NAME_MAX)
4081 char* hostname_cleanup(char *s) {
4084 for (p = s, d = s; *p; p++)
4085 if ((*p >= 'a' && *p <= 'z') ||
4086 (*p >= 'A' && *p <= 'Z') ||
4087 (*p >= '0' && *p <= '9') ||
4095 strshorten(s, HOST_NAME_MAX);
4099 int pipe_eof(int fd) {
4100 struct pollfd pollfd;
4105 pollfd.events = POLLIN|POLLHUP;
4107 r = poll(&pollfd, 1, 0);
4114 return pollfd.revents & POLLHUP;
4117 int fd_wait_for_event(int fd, int event, usec_t t) {
4118 struct pollfd pollfd;
4123 pollfd.events = event;
4125 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4132 return pollfd.revents;
4135 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4146 t = new(char, strlen(path) + 1 + 6 + 1);
4150 fn = path_get_file_name(path);
4154 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4156 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4162 f = fdopen(fd, "we");
4175 int terminal_vhangup_fd(int fd) {
4178 if (ioctl(fd, TIOCVHANGUP) < 0)
4184 int terminal_vhangup(const char *name) {
4187 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4191 r = terminal_vhangup_fd(fd);
4192 close_nointr_nofail(fd);
4197 int vt_disallocate(const char *name) {
4201 /* Deallocate the VT if possible. If not possible
4202 * (i.e. because it is the active one), at least clear it
4203 * entirely (including the scrollback buffer) */
4205 if (!startswith(name, "/dev/"))
4208 if (!tty_is_vc(name)) {
4209 /* So this is not a VT. I guess we cannot deallocate
4210 * it then. But let's at least clear the screen */
4212 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4217 "\033[r" /* clear scrolling region */
4218 "\033[H" /* move home */
4219 "\033[2J", /* clear screen */
4221 close_nointr_nofail(fd);
4226 if (!startswith(name, "/dev/tty"))
4229 r = safe_atou(name+8, &u);
4236 /* Try to deallocate */
4237 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4241 r = ioctl(fd, VT_DISALLOCATE, u);
4242 close_nointr_nofail(fd);
4250 /* Couldn't deallocate, so let's clear it fully with
4252 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4257 "\033[r" /* clear scrolling region */
4258 "\033[H" /* move home */
4259 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4261 close_nointr_nofail(fd);
4266 int copy_file(const char *from, const char *to) {
4272 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4276 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4278 close_nointr_nofail(fdf);
4286 n = read(fdf, buf, sizeof(buf));
4290 close_nointr_nofail(fdf);
4301 k = loop_write(fdt, buf, n, false);
4303 r = k < 0 ? k : (errno ? -errno : -EIO);
4305 close_nointr_nofail(fdf);
4313 close_nointr_nofail(fdf);
4314 r = close_nointr(fdt);
4324 int symlink_atomic(const char *from, const char *to) {
4326 _cleanup_free_ char *t;
4329 unsigned long long ull;
4336 t = new(char, strlen(to) + 1 + 16 + 1);
4340 fn = path_get_file_name(to);
4344 x = stpcpy(t+k+1, fn);
4347 for (i = 0; i < 16; i++) {
4348 *(x++) = hexchar(ull & 0xF);
4354 if (symlink(from, t) < 0)
4357 if (rename(t, to) < 0) {
4366 bool display_is_local(const char *display) {
4370 display[0] == ':' &&
4371 display[1] >= '0' &&
4375 int socket_from_display(const char *display, char **path) {
4382 if (!display_is_local(display))
4385 k = strspn(display+1, "0123456789");
4387 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4391 c = stpcpy(f, "/tmp/.X11-unix/X");
4392 memcpy(c, display+1, k);
4401 const char **username,
4402 uid_t *uid, gid_t *gid,
4404 const char **shell) {
4412 /* We enforce some special rules for uid=0: in order to avoid
4413 * NSS lookups for root we hardcode its data. */
4415 if (streq(*username, "root") || streq(*username, "0")) {
4433 if (parse_uid(*username, &u) >= 0) {
4437 /* If there are multiple users with the same id, make
4438 * sure to leave $USER to the configured value instead
4439 * of the first occurrence in the database. However if
4440 * the uid was configured by a numeric uid, then let's
4441 * pick the real username from /etc/passwd. */
4443 *username = p->pw_name;
4446 p = getpwnam(*username);
4450 return errno != 0 ? -errno : -ESRCH;
4462 *shell = p->pw_shell;
4467 char* uid_to_name(uid_t uid) {
4472 return strdup("root");
4476 return strdup(p->pw_name);
4478 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4484 int get_group_creds(const char **groupname, gid_t *gid) {
4490 /* We enforce some special rules for gid=0: in order to avoid
4491 * NSS lookups for root we hardcode its data. */
4493 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4494 *groupname = "root";
4502 if (parse_gid(*groupname, &id) >= 0) {
4507 *groupname = g->gr_name;
4510 g = getgrnam(*groupname);
4514 return errno != 0 ? -errno : -ESRCH;
4522 int in_group(const char *name) {
4524 int ngroups_max, r, i;
4526 r = get_group_creds(&name, &gid);
4530 if (getgid() == gid)
4533 if (getegid() == gid)
4536 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4537 assert(ngroups_max > 0);
4539 gids = alloca(sizeof(gid_t) * ngroups_max);
4541 r = getgroups(ngroups_max, gids);
4545 for (i = 0; i < r; i++)
4552 int glob_exists(const char *path) {
4560 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4562 if (k == GLOB_NOMATCH)
4564 else if (k == GLOB_NOSPACE)
4567 r = !strv_isempty(g.gl_pathv);
4569 r = errno ? -errno : -EIO;
4576 int dirent_ensure_type(DIR *d, struct dirent *de) {
4582 if (de->d_type != DT_UNKNOWN)
4585 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4589 S_ISREG(st.st_mode) ? DT_REG :
4590 S_ISDIR(st.st_mode) ? DT_DIR :
4591 S_ISLNK(st.st_mode) ? DT_LNK :
4592 S_ISFIFO(st.st_mode) ? DT_FIFO :
4593 S_ISSOCK(st.st_mode) ? DT_SOCK :
4594 S_ISCHR(st.st_mode) ? DT_CHR :
4595 S_ISBLK(st.st_mode) ? DT_BLK :
4601 int in_search_path(const char *path, char **search) {
4605 r = path_get_parent(path, &parent);
4611 STRV_FOREACH(i, search) {
4612 if (path_equal(parent, *i)) {
4623 int get_files_in_directory(const char *path, char ***list) {
4631 /* Returns all files in a directory in *list, and the number
4632 * of files as return value. If list is NULL returns only the
4641 union dirent_storage buf;
4644 k = readdir_r(d, &buf.de, &de);
4653 dirent_ensure_type(d, de);
4655 if (!dirent_is_file(de))
4659 if ((unsigned) r >= n) {
4663 t = realloc(l, sizeof(char*) * n);
4672 assert((unsigned) r < n);
4674 l[r] = strdup(de->d_name);
4698 char *strjoin(const char *x, ...) {
4712 t = va_arg(ap, const char *);
4717 if (n > ((size_t) -1) - l) {
4741 t = va_arg(ap, const char *);
4755 bool is_main_thread(void) {
4756 static __thread int cached = 0;
4758 if (_unlikely_(cached == 0))
4759 cached = getpid() == gettid() ? 1 : -1;
4764 int block_get_whole_disk(dev_t d, dev_t *ret) {
4771 /* If it has a queue this is good enough for us */
4772 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4775 r = access(p, F_OK);
4783 /* If it is a partition find the originating device */
4784 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4787 r = access(p, F_OK);
4793 /* Get parent dev_t */
4794 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4797 r = read_one_line_file(p, &s);
4803 r = sscanf(s, "%u:%u", &m, &n);
4809 /* Only return this if it is really good enough for us. */
4810 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4813 r = access(p, F_OK);
4817 *ret = makedev(m, n);
4824 int file_is_priv_sticky(const char *p) {
4829 if (lstat(p, &st) < 0)
4833 (st.st_uid == 0 || st.st_uid == getuid()) &&
4834 (st.st_mode & S_ISVTX);
4837 static const char *const ioprio_class_table[] = {
4838 [IOPRIO_CLASS_NONE] = "none",
4839 [IOPRIO_CLASS_RT] = "realtime",
4840 [IOPRIO_CLASS_BE] = "best-effort",
4841 [IOPRIO_CLASS_IDLE] = "idle"
4844 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4846 static const char *const sigchld_code_table[] = {
4847 [CLD_EXITED] = "exited",
4848 [CLD_KILLED] = "killed",
4849 [CLD_DUMPED] = "dumped",
4850 [CLD_TRAPPED] = "trapped",
4851 [CLD_STOPPED] = "stopped",
4852 [CLD_CONTINUED] = "continued",
4855 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4857 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4858 [LOG_FAC(LOG_KERN)] = "kern",
4859 [LOG_FAC(LOG_USER)] = "user",
4860 [LOG_FAC(LOG_MAIL)] = "mail",
4861 [LOG_FAC(LOG_DAEMON)] = "daemon",
4862 [LOG_FAC(LOG_AUTH)] = "auth",
4863 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4864 [LOG_FAC(LOG_LPR)] = "lpr",
4865 [LOG_FAC(LOG_NEWS)] = "news",
4866 [LOG_FAC(LOG_UUCP)] = "uucp",
4867 [LOG_FAC(LOG_CRON)] = "cron",
4868 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4869 [LOG_FAC(LOG_FTP)] = "ftp",
4870 [LOG_FAC(LOG_LOCAL0)] = "local0",
4871 [LOG_FAC(LOG_LOCAL1)] = "local1",
4872 [LOG_FAC(LOG_LOCAL2)] = "local2",
4873 [LOG_FAC(LOG_LOCAL3)] = "local3",
4874 [LOG_FAC(LOG_LOCAL4)] = "local4",
4875 [LOG_FAC(LOG_LOCAL5)] = "local5",
4876 [LOG_FAC(LOG_LOCAL6)] = "local6",
4877 [LOG_FAC(LOG_LOCAL7)] = "local7"
4880 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4882 static const char *const log_level_table[] = {
4883 [LOG_EMERG] = "emerg",
4884 [LOG_ALERT] = "alert",
4885 [LOG_CRIT] = "crit",
4887 [LOG_WARNING] = "warning",
4888 [LOG_NOTICE] = "notice",
4889 [LOG_INFO] = "info",
4890 [LOG_DEBUG] = "debug"
4893 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4895 static const char* const sched_policy_table[] = {
4896 [SCHED_OTHER] = "other",
4897 [SCHED_BATCH] = "batch",
4898 [SCHED_IDLE] = "idle",
4899 [SCHED_FIFO] = "fifo",
4903 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4905 static const char* const rlimit_table[] = {
4906 [RLIMIT_CPU] = "LimitCPU",
4907 [RLIMIT_FSIZE] = "LimitFSIZE",
4908 [RLIMIT_DATA] = "LimitDATA",
4909 [RLIMIT_STACK] = "LimitSTACK",
4910 [RLIMIT_CORE] = "LimitCORE",
4911 [RLIMIT_RSS] = "LimitRSS",
4912 [RLIMIT_NOFILE] = "LimitNOFILE",
4913 [RLIMIT_AS] = "LimitAS",
4914 [RLIMIT_NPROC] = "LimitNPROC",
4915 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4916 [RLIMIT_LOCKS] = "LimitLOCKS",
4917 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4918 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4919 [RLIMIT_NICE] = "LimitNICE",
4920 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4921 [RLIMIT_RTTIME] = "LimitRTTIME"
4924 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4926 static const char* const ip_tos_table[] = {
4927 [IPTOS_LOWDELAY] = "low-delay",
4928 [IPTOS_THROUGHPUT] = "throughput",
4929 [IPTOS_RELIABILITY] = "reliability",
4930 [IPTOS_LOWCOST] = "low-cost",
4933 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4935 static const char *const __signal_table[] = {
4952 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4963 [SIGVTALRM] = "VTALRM",
4965 [SIGWINCH] = "WINCH",
4971 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4973 const char *signal_to_string(int signo) {
4974 static __thread char buf[12];
4977 name = __signal_to_string(signo);
4981 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4982 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4984 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4989 int signal_from_string(const char *s) {
4994 signo = __signal_from_string(s);
4998 if (startswith(s, "RTMIN+")) {
5002 if (safe_atou(s, &u) >= 0) {
5003 signo = (int) u + offset;
5004 if (signo > 0 && signo < _NSIG)
5010 bool kexec_loaded(void) {
5011 bool loaded = false;
5014 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5022 int strdup_or_null(const char *a, char **b) {
5040 int prot_from_flags(int flags) {
5042 switch (flags & O_ACCMODE) {
5051 return PROT_READ|PROT_WRITE;
5058 char *format_bytes(char *buf, size_t l, off_t t) {
5061 static const struct {
5065 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5066 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5067 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5068 { "G", 1024ULL*1024ULL*1024ULL },
5069 { "M", 1024ULL*1024ULL },
5073 for (i = 0; i < ELEMENTSOF(table); i++) {
5075 if (t >= table[i].factor) {
5078 (unsigned long long) (t / table[i].factor),
5079 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5086 snprintf(buf, l, "%lluB", (unsigned long long) t);
5094 void* memdup(const void *p, size_t l) {
5107 int fd_inc_sndbuf(int fd, size_t n) {
5109 socklen_t l = sizeof(value);
5111 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5113 l == sizeof(value) &&
5114 (size_t) value >= n*2)
5118 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5125 int fd_inc_rcvbuf(int fd, size_t n) {
5127 socklen_t l = sizeof(value);
5129 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5131 l == sizeof(value) &&
5132 (size_t) value >= n*2)
5136 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5143 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5144 pid_t parent_pid, agent_pid;
5146 bool stdout_is_tty, stderr_is_tty;
5154 parent_pid = getpid();
5156 /* Spawns a temporary TTY agent, making sure it goes away when
5163 if (agent_pid != 0) {
5170 * Make sure the agent goes away when the parent dies */
5171 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5172 _exit(EXIT_FAILURE);
5174 /* Check whether our parent died before we were able
5175 * to set the death signal */
5176 if (getppid() != parent_pid)
5177 _exit(EXIT_SUCCESS);
5179 /* Don't leak fds to the agent */
5180 close_all_fds(except, n_except);
5182 stdout_is_tty = isatty(STDOUT_FILENO);
5183 stderr_is_tty = isatty(STDERR_FILENO);
5185 if (!stdout_is_tty || !stderr_is_tty) {
5186 /* Detach from stdout/stderr. and reopen
5187 * /dev/tty for them. This is important to
5188 * ensure that when systemctl is started via
5189 * popen() or a similar call that expects to
5190 * read EOF we actually do generate EOF and
5191 * not delay this indefinitely by because we
5192 * keep an unused copy of stdin around. */
5193 fd = open("/dev/tty", O_WRONLY);
5195 log_error("Failed to open /dev/tty: %m");
5196 _exit(EXIT_FAILURE);
5200 dup2(fd, STDOUT_FILENO);
5203 dup2(fd, STDERR_FILENO);
5209 /* Count arguments */
5211 for (n = 0; va_arg(ap, char*); n++)
5216 l = alloca(sizeof(char *) * (n + 1));
5218 /* Fill in arguments */
5220 for (i = 0; i <= n; i++)
5221 l[i] = va_arg(ap, char*);
5225 _exit(EXIT_FAILURE);
5228 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5229 struct rlimit highest, fixed;
5233 if (setrlimit(resource, rlim) >= 0)
5239 /* So we failed to set the desired setrlimit, then let's try
5240 * to get as close as we can */
5241 assert_se(getrlimit(resource, &highest) == 0);
5243 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5244 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5246 if (setrlimit(resource, &fixed) < 0)
5252 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5253 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5265 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5268 f = fopen(path, "re");
5276 char line[LINE_MAX];
5279 for (i = 0; i < sizeof(line)-1; i++) {
5283 if (_unlikely_(c == EOF)) {
5293 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5294 value = strdup(line + l + 1);
5314 int can_sleep(const char *type) {
5318 _cleanup_free_ char *p = NULL;
5322 /* If /sys is read-only we cannot sleep */
5323 if (access("/sys/power/state", W_OK) < 0)
5326 r = read_one_line_file("/sys/power/state", &p);
5331 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5332 if (l == k && memcmp(w, type, l) == 0)
5338 int can_sleep_disk(const char *type) {
5342 _cleanup_free_ char *p = NULL;
5346 /* If /sys is read-only we cannot sleep */
5347 if (access("/sys/power/state", W_OK) < 0 ||
5348 access("/sys/power/disk", W_OK) < 0)
5351 r = read_one_line_file("/sys/power/disk", &p);
5356 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5357 if (l == k && memcmp(w, type, l) == 0)
5360 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5367 bool is_valid_documentation_url(const char *url) {
5370 if (startswith(url, "http://") && url[7])
5373 if (startswith(url, "https://") && url[8])
5376 if (startswith(url, "file:") && url[5])
5379 if (startswith(url, "info:") && url[5])
5382 if (startswith(url, "man:") && url[4])
5388 bool in_initrd(void) {
5389 static __thread int saved = -1;
5395 /* We make two checks here:
5397 * 1. the flag file /etc/initrd-release must exist
5398 * 2. the root file system must be a memory file system
5400 * The second check is extra paranoia, since misdetecting an
5401 * initrd can have bad bad consequences due the initrd
5402 * emptying when transititioning to the main systemd.
5405 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5406 statfs("/", &s) >= 0 &&
5407 is_temporary_fs(&s);
5412 void warn_melody(void) {
5413 _cleanup_close_ int fd = -1;
5415 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5419 /* Yeah, this is synchronous. Kinda sucks. But well... */
5421 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5422 usleep(125*USEC_PER_MSEC);
5424 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5425 usleep(125*USEC_PER_MSEC);
5427 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5428 usleep(125*USEC_PER_MSEC);
5430 ioctl(fd, KIOCSOUND, 0);
5433 int make_console_stdio(void) {
5436 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5438 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5440 log_error("Failed to acquire terminal: %s", strerror(-fd));
5446 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5453 int get_home_dir(char **_h) {
5461 /* Take the user specified one */
5472 /* Hardcode home directory for root to avoid NSS */
5475 h = strdup("/root");
5483 /* Check the database... */
5487 return errno ? -errno : -ESRCH;
5489 if (!path_is_absolute(p->pw_dir))
5492 h = strdup(p->pw_dir);
5500 int get_shell(char **_sh) {
5508 /* Take the user specified one */
5509 e = getenv("SHELL");
5519 /* Hardcode home directory for root to avoid NSS */
5522 sh = strdup("/bin/sh");
5530 /* Check the database... */
5534 return errno ? -errno : -ESRCH;
5536 if (!path_is_absolute(p->pw_shell))
5539 sh = strdup(p->pw_shell);
5547 void freep(void *p) {
5551 void fclosep(FILE **f) {
5556 void closep(int *fd) {
5558 close_nointr_nofail(*fd);
5561 void closedirp(DIR **d) {
5566 void umaskp(mode_t *u) {
5570 bool filename_is_safe(const char *p) {
5584 if (strlen(p) > FILENAME_MAX)
5590 bool string_is_safe(const char *p) {
5595 for (t = p; *t; t++) {
5596 if (*t > 0 && *t < ' ')
5599 if (strchr("\\\"\'", *t))
5606 bool path_is_safe(const char *p) {
5611 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5614 if (strlen(p) > PATH_MAX)
5617 /* The following two checks are not really dangerous, but hey, they still are confusing */
5618 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5621 if (strstr(p, "//"))
5627 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5628 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5629 int (*compar) (const void *, const void *, void *), void *arg) {
5638 p = (void *)(((const char *) base) + (idx * size));
5639 comparison = compar(key, p, arg);
5642 else if (comparison > 0)
5650 bool is_locale_utf8(void) {
5652 static int cached_answer = -1;
5654 if (cached_answer >= 0)
5657 if (!setlocale(LC_ALL, "")) {
5658 cached_answer = true;
5662 set = nl_langinfo(CODESET);
5664 cached_answer = true;
5668 cached_answer = streq(set, "UTF-8");
5670 return (bool)cached_answer;
5673 const char *draw_special_char(DrawSpecialChar ch) {
5674 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5676 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5677 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5678 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5679 [DRAW_TREE_SPACE] = " ", /* */
5680 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5682 /* ASCII fallback */ {
5683 [DRAW_TREE_VERT] = "| ",
5684 [DRAW_TREE_BRANCH] = "|-",
5685 [DRAW_TREE_RIGHT] = "`-",
5686 [DRAW_TREE_SPACE] = " ",
5687 [DRAW_TRIANGULAR_BULLET] = "> ",
5691 return draw_table[!is_locale_utf8()][ch];
5694 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5697 size_t l, old_len, new_len;
5703 old_len = strlen(old_string);
5704 new_len = strlen(new_string);
5717 if (!startswith(f, old_string)) {
5723 nl = l - old_len + new_len;
5724 a = realloc(r, nl + 1);
5732 t = stpcpy(t, new_string);
5744 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5745 const char *i, *begin = NULL;
5750 } state = STATE_OTHER;
5752 size_t osz = 0, isz;
5758 /* Strips ANSI color and replaces TABs by 8 spaces */
5760 isz = _isz ? *_isz : strlen(*ibuf);
5762 f = open_memstream(&obuf, &osz);
5766 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5771 if (i >= *ibuf + isz) /* EOT */
5773 else if (*i == '\x1B')
5774 state = STATE_ESCAPE;
5775 else if (*i == '\t')
5782 if (i >= *ibuf + isz) { /* EOT */
5785 } else if (*i == '[') {
5786 state = STATE_BRACKET;
5791 state = STATE_OTHER;
5798 if (i >= *ibuf + isz || /* EOT */
5799 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5802 state = STATE_OTHER;
5804 } else if (*i == 'm')
5805 state = STATE_OTHER;
5827 int on_ac_power(void) {
5828 bool found_offline = false, found_online = false;
5829 _cleanup_closedir_ DIR *d = NULL;
5831 d = opendir("/sys/class/power_supply");
5837 union dirent_storage buf;
5838 _cleanup_free_ char *p = NULL;
5839 _cleanup_close_ int fd = -1, device = -1;
5844 k = readdir_r(d, &buf.de, &de);
5851 if (ignore_file(de->d_name))
5854 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5856 if (errno == ENOENT || errno == ENOTDIR)
5862 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5864 if (errno == ENOENT)
5870 n = read(fd, contents, sizeof(contents));
5874 if (n != 6 || memcmp(contents, "Mains\n", 6))
5877 close_nointr_nofail(fd);
5878 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5880 if (errno == ENOENT)
5886 n = read(fd, contents, sizeof(contents));
5890 if (n != 2 || contents[1] != '\n')
5893 if (contents[0] == '1') {
5894 found_online = true;
5896 } else if (contents[0] == '0')
5897 found_offline = true;
5902 return found_online || !found_offline;