1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
76 char **saved_argv = NULL;
78 static volatile unsigned cached_columns = 0;
79 static volatile unsigned cached_lines = 0;
81 size_t page_size(void) {
82 static __thread size_t pgsz = 0;
85 if (_likely_(pgsz > 0))
88 r = sysconf(_SC_PAGESIZE);
95 bool streq_ptr(const char *a, const char *b) {
97 /* Like streq(), but tries to make sense of NULL pointers */
108 char* endswith(const char *s, const char *postfix) {
115 pl = strlen(postfix);
118 return (char*) s + sl;
123 if (memcmp(s + sl - pl, postfix, pl) != 0)
126 return (char*) s + sl - pl;
129 char* startswith(const char *s, const char *prefix) {
146 char* startswith_no_case(const char *s, const char *prefix) {
156 if (tolower(*a) != tolower(*b))
163 bool first_word(const char *s, const char *word) {
178 if (memcmp(s, word, wl) != 0)
182 strchr(WHITESPACE, s[wl]);
185 int close_nointr(int fd) {
200 void close_nointr_nofail(int fd) {
201 int saved_errno = errno;
203 /* like close_nointr() but cannot fail, and guarantees errno
206 assert_se(close_nointr(fd) == 0);
211 void close_many(const int fds[], unsigned n_fd) {
214 for (i = 0; i < n_fd; i++)
215 close_nointr_nofail(fds[i]);
218 int parse_boolean(const char *v) {
221 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
223 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
229 int parse_pid(const char *s, pid_t* ret_pid) {
230 unsigned long ul = 0;
237 r = safe_atolu(s, &ul);
243 if ((unsigned long) pid != ul)
253 int parse_uid(const char *s, uid_t* ret_uid) {
254 unsigned long ul = 0;
261 r = safe_atolu(s, &ul);
267 if ((unsigned long) uid != ul)
274 int safe_atou(const char *s, unsigned *ret_u) {
282 l = strtoul(s, &x, 0);
284 if (!x || x == s || *x || errno)
285 return errno ? -errno : -EINVAL;
287 if ((unsigned long) (unsigned) l != l)
290 *ret_u = (unsigned) l;
294 int safe_atoi(const char *s, int *ret_i) {
302 l = strtol(s, &x, 0);
304 if (!x || x == s || *x || errno)
305 return errno ? -errno : -EINVAL;
307 if ((long) (int) l != l)
314 int safe_atollu(const char *s, long long unsigned *ret_llu) {
316 unsigned long long l;
322 l = strtoull(s, &x, 0);
324 if (!x || x == s || *x || errno)
325 return errno ? -errno : -EINVAL;
331 int safe_atolli(const char *s, long long int *ret_lli) {
339 l = strtoll(s, &x, 0);
341 if (!x || x == s || *x || errno)
342 return errno ? -errno : -EINVAL;
348 /* Split a string into words. */
349 char *split(const char *c, size_t *l, const char *separator, char **state) {
352 current = *state ? *state : (char*) c;
354 if (!*current || *c == 0)
357 current += strspn(current, separator);
358 *l = strcspn(current, separator);
361 return (char*) current;
364 /* Split a string into words, but consider strings enclosed in '' and
365 * "" as words even if they include spaces. */
366 char *split_quoted(const char *c, size_t *l, char **state) {
368 bool escaped = false;
370 current = *state ? *state : (char*) c;
372 if (!*current || *c == 0)
375 current += strspn(current, WHITESPACE);
377 if (*current == '\'') {
380 for (e = current; *e; e++) {
390 *state = *e == 0 ? e : e+1;
391 } else if (*current == '\"') {
394 for (e = current; *e; e++) {
404 *state = *e == 0 ? e : e+1;
406 for (e = current; *e; e++) {
411 else if (strchr(WHITESPACE, *e))
418 return (char*) current;
421 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
423 _cleanup_fclose_ FILE *f = NULL;
424 char fn[PATH_MAX], line[LINE_MAX], *p;
430 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
437 if (!fgets(line, sizeof(line), f)) {
438 r = feof(f) ? -EIO : -errno;
442 /* Let's skip the pid and comm fields. The latter is enclosed
443 * in () but does not escape any () in its value, so let's
444 * skip over it manually */
446 p = strrchr(line, ')');
458 if ((long unsigned) (pid_t) ppid != ppid)
461 *_ppid = (pid_t) ppid;
466 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
467 _cleanup_fclose_ FILE *f = NULL;
468 char fn[PATH_MAX], line[LINE_MAX], *p;
473 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
480 if (!fgets(line, sizeof(line), f)) {
487 /* Let's skip the pid and comm fields. The latter is enclosed
488 * in () but does not escape any () in its value, so let's
489 * skip over it manually */
491 p = strrchr(line, ')');
513 "%*d " /* priority */
515 "%*d " /* num_threads */
516 "%*d " /* itrealvalue */
517 "%llu " /* starttime */,
524 int write_one_line_file(const char *fn, const char *line) {
525 _cleanup_fclose_ FILE *f = NULL;
535 if (fputs(line, f) < 0)
536 return errno ? -errno : -EIO;
538 if (!endswith(line, "\n"))
544 return errno ? -errno : -EIO;
549 int fchmod_umask(int fd, mode_t m) {
554 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
560 int write_one_line_file_atomic(const char *fn, const char *line) {
561 _cleanup_fclose_ FILE *f = NULL;
562 _cleanup_free_ char *p = NULL;
568 r = fopen_temporary(fn, &f, &p);
572 fchmod_umask(fileno(f), 0644);
575 if (fputs(line, f) < 0) {
580 if (!endswith(line, "\n"))
586 r = errno ? -errno : -EIO;
588 if (rename(p, fn) < 0)
601 int read_one_line_file(const char *fn, char **line) {
602 _cleanup_fclose_ FILE *f = NULL;
603 char t[LINE_MAX], *c;
612 if (!fgets(t, sizeof(t), f)) {
615 return errno ? -errno : -EIO;
629 int read_full_file(const char *fn, char **contents, size_t *size) {
630 _cleanup_fclose_ FILE *f = NULL;
632 _cleanup_free_ char *buf = NULL;
642 if (fstat(fileno(f), &st) < 0)
646 if (st.st_size > 4*1024*1024)
649 n = st.st_size > 0 ? st.st_size : LINE_MAX;
656 t = realloc(buf, n+1);
661 k = fread(buf + l, 1, n - l, f);
690 const char *separator, ...) {
693 char *contents = NULL, *p;
698 if ((r = read_full_file(fname, &contents, NULL)) < 0)
703 const char *key = NULL;
705 p += strspn(p, separator);
706 p += strspn(p, WHITESPACE);
711 if (!strchr(COMMENTS, *p)) {
715 va_start(ap, separator);
716 while ((key = va_arg(ap, char *))) {
720 value = va_arg(ap, char **);
723 if (strncmp(p, key, n) != 0 ||
728 n = strcspn(p, separator);
731 strchr(QUOTES, p[0]) &&
733 v = strndup(p+1, n-2);
744 /* return empty value strings as NULL */
761 p += strcspn(p, separator);
769 int load_env_file(const char *fname, char ***rl) {
771 _cleanup_fclose_ FILE *f;
772 _cleanup_strv_free_ char **m = NULL;
773 _cleanup_free_ char *c = NULL;
778 /* This reads an environment file, but will not complain about
779 * any invalid assignments, that needs to be done by the
782 f = fopen(fname, "re");
787 char l[LINE_MAX], *p, *cs, *b;
789 if (!fgets(l, sizeof(l), f)) {
793 /* The previous line was a continuation line?
794 * Let's process it now, before we leave the
802 /* Is this a continuation line? If so, just append
803 * this to c, and go to next line right-away */
804 cs = endswith(l, "\\\n");
816 /* If the previous line was a continuation line,
817 * append the current line to it */
828 p = strstrip(c ? c : l);
830 if (*p && !strchr(COMMENTS, *p)) {
831 _cleanup_free_ char *u;
834 u = normalize_env_assignment(p);
838 k = strv_extend(&m, u);
853 int write_env_file(const char *fname, char **l) {
858 r = fopen_temporary(fname, &f, &p);
862 fchmod_umask(fileno(f), 0644);
878 if (rename(p, fname) < 0)
893 char *truncate_nl(char *s) {
896 s[strcspn(s, NEWLINE)] = 0;
900 int get_process_comm(pid_t pid, char **name) {
906 r = read_one_line_file("/proc/self/comm", name);
909 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
912 r = read_one_line_file(p, name);
919 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
927 f = fopen("/proc/self/cmdline", "re");
930 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
939 if (max_length == 0) {
941 while ((c = getc(f)) != EOF) {
942 k = realloc(r, len+1);
949 r[len-1] = isprint(c) ? c : ' ';
956 r = new(char, max_length);
964 while ((c = getc(f)) != EOF) {
986 size_t n = MIN(left-1, 3U);
995 /* Kernel threads have no argv[] */
996 if (r == NULL || r[0] == 0) {
1005 h = get_process_comm(pid, &t);
1009 r = strjoin("[", t, "]", NULL);
1020 int is_kernel_thread(pid_t pid) {
1030 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1039 count = fread(&c, 1, 1, f);
1043 /* Kernel threads have an empty cmdline */
1046 return eof ? 1 : -errno;
1051 int get_process_exe(pid_t pid, char **name) {
1057 r = readlink_malloc("/proc/self/exe", name);
1060 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1063 r = readlink_malloc(p, name);
1070 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1071 _cleanup_fclose_ FILE *f = NULL;
1072 _cleanup_free_ char *p = NULL;
1080 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1087 FOREACH_LINE(f, line, return -errno) {
1092 if (startswith(l, field)) {
1094 l += strspn(l, WHITESPACE);
1096 l[strcspn(l, WHITESPACE)] = 0;
1098 return parse_uid(l, uid);
1105 int get_process_uid(pid_t pid, uid_t *uid) {
1106 return get_process_id(pid, "Uid:", uid);
1109 int get_process_gid(pid_t pid, gid_t *gid) {
1110 return get_process_id(pid, "Gid:", gid);
1113 char *strnappend(const char *s, const char *suffix, size_t b) {
1121 return strndup(suffix, b);
1130 if (b > ((size_t) -1) - a)
1133 r = new(char, a+b+1);
1138 memcpy(r+a, suffix, b);
1144 char *strappend(const char *s, const char *suffix) {
1145 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1148 int readlink_malloc(const char *p, char **r) {
1158 if (!(c = new(char, l)))
1161 if ((n = readlink(p, c, l-1)) < 0) {
1167 if ((size_t) n < l-1) {
1178 int readlink_and_make_absolute(const char *p, char **r) {
1185 if ((j = readlink_malloc(p, &target)) < 0)
1188 k = file_in_same_dir(p, target);
1198 int readlink_and_canonicalize(const char *p, char **r) {
1205 j = readlink_and_make_absolute(p, &t);
1209 s = canonicalize_file_name(t);
1216 path_kill_slashes(*r);
1221 int reset_all_signal_handlers(void) {
1224 for (sig = 1; sig < _NSIG; sig++) {
1225 struct sigaction sa;
1227 if (sig == SIGKILL || sig == SIGSTOP)
1231 sa.sa_handler = SIG_DFL;
1232 sa.sa_flags = SA_RESTART;
1234 /* On Linux the first two RT signals are reserved by
1235 * glibc, and sigaction() will return EINVAL for them. */
1236 if ((sigaction(sig, &sa, NULL) < 0))
1237 if (errno != EINVAL)
1244 char *strstrip(char *s) {
1247 /* Drops trailing whitespace. Modifies the string in
1248 * place. Returns pointer to first non-space character */
1250 s += strspn(s, WHITESPACE);
1252 for (e = strchr(s, 0); e > s; e --)
1253 if (!strchr(WHITESPACE, e[-1]))
1261 char *delete_chars(char *s, const char *bad) {
1264 /* Drops all whitespace, regardless where in the string */
1266 for (f = s, t = s; *f; f++) {
1267 if (strchr(bad, *f))
1278 bool in_charset(const char *s, const char* charset) {
1284 for (i = s; *i; i++)
1285 if (!strchr(charset, *i))
1291 char *file_in_same_dir(const char *path, const char *filename) {
1298 /* This removes the last component of path and appends
1299 * filename, unless the latter is absolute anyway or the
1302 if (path_is_absolute(filename))
1303 return strdup(filename);
1305 if (!(e = strrchr(path, '/')))
1306 return strdup(filename);
1308 k = strlen(filename);
1309 if (!(r = new(char, e-path+1+k+1)))
1312 memcpy(r, path, e-path+1);
1313 memcpy(r+(e-path)+1, filename, k+1);
1318 int rmdir_parents(const char *path, const char *stop) {
1327 /* Skip trailing slashes */
1328 while (l > 0 && path[l-1] == '/')
1334 /* Skip last component */
1335 while (l > 0 && path[l-1] != '/')
1338 /* Skip trailing slashes */
1339 while (l > 0 && path[l-1] == '/')
1345 if (!(t = strndup(path, l)))
1348 if (path_startswith(stop, t)) {
1357 if (errno != ENOENT)
1365 char hexchar(int x) {
1366 static const char table[16] = "0123456789abcdef";
1368 return table[x & 15];
1371 int unhexchar(char c) {
1373 if (c >= '0' && c <= '9')
1376 if (c >= 'a' && c <= 'f')
1377 return c - 'a' + 10;
1379 if (c >= 'A' && c <= 'F')
1380 return c - 'A' + 10;
1385 char octchar(int x) {
1386 return '0' + (x & 7);
1389 int unoctchar(char c) {
1391 if (c >= '0' && c <= '7')
1397 char decchar(int x) {
1398 return '0' + (x % 10);
1401 int undecchar(char c) {
1403 if (c >= '0' && c <= '9')
1409 char *cescape(const char *s) {
1415 /* Does C style string escaping. */
1417 r = new(char, strlen(s)*4 + 1);
1421 for (f = s, t = r; *f; f++)
1467 /* For special chars we prefer octal over
1468 * hexadecimal encoding, simply because glib's
1469 * g_strescape() does the same */
1470 if ((*f < ' ') || (*f >= 127)) {
1472 *(t++) = octchar((unsigned char) *f >> 6);
1473 *(t++) = octchar((unsigned char) *f >> 3);
1474 *(t++) = octchar((unsigned char) *f);
1485 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1492 /* Undoes C style string escaping, and optionally prefixes it. */
1494 pl = prefix ? strlen(prefix) : 0;
1496 r = new(char, pl+length+1);
1501 memcpy(r, prefix, pl);
1503 for (f = s, t = r + pl; f < s + length; f++) {
1546 /* This is an extension of the XDG syntax files */
1551 /* hexadecimal encoding */
1554 a = unhexchar(f[1]);
1555 b = unhexchar(f[2]);
1557 if (a < 0 || b < 0) {
1558 /* Invalid escape code, let's take it literal then */
1562 *(t++) = (char) ((a << 4) | b);
1577 /* octal encoding */
1580 a = unoctchar(f[0]);
1581 b = unoctchar(f[1]);
1582 c = unoctchar(f[2]);
1584 if (a < 0 || b < 0 || c < 0) {
1585 /* Invalid escape code, let's take it literal then */
1589 *(t++) = (char) ((a << 6) | (b << 3) | c);
1597 /* premature end of string.*/
1602 /* Invalid escape code, let's take it literal then */
1614 char *cunescape_length(const char *s, size_t length) {
1615 return cunescape_length_with_prefix(s, length, NULL);
1618 char *cunescape(const char *s) {
1621 return cunescape_length(s, strlen(s));
1624 char *xescape(const char *s, const char *bad) {
1628 /* Escapes all chars in bad, in addition to \ and all special
1629 * chars, in \xFF style escaping. May be reversed with
1632 r = new(char, strlen(s) * 4 + 1);
1636 for (f = s, t = r; *f; f++) {
1638 if ((*f < ' ') || (*f >= 127) ||
1639 (*f == '\\') || strchr(bad, *f)) {
1642 *(t++) = hexchar(*f >> 4);
1643 *(t++) = hexchar(*f);
1653 char *bus_path_escape(const char *s) {
1659 /* Escapes all chars that D-Bus' object path cannot deal
1660 * with. Can be reverse with bus_path_unescape() */
1662 if (!(r = new(char, strlen(s)*3+1)))
1665 for (f = s, t = r; *f; f++) {
1667 if (!(*f >= 'A' && *f <= 'Z') &&
1668 !(*f >= 'a' && *f <= 'z') &&
1669 !(*f >= '0' && *f <= '9')) {
1671 *(t++) = hexchar(*f >> 4);
1672 *(t++) = hexchar(*f);
1682 char *bus_path_unescape(const char *f) {
1687 if (!(r = strdup(f)))
1690 for (t = r; *f; f++) {
1695 if ((a = unhexchar(f[1])) < 0 ||
1696 (b = unhexchar(f[2])) < 0) {
1697 /* Invalid escape code, let's take it literal then */
1700 *(t++) = (char) ((a << 4) | b);
1712 char *ascii_strlower(char *t) {
1717 for (p = t; *p; p++)
1718 if (*p >= 'A' && *p <= 'Z')
1719 *p = *p - 'A' + 'a';
1724 static bool ignore_file_allow_backup(const char *filename) {
1728 filename[0] == '.' ||
1729 streq(filename, "lost+found") ||
1730 streq(filename, "aquota.user") ||
1731 streq(filename, "aquota.group") ||
1732 endswith(filename, ".rpmnew") ||
1733 endswith(filename, ".rpmsave") ||
1734 endswith(filename, ".rpmorig") ||
1735 endswith(filename, ".dpkg-old") ||
1736 endswith(filename, ".dpkg-new") ||
1737 endswith(filename, ".swp");
1740 bool ignore_file(const char *filename) {
1743 if (endswith(filename, "~"))
1746 return ignore_file_allow_backup(filename);
1749 int fd_nonblock(int fd, bool nonblock) {
1754 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1758 flags |= O_NONBLOCK;
1760 flags &= ~O_NONBLOCK;
1762 if (fcntl(fd, F_SETFL, flags) < 0)
1768 int fd_cloexec(int fd, bool cloexec) {
1773 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1777 flags |= FD_CLOEXEC;
1779 flags &= ~FD_CLOEXEC;
1781 if (fcntl(fd, F_SETFD, flags) < 0)
1787 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1790 assert(n_fdset == 0 || fdset);
1792 for (i = 0; i < n_fdset; i++)
1799 int close_all_fds(const int except[], unsigned n_except) {
1804 assert(n_except == 0 || except);
1806 d = opendir("/proc/self/fd");
1811 /* When /proc isn't available (for example in chroots)
1812 * the fallback is brute forcing through the fd
1815 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1816 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1818 if (fd_in_set(fd, except, n_except))
1821 if (close_nointr(fd) < 0)
1822 if (errno != EBADF && r == 0)
1829 while ((de = readdir(d))) {
1832 if (ignore_file(de->d_name))
1835 if (safe_atoi(de->d_name, &fd) < 0)
1836 /* Let's better ignore this, just in case */
1845 if (fd_in_set(fd, except, n_except))
1848 if (close_nointr(fd) < 0) {
1849 /* Valgrind has its own FD and doesn't want to have it closed */
1850 if (errno != EBADF && r == 0)
1859 bool chars_intersect(const char *a, const char *b) {
1862 /* Returns true if any of the chars in a are in b. */
1863 for (p = a; *p; p++)
1870 bool fstype_is_network(const char *fstype) {
1871 static const char table[] =
1880 return nulstr_contains(table, fstype);
1884 _cleanup_close_ int fd;
1886 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1892 TIOCL_GETKMSGREDIRECT,
1896 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1899 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1902 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1908 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1909 struct termios old_termios, new_termios;
1911 char line[LINE_MAX];
1916 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1917 new_termios = old_termios;
1919 new_termios.c_lflag &= ~ICANON;
1920 new_termios.c_cc[VMIN] = 1;
1921 new_termios.c_cc[VTIME] = 0;
1923 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1926 if (t != (usec_t) -1) {
1927 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1928 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1933 k = fread(&c, 1, 1, f);
1935 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1941 *need_nl = c != '\n';
1948 if (t != (usec_t) -1)
1949 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1952 if (!fgets(line, sizeof(line), f))
1957 if (strlen(line) != 1)
1967 int ask(char *ret, const char *replies, const char *text, ...) {
1977 bool need_nl = true;
1980 fputs(ANSI_HIGHLIGHT_ON, stdout);
1987 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1991 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1994 if (r == -EBADMSG) {
1995 puts("Bad input, please try again.");
2006 if (strchr(replies, c)) {
2011 puts("Read unexpected character, please try again.");
2015 int reset_terminal_fd(int fd, bool switch_to_text) {
2016 struct termios termios;
2019 /* Set terminal to some sane defaults */
2023 /* We leave locked terminal attributes untouched, so that
2024 * Plymouth may set whatever it wants to set, and we don't
2025 * interfere with that. */
2027 /* Disable exclusive mode, just in case */
2028 ioctl(fd, TIOCNXCL);
2030 /* Switch to text mode */
2032 ioctl(fd, KDSETMODE, KD_TEXT);
2034 /* Enable console unicode mode */
2035 ioctl(fd, KDSKBMODE, K_UNICODE);
2037 if (tcgetattr(fd, &termios) < 0) {
2042 /* We only reset the stuff that matters to the software. How
2043 * hardware is set up we don't touch assuming that somebody
2044 * else will do that for us */
2046 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2047 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2048 termios.c_oflag |= ONLCR;
2049 termios.c_cflag |= CREAD;
2050 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2052 termios.c_cc[VINTR] = 03; /* ^C */
2053 termios.c_cc[VQUIT] = 034; /* ^\ */
2054 termios.c_cc[VERASE] = 0177;
2055 termios.c_cc[VKILL] = 025; /* ^X */
2056 termios.c_cc[VEOF] = 04; /* ^D */
2057 termios.c_cc[VSTART] = 021; /* ^Q */
2058 termios.c_cc[VSTOP] = 023; /* ^S */
2059 termios.c_cc[VSUSP] = 032; /* ^Z */
2060 termios.c_cc[VLNEXT] = 026; /* ^V */
2061 termios.c_cc[VWERASE] = 027; /* ^W */
2062 termios.c_cc[VREPRINT] = 022; /* ^R */
2063 termios.c_cc[VEOL] = 0;
2064 termios.c_cc[VEOL2] = 0;
2066 termios.c_cc[VTIME] = 0;
2067 termios.c_cc[VMIN] = 1;
2069 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2073 /* Just in case, flush all crap out */
2074 tcflush(fd, TCIOFLUSH);
2079 int reset_terminal(const char *name) {
2082 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2086 r = reset_terminal_fd(fd, true);
2087 close_nointr_nofail(fd);
2092 int open_terminal(const char *name, int mode) {
2097 * If a TTY is in the process of being closed opening it might
2098 * cause EIO. This is horribly awful, but unlikely to be
2099 * changed in the kernel. Hence we work around this problem by
2100 * retrying a couple of times.
2102 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2106 fd = open(name, mode);
2113 /* Max 1s in total */
2117 usleep(50 * USEC_PER_MSEC);
2126 close_nointr_nofail(fd);
2131 close_nointr_nofail(fd);
2138 int flush_fd(int fd) {
2139 struct pollfd pollfd;
2143 pollfd.events = POLLIN;
2150 if ((r = poll(&pollfd, 1, 0)) < 0) {
2161 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2166 if (errno == EAGAIN)
2177 int acquire_terminal(
2181 bool ignore_tiocstty_eperm,
2184 int fd = -1, notify = -1, r = 0, wd = -1;
2186 struct sigaction sa_old, sa_new;
2190 /* We use inotify to be notified when the tty is closed. We
2191 * create the watch before checking if we can actually acquire
2192 * it, so that we don't lose any event.
2194 * Note: strictly speaking this actually watches for the
2195 * device being closed, it does *not* really watch whether a
2196 * tty loses its controlling process. However, unless some
2197 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2198 * its tty otherwise this will not become a problem. As long
2199 * as the administrator makes sure not configure any service
2200 * on the same tty as an untrusted user this should not be a
2201 * problem. (Which he probably should not do anyway.) */
2203 if (timeout != (usec_t) -1)
2204 ts = now(CLOCK_MONOTONIC);
2206 if (!fail && !force) {
2207 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2213 wd = inotify_add_watch(notify, name, IN_CLOSE);
2222 r = flush_fd(notify);
2227 /* We pass here O_NOCTTY only so that we can check the return
2228 * value TIOCSCTTY and have a reliable way to figure out if we
2229 * successfully became the controlling process of the tty */
2230 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2234 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2235 * if we already own the tty. */
2237 sa_new.sa_handler = SIG_IGN;
2238 sa_new.sa_flags = SA_RESTART;
2239 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2241 /* First, try to get the tty */
2242 if (ioctl(fd, TIOCSCTTY, force) < 0)
2245 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2247 /* Sometimes it makes sense to ignore TIOCSCTTY
2248 * returning EPERM, i.e. when very likely we already
2249 * are have this controlling terminal. */
2250 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2253 if (r < 0 && (force || fail || r != -EPERM)) {
2262 assert(notify >= 0);
2265 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2267 struct inotify_event *e;
2269 if (timeout != (usec_t) -1) {
2272 n = now(CLOCK_MONOTONIC);
2273 if (ts + timeout < n) {
2278 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2288 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2291 if (errno == EINTR || errno == EAGAIN)
2298 e = (struct inotify_event*) inotify_buffer;
2303 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2308 step = sizeof(struct inotify_event) + e->len;
2309 assert(step <= (size_t) l);
2311 e = (struct inotify_event*) ((uint8_t*) e + step);
2318 /* We close the tty fd here since if the old session
2319 * ended our handle will be dead. It's important that
2320 * we do this after sleeping, so that we don't enter
2321 * an endless loop. */
2322 close_nointr_nofail(fd);
2326 close_nointr_nofail(notify);
2328 r = reset_terminal_fd(fd, true);
2330 log_warning("Failed to reset terminal: %s", strerror(-r));
2336 close_nointr_nofail(fd);
2339 close_nointr_nofail(notify);
2344 int release_terminal(void) {
2346 struct sigaction sa_old, sa_new;
2348 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2351 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2352 * by our own TIOCNOTTY */
2355 sa_new.sa_handler = SIG_IGN;
2356 sa_new.sa_flags = SA_RESTART;
2357 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2359 if (ioctl(fd, TIOCNOTTY) < 0)
2362 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2364 close_nointr_nofail(fd);
2368 int sigaction_many(const struct sigaction *sa, ...) {
2373 while ((sig = va_arg(ap, int)) > 0)
2374 if (sigaction(sig, sa, NULL) < 0)
2381 int ignore_signals(int sig, ...) {
2382 struct sigaction sa;
2387 sa.sa_handler = SIG_IGN;
2388 sa.sa_flags = SA_RESTART;
2390 if (sigaction(sig, &sa, NULL) < 0)
2394 while ((sig = va_arg(ap, int)) > 0)
2395 if (sigaction(sig, &sa, NULL) < 0)
2402 int default_signals(int sig, ...) {
2403 struct sigaction sa;
2408 sa.sa_handler = SIG_DFL;
2409 sa.sa_flags = SA_RESTART;
2411 if (sigaction(sig, &sa, NULL) < 0)
2415 while ((sig = va_arg(ap, int)) > 0)
2416 if (sigaction(sig, &sa, NULL) < 0)
2423 int close_pipe(int p[]) {
2429 a = close_nointr(p[0]);
2434 b = close_nointr(p[1]);
2438 return a < 0 ? a : b;
2441 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2450 while (nbytes > 0) {
2453 if ((k = read(fd, p, nbytes)) <= 0) {
2455 if (k < 0 && errno == EINTR)
2458 if (k < 0 && errno == EAGAIN && do_poll) {
2459 struct pollfd pollfd;
2463 pollfd.events = POLLIN;
2465 if (poll(&pollfd, 1, -1) < 0) {
2469 return n > 0 ? n : -errno;
2472 if (pollfd.revents != POLLIN)
2473 return n > 0 ? n : -EIO;
2478 return n > 0 ? n : (k < 0 ? -errno : 0);
2489 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2498 while (nbytes > 0) {
2501 k = write(fd, p, nbytes);
2504 if (k < 0 && errno == EINTR)
2507 if (k < 0 && errno == EAGAIN && do_poll) {
2508 struct pollfd pollfd;
2512 pollfd.events = POLLOUT;
2514 if (poll(&pollfd, 1, -1) < 0) {
2518 return n > 0 ? n : -errno;
2521 if (pollfd.revents != POLLOUT)
2522 return n > 0 ? n : -EIO;
2527 return n > 0 ? n : (k < 0 ? -errno : 0);
2538 int parse_bytes(const char *t, off_t *bytes) {
2539 static const struct {
2545 { "M", 1024ULL*1024ULL },
2546 { "G", 1024ULL*1024ULL*1024ULL },
2547 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2548 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2549 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2566 l = strtoll(p, &e, 10);
2577 e += strspn(e, WHITESPACE);
2579 for (i = 0; i < ELEMENTSOF(table); i++)
2580 if (startswith(e, table[i].suffix)) {
2581 r += (off_t) l * table[i].factor;
2582 p = e + strlen(table[i].suffix);
2586 if (i >= ELEMENTSOF(table))
2596 int make_stdio(int fd) {
2601 r = dup3(fd, STDIN_FILENO, 0);
2602 s = dup3(fd, STDOUT_FILENO, 0);
2603 t = dup3(fd, STDERR_FILENO, 0);
2606 close_nointr_nofail(fd);
2608 if (r < 0 || s < 0 || t < 0)
2611 /* We rely here that the new fd has O_CLOEXEC not set */
2616 int make_null_stdio(void) {
2619 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2623 return make_stdio(null_fd);
2626 bool is_device_path(const char *path) {
2628 /* Returns true on paths that refer to a device, either in
2629 * sysfs or in /dev */
2632 path_startswith(path, "/dev/") ||
2633 path_startswith(path, "/sys/");
2636 int dir_is_empty(const char *path) {
2637 _cleanup_closedir_ DIR *d;
2646 union dirent_storage buf;
2648 r = readdir_r(d, &buf.de, &de);
2655 if (!ignore_file(de->d_name))
2660 unsigned long long random_ull(void) {
2661 _cleanup_close_ int fd;
2665 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2669 r = loop_read(fd, &ull, sizeof(ull), true);
2670 if (r != sizeof(ull))
2676 return random() * RAND_MAX + random();
2679 void rename_process(const char name[8]) {
2682 /* This is a like a poor man's setproctitle(). It changes the
2683 * comm field, argv[0], and also the glibc's internally used
2684 * name of the process. For the first one a limit of 16 chars
2685 * applies, to the second one usually one of 10 (i.e. length
2686 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2687 * "systemd"). If you pass a longer string it will be
2690 prctl(PR_SET_NAME, name);
2692 if (program_invocation_name)
2693 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2695 if (saved_argc > 0) {
2699 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2701 for (i = 1; i < saved_argc; i++) {
2705 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2710 void sigset_add_many(sigset_t *ss, ...) {
2717 while ((sig = va_arg(ap, int)) > 0)
2718 assert_se(sigaddset(ss, sig) == 0);
2722 char* gethostname_malloc(void) {
2725 assert_se(uname(&u) >= 0);
2727 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2728 return strdup(u.nodename);
2730 return strdup(u.sysname);
2733 bool hostname_is_set(void) {
2736 assert_se(uname(&u) >= 0);
2738 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2741 static char *lookup_uid(uid_t uid) {
2744 _cleanup_free_ char *buf = NULL;
2745 struct passwd pwbuf, *pw = NULL;
2747 /* Shortcut things to avoid NSS lookups */
2749 return strdup("root");
2751 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2755 buf = malloc(bufsize);
2759 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2760 return strdup(pw->pw_name);
2762 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2768 char* getlogname_malloc(void) {
2772 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2777 return lookup_uid(uid);
2780 char *getusername_malloc(void) {
2787 return lookup_uid(getuid());
2790 int getttyname_malloc(int fd, char **r) {
2791 char path[PATH_MAX], *c;
2796 k = ttyname_r(fd, path, sizeof(path));
2802 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2810 int getttyname_harder(int fd, char **r) {
2814 k = getttyname_malloc(fd, &s);
2818 if (streq(s, "tty")) {
2820 return get_ctty(0, NULL, r);
2827 int get_ctty_devnr(pid_t pid, dev_t *d) {
2829 char line[LINE_MAX], *p, *fn;
2830 unsigned long ttynr;
2833 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2836 f = fopen(fn, "re");
2841 if (!fgets(line, sizeof(line), f)) {
2842 k = feof(f) ? -EIO : -errno;
2849 p = strrchr(line, ')');
2859 "%*d " /* session */
2864 if (major(ttynr) == 0 && minor(ttynr) == 0)
2871 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2873 char fn[PATH_MAX], *s, *b, *p;
2878 k = get_ctty_devnr(pid, &devnr);
2882 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2885 k = readlink_malloc(fn, &s);
2891 /* This is an ugly hack */
2892 if (major(devnr) == 136) {
2893 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2903 /* Probably something like the ptys which have no
2904 * symlink in /dev/char. Let's return something
2905 * vaguely useful. */
2918 if (startswith(s, "/dev/"))
2920 else if (startswith(s, "../"))
2938 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2944 /* This returns the first error we run into, but nevertheless
2945 * tries to go on. This closes the passed fd. */
2949 close_nointr_nofail(fd);
2951 return errno == ENOENT ? 0 : -errno;
2956 union dirent_storage buf;
2957 bool is_dir, keep_around;
2961 r = readdir_r(d, &buf.de, &de);
2962 if (r != 0 && ret == 0) {
2970 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2973 if (de->d_type == DT_UNKNOWN ||
2975 (de->d_type == DT_DIR && root_dev)) {
2976 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2977 if (ret == 0 && errno != ENOENT)
2982 is_dir = S_ISDIR(st.st_mode);
2985 (st.st_uid == 0 || st.st_uid == getuid()) &&
2986 (st.st_mode & S_ISVTX);
2988 is_dir = de->d_type == DT_DIR;
2989 keep_around = false;
2995 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2996 if (root_dev && st.st_dev != root_dev->st_dev)
2999 subdir_fd = openat(fd, de->d_name,
3000 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3001 if (subdir_fd < 0) {
3002 if (ret == 0 && errno != ENOENT)
3007 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3008 if (r < 0 && ret == 0)
3012 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3013 if (ret == 0 && errno != ENOENT)
3017 } else if (!only_dirs && !keep_around) {
3019 if (unlinkat(fd, de->d_name, 0) < 0) {
3020 if (ret == 0 && errno != ENOENT)
3031 static int is_temporary_fs(struct statfs *s) {
3033 return s->f_type == TMPFS_MAGIC ||
3034 (long)s->f_type == (long)RAMFS_MAGIC;
3037 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3042 if (fstatfs(fd, &s) < 0) {
3043 close_nointr_nofail(fd);
3047 /* We refuse to clean disk file systems with this call. This
3048 * is extra paranoia just to be sure we never ever remove
3050 if (!is_temporary_fs(&s)) {
3051 log_error("Attempted to remove disk file system, and we can't allow that.");
3052 close_nointr_nofail(fd);
3056 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3059 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3065 /* We refuse to clean the root file system with this
3066 * call. This is extra paranoia to never cause a really
3067 * seriously broken system. */
3068 if (path_equal(path, "/")) {
3069 log_error("Attempted to remove entire root file system, and we can't allow that.");
3073 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3076 if (errno != ENOTDIR)
3080 if (statfs(path, &s) < 0)
3083 if (!is_temporary_fs(&s)) {
3084 log_error("Attempted to remove disk file system, and we can't allow that.");
3089 if (delete_root && !only_dirs)
3090 if (unlink(path) < 0 && errno != ENOENT)
3097 if (fstatfs(fd, &s) < 0) {
3098 close_nointr_nofail(fd);
3102 if (!is_temporary_fs(&s)) {
3103 log_error("Attempted to remove disk file system, and we can't allow that.");
3104 close_nointr_nofail(fd);
3109 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3112 if (honour_sticky && file_is_priv_sticky(path) > 0)
3115 if (rmdir(path) < 0 && errno != ENOENT) {
3124 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3125 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3128 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3129 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3132 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3135 /* Under the assumption that we are running privileged we
3136 * first change the access mode and only then hand out
3137 * ownership to avoid a window where access is too open. */
3139 if (mode != (mode_t) -1)
3140 if (chmod(path, mode) < 0)
3143 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3144 if (chown(path, uid, gid) < 0)
3150 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3153 /* Under the assumption that we are running privileged we
3154 * first change the access mode and only then hand out
3155 * ownership to avoid a window where access is too open. */
3157 if (fchmod(fd, mode) < 0)
3160 if (fchown(fd, uid, gid) < 0)
3166 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3170 /* Allocates the cpuset in the right size */
3173 if (!(r = CPU_ALLOC(n)))
3176 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3177 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3187 if (errno != EINVAL)
3194 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3195 static const char status_indent[] = " "; /* "[" STATUS "] " */
3196 _cleanup_free_ char *s = NULL;
3197 _cleanup_close_ int fd = -1;
3198 struct iovec iovec[5];
3203 /* This is independent of logging, as status messages are
3204 * optional and go exclusively to the console. */
3206 if (vasprintf(&s, format, ap) < 0)
3209 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3222 sl = status ? sizeof(status_indent)-1 : 0;
3228 e = ellipsize(s, emax, 75);
3238 if (!isempty(status)) {
3239 IOVEC_SET_STRING(iovec[n++], "[");
3240 IOVEC_SET_STRING(iovec[n++], status);
3241 IOVEC_SET_STRING(iovec[n++], "] ");
3243 IOVEC_SET_STRING(iovec[n++], status_indent);
3246 IOVEC_SET_STRING(iovec[n++], s);
3247 IOVEC_SET_STRING(iovec[n++], "\n");
3249 if (writev(fd, iovec, n) < 0)
3255 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3261 va_start(ap, format);
3262 r = status_vprintf(status, ellipse, format, ap);
3268 int status_welcome(void) {
3270 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3272 r = parse_env_file("/etc/os-release", NEWLINE,
3273 "PRETTY_NAME", &pretty_name,
3274 "ANSI_COLOR", &ansi_color,
3276 if (r < 0 && r != -ENOENT)
3277 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3279 return status_printf(NULL, false,
3280 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3281 isempty(ansi_color) ? "1" : ansi_color,
3282 isempty(pretty_name) ? "Linux" : pretty_name);
3285 char *replace_env(const char *format, char **env) {
3292 const char *e, *word = format;
3297 for (e = format; *e; e ++) {
3308 if (!(k = strnappend(r, word, e-word-1)))
3317 } else if (*e == '$') {
3318 if (!(k = strnappend(r, word, e-word)))
3334 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3336 k = strappend(r, t);
3350 if (!(k = strnappend(r, word, e-word)))
3361 char **replace_env_argv(char **argv, char **env) {
3363 unsigned k = 0, l = 0;
3365 l = strv_length(argv);
3367 if (!(r = new(char*, l+1)))
3370 STRV_FOREACH(i, argv) {
3372 /* If $FOO appears as single word, replace it by the split up variable */
3373 if ((*i)[0] == '$' && (*i)[1] != '{') {
3378 e = strv_env_get(env, *i+1);
3381 if (!(m = strv_split_quoted(e))) {
3392 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3401 memcpy(r + k, m, q * sizeof(char*));
3409 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3410 if (!(r[k++] = replace_env(*i, env))) {
3420 int fd_columns(int fd) {
3424 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3433 unsigned columns(void) {
3437 if (_likely_(cached_columns > 0))
3438 return cached_columns;
3441 e = getenv("COLUMNS");
3446 c = fd_columns(STDOUT_FILENO);
3455 int fd_lines(int fd) {
3459 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3468 unsigned lines(void) {
3472 if (_likely_(cached_lines > 0))
3473 return cached_lines;
3476 e = getenv("LINES");
3481 l = fd_lines(STDOUT_FILENO);
3487 return cached_lines;
3490 /* intended to be used as a SIGWINCH sighandler */
3491 void columns_lines_cache_reset(int signum) {
3497 static int cached_on_tty = -1;
3499 if (_unlikely_(cached_on_tty < 0))
3500 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3502 return cached_on_tty;
3505 int running_in_chroot(void) {
3511 /* Only works as root */
3513 if (stat("/proc/1/root", &a) < 0)
3516 if (stat("/", &b) < 0)
3520 a.st_dev != b.st_dev ||
3521 a.st_ino != b.st_ino;
3524 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3529 assert(percent <= 100);
3530 assert(new_length >= 3);
3532 if (old_length <= 3 || old_length <= new_length)
3533 return strndup(s, old_length);
3535 r = new0(char, new_length+1);
3539 x = (new_length * percent) / 100;
3541 if (x > new_length - 3)
3549 s + old_length - (new_length - x - 3),
3550 new_length - x - 3);
3555 char *ellipsize(const char *s, size_t length, unsigned percent) {
3556 return ellipsize_mem(s, strlen(s), length, percent);
3559 int touch(const char *path) {
3564 /* This just opens the file for writing, ensuring it
3565 * exists. It doesn't call utimensat() the way /usr/bin/touch
3568 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3572 close_nointr_nofail(fd);
3576 char *unquote(const char *s, const char* quotes) {
3580 /* This is rather stupid, simply removes the heading and
3581 * trailing quotes if there is one. Doesn't care about
3582 * escaping or anything. We should make this smarter one
3589 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3590 return strndup(s+1, l-2);
3595 char *normalize_env_assignment(const char *s) {
3596 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3599 eq = strchr(s, '=');
3611 memmove(r, t, strlen(t) + 1);
3615 name = strndup(s, eq - s);
3623 value = unquote(strstrip(p), QUOTES);
3627 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3633 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3644 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3656 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3663 r = wait_for_terminate(pid, &status);
3665 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3669 if (status.si_code == CLD_EXITED) {
3670 if (status.si_status != 0) {
3671 log_warning("%s failed with error code %i.", name, status.si_status);
3672 return status.si_status;
3675 log_debug("%s succeeded.", name);
3678 } else if (status.si_code == CLD_KILLED ||
3679 status.si_code == CLD_DUMPED) {
3681 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3685 log_warning("%s failed due to unknown reason.", name);
3689 _noreturn_ void freeze(void) {
3691 /* Make sure nobody waits for us on a socket anymore */
3692 close_all_fds(NULL, 0);
3700 bool null_or_empty(struct stat *st) {
3703 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3706 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3712 int null_or_empty_path(const char *fn) {
3717 if (stat(fn, &st) < 0)
3720 return null_or_empty(&st);
3723 DIR *xopendirat(int fd, const char *name, int flags) {
3727 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3733 close_nointr_nofail(nfd);
3740 int signal_from_string_try_harder(const char *s) {
3744 signo = signal_from_string(s);
3746 if (startswith(s, "SIG"))
3747 return signal_from_string(s+3);
3752 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3756 /* FIXME: to follow udev's logic 100% we need to leave valid
3757 * UTF8 chars unescaped */
3759 u = unquote(tagvalue, "\"\'");
3763 t = xescape(u, "/ ");
3769 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3778 char *fstab_node_to_udev_node(const char *p) {
3781 if (startswith(p, "LABEL="))
3782 return tag_to_udev_node(p+6, "label");
3784 if (startswith(p, "UUID="))
3785 return tag_to_udev_node(p+5, "uuid");
3787 if (startswith(p, "PARTUUID="))
3788 return tag_to_udev_node(p+9, "partuuid");
3790 if (startswith(p, "PARTLABEL="))
3791 return tag_to_udev_node(p+10, "partlabel");
3796 bool tty_is_vc(const char *tty) {
3799 if (startswith(tty, "/dev/"))
3802 return vtnr_from_tty(tty) >= 0;
3805 bool tty_is_console(const char *tty) {
3808 if (startswith(tty, "/dev/"))
3811 return streq(tty, "console");
3814 int vtnr_from_tty(const char *tty) {
3819 if (startswith(tty, "/dev/"))
3822 if (!startswith(tty, "tty") )
3825 if (tty[3] < '0' || tty[3] > '9')
3828 r = safe_atoi(tty+3, &i);
3832 if (i < 0 || i > 63)
3838 bool tty_is_vc_resolve(const char *tty) {
3839 char *active = NULL;
3844 if (startswith(tty, "/dev/"))
3847 /* Resolve where /dev/console is pointing to, if /sys is
3848 * actually ours (i.e. not read-only-mounted which is a sign
3849 * for container setups) */
3850 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3851 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3852 /* If multiple log outputs are configured the
3853 * last one is what /dev/console points to */
3854 tty = strrchr(active, ' ');
3867 const char *default_term_for_tty(const char *tty) {
3870 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3873 bool dirent_is_file(const struct dirent *de) {
3876 if (ignore_file(de->d_name))
3879 if (de->d_type != DT_REG &&
3880 de->d_type != DT_LNK &&
3881 de->d_type != DT_UNKNOWN)
3887 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3890 if (de->d_type != DT_REG &&
3891 de->d_type != DT_LNK &&
3892 de->d_type != DT_UNKNOWN)
3895 if (ignore_file_allow_backup(de->d_name))
3898 return endswith(de->d_name, suffix);
3901 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3904 Hashmap *pids = NULL;
3908 /* Executes all binaries in a directory in parallel and waits
3909 * until all they all finished. */
3912 if (!(_d = opendir(directory))) {
3914 if (errno == ENOENT)
3917 log_error("Failed to enumerate directory %s: %m", directory);
3924 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3925 log_error("Failed to allocate set.");
3929 while ((de = readdir(d))) {
3934 if (!dirent_is_file(de))
3937 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3942 if ((pid = fork()) < 0) {
3943 log_error("Failed to fork: %m");
3961 log_error("Failed to execute %s: %m", path);
3962 _exit(EXIT_FAILURE);
3965 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3967 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3968 log_error("Failed to add PID to set: %s", strerror(-k));
3973 while (!hashmap_isempty(pids)) {
3974 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3979 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3984 log_error("waitid() failed: %m");
3988 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3989 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3990 if (si.si_code == CLD_EXITED)
3991 log_error("%s exited with exit status %i.", path, si.si_status);
3993 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3995 log_debug("%s exited successfully.", path);
4006 hashmap_free_free(pids);
4009 int kill_and_sigcont(pid_t pid, int sig) {
4012 r = kill(pid, sig) < 0 ? -errno : 0;
4020 bool nulstr_contains(const char*nulstr, const char *needle) {
4026 NULSTR_FOREACH(i, nulstr)
4027 if (streq(i, needle))
4033 bool plymouth_running(void) {
4034 return access("/run/plymouth/pid", F_OK) >= 0;
4037 char* strshorten(char *s, size_t l) {
4046 static bool hostname_valid_char(char c) {
4048 (c >= 'a' && c <= 'z') ||
4049 (c >= 'A' && c <= 'Z') ||
4050 (c >= '0' && c <= '9') ||
4056 bool hostname_is_valid(const char *s) {
4062 for (p = s; *p; p++)
4063 if (!hostname_valid_char(*p))
4066 if (p-s > HOST_NAME_MAX)
4072 char* hostname_cleanup(char *s) {
4075 for (p = s, d = s; *p; p++)
4076 if ((*p >= 'a' && *p <= 'z') ||
4077 (*p >= 'A' && *p <= 'Z') ||
4078 (*p >= '0' && *p <= '9') ||
4086 strshorten(s, HOST_NAME_MAX);
4090 int pipe_eof(int fd) {
4091 struct pollfd pollfd;
4096 pollfd.events = POLLIN|POLLHUP;
4098 r = poll(&pollfd, 1, 0);
4105 return pollfd.revents & POLLHUP;
4108 int fd_wait_for_event(int fd, int event, usec_t t) {
4109 struct pollfd pollfd;
4114 pollfd.events = event;
4116 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4123 return pollfd.revents;
4126 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4137 t = new(char, strlen(path) + 1 + 6 + 1);
4141 fn = path_get_file_name(path);
4145 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4147 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4153 f = fdopen(fd, "we");
4166 int terminal_vhangup_fd(int fd) {
4169 if (ioctl(fd, TIOCVHANGUP) < 0)
4175 int terminal_vhangup(const char *name) {
4178 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4182 r = terminal_vhangup_fd(fd);
4183 close_nointr_nofail(fd);
4188 int vt_disallocate(const char *name) {
4192 /* Deallocate the VT if possible. If not possible
4193 * (i.e. because it is the active one), at least clear it
4194 * entirely (including the scrollback buffer) */
4196 if (!startswith(name, "/dev/"))
4199 if (!tty_is_vc(name)) {
4200 /* So this is not a VT. I guess we cannot deallocate
4201 * it then. But let's at least clear the screen */
4203 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4208 "\033[r" /* clear scrolling region */
4209 "\033[H" /* move home */
4210 "\033[2J", /* clear screen */
4212 close_nointr_nofail(fd);
4217 if (!startswith(name, "/dev/tty"))
4220 r = safe_atou(name+8, &u);
4227 /* Try to deallocate */
4228 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4232 r = ioctl(fd, VT_DISALLOCATE, u);
4233 close_nointr_nofail(fd);
4241 /* Couldn't deallocate, so let's clear it fully with
4243 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4248 "\033[r" /* clear scrolling region */
4249 "\033[H" /* move home */
4250 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4252 close_nointr_nofail(fd);
4257 int copy_file(const char *from, const char *to) {
4263 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4267 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4269 close_nointr_nofail(fdf);
4277 n = read(fdf, buf, sizeof(buf));
4281 close_nointr_nofail(fdf);
4292 k = loop_write(fdt, buf, n, false);
4294 r = k < 0 ? k : (errno ? -errno : -EIO);
4296 close_nointr_nofail(fdf);
4304 close_nointr_nofail(fdf);
4305 r = close_nointr(fdt);
4315 int symlink_atomic(const char *from, const char *to) {
4317 _cleanup_free_ char *t;
4320 unsigned long long ull;
4327 t = new(char, strlen(to) + 1 + 16 + 1);
4331 fn = path_get_file_name(to);
4335 x = stpcpy(t+k+1, fn);
4338 for (i = 0; i < 16; i++) {
4339 *(x++) = hexchar(ull & 0xF);
4345 if (symlink(from, t) < 0)
4348 if (rename(t, to) < 0) {
4357 bool display_is_local(const char *display) {
4361 display[0] == ':' &&
4362 display[1] >= '0' &&
4366 int socket_from_display(const char *display, char **path) {
4373 if (!display_is_local(display))
4376 k = strspn(display+1, "0123456789");
4378 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4382 c = stpcpy(f, "/tmp/.X11-unix/X");
4383 memcpy(c, display+1, k);
4392 const char **username,
4393 uid_t *uid, gid_t *gid,
4395 const char **shell) {
4403 /* We enforce some special rules for uid=0: in order to avoid
4404 * NSS lookups for root we hardcode its data. */
4406 if (streq(*username, "root") || streq(*username, "0")) {
4424 if (parse_uid(*username, &u) >= 0) {
4428 /* If there are multiple users with the same id, make
4429 * sure to leave $USER to the configured value instead
4430 * of the first occurrence in the database. However if
4431 * the uid was configured by a numeric uid, then let's
4432 * pick the real username from /etc/passwd. */
4434 *username = p->pw_name;
4437 p = getpwnam(*username);
4441 return errno != 0 ? -errno : -ESRCH;
4453 *shell = p->pw_shell;
4458 char* uid_to_name(uid_t uid) {
4463 return strdup("root");
4467 return strdup(p->pw_name);
4469 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4475 int get_group_creds(const char **groupname, gid_t *gid) {
4481 /* We enforce some special rules for gid=0: in order to avoid
4482 * NSS lookups for root we hardcode its data. */
4484 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4485 *groupname = "root";
4493 if (parse_gid(*groupname, &id) >= 0) {
4498 *groupname = g->gr_name;
4501 g = getgrnam(*groupname);
4505 return errno != 0 ? -errno : -ESRCH;
4513 int in_group(const char *name) {
4515 int ngroups_max, r, i;
4517 r = get_group_creds(&name, &gid);
4521 if (getgid() == gid)
4524 if (getegid() == gid)
4527 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4528 assert(ngroups_max > 0);
4530 gids = alloca(sizeof(gid_t) * ngroups_max);
4532 r = getgroups(ngroups_max, gids);
4536 for (i = 0; i < r; i++)
4543 int glob_exists(const char *path) {
4551 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4553 if (k == GLOB_NOMATCH)
4555 else if (k == GLOB_NOSPACE)
4558 r = !strv_isempty(g.gl_pathv);
4560 r = errno ? -errno : -EIO;
4567 int dirent_ensure_type(DIR *d, struct dirent *de) {
4573 if (de->d_type != DT_UNKNOWN)
4576 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4580 S_ISREG(st.st_mode) ? DT_REG :
4581 S_ISDIR(st.st_mode) ? DT_DIR :
4582 S_ISLNK(st.st_mode) ? DT_LNK :
4583 S_ISFIFO(st.st_mode) ? DT_FIFO :
4584 S_ISSOCK(st.st_mode) ? DT_SOCK :
4585 S_ISCHR(st.st_mode) ? DT_CHR :
4586 S_ISBLK(st.st_mode) ? DT_BLK :
4592 int in_search_path(const char *path, char **search) {
4596 r = path_get_parent(path, &parent);
4602 STRV_FOREACH(i, search) {
4603 if (path_equal(parent, *i)) {
4614 int get_files_in_directory(const char *path, char ***list) {
4622 /* Returns all files in a directory in *list, and the number
4623 * of files as return value. If list is NULL returns only the
4632 union dirent_storage buf;
4635 k = readdir_r(d, &buf.de, &de);
4644 dirent_ensure_type(d, de);
4646 if (!dirent_is_file(de))
4650 if ((unsigned) r >= n) {
4654 t = realloc(l, sizeof(char*) * n);
4663 assert((unsigned) r < n);
4665 l[r] = strdup(de->d_name);
4689 char *strjoin(const char *x, ...) {
4703 t = va_arg(ap, const char *);
4708 if (n > ((size_t) -1) - l) {
4732 t = va_arg(ap, const char *);
4746 bool is_main_thread(void) {
4747 static __thread int cached = 0;
4749 if (_unlikely_(cached == 0))
4750 cached = getpid() == gettid() ? 1 : -1;
4755 int block_get_whole_disk(dev_t d, dev_t *ret) {
4762 /* If it has a queue this is good enough for us */
4763 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4766 r = access(p, F_OK);
4774 /* If it is a partition find the originating device */
4775 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4778 r = access(p, F_OK);
4784 /* Get parent dev_t */
4785 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4788 r = read_one_line_file(p, &s);
4794 r = sscanf(s, "%u:%u", &m, &n);
4800 /* Only return this if it is really good enough for us. */
4801 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4804 r = access(p, F_OK);
4808 *ret = makedev(m, n);
4815 int file_is_priv_sticky(const char *p) {
4820 if (lstat(p, &st) < 0)
4824 (st.st_uid == 0 || st.st_uid == getuid()) &&
4825 (st.st_mode & S_ISVTX);
4828 static const char *const ioprio_class_table[] = {
4829 [IOPRIO_CLASS_NONE] = "none",
4830 [IOPRIO_CLASS_RT] = "realtime",
4831 [IOPRIO_CLASS_BE] = "best-effort",
4832 [IOPRIO_CLASS_IDLE] = "idle"
4835 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4837 static const char *const sigchld_code_table[] = {
4838 [CLD_EXITED] = "exited",
4839 [CLD_KILLED] = "killed",
4840 [CLD_DUMPED] = "dumped",
4841 [CLD_TRAPPED] = "trapped",
4842 [CLD_STOPPED] = "stopped",
4843 [CLD_CONTINUED] = "continued",
4846 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4848 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4849 [LOG_FAC(LOG_KERN)] = "kern",
4850 [LOG_FAC(LOG_USER)] = "user",
4851 [LOG_FAC(LOG_MAIL)] = "mail",
4852 [LOG_FAC(LOG_DAEMON)] = "daemon",
4853 [LOG_FAC(LOG_AUTH)] = "auth",
4854 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4855 [LOG_FAC(LOG_LPR)] = "lpr",
4856 [LOG_FAC(LOG_NEWS)] = "news",
4857 [LOG_FAC(LOG_UUCP)] = "uucp",
4858 [LOG_FAC(LOG_CRON)] = "cron",
4859 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4860 [LOG_FAC(LOG_FTP)] = "ftp",
4861 [LOG_FAC(LOG_LOCAL0)] = "local0",
4862 [LOG_FAC(LOG_LOCAL1)] = "local1",
4863 [LOG_FAC(LOG_LOCAL2)] = "local2",
4864 [LOG_FAC(LOG_LOCAL3)] = "local3",
4865 [LOG_FAC(LOG_LOCAL4)] = "local4",
4866 [LOG_FAC(LOG_LOCAL5)] = "local5",
4867 [LOG_FAC(LOG_LOCAL6)] = "local6",
4868 [LOG_FAC(LOG_LOCAL7)] = "local7"
4871 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4873 static const char *const log_level_table[] = {
4874 [LOG_EMERG] = "emerg",
4875 [LOG_ALERT] = "alert",
4876 [LOG_CRIT] = "crit",
4878 [LOG_WARNING] = "warning",
4879 [LOG_NOTICE] = "notice",
4880 [LOG_INFO] = "info",
4881 [LOG_DEBUG] = "debug"
4884 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4886 static const char* const sched_policy_table[] = {
4887 [SCHED_OTHER] = "other",
4888 [SCHED_BATCH] = "batch",
4889 [SCHED_IDLE] = "idle",
4890 [SCHED_FIFO] = "fifo",
4894 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4896 static const char* const rlimit_table[] = {
4897 [RLIMIT_CPU] = "LimitCPU",
4898 [RLIMIT_FSIZE] = "LimitFSIZE",
4899 [RLIMIT_DATA] = "LimitDATA",
4900 [RLIMIT_STACK] = "LimitSTACK",
4901 [RLIMIT_CORE] = "LimitCORE",
4902 [RLIMIT_RSS] = "LimitRSS",
4903 [RLIMIT_NOFILE] = "LimitNOFILE",
4904 [RLIMIT_AS] = "LimitAS",
4905 [RLIMIT_NPROC] = "LimitNPROC",
4906 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4907 [RLIMIT_LOCKS] = "LimitLOCKS",
4908 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4909 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4910 [RLIMIT_NICE] = "LimitNICE",
4911 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4912 [RLIMIT_RTTIME] = "LimitRTTIME"
4915 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4917 static const char* const ip_tos_table[] = {
4918 [IPTOS_LOWDELAY] = "low-delay",
4919 [IPTOS_THROUGHPUT] = "throughput",
4920 [IPTOS_RELIABILITY] = "reliability",
4921 [IPTOS_LOWCOST] = "low-cost",
4924 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4926 static const char *const __signal_table[] = {
4943 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4954 [SIGVTALRM] = "VTALRM",
4956 [SIGWINCH] = "WINCH",
4962 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4964 const char *signal_to_string(int signo) {
4965 static __thread char buf[12];
4968 name = __signal_to_string(signo);
4972 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4973 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4975 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4980 int signal_from_string(const char *s) {
4985 signo = __signal_from_string(s);
4989 if (startswith(s, "RTMIN+")) {
4993 if (safe_atou(s, &u) >= 0) {
4994 signo = (int) u + offset;
4995 if (signo > 0 && signo < _NSIG)
5001 bool kexec_loaded(void) {
5002 bool loaded = false;
5005 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5013 int strdup_or_null(const char *a, char **b) {
5031 int prot_from_flags(int flags) {
5033 switch (flags & O_ACCMODE) {
5042 return PROT_READ|PROT_WRITE;
5049 char *format_bytes(char *buf, size_t l, off_t t) {
5052 static const struct {
5056 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5057 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5058 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5059 { "G", 1024ULL*1024ULL*1024ULL },
5060 { "M", 1024ULL*1024ULL },
5064 for (i = 0; i < ELEMENTSOF(table); i++) {
5066 if (t >= table[i].factor) {
5069 (unsigned long long) (t / table[i].factor),
5070 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5077 snprintf(buf, l, "%lluB", (unsigned long long) t);
5085 void* memdup(const void *p, size_t l) {
5098 int fd_inc_sndbuf(int fd, size_t n) {
5100 socklen_t l = sizeof(value);
5102 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5104 l == sizeof(value) &&
5105 (size_t) value >= n*2)
5109 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5116 int fd_inc_rcvbuf(int fd, size_t n) {
5118 socklen_t l = sizeof(value);
5120 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5122 l == sizeof(value) &&
5123 (size_t) value >= n*2)
5127 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5134 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5135 pid_t parent_pid, agent_pid;
5137 bool stdout_is_tty, stderr_is_tty;
5145 parent_pid = getpid();
5147 /* Spawns a temporary TTY agent, making sure it goes away when
5154 if (agent_pid != 0) {
5161 * Make sure the agent goes away when the parent dies */
5162 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5163 _exit(EXIT_FAILURE);
5165 /* Check whether our parent died before we were able
5166 * to set the death signal */
5167 if (getppid() != parent_pid)
5168 _exit(EXIT_SUCCESS);
5170 /* Don't leak fds to the agent */
5171 close_all_fds(except, n_except);
5173 stdout_is_tty = isatty(STDOUT_FILENO);
5174 stderr_is_tty = isatty(STDERR_FILENO);
5176 if (!stdout_is_tty || !stderr_is_tty) {
5177 /* Detach from stdout/stderr. and reopen
5178 * /dev/tty for them. This is important to
5179 * ensure that when systemctl is started via
5180 * popen() or a similar call that expects to
5181 * read EOF we actually do generate EOF and
5182 * not delay this indefinitely by because we
5183 * keep an unused copy of stdin around. */
5184 fd = open("/dev/tty", O_WRONLY);
5186 log_error("Failed to open /dev/tty: %m");
5187 _exit(EXIT_FAILURE);
5191 dup2(fd, STDOUT_FILENO);
5194 dup2(fd, STDERR_FILENO);
5200 /* Count arguments */
5202 for (n = 0; va_arg(ap, char*); n++)
5207 l = alloca(sizeof(char *) * (n + 1));
5209 /* Fill in arguments */
5211 for (i = 0; i <= n; i++)
5212 l[i] = va_arg(ap, char*);
5216 _exit(EXIT_FAILURE);
5219 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5220 struct rlimit highest, fixed;
5224 if (setrlimit(resource, rlim) >= 0)
5230 /* So we failed to set the desired setrlimit, then let's try
5231 * to get as close as we can */
5232 assert_se(getrlimit(resource, &highest) == 0);
5234 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5235 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5237 if (setrlimit(resource, &fixed) < 0)
5243 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5244 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5256 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5259 f = fopen(path, "re");
5267 char line[LINE_MAX];
5270 for (i = 0; i < sizeof(line)-1; i++) {
5274 if (_unlikely_(c == EOF)) {
5284 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5285 value = strdup(line + l + 1);
5305 int can_sleep(const char *type) {
5309 _cleanup_free_ char *p = NULL;
5313 /* If /sys is read-only we cannot sleep */
5314 if (access("/sys/power/state", W_OK) < 0)
5317 r = read_one_line_file("/sys/power/state", &p);
5322 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5323 if (l == k && memcmp(w, type, l) == 0)
5329 int can_sleep_disk(const char *type) {
5333 _cleanup_free_ char *p = NULL;
5337 /* If /sys is read-only we cannot sleep */
5338 if (access("/sys/power/state", W_OK) < 0 ||
5339 access("/sys/power/disk", W_OK) < 0)
5342 r = read_one_line_file("/sys/power/disk", &p);
5347 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5348 if (l == k && memcmp(w, type, l) == 0)
5351 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5358 bool is_valid_documentation_url(const char *url) {
5361 if (startswith(url, "http://") && url[7])
5364 if (startswith(url, "https://") && url[8])
5367 if (startswith(url, "file:") && url[5])
5370 if (startswith(url, "info:") && url[5])
5373 if (startswith(url, "man:") && url[4])
5379 bool in_initrd(void) {
5380 static __thread int saved = -1;
5386 /* We make two checks here:
5388 * 1. the flag file /etc/initrd-release must exist
5389 * 2. the root file system must be a memory file system
5391 * The second check is extra paranoia, since misdetecting an
5392 * initrd can have bad bad consequences due the initrd
5393 * emptying when transititioning to the main systemd.
5396 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5397 statfs("/", &s) >= 0 &&
5398 is_temporary_fs(&s);
5403 void warn_melody(void) {
5404 _cleanup_close_ int fd = -1;
5406 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5410 /* Yeah, this is synchronous. Kinda sucks. But well... */
5412 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5413 usleep(125*USEC_PER_MSEC);
5415 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5416 usleep(125*USEC_PER_MSEC);
5418 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5419 usleep(125*USEC_PER_MSEC);
5421 ioctl(fd, KIOCSOUND, 0);
5424 int make_console_stdio(void) {
5427 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5429 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5431 log_error("Failed to acquire terminal: %s", strerror(-fd));
5437 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5444 int get_home_dir(char **_h) {
5452 /* Take the user specified one */
5463 /* Hardcode home directory for root to avoid NSS */
5466 h = strdup("/root");
5474 /* Check the database... */
5478 return errno ? -errno : -ESRCH;
5480 if (!path_is_absolute(p->pw_dir))
5483 h = strdup(p->pw_dir);
5491 int get_shell(char **_sh) {
5499 /* Take the user specified one */
5500 e = getenv("SHELL");
5510 /* Hardcode home directory for root to avoid NSS */
5513 sh = strdup("/bin/sh");
5521 /* Check the database... */
5525 return errno ? -errno : -ESRCH;
5527 if (!path_is_absolute(p->pw_shell))
5530 sh = strdup(p->pw_shell);
5538 void freep(void *p) {
5542 void fclosep(FILE **f) {
5547 void pclosep(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 bool string_has_cc(const char *p) {
5607 for (t = p; *t; t++)
5608 if (*t > 0 && *t < ' ')
5614 bool path_is_safe(const char *p) {
5619 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5622 if (strlen(p) > PATH_MAX)
5625 /* The following two checks are not really dangerous, but hey, they still are confusing */
5626 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5629 if (strstr(p, "//"))
5635 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5636 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5637 int (*compar) (const void *, const void *, void *), void *arg) {
5646 p = (void *)(((const char *) base) + (idx * size));
5647 comparison = compar(key, p, arg);
5650 else if (comparison > 0)
5658 bool is_locale_utf8(void) {
5660 static int cached_answer = -1;
5662 if (cached_answer >= 0)
5665 if (!setlocale(LC_ALL, "")) {
5666 cached_answer = true;
5670 set = nl_langinfo(CODESET);
5672 cached_answer = true;
5676 cached_answer = streq(set, "UTF-8");
5678 return (bool)cached_answer;
5681 const char *draw_special_char(DrawSpecialChar ch) {
5682 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5684 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5685 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5686 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5687 [DRAW_TREE_SPACE] = " ", /* */
5688 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5690 /* ASCII fallback */ {
5691 [DRAW_TREE_VERT] = "| ",
5692 [DRAW_TREE_BRANCH] = "|-",
5693 [DRAW_TREE_RIGHT] = "`-",
5694 [DRAW_TREE_SPACE] = " ",
5695 [DRAW_TRIANGULAR_BULLET] = "> ",
5699 return draw_table[!is_locale_utf8()][ch];
5702 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5705 size_t l, old_len, new_len;
5711 old_len = strlen(old_string);
5712 new_len = strlen(new_string);
5725 if (!startswith(f, old_string)) {
5731 nl = l - old_len + new_len;
5732 a = realloc(r, nl + 1);
5740 t = stpcpy(t, new_string);
5752 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5753 const char *i, *begin = NULL;
5758 } state = STATE_OTHER;
5760 size_t osz = 0, isz;
5766 /* Strips ANSI color and replaces TABs by 8 spaces */
5768 isz = _isz ? *_isz : strlen(*ibuf);
5770 f = open_memstream(&obuf, &osz);
5774 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5779 if (i >= *ibuf + isz) /* EOT */
5781 else if (*i == '\x1B')
5782 state = STATE_ESCAPE;
5783 else if (*i == '\t')
5790 if (i >= *ibuf + isz) { /* EOT */
5793 } else if (*i == '[') {
5794 state = STATE_BRACKET;
5799 state = STATE_OTHER;
5806 if (i >= *ibuf + isz || /* EOT */
5807 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5810 state = STATE_OTHER;
5812 } else if (*i == 'm')
5813 state = STATE_OTHER;
5835 int on_ac_power(void) {
5836 bool found_offline = false, found_online = false;
5837 _cleanup_closedir_ DIR *d = NULL;
5839 d = opendir("/sys/class/power_supply");
5845 union dirent_storage buf;
5846 _cleanup_free_ char *p = NULL;
5847 _cleanup_close_ int fd = -1, device = -1;
5852 k = readdir_r(d, &buf.de, &de);
5859 if (ignore_file(de->d_name))
5862 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5864 if (errno == ENOENT || errno == ENOTDIR)
5870 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5872 if (errno == ENOENT)
5878 n = read(fd, contents, sizeof(contents));
5882 if (n != 6 || memcmp(contents, "Mains\n", 6))
5885 close_nointr_nofail(fd);
5886 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5888 if (errno == ENOENT)
5894 n = read(fd, contents, sizeof(contents));
5898 if (n != 2 || contents[1] != '\n')
5901 if (contents[0] == '1') {
5902 found_online = true;
5904 } else if (contents[0] == '0')
5905 found_offline = true;
5910 return found_online || !found_offline;