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) {
191 /* Just ignore EINTR; a retry loop is the wrong
192 * thing to do on Linux.
194 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
195 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
196 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
197 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
199 if (_unlikely_(r < 0 && errno == EINTR))
207 void close_nointr_nofail(int fd) {
208 int saved_errno = errno;
210 /* like close_nointr() but cannot fail, and guarantees errno
213 assert_se(close_nointr(fd) == 0);
218 void close_many(const int fds[], unsigned n_fd) {
221 for (i = 0; i < n_fd; i++)
222 close_nointr_nofail(fds[i]);
225 int parse_boolean(const char *v) {
228 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
230 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
236 int parse_pid(const char *s, pid_t* ret_pid) {
237 unsigned long ul = 0;
244 r = safe_atolu(s, &ul);
250 if ((unsigned long) pid != ul)
260 int parse_uid(const char *s, uid_t* ret_uid) {
261 unsigned long ul = 0;
268 r = safe_atolu(s, &ul);
274 if ((unsigned long) uid != ul)
281 int safe_atou(const char *s, unsigned *ret_u) {
289 l = strtoul(s, &x, 0);
291 if (!x || x == s || *x || errno)
292 return errno ? -errno : -EINVAL;
294 if ((unsigned long) (unsigned) l != l)
297 *ret_u = (unsigned) l;
301 int safe_atoi(const char *s, int *ret_i) {
309 l = strtol(s, &x, 0);
311 if (!x || x == s || *x || errno)
312 return errno ? -errno : -EINVAL;
314 if ((long) (int) l != l)
321 int safe_atollu(const char *s, long long unsigned *ret_llu) {
323 unsigned long long l;
329 l = strtoull(s, &x, 0);
331 if (!x || x == s || *x || errno)
332 return errno ? -errno : -EINVAL;
338 int safe_atolli(const char *s, long long int *ret_lli) {
346 l = strtoll(s, &x, 0);
348 if (!x || x == s || *x || errno)
349 return errno ? -errno : -EINVAL;
355 /* Split a string into words. */
356 char *split(const char *c, size_t *l, const char *separator, char **state) {
359 current = *state ? *state : (char*) c;
361 if (!*current || *c == 0)
364 current += strspn(current, separator);
365 *l = strcspn(current, separator);
368 return (char*) current;
371 /* Split a string into words, but consider strings enclosed in '' and
372 * "" as words even if they include spaces. */
373 char *split_quoted(const char *c, size_t *l, char **state) {
375 bool escaped = false;
377 current = *state ? *state : (char*) c;
379 if (!*current || *c == 0)
382 current += strspn(current, WHITESPACE);
384 if (*current == '\'') {
387 for (e = current; *e; e++) {
397 *state = *e == 0 ? e : e+1;
398 } else if (*current == '\"') {
401 for (e = current; *e; e++) {
411 *state = *e == 0 ? e : e+1;
413 for (e = current; *e; e++) {
418 else if (strchr(WHITESPACE, *e))
425 return (char*) current;
428 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
430 _cleanup_fclose_ FILE *f = NULL;
431 char fn[PATH_MAX], line[LINE_MAX], *p;
437 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
444 if (!fgets(line, sizeof(line), f)) {
445 r = feof(f) ? -EIO : -errno;
449 /* Let's skip the pid and comm fields. The latter is enclosed
450 * in () but does not escape any () in its value, so let's
451 * skip over it manually */
453 p = strrchr(line, ')');
465 if ((long unsigned) (pid_t) ppid != ppid)
468 *_ppid = (pid_t) ppid;
473 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
474 _cleanup_fclose_ FILE *f = NULL;
475 char fn[PATH_MAX], line[LINE_MAX], *p;
480 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
487 if (!fgets(line, sizeof(line), f)) {
494 /* Let's skip the pid and comm fields. The latter is enclosed
495 * in () but does not escape any () in its value, so let's
496 * skip over it manually */
498 p = strrchr(line, ')');
520 "%*d " /* priority */
522 "%*d " /* num_threads */
523 "%*d " /* itrealvalue */
524 "%llu " /* starttime */,
531 int write_one_line_file(const char *fn, const char *line) {
532 _cleanup_fclose_ FILE *f = NULL;
542 if (fputs(line, f) < 0)
543 return errno ? -errno : -EIO;
545 if (!endswith(line, "\n"))
551 return errno ? -errno : -EIO;
556 int fchmod_umask(int fd, mode_t m) {
561 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
567 int write_one_line_file_atomic(const char *fn, const char *line) {
568 _cleanup_fclose_ FILE *f = NULL;
569 _cleanup_free_ char *p = NULL;
575 r = fopen_temporary(fn, &f, &p);
579 fchmod_umask(fileno(f), 0644);
582 if (fputs(line, f) < 0) {
587 if (!endswith(line, "\n"))
593 r = errno ? -errno : -EIO;
595 if (rename(p, fn) < 0)
608 int read_one_line_file(const char *fn, char **line) {
609 _cleanup_fclose_ FILE *f = NULL;
610 char t[LINE_MAX], *c;
619 if (!fgets(t, sizeof(t), f)) {
622 return errno ? -errno : -EIO;
636 int read_full_file(const char *fn, char **contents, size_t *size) {
637 _cleanup_fclose_ FILE *f = NULL;
639 _cleanup_free_ char *buf = NULL;
649 if (fstat(fileno(f), &st) < 0)
653 if (st.st_size > 4*1024*1024)
656 n = st.st_size > 0 ? st.st_size : LINE_MAX;
663 t = realloc(buf, n+1);
668 k = fread(buf + l, 1, n - l, f);
697 const char *separator, ...) {
700 char *contents = NULL, *p;
705 if ((r = read_full_file(fname, &contents, NULL)) < 0)
710 const char *key = NULL;
712 p += strspn(p, separator);
713 p += strspn(p, WHITESPACE);
718 if (!strchr(COMMENTS, *p)) {
722 va_start(ap, separator);
723 while ((key = va_arg(ap, char *))) {
727 value = va_arg(ap, char **);
730 if (!strneq(p, key, n) ||
735 n = strcspn(p, separator);
738 strchr(QUOTES, p[0]) &&
740 v = strndup(p+1, n-2);
751 /* return empty value strings as NULL */
768 p += strcspn(p, separator);
776 int load_env_file(const char *fname, char ***rl) {
778 _cleanup_fclose_ FILE *f;
779 _cleanup_strv_free_ char **m = NULL;
780 _cleanup_free_ char *c = NULL;
785 /* This reads an environment file, but will not complain about
786 * any invalid assignments, that needs to be done by the
789 f = fopen(fname, "re");
794 char l[LINE_MAX], *p, *cs, *b;
796 if (!fgets(l, sizeof(l), f)) {
800 /* The previous line was a continuation line?
801 * Let's process it now, before we leave the
809 /* Is this a continuation line? If so, just append
810 * this to c, and go to next line right-away */
811 cs = endswith(l, "\\\n");
823 /* If the previous line was a continuation line,
824 * append the current line to it */
835 p = strstrip(c ? c : l);
837 if (*p && !strchr(COMMENTS, *p)) {
838 _cleanup_free_ char *u;
841 u = normalize_env_assignment(p);
845 k = strv_extend(&m, u);
860 int write_env_file(const char *fname, char **l) {
865 r = fopen_temporary(fname, &f, &p);
869 fchmod_umask(fileno(f), 0644);
885 if (rename(p, fname) < 0)
900 char *truncate_nl(char *s) {
903 s[strcspn(s, NEWLINE)] = 0;
907 int get_process_comm(pid_t pid, char **name) {
913 r = read_one_line_file("/proc/self/comm", name);
916 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
919 r = read_one_line_file(p, name);
926 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
934 f = fopen("/proc/self/cmdline", "re");
937 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
946 if (max_length == 0) {
948 while ((c = getc(f)) != EOF) {
949 k = realloc(r, len+1);
956 r[len-1] = isprint(c) ? c : ' ';
963 r = new(char, max_length);
971 while ((c = getc(f)) != EOF) {
993 size_t n = MIN(left-1, 3U);
1002 /* Kernel threads have no argv[] */
1003 if (r == NULL || r[0] == 0) {
1012 h = get_process_comm(pid, &t);
1016 r = strjoin("[", t, "]", NULL);
1027 int is_kernel_thread(pid_t pid) {
1037 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1046 count = fread(&c, 1, 1, f);
1050 /* Kernel threads have an empty cmdline */
1053 return eof ? 1 : -errno;
1058 int get_process_exe(pid_t pid, char **name) {
1064 r = readlink_malloc("/proc/self/exe", name);
1067 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1070 r = readlink_malloc(p, name);
1077 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
1078 _cleanup_fclose_ FILE *f = NULL;
1079 _cleanup_free_ char *p = NULL;
1087 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1094 FOREACH_LINE(f, line, return -errno) {
1099 if (startswith(l, field)) {
1101 l += strspn(l, WHITESPACE);
1103 l[strcspn(l, WHITESPACE)] = 0;
1105 return parse_uid(l, uid);
1112 int get_process_uid(pid_t pid, uid_t *uid) {
1113 return get_process_id(pid, "Uid:", uid);
1116 int get_process_gid(pid_t pid, gid_t *gid) {
1117 return get_process_id(pid, "Gid:", gid);
1120 char *strnappend(const char *s, const char *suffix, size_t b) {
1128 return strndup(suffix, b);
1137 if (b > ((size_t) -1) - a)
1140 r = new(char, a+b+1);
1145 memcpy(r+a, suffix, b);
1151 char *strappend(const char *s, const char *suffix) {
1152 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1155 int readlink_malloc(const char *p, char **r) {
1165 if (!(c = new(char, l)))
1168 if ((n = readlink(p, c, l-1)) < 0) {
1174 if ((size_t) n < l-1) {
1185 int readlink_and_make_absolute(const char *p, char **r) {
1192 if ((j = readlink_malloc(p, &target)) < 0)
1195 k = file_in_same_dir(p, target);
1205 int readlink_and_canonicalize(const char *p, char **r) {
1212 j = readlink_and_make_absolute(p, &t);
1216 s = canonicalize_file_name(t);
1223 path_kill_slashes(*r);
1228 int reset_all_signal_handlers(void) {
1231 for (sig = 1; sig < _NSIG; sig++) {
1232 struct sigaction sa;
1234 if (sig == SIGKILL || sig == SIGSTOP)
1238 sa.sa_handler = SIG_DFL;
1239 sa.sa_flags = SA_RESTART;
1241 /* On Linux the first two RT signals are reserved by
1242 * glibc, and sigaction() will return EINVAL for them. */
1243 if ((sigaction(sig, &sa, NULL) < 0))
1244 if (errno != EINVAL)
1251 char *strstrip(char *s) {
1254 /* Drops trailing whitespace. Modifies the string in
1255 * place. Returns pointer to first non-space character */
1257 s += strspn(s, WHITESPACE);
1259 for (e = strchr(s, 0); e > s; e --)
1260 if (!strchr(WHITESPACE, e[-1]))
1268 char *delete_chars(char *s, const char *bad) {
1271 /* Drops all whitespace, regardless where in the string */
1273 for (f = s, t = s; *f; f++) {
1274 if (strchr(bad, *f))
1285 bool in_charset(const char *s, const char* charset) {
1291 for (i = s; *i; i++)
1292 if (!strchr(charset, *i))
1298 char *file_in_same_dir(const char *path, const char *filename) {
1305 /* This removes the last component of path and appends
1306 * filename, unless the latter is absolute anyway or the
1309 if (path_is_absolute(filename))
1310 return strdup(filename);
1312 if (!(e = strrchr(path, '/')))
1313 return strdup(filename);
1315 k = strlen(filename);
1316 if (!(r = new(char, e-path+1+k+1)))
1319 memcpy(r, path, e-path+1);
1320 memcpy(r+(e-path)+1, filename, k+1);
1325 int rmdir_parents(const char *path, const char *stop) {
1334 /* Skip trailing slashes */
1335 while (l > 0 && path[l-1] == '/')
1341 /* Skip last component */
1342 while (l > 0 && path[l-1] != '/')
1345 /* Skip trailing slashes */
1346 while (l > 0 && path[l-1] == '/')
1352 if (!(t = strndup(path, l)))
1355 if (path_startswith(stop, t)) {
1364 if (errno != ENOENT)
1372 char hexchar(int x) {
1373 static const char table[16] = "0123456789abcdef";
1375 return table[x & 15];
1378 int unhexchar(char c) {
1380 if (c >= '0' && c <= '9')
1383 if (c >= 'a' && c <= 'f')
1384 return c - 'a' + 10;
1386 if (c >= 'A' && c <= 'F')
1387 return c - 'A' + 10;
1392 char octchar(int x) {
1393 return '0' + (x & 7);
1396 int unoctchar(char c) {
1398 if (c >= '0' && c <= '7')
1404 char decchar(int x) {
1405 return '0' + (x % 10);
1408 int undecchar(char c) {
1410 if (c >= '0' && c <= '9')
1416 char *cescape(const char *s) {
1422 /* Does C style string escaping. */
1424 r = new(char, strlen(s)*4 + 1);
1428 for (f = s, t = r; *f; f++)
1474 /* For special chars we prefer octal over
1475 * hexadecimal encoding, simply because glib's
1476 * g_strescape() does the same */
1477 if ((*f < ' ') || (*f >= 127)) {
1479 *(t++) = octchar((unsigned char) *f >> 6);
1480 *(t++) = octchar((unsigned char) *f >> 3);
1481 *(t++) = octchar((unsigned char) *f);
1492 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1499 /* Undoes C style string escaping, and optionally prefixes it. */
1501 pl = prefix ? strlen(prefix) : 0;
1503 r = new(char, pl+length+1);
1508 memcpy(r, prefix, pl);
1510 for (f = s, t = r + pl; f < s + length; f++) {
1553 /* This is an extension of the XDG syntax files */
1558 /* hexadecimal encoding */
1561 a = unhexchar(f[1]);
1562 b = unhexchar(f[2]);
1564 if (a < 0 || b < 0) {
1565 /* Invalid escape code, let's take it literal then */
1569 *(t++) = (char) ((a << 4) | b);
1584 /* octal encoding */
1587 a = unoctchar(f[0]);
1588 b = unoctchar(f[1]);
1589 c = unoctchar(f[2]);
1591 if (a < 0 || b < 0 || c < 0) {
1592 /* Invalid escape code, let's take it literal then */
1596 *(t++) = (char) ((a << 6) | (b << 3) | c);
1604 /* premature end of string.*/
1609 /* Invalid escape code, let's take it literal then */
1621 char *cunescape_length(const char *s, size_t length) {
1622 return cunescape_length_with_prefix(s, length, NULL);
1625 char *cunescape(const char *s) {
1628 return cunescape_length(s, strlen(s));
1631 char *xescape(const char *s, const char *bad) {
1635 /* Escapes all chars in bad, in addition to \ and all special
1636 * chars, in \xFF style escaping. May be reversed with
1639 r = new(char, strlen(s) * 4 + 1);
1643 for (f = s, t = r; *f; f++) {
1645 if ((*f < ' ') || (*f >= 127) ||
1646 (*f == '\\') || strchr(bad, *f)) {
1649 *(t++) = hexchar(*f >> 4);
1650 *(t++) = hexchar(*f);
1660 char *bus_path_escape(const char *s) {
1666 /* Escapes all chars that D-Bus' object path cannot deal
1667 * with. Can be reverse with bus_path_unescape() */
1669 if (!(r = new(char, strlen(s)*3+1)))
1672 for (f = s, t = r; *f; f++) {
1674 if (!(*f >= 'A' && *f <= 'Z') &&
1675 !(*f >= 'a' && *f <= 'z') &&
1676 !(*f >= '0' && *f <= '9')) {
1678 *(t++) = hexchar(*f >> 4);
1679 *(t++) = hexchar(*f);
1689 char *bus_path_unescape(const char *f) {
1694 if (!(r = strdup(f)))
1697 for (t = r; *f; f++) {
1702 if ((a = unhexchar(f[1])) < 0 ||
1703 (b = unhexchar(f[2])) < 0) {
1704 /* Invalid escape code, let's take it literal then */
1707 *(t++) = (char) ((a << 4) | b);
1719 char *ascii_strlower(char *t) {
1724 for (p = t; *p; p++)
1725 if (*p >= 'A' && *p <= 'Z')
1726 *p = *p - 'A' + 'a';
1731 static bool ignore_file_allow_backup(const char *filename) {
1735 filename[0] == '.' ||
1736 streq(filename, "lost+found") ||
1737 streq(filename, "aquota.user") ||
1738 streq(filename, "aquota.group") ||
1739 endswith(filename, ".rpmnew") ||
1740 endswith(filename, ".rpmsave") ||
1741 endswith(filename, ".rpmorig") ||
1742 endswith(filename, ".dpkg-old") ||
1743 endswith(filename, ".dpkg-new") ||
1744 endswith(filename, ".swp");
1747 bool ignore_file(const char *filename) {
1750 if (endswith(filename, "~"))
1753 return ignore_file_allow_backup(filename);
1756 int fd_nonblock(int fd, bool nonblock) {
1761 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1765 flags |= O_NONBLOCK;
1767 flags &= ~O_NONBLOCK;
1769 if (fcntl(fd, F_SETFL, flags) < 0)
1775 int fd_cloexec(int fd, bool cloexec) {
1780 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1784 flags |= FD_CLOEXEC;
1786 flags &= ~FD_CLOEXEC;
1788 if (fcntl(fd, F_SETFD, flags) < 0)
1794 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1797 assert(n_fdset == 0 || fdset);
1799 for (i = 0; i < n_fdset; i++)
1806 int close_all_fds(const int except[], unsigned n_except) {
1811 assert(n_except == 0 || except);
1813 d = opendir("/proc/self/fd");
1818 /* When /proc isn't available (for example in chroots)
1819 * the fallback is brute forcing through the fd
1822 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1823 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1825 if (fd_in_set(fd, except, n_except))
1828 if (close_nointr(fd) < 0)
1829 if (errno != EBADF && r == 0)
1836 while ((de = readdir(d))) {
1839 if (ignore_file(de->d_name))
1842 if (safe_atoi(de->d_name, &fd) < 0)
1843 /* Let's better ignore this, just in case */
1852 if (fd_in_set(fd, except, n_except))
1855 if (close_nointr(fd) < 0) {
1856 /* Valgrind has its own FD and doesn't want to have it closed */
1857 if (errno != EBADF && r == 0)
1866 bool chars_intersect(const char *a, const char *b) {
1869 /* Returns true if any of the chars in a are in b. */
1870 for (p = a; *p; p++)
1877 bool fstype_is_network(const char *fstype) {
1878 static const char table[] =
1887 return nulstr_contains(table, fstype);
1891 _cleanup_close_ int fd;
1893 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1899 TIOCL_GETKMSGREDIRECT,
1903 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1906 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1909 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1915 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1916 struct termios old_termios, new_termios;
1918 char line[LINE_MAX];
1923 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1924 new_termios = old_termios;
1926 new_termios.c_lflag &= ~ICANON;
1927 new_termios.c_cc[VMIN] = 1;
1928 new_termios.c_cc[VTIME] = 0;
1930 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1933 if (t != (usec_t) -1) {
1934 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1935 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1940 k = fread(&c, 1, 1, f);
1942 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1948 *need_nl = c != '\n';
1955 if (t != (usec_t) -1)
1956 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1959 if (!fgets(line, sizeof(line), f))
1964 if (strlen(line) != 1)
1974 int ask(char *ret, const char *replies, const char *text, ...) {
1984 bool need_nl = true;
1987 fputs(ANSI_HIGHLIGHT_ON, stdout);
1994 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1998 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2001 if (r == -EBADMSG) {
2002 puts("Bad input, please try again.");
2013 if (strchr(replies, c)) {
2018 puts("Read unexpected character, please try again.");
2022 int reset_terminal_fd(int fd, bool switch_to_text) {
2023 struct termios termios;
2026 /* Set terminal to some sane defaults */
2030 /* We leave locked terminal attributes untouched, so that
2031 * Plymouth may set whatever it wants to set, and we don't
2032 * interfere with that. */
2034 /* Disable exclusive mode, just in case */
2035 ioctl(fd, TIOCNXCL);
2037 /* Switch to text mode */
2039 ioctl(fd, KDSETMODE, KD_TEXT);
2041 /* Enable console unicode mode */
2042 ioctl(fd, KDSKBMODE, K_UNICODE);
2044 if (tcgetattr(fd, &termios) < 0) {
2049 /* We only reset the stuff that matters to the software. How
2050 * hardware is set up we don't touch assuming that somebody
2051 * else will do that for us */
2053 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2054 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2055 termios.c_oflag |= ONLCR;
2056 termios.c_cflag |= CREAD;
2057 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2059 termios.c_cc[VINTR] = 03; /* ^C */
2060 termios.c_cc[VQUIT] = 034; /* ^\ */
2061 termios.c_cc[VERASE] = 0177;
2062 termios.c_cc[VKILL] = 025; /* ^X */
2063 termios.c_cc[VEOF] = 04; /* ^D */
2064 termios.c_cc[VSTART] = 021; /* ^Q */
2065 termios.c_cc[VSTOP] = 023; /* ^S */
2066 termios.c_cc[VSUSP] = 032; /* ^Z */
2067 termios.c_cc[VLNEXT] = 026; /* ^V */
2068 termios.c_cc[VWERASE] = 027; /* ^W */
2069 termios.c_cc[VREPRINT] = 022; /* ^R */
2070 termios.c_cc[VEOL] = 0;
2071 termios.c_cc[VEOL2] = 0;
2073 termios.c_cc[VTIME] = 0;
2074 termios.c_cc[VMIN] = 1;
2076 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2080 /* Just in case, flush all crap out */
2081 tcflush(fd, TCIOFLUSH);
2086 int reset_terminal(const char *name) {
2089 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2093 r = reset_terminal_fd(fd, true);
2094 close_nointr_nofail(fd);
2099 int open_terminal(const char *name, int mode) {
2104 * If a TTY is in the process of being closed opening it might
2105 * cause EIO. This is horribly awful, but unlikely to be
2106 * changed in the kernel. Hence we work around this problem by
2107 * retrying a couple of times.
2109 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2113 fd = open(name, mode);
2120 /* Max 1s in total */
2124 usleep(50 * USEC_PER_MSEC);
2133 close_nointr_nofail(fd);
2138 close_nointr_nofail(fd);
2145 int flush_fd(int fd) {
2146 struct pollfd pollfd;
2150 pollfd.events = POLLIN;
2157 if ((r = poll(&pollfd, 1, 0)) < 0) {
2168 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2173 if (errno == EAGAIN)
2184 int acquire_terminal(
2188 bool ignore_tiocstty_eperm,
2191 int fd = -1, notify = -1, r = 0, wd = -1;
2193 struct sigaction sa_old, sa_new;
2197 /* We use inotify to be notified when the tty is closed. We
2198 * create the watch before checking if we can actually acquire
2199 * it, so that we don't lose any event.
2201 * Note: strictly speaking this actually watches for the
2202 * device being closed, it does *not* really watch whether a
2203 * tty loses its controlling process. However, unless some
2204 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2205 * its tty otherwise this will not become a problem. As long
2206 * as the administrator makes sure not configure any service
2207 * on the same tty as an untrusted user this should not be a
2208 * problem. (Which he probably should not do anyway.) */
2210 if (timeout != (usec_t) -1)
2211 ts = now(CLOCK_MONOTONIC);
2213 if (!fail && !force) {
2214 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2220 wd = inotify_add_watch(notify, name, IN_CLOSE);
2229 r = flush_fd(notify);
2234 /* We pass here O_NOCTTY only so that we can check the return
2235 * value TIOCSCTTY and have a reliable way to figure out if we
2236 * successfully became the controlling process of the tty */
2237 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2241 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2242 * if we already own the tty. */
2244 sa_new.sa_handler = SIG_IGN;
2245 sa_new.sa_flags = SA_RESTART;
2246 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2248 /* First, try to get the tty */
2249 if (ioctl(fd, TIOCSCTTY, force) < 0)
2252 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2254 /* Sometimes it makes sense to ignore TIOCSCTTY
2255 * returning EPERM, i.e. when very likely we already
2256 * are have this controlling terminal. */
2257 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2260 if (r < 0 && (force || fail || r != -EPERM)) {
2269 assert(notify >= 0);
2272 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2274 struct inotify_event *e;
2276 if (timeout != (usec_t) -1) {
2279 n = now(CLOCK_MONOTONIC);
2280 if (ts + timeout < n) {
2285 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2295 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2298 if (errno == EINTR || errno == EAGAIN)
2305 e = (struct inotify_event*) inotify_buffer;
2310 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2315 step = sizeof(struct inotify_event) + e->len;
2316 assert(step <= (size_t) l);
2318 e = (struct inotify_event*) ((uint8_t*) e + step);
2325 /* We close the tty fd here since if the old session
2326 * ended our handle will be dead. It's important that
2327 * we do this after sleeping, so that we don't enter
2328 * an endless loop. */
2329 close_nointr_nofail(fd);
2333 close_nointr_nofail(notify);
2335 r = reset_terminal_fd(fd, true);
2337 log_warning("Failed to reset terminal: %s", strerror(-r));
2343 close_nointr_nofail(fd);
2346 close_nointr_nofail(notify);
2351 int release_terminal(void) {
2353 struct sigaction sa_old, sa_new;
2355 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2358 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2359 * by our own TIOCNOTTY */
2362 sa_new.sa_handler = SIG_IGN;
2363 sa_new.sa_flags = SA_RESTART;
2364 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2366 if (ioctl(fd, TIOCNOTTY) < 0)
2369 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2371 close_nointr_nofail(fd);
2375 int sigaction_many(const struct sigaction *sa, ...) {
2380 while ((sig = va_arg(ap, int)) > 0)
2381 if (sigaction(sig, sa, NULL) < 0)
2388 int ignore_signals(int sig, ...) {
2389 struct sigaction sa;
2394 sa.sa_handler = SIG_IGN;
2395 sa.sa_flags = SA_RESTART;
2397 if (sigaction(sig, &sa, NULL) < 0)
2401 while ((sig = va_arg(ap, int)) > 0)
2402 if (sigaction(sig, &sa, NULL) < 0)
2409 int default_signals(int sig, ...) {
2410 struct sigaction sa;
2415 sa.sa_handler = SIG_DFL;
2416 sa.sa_flags = SA_RESTART;
2418 if (sigaction(sig, &sa, NULL) < 0)
2422 while ((sig = va_arg(ap, int)) > 0)
2423 if (sigaction(sig, &sa, NULL) < 0)
2430 int close_pipe(int p[]) {
2436 a = close_nointr(p[0]);
2441 b = close_nointr(p[1]);
2445 return a < 0 ? a : b;
2448 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2457 while (nbytes > 0) {
2460 if ((k = read(fd, p, nbytes)) <= 0) {
2462 if (k < 0 && errno == EINTR)
2465 if (k < 0 && errno == EAGAIN && do_poll) {
2466 struct pollfd pollfd;
2470 pollfd.events = POLLIN;
2472 if (poll(&pollfd, 1, -1) < 0) {
2476 return n > 0 ? n : -errno;
2479 if (pollfd.revents != POLLIN)
2480 return n > 0 ? n : -EIO;
2485 return n > 0 ? n : (k < 0 ? -errno : 0);
2496 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2505 while (nbytes > 0) {
2508 k = write(fd, p, nbytes);
2511 if (k < 0 && errno == EINTR)
2514 if (k < 0 && errno == EAGAIN && do_poll) {
2515 struct pollfd pollfd;
2519 pollfd.events = POLLOUT;
2521 if (poll(&pollfd, 1, -1) < 0) {
2525 return n > 0 ? n : -errno;
2528 if (pollfd.revents != POLLOUT)
2529 return n > 0 ? n : -EIO;
2534 return n > 0 ? n : (k < 0 ? -errno : 0);
2545 int parse_bytes(const char *t, off_t *bytes) {
2546 static const struct {
2552 { "M", 1024ULL*1024ULL },
2553 { "G", 1024ULL*1024ULL*1024ULL },
2554 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2555 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2556 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2573 l = strtoll(p, &e, 10);
2584 e += strspn(e, WHITESPACE);
2586 for (i = 0; i < ELEMENTSOF(table); i++)
2587 if (startswith(e, table[i].suffix)) {
2588 r += (off_t) l * table[i].factor;
2589 p = e + strlen(table[i].suffix);
2593 if (i >= ELEMENTSOF(table))
2603 int make_stdio(int fd) {
2608 r = dup3(fd, STDIN_FILENO, 0);
2609 s = dup3(fd, STDOUT_FILENO, 0);
2610 t = dup3(fd, STDERR_FILENO, 0);
2613 close_nointr_nofail(fd);
2615 if (r < 0 || s < 0 || t < 0)
2618 /* We rely here that the new fd has O_CLOEXEC not set */
2623 int make_null_stdio(void) {
2626 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2630 return make_stdio(null_fd);
2633 bool is_device_path(const char *path) {
2635 /* Returns true on paths that refer to a device, either in
2636 * sysfs or in /dev */
2639 path_startswith(path, "/dev/") ||
2640 path_startswith(path, "/sys/");
2643 int dir_is_empty(const char *path) {
2644 _cleanup_closedir_ DIR *d;
2653 union dirent_storage buf;
2655 r = readdir_r(d, &buf.de, &de);
2662 if (!ignore_file(de->d_name))
2667 unsigned long long random_ull(void) {
2668 _cleanup_close_ int fd;
2672 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2676 r = loop_read(fd, &ull, sizeof(ull), true);
2677 if (r != sizeof(ull))
2683 return random() * RAND_MAX + random();
2686 void rename_process(const char name[8]) {
2689 /* This is a like a poor man's setproctitle(). It changes the
2690 * comm field, argv[0], and also the glibc's internally used
2691 * name of the process. For the first one a limit of 16 chars
2692 * applies, to the second one usually one of 10 (i.e. length
2693 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2694 * "systemd"). If you pass a longer string it will be
2697 prctl(PR_SET_NAME, name);
2699 if (program_invocation_name)
2700 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2702 if (saved_argc > 0) {
2706 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2708 for (i = 1; i < saved_argc; i++) {
2712 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2717 void sigset_add_many(sigset_t *ss, ...) {
2724 while ((sig = va_arg(ap, int)) > 0)
2725 assert_se(sigaddset(ss, sig) == 0);
2729 char* gethostname_malloc(void) {
2732 assert_se(uname(&u) >= 0);
2734 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2735 return strdup(u.nodename);
2737 return strdup(u.sysname);
2740 bool hostname_is_set(void) {
2743 assert_se(uname(&u) >= 0);
2745 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2748 static char *lookup_uid(uid_t uid) {
2751 _cleanup_free_ char *buf = NULL;
2752 struct passwd pwbuf, *pw = NULL;
2754 /* Shortcut things to avoid NSS lookups */
2756 return strdup("root");
2758 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2762 buf = malloc(bufsize);
2766 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2767 return strdup(pw->pw_name);
2769 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2775 char* getlogname_malloc(void) {
2779 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2784 return lookup_uid(uid);
2787 char *getusername_malloc(void) {
2794 return lookup_uid(getuid());
2797 int getttyname_malloc(int fd, char **r) {
2798 char path[PATH_MAX], *c;
2803 k = ttyname_r(fd, path, sizeof(path));
2809 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2817 int getttyname_harder(int fd, char **r) {
2821 k = getttyname_malloc(fd, &s);
2825 if (streq(s, "tty")) {
2827 return get_ctty(0, NULL, r);
2834 int get_ctty_devnr(pid_t pid, dev_t *d) {
2836 char line[LINE_MAX], *p, *fn;
2837 unsigned long ttynr;
2840 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2843 f = fopen(fn, "re");
2848 if (!fgets(line, sizeof(line), f)) {
2849 k = feof(f) ? -EIO : -errno;
2856 p = strrchr(line, ')');
2866 "%*d " /* session */
2871 if (major(ttynr) == 0 && minor(ttynr) == 0)
2878 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2880 char fn[PATH_MAX], *s, *b, *p;
2885 k = get_ctty_devnr(pid, &devnr);
2889 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2892 k = readlink_malloc(fn, &s);
2898 /* This is an ugly hack */
2899 if (major(devnr) == 136) {
2900 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2910 /* Probably something like the ptys which have no
2911 * symlink in /dev/char. Let's return something
2912 * vaguely useful. */
2925 if (startswith(s, "/dev/"))
2927 else if (startswith(s, "../"))
2945 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2951 /* This returns the first error we run into, but nevertheless
2952 * tries to go on. This closes the passed fd. */
2956 close_nointr_nofail(fd);
2958 return errno == ENOENT ? 0 : -errno;
2963 union dirent_storage buf;
2964 bool is_dir, keep_around;
2968 r = readdir_r(d, &buf.de, &de);
2969 if (r != 0 && ret == 0) {
2977 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2980 if (de->d_type == DT_UNKNOWN ||
2982 (de->d_type == DT_DIR && root_dev)) {
2983 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2984 if (ret == 0 && errno != ENOENT)
2989 is_dir = S_ISDIR(st.st_mode);
2992 (st.st_uid == 0 || st.st_uid == getuid()) &&
2993 (st.st_mode & S_ISVTX);
2995 is_dir = de->d_type == DT_DIR;
2996 keep_around = false;
3002 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3003 if (root_dev && st.st_dev != root_dev->st_dev)
3006 subdir_fd = openat(fd, de->d_name,
3007 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3008 if (subdir_fd < 0) {
3009 if (ret == 0 && errno != ENOENT)
3014 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3015 if (r < 0 && ret == 0)
3019 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3020 if (ret == 0 && errno != ENOENT)
3024 } else if (!only_dirs && !keep_around) {
3026 if (unlinkat(fd, de->d_name, 0) < 0) {
3027 if (ret == 0 && errno != ENOENT)
3038 static int is_temporary_fs(struct statfs *s) {
3040 return s->f_type == TMPFS_MAGIC ||
3041 (long)s->f_type == (long)RAMFS_MAGIC;
3044 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3049 if (fstatfs(fd, &s) < 0) {
3050 close_nointr_nofail(fd);
3054 /* We refuse to clean disk file systems with this call. This
3055 * is extra paranoia just to be sure we never ever remove
3057 if (!is_temporary_fs(&s)) {
3058 log_error("Attempted to remove disk file system, and we can't allow that.");
3059 close_nointr_nofail(fd);
3063 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3066 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3072 /* We refuse to clean the root file system with this
3073 * call. This is extra paranoia to never cause a really
3074 * seriously broken system. */
3075 if (path_equal(path, "/")) {
3076 log_error("Attempted to remove entire root file system, and we can't allow that.");
3080 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3083 if (errno != ENOTDIR)
3087 if (statfs(path, &s) < 0)
3090 if (!is_temporary_fs(&s)) {
3091 log_error("Attempted to remove disk file system, and we can't allow that.");
3096 if (delete_root && !only_dirs)
3097 if (unlink(path) < 0 && errno != ENOENT)
3104 if (fstatfs(fd, &s) < 0) {
3105 close_nointr_nofail(fd);
3109 if (!is_temporary_fs(&s)) {
3110 log_error("Attempted to remove disk file system, and we can't allow that.");
3111 close_nointr_nofail(fd);
3116 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3119 if (honour_sticky && file_is_priv_sticky(path) > 0)
3122 if (rmdir(path) < 0 && errno != ENOENT) {
3131 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3132 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3135 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3136 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3139 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3142 /* Under the assumption that we are running privileged we
3143 * first change the access mode and only then hand out
3144 * ownership to avoid a window where access is too open. */
3146 if (mode != (mode_t) -1)
3147 if (chmod(path, mode) < 0)
3150 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3151 if (chown(path, uid, gid) < 0)
3157 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3160 /* Under the assumption that we are running privileged we
3161 * first change the access mode and only then hand out
3162 * ownership to avoid a window where access is too open. */
3164 if (fchmod(fd, mode) < 0)
3167 if (fchown(fd, uid, gid) < 0)
3173 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3177 /* Allocates the cpuset in the right size */
3180 if (!(r = CPU_ALLOC(n)))
3183 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3184 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3194 if (errno != EINVAL)
3201 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3202 static const char status_indent[] = " "; /* "[" STATUS "] " */
3203 _cleanup_free_ char *s = NULL;
3204 _cleanup_close_ int fd = -1;
3205 struct iovec iovec[5];
3210 /* This is independent of logging, as status messages are
3211 * optional and go exclusively to the console. */
3213 if (vasprintf(&s, format, ap) < 0)
3216 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3229 sl = status ? sizeof(status_indent)-1 : 0;
3235 e = ellipsize(s, emax, 75);
3245 if (!isempty(status)) {
3246 IOVEC_SET_STRING(iovec[n++], "[");
3247 IOVEC_SET_STRING(iovec[n++], status);
3248 IOVEC_SET_STRING(iovec[n++], "] ");
3250 IOVEC_SET_STRING(iovec[n++], status_indent);
3253 IOVEC_SET_STRING(iovec[n++], s);
3254 IOVEC_SET_STRING(iovec[n++], "\n");
3256 if (writev(fd, iovec, n) < 0)
3262 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3268 va_start(ap, format);
3269 r = status_vprintf(status, ellipse, format, ap);
3275 int status_welcome(void) {
3277 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3279 r = parse_env_file("/etc/os-release", NEWLINE,
3280 "PRETTY_NAME", &pretty_name,
3281 "ANSI_COLOR", &ansi_color,
3283 if (r < 0 && r != -ENOENT)
3284 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3286 return status_printf(NULL, false,
3287 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3288 isempty(ansi_color) ? "1" : ansi_color,
3289 isempty(pretty_name) ? "Linux" : pretty_name);
3292 char *replace_env(const char *format, char **env) {
3299 const char *e, *word = format;
3304 for (e = format; *e; e ++) {
3315 if (!(k = strnappend(r, word, e-word-1)))
3324 } else if (*e == '$') {
3325 if (!(k = strnappend(r, word, e-word)))
3341 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3343 k = strappend(r, t);
3357 if (!(k = strnappend(r, word, e-word)))
3368 char **replace_env_argv(char **argv, char **env) {
3370 unsigned k = 0, l = 0;
3372 l = strv_length(argv);
3374 if (!(r = new(char*, l+1)))
3377 STRV_FOREACH(i, argv) {
3379 /* If $FOO appears as single word, replace it by the split up variable */
3380 if ((*i)[0] == '$' && (*i)[1] != '{') {
3385 e = strv_env_get(env, *i+1);
3388 if (!(m = strv_split_quoted(e))) {
3399 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3408 memcpy(r + k, m, q * sizeof(char*));
3416 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3417 if (!(r[k++] = replace_env(*i, env))) {
3427 int fd_columns(int fd) {
3431 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3440 unsigned columns(void) {
3444 if (_likely_(cached_columns > 0))
3445 return cached_columns;
3448 e = getenv("COLUMNS");
3453 c = fd_columns(STDOUT_FILENO);
3462 int fd_lines(int fd) {
3466 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3475 unsigned lines(void) {
3479 if (_likely_(cached_lines > 0))
3480 return cached_lines;
3483 e = getenv("LINES");
3488 l = fd_lines(STDOUT_FILENO);
3494 return cached_lines;
3497 /* intended to be used as a SIGWINCH sighandler */
3498 void columns_lines_cache_reset(int signum) {
3504 static int cached_on_tty = -1;
3506 if (_unlikely_(cached_on_tty < 0))
3507 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3509 return cached_on_tty;
3512 int running_in_chroot(void) {
3518 /* Only works as root */
3520 if (stat("/proc/1/root", &a) < 0)
3523 if (stat("/", &b) < 0)
3527 a.st_dev != b.st_dev ||
3528 a.st_ino != b.st_ino;
3531 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3536 assert(percent <= 100);
3537 assert(new_length >= 3);
3539 if (old_length <= 3 || old_length <= new_length)
3540 return strndup(s, old_length);
3542 r = new0(char, new_length+1);
3546 x = (new_length * percent) / 100;
3548 if (x > new_length - 3)
3556 s + old_length - (new_length - x - 3),
3557 new_length - x - 3);
3562 char *ellipsize(const char *s, size_t length, unsigned percent) {
3563 return ellipsize_mem(s, strlen(s), length, percent);
3566 int touch(const char *path) {
3571 /* This just opens the file for writing, ensuring it
3572 * exists. It doesn't call utimensat() the way /usr/bin/touch
3575 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3579 close_nointr_nofail(fd);
3583 char *unquote(const char *s, const char* quotes) {
3587 /* This is rather stupid, simply removes the heading and
3588 * trailing quotes if there is one. Doesn't care about
3589 * escaping or anything. We should make this smarter one
3596 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3597 return strndup(s+1, l-2);
3602 char *normalize_env_assignment(const char *s) {
3603 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3606 eq = strchr(s, '=');
3618 memmove(r, t, strlen(t) + 1);
3622 name = strndup(s, eq - s);
3630 value = unquote(strstrip(p), QUOTES);
3634 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3640 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3651 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3663 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3670 r = wait_for_terminate(pid, &status);
3672 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3676 if (status.si_code == CLD_EXITED) {
3677 if (status.si_status != 0) {
3678 log_warning("%s failed with error code %i.", name, status.si_status);
3679 return status.si_status;
3682 log_debug("%s succeeded.", name);
3685 } else if (status.si_code == CLD_KILLED ||
3686 status.si_code == CLD_DUMPED) {
3688 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3692 log_warning("%s failed due to unknown reason.", name);
3696 _noreturn_ void freeze(void) {
3698 /* Make sure nobody waits for us on a socket anymore */
3699 close_all_fds(NULL, 0);
3707 bool null_or_empty(struct stat *st) {
3710 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3713 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3719 int null_or_empty_path(const char *fn) {
3724 if (stat(fn, &st) < 0)
3727 return null_or_empty(&st);
3730 DIR *xopendirat(int fd, const char *name, int flags) {
3734 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3740 close_nointr_nofail(nfd);
3747 int signal_from_string_try_harder(const char *s) {
3751 signo = signal_from_string(s);
3753 if (startswith(s, "SIG"))
3754 return signal_from_string(s+3);
3759 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3763 /* FIXME: to follow udev's logic 100% we need to leave valid
3764 * UTF8 chars unescaped */
3766 u = unquote(tagvalue, "\"\'");
3770 t = xescape(u, "/ ");
3776 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3785 char *fstab_node_to_udev_node(const char *p) {
3788 if (startswith(p, "LABEL="))
3789 return tag_to_udev_node(p+6, "label");
3791 if (startswith(p, "UUID="))
3792 return tag_to_udev_node(p+5, "uuid");
3794 if (startswith(p, "PARTUUID="))
3795 return tag_to_udev_node(p+9, "partuuid");
3797 if (startswith(p, "PARTLABEL="))
3798 return tag_to_udev_node(p+10, "partlabel");
3803 bool tty_is_vc(const char *tty) {
3806 if (startswith(tty, "/dev/"))
3809 return vtnr_from_tty(tty) >= 0;
3812 bool tty_is_console(const char *tty) {
3815 if (startswith(tty, "/dev/"))
3818 return streq(tty, "console");
3821 int vtnr_from_tty(const char *tty) {
3826 if (startswith(tty, "/dev/"))
3829 if (!startswith(tty, "tty") )
3832 if (tty[3] < '0' || tty[3] > '9')
3835 r = safe_atoi(tty+3, &i);
3839 if (i < 0 || i > 63)
3845 bool tty_is_vc_resolve(const char *tty) {
3846 char *active = NULL;
3851 if (startswith(tty, "/dev/"))
3854 /* Resolve where /dev/console is pointing to, if /sys is
3855 * actually ours (i.e. not read-only-mounted which is a sign
3856 * for container setups) */
3857 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3858 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3859 /* If multiple log outputs are configured the
3860 * last one is what /dev/console points to */
3861 tty = strrchr(active, ' ');
3874 const char *default_term_for_tty(const char *tty) {
3877 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3880 bool dirent_is_file(const struct dirent *de) {
3883 if (ignore_file(de->d_name))
3886 if (de->d_type != DT_REG &&
3887 de->d_type != DT_LNK &&
3888 de->d_type != DT_UNKNOWN)
3894 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3897 if (de->d_type != DT_REG &&
3898 de->d_type != DT_LNK &&
3899 de->d_type != DT_UNKNOWN)
3902 if (ignore_file_allow_backup(de->d_name))
3905 return endswith(de->d_name, suffix);
3908 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3911 Hashmap *pids = NULL;
3915 /* Executes all binaries in a directory in parallel and waits
3916 * until all they all finished. */
3919 if (!(_d = opendir(directory))) {
3921 if (errno == ENOENT)
3924 log_error("Failed to enumerate directory %s: %m", directory);
3931 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3932 log_error("Failed to allocate set.");
3936 while ((de = readdir(d))) {
3941 if (!dirent_is_file(de))
3944 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3949 if ((pid = fork()) < 0) {
3950 log_error("Failed to fork: %m");
3968 log_error("Failed to execute %s: %m", path);
3969 _exit(EXIT_FAILURE);
3972 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3974 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3975 log_error("Failed to add PID to set: %s", strerror(-k));
3980 while (!hashmap_isempty(pids)) {
3981 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3986 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3991 log_error("waitid() failed: %m");
3995 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3996 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3997 if (si.si_code == CLD_EXITED)
3998 log_error("%s exited with exit status %i.", path, si.si_status);
4000 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4002 log_debug("%s exited successfully.", path);
4013 hashmap_free_free(pids);
4016 int kill_and_sigcont(pid_t pid, int sig) {
4019 r = kill(pid, sig) < 0 ? -errno : 0;
4027 bool nulstr_contains(const char*nulstr, const char *needle) {
4033 NULSTR_FOREACH(i, nulstr)
4034 if (streq(i, needle))
4040 bool plymouth_running(void) {
4041 return access("/run/plymouth/pid", F_OK) >= 0;
4044 char* strshorten(char *s, size_t l) {
4053 static bool hostname_valid_char(char c) {
4055 (c >= 'a' && c <= 'z') ||
4056 (c >= 'A' && c <= 'Z') ||
4057 (c >= '0' && c <= '9') ||
4063 bool hostname_is_valid(const char *s) {
4069 for (p = s; *p; p++)
4070 if (!hostname_valid_char(*p))
4073 if (p-s > HOST_NAME_MAX)
4079 char* hostname_cleanup(char *s) {
4082 for (p = s, d = s; *p; p++)
4083 if ((*p >= 'a' && *p <= 'z') ||
4084 (*p >= 'A' && *p <= 'Z') ||
4085 (*p >= '0' && *p <= '9') ||
4093 strshorten(s, HOST_NAME_MAX);
4097 int pipe_eof(int fd) {
4098 struct pollfd pollfd;
4103 pollfd.events = POLLIN|POLLHUP;
4105 r = poll(&pollfd, 1, 0);
4112 return pollfd.revents & POLLHUP;
4115 int fd_wait_for_event(int fd, int event, usec_t t) {
4116 struct pollfd pollfd;
4121 pollfd.events = event;
4123 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4130 return pollfd.revents;
4133 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4144 t = new(char, strlen(path) + 1 + 6 + 1);
4148 fn = path_get_file_name(path);
4152 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4154 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4160 f = fdopen(fd, "we");
4173 int terminal_vhangup_fd(int fd) {
4176 if (ioctl(fd, TIOCVHANGUP) < 0)
4182 int terminal_vhangup(const char *name) {
4185 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4189 r = terminal_vhangup_fd(fd);
4190 close_nointr_nofail(fd);
4195 int vt_disallocate(const char *name) {
4199 /* Deallocate the VT if possible. If not possible
4200 * (i.e. because it is the active one), at least clear it
4201 * entirely (including the scrollback buffer) */
4203 if (!startswith(name, "/dev/"))
4206 if (!tty_is_vc(name)) {
4207 /* So this is not a VT. I guess we cannot deallocate
4208 * it then. But let's at least clear the screen */
4210 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4215 "\033[r" /* clear scrolling region */
4216 "\033[H" /* move home */
4217 "\033[2J", /* clear screen */
4219 close_nointr_nofail(fd);
4224 if (!startswith(name, "/dev/tty"))
4227 r = safe_atou(name+8, &u);
4234 /* Try to deallocate */
4235 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4239 r = ioctl(fd, VT_DISALLOCATE, u);
4240 close_nointr_nofail(fd);
4248 /* Couldn't deallocate, so let's clear it fully with
4250 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4255 "\033[r" /* clear scrolling region */
4256 "\033[H" /* move home */
4257 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4259 close_nointr_nofail(fd);
4264 int copy_file(const char *from, const char *to) {
4270 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4274 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4276 close_nointr_nofail(fdf);
4284 n = read(fdf, buf, sizeof(buf));
4288 close_nointr_nofail(fdf);
4299 k = loop_write(fdt, buf, n, false);
4301 r = k < 0 ? k : (errno ? -errno : -EIO);
4303 close_nointr_nofail(fdf);
4311 close_nointr_nofail(fdf);
4312 r = close_nointr(fdt);
4322 int symlink_atomic(const char *from, const char *to) {
4324 _cleanup_free_ char *t;
4327 unsigned long long ull;
4334 t = new(char, strlen(to) + 1 + 16 + 1);
4338 fn = path_get_file_name(to);
4342 x = stpcpy(t+k+1, fn);
4345 for (i = 0; i < 16; i++) {
4346 *(x++) = hexchar(ull & 0xF);
4352 if (symlink(from, t) < 0)
4355 if (rename(t, to) < 0) {
4364 bool display_is_local(const char *display) {
4368 display[0] == ':' &&
4369 display[1] >= '0' &&
4373 int socket_from_display(const char *display, char **path) {
4380 if (!display_is_local(display))
4383 k = strspn(display+1, "0123456789");
4385 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4389 c = stpcpy(f, "/tmp/.X11-unix/X");
4390 memcpy(c, display+1, k);
4399 const char **username,
4400 uid_t *uid, gid_t *gid,
4402 const char **shell) {
4410 /* We enforce some special rules for uid=0: in order to avoid
4411 * NSS lookups for root we hardcode its data. */
4413 if (streq(*username, "root") || streq(*username, "0")) {
4431 if (parse_uid(*username, &u) >= 0) {
4435 /* If there are multiple users with the same id, make
4436 * sure to leave $USER to the configured value instead
4437 * of the first occurrence in the database. However if
4438 * the uid was configured by a numeric uid, then let's
4439 * pick the real username from /etc/passwd. */
4441 *username = p->pw_name;
4444 p = getpwnam(*username);
4448 return errno != 0 ? -errno : -ESRCH;
4460 *shell = p->pw_shell;
4465 char* uid_to_name(uid_t uid) {
4470 return strdup("root");
4474 return strdup(p->pw_name);
4476 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4482 int get_group_creds(const char **groupname, gid_t *gid) {
4488 /* We enforce some special rules for gid=0: in order to avoid
4489 * NSS lookups for root we hardcode its data. */
4491 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4492 *groupname = "root";
4500 if (parse_gid(*groupname, &id) >= 0) {
4505 *groupname = g->gr_name;
4508 g = getgrnam(*groupname);
4512 return errno != 0 ? -errno : -ESRCH;
4520 int in_group(const char *name) {
4522 int ngroups_max, r, i;
4524 r = get_group_creds(&name, &gid);
4528 if (getgid() == gid)
4531 if (getegid() == gid)
4534 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4535 assert(ngroups_max > 0);
4537 gids = alloca(sizeof(gid_t) * ngroups_max);
4539 r = getgroups(ngroups_max, gids);
4543 for (i = 0; i < r; i++)
4550 int glob_exists(const char *path) {
4558 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4560 if (k == GLOB_NOMATCH)
4562 else if (k == GLOB_NOSPACE)
4565 r = !strv_isempty(g.gl_pathv);
4567 r = errno ? -errno : -EIO;
4574 int dirent_ensure_type(DIR *d, struct dirent *de) {
4580 if (de->d_type != DT_UNKNOWN)
4583 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4587 S_ISREG(st.st_mode) ? DT_REG :
4588 S_ISDIR(st.st_mode) ? DT_DIR :
4589 S_ISLNK(st.st_mode) ? DT_LNK :
4590 S_ISFIFO(st.st_mode) ? DT_FIFO :
4591 S_ISSOCK(st.st_mode) ? DT_SOCK :
4592 S_ISCHR(st.st_mode) ? DT_CHR :
4593 S_ISBLK(st.st_mode) ? DT_BLK :
4599 int in_search_path(const char *path, char **search) {
4603 r = path_get_parent(path, &parent);
4609 STRV_FOREACH(i, search) {
4610 if (path_equal(parent, *i)) {
4621 int get_files_in_directory(const char *path, char ***list) {
4629 /* Returns all files in a directory in *list, and the number
4630 * of files as return value. If list is NULL returns only the
4639 union dirent_storage buf;
4642 k = readdir_r(d, &buf.de, &de);
4651 dirent_ensure_type(d, de);
4653 if (!dirent_is_file(de))
4657 if ((unsigned) r >= n) {
4661 t = realloc(l, sizeof(char*) * n);
4670 assert((unsigned) r < n);
4672 l[r] = strdup(de->d_name);
4696 char *strjoin(const char *x, ...) {
4710 t = va_arg(ap, const char *);
4715 if (n > ((size_t) -1) - l) {
4739 t = va_arg(ap, const char *);
4753 bool is_main_thread(void) {
4754 static __thread int cached = 0;
4756 if (_unlikely_(cached == 0))
4757 cached = getpid() == gettid() ? 1 : -1;
4762 int block_get_whole_disk(dev_t d, dev_t *ret) {
4769 /* If it has a queue this is good enough for us */
4770 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4773 r = access(p, F_OK);
4781 /* If it is a partition find the originating device */
4782 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4785 r = access(p, F_OK);
4791 /* Get parent dev_t */
4792 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4795 r = read_one_line_file(p, &s);
4801 r = sscanf(s, "%u:%u", &m, &n);
4807 /* Only return this if it is really good enough for us. */
4808 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4811 r = access(p, F_OK);
4815 *ret = makedev(m, n);
4822 int file_is_priv_sticky(const char *p) {
4827 if (lstat(p, &st) < 0)
4831 (st.st_uid == 0 || st.st_uid == getuid()) &&
4832 (st.st_mode & S_ISVTX);
4835 static const char *const ioprio_class_table[] = {
4836 [IOPRIO_CLASS_NONE] = "none",
4837 [IOPRIO_CLASS_RT] = "realtime",
4838 [IOPRIO_CLASS_BE] = "best-effort",
4839 [IOPRIO_CLASS_IDLE] = "idle"
4842 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4844 static const char *const sigchld_code_table[] = {
4845 [CLD_EXITED] = "exited",
4846 [CLD_KILLED] = "killed",
4847 [CLD_DUMPED] = "dumped",
4848 [CLD_TRAPPED] = "trapped",
4849 [CLD_STOPPED] = "stopped",
4850 [CLD_CONTINUED] = "continued",
4853 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4855 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4856 [LOG_FAC(LOG_KERN)] = "kern",
4857 [LOG_FAC(LOG_USER)] = "user",
4858 [LOG_FAC(LOG_MAIL)] = "mail",
4859 [LOG_FAC(LOG_DAEMON)] = "daemon",
4860 [LOG_FAC(LOG_AUTH)] = "auth",
4861 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4862 [LOG_FAC(LOG_LPR)] = "lpr",
4863 [LOG_FAC(LOG_NEWS)] = "news",
4864 [LOG_FAC(LOG_UUCP)] = "uucp",
4865 [LOG_FAC(LOG_CRON)] = "cron",
4866 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4867 [LOG_FAC(LOG_FTP)] = "ftp",
4868 [LOG_FAC(LOG_LOCAL0)] = "local0",
4869 [LOG_FAC(LOG_LOCAL1)] = "local1",
4870 [LOG_FAC(LOG_LOCAL2)] = "local2",
4871 [LOG_FAC(LOG_LOCAL3)] = "local3",
4872 [LOG_FAC(LOG_LOCAL4)] = "local4",
4873 [LOG_FAC(LOG_LOCAL5)] = "local5",
4874 [LOG_FAC(LOG_LOCAL6)] = "local6",
4875 [LOG_FAC(LOG_LOCAL7)] = "local7"
4878 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4880 static const char *const log_level_table[] = {
4881 [LOG_EMERG] = "emerg",
4882 [LOG_ALERT] = "alert",
4883 [LOG_CRIT] = "crit",
4885 [LOG_WARNING] = "warning",
4886 [LOG_NOTICE] = "notice",
4887 [LOG_INFO] = "info",
4888 [LOG_DEBUG] = "debug"
4891 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4893 static const char* const sched_policy_table[] = {
4894 [SCHED_OTHER] = "other",
4895 [SCHED_BATCH] = "batch",
4896 [SCHED_IDLE] = "idle",
4897 [SCHED_FIFO] = "fifo",
4901 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4903 static const char* const rlimit_table[] = {
4904 [RLIMIT_CPU] = "LimitCPU",
4905 [RLIMIT_FSIZE] = "LimitFSIZE",
4906 [RLIMIT_DATA] = "LimitDATA",
4907 [RLIMIT_STACK] = "LimitSTACK",
4908 [RLIMIT_CORE] = "LimitCORE",
4909 [RLIMIT_RSS] = "LimitRSS",
4910 [RLIMIT_NOFILE] = "LimitNOFILE",
4911 [RLIMIT_AS] = "LimitAS",
4912 [RLIMIT_NPROC] = "LimitNPROC",
4913 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4914 [RLIMIT_LOCKS] = "LimitLOCKS",
4915 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4916 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4917 [RLIMIT_NICE] = "LimitNICE",
4918 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4919 [RLIMIT_RTTIME] = "LimitRTTIME"
4922 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4924 static const char* const ip_tos_table[] = {
4925 [IPTOS_LOWDELAY] = "low-delay",
4926 [IPTOS_THROUGHPUT] = "throughput",
4927 [IPTOS_RELIABILITY] = "reliability",
4928 [IPTOS_LOWCOST] = "low-cost",
4931 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4933 static const char *const __signal_table[] = {
4950 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4961 [SIGVTALRM] = "VTALRM",
4963 [SIGWINCH] = "WINCH",
4969 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4971 const char *signal_to_string(int signo) {
4972 static __thread char buf[12];
4975 name = __signal_to_string(signo);
4979 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4980 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4982 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4987 int signal_from_string(const char *s) {
4992 signo = __signal_from_string(s);
4996 if (startswith(s, "RTMIN+")) {
5000 if (safe_atou(s, &u) >= 0) {
5001 signo = (int) u + offset;
5002 if (signo > 0 && signo < _NSIG)
5008 bool kexec_loaded(void) {
5009 bool loaded = false;
5012 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5020 int strdup_or_null(const char *a, char **b) {
5038 int prot_from_flags(int flags) {
5040 switch (flags & O_ACCMODE) {
5049 return PROT_READ|PROT_WRITE;
5056 char *format_bytes(char *buf, size_t l, off_t t) {
5059 static const struct {
5063 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5064 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5065 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5066 { "G", 1024ULL*1024ULL*1024ULL },
5067 { "M", 1024ULL*1024ULL },
5071 for (i = 0; i < ELEMENTSOF(table); i++) {
5073 if (t >= table[i].factor) {
5076 (unsigned long long) (t / table[i].factor),
5077 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5084 snprintf(buf, l, "%lluB", (unsigned long long) t);
5092 void* memdup(const void *p, size_t l) {
5105 int fd_inc_sndbuf(int fd, size_t n) {
5107 socklen_t l = sizeof(value);
5109 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5111 l == sizeof(value) &&
5112 (size_t) value >= n*2)
5116 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5123 int fd_inc_rcvbuf(int fd, size_t n) {
5125 socklen_t l = sizeof(value);
5127 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5129 l == sizeof(value) &&
5130 (size_t) value >= n*2)
5134 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5141 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5142 pid_t parent_pid, agent_pid;
5144 bool stdout_is_tty, stderr_is_tty;
5152 parent_pid = getpid();
5154 /* Spawns a temporary TTY agent, making sure it goes away when
5161 if (agent_pid != 0) {
5168 * Make sure the agent goes away when the parent dies */
5169 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5170 _exit(EXIT_FAILURE);
5172 /* Check whether our parent died before we were able
5173 * to set the death signal */
5174 if (getppid() != parent_pid)
5175 _exit(EXIT_SUCCESS);
5177 /* Don't leak fds to the agent */
5178 close_all_fds(except, n_except);
5180 stdout_is_tty = isatty(STDOUT_FILENO);
5181 stderr_is_tty = isatty(STDERR_FILENO);
5183 if (!stdout_is_tty || !stderr_is_tty) {
5184 /* Detach from stdout/stderr. and reopen
5185 * /dev/tty for them. This is important to
5186 * ensure that when systemctl is started via
5187 * popen() or a similar call that expects to
5188 * read EOF we actually do generate EOF and
5189 * not delay this indefinitely by because we
5190 * keep an unused copy of stdin around. */
5191 fd = open("/dev/tty", O_WRONLY);
5193 log_error("Failed to open /dev/tty: %m");
5194 _exit(EXIT_FAILURE);
5198 dup2(fd, STDOUT_FILENO);
5201 dup2(fd, STDERR_FILENO);
5207 /* Count arguments */
5209 for (n = 0; va_arg(ap, char*); n++)
5214 l = alloca(sizeof(char *) * (n + 1));
5216 /* Fill in arguments */
5218 for (i = 0; i <= n; i++)
5219 l[i] = va_arg(ap, char*);
5223 _exit(EXIT_FAILURE);
5226 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5227 struct rlimit highest, fixed;
5231 if (setrlimit(resource, rlim) >= 0)
5237 /* So we failed to set the desired setrlimit, then let's try
5238 * to get as close as we can */
5239 assert_se(getrlimit(resource, &highest) == 0);
5241 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5242 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5244 if (setrlimit(resource, &fixed) < 0)
5250 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5251 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5263 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5266 f = fopen(path, "re");
5274 char line[LINE_MAX];
5277 for (i = 0; i < sizeof(line)-1; i++) {
5281 if (_unlikely_(c == EOF)) {
5291 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5292 value = strdup(line + l + 1);
5312 int can_sleep(const char *type) {
5316 _cleanup_free_ char *p = NULL;
5320 /* If /sys is read-only we cannot sleep */
5321 if (access("/sys/power/state", W_OK) < 0)
5324 r = read_one_line_file("/sys/power/state", &p);
5329 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5330 if (l == k && memcmp(w, type, l) == 0)
5336 int can_sleep_disk(const char *type) {
5340 _cleanup_free_ char *p = NULL;
5344 /* If /sys is read-only we cannot sleep */
5345 if (access("/sys/power/state", W_OK) < 0 ||
5346 access("/sys/power/disk", W_OK) < 0)
5349 r = read_one_line_file("/sys/power/disk", &p);
5354 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5355 if (l == k && memcmp(w, type, l) == 0)
5358 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5365 bool is_valid_documentation_url(const char *url) {
5368 if (startswith(url, "http://") && url[7])
5371 if (startswith(url, "https://") && url[8])
5374 if (startswith(url, "file:") && url[5])
5377 if (startswith(url, "info:") && url[5])
5380 if (startswith(url, "man:") && url[4])
5386 bool in_initrd(void) {
5387 static __thread int saved = -1;
5393 /* We make two checks here:
5395 * 1. the flag file /etc/initrd-release must exist
5396 * 2. the root file system must be a memory file system
5398 * The second check is extra paranoia, since misdetecting an
5399 * initrd can have bad bad consequences due the initrd
5400 * emptying when transititioning to the main systemd.
5403 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5404 statfs("/", &s) >= 0 &&
5405 is_temporary_fs(&s);
5410 void warn_melody(void) {
5411 _cleanup_close_ int fd = -1;
5413 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5417 /* Yeah, this is synchronous. Kinda sucks. But well... */
5419 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5420 usleep(125*USEC_PER_MSEC);
5422 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5423 usleep(125*USEC_PER_MSEC);
5425 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5426 usleep(125*USEC_PER_MSEC);
5428 ioctl(fd, KIOCSOUND, 0);
5431 int make_console_stdio(void) {
5434 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5436 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5438 log_error("Failed to acquire terminal: %s", strerror(-fd));
5444 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5451 int get_home_dir(char **_h) {
5459 /* Take the user specified one */
5470 /* Hardcode home directory for root to avoid NSS */
5473 h = strdup("/root");
5481 /* Check the database... */
5485 return errno ? -errno : -ESRCH;
5487 if (!path_is_absolute(p->pw_dir))
5490 h = strdup(p->pw_dir);
5498 int get_shell(char **_sh) {
5506 /* Take the user specified one */
5507 e = getenv("SHELL");
5517 /* Hardcode home directory for root to avoid NSS */
5520 sh = strdup("/bin/sh");
5528 /* Check the database... */
5532 return errno ? -errno : -ESRCH;
5534 if (!path_is_absolute(p->pw_shell))
5537 sh = strdup(p->pw_shell);
5545 void freep(void *p) {
5549 void fclosep(FILE **f) {
5554 void pclosep(FILE **f) {
5559 void closep(int *fd) {
5561 close_nointr_nofail(*fd);
5564 void closedirp(DIR **d) {
5569 void umaskp(mode_t *u) {
5573 bool filename_is_safe(const char *p) {
5587 if (strlen(p) > FILENAME_MAX)
5593 bool string_is_safe(const char *p) {
5598 for (t = p; *t; t++) {
5599 if (*t > 0 && *t < ' ')
5602 if (strchr("\\\"\'", *t))
5609 bool string_has_cc(const char *p) {
5614 for (t = p; *t; t++)
5615 if (*t > 0 && *t < ' ')
5621 bool path_is_safe(const char *p) {
5626 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5629 if (strlen(p) > PATH_MAX)
5632 /* The following two checks are not really dangerous, but hey, they still are confusing */
5633 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5636 if (strstr(p, "//"))
5642 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5643 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5644 int (*compar) (const void *, const void *, void *), void *arg) {
5653 p = (void *)(((const char *) base) + (idx * size));
5654 comparison = compar(key, p, arg);
5657 else if (comparison > 0)
5665 bool is_locale_utf8(void) {
5667 static int cached_answer = -1;
5669 if (cached_answer >= 0)
5672 if (!setlocale(LC_ALL, "")) {
5673 cached_answer = true;
5677 set = nl_langinfo(CODESET);
5679 cached_answer = true;
5683 cached_answer = streq(set, "UTF-8");
5685 return (bool)cached_answer;
5688 const char *draw_special_char(DrawSpecialChar ch) {
5689 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5691 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5692 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5693 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5694 [DRAW_TREE_SPACE] = " ", /* */
5695 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5697 /* ASCII fallback */ {
5698 [DRAW_TREE_VERT] = "| ",
5699 [DRAW_TREE_BRANCH] = "|-",
5700 [DRAW_TREE_RIGHT] = "`-",
5701 [DRAW_TREE_SPACE] = " ",
5702 [DRAW_TRIANGULAR_BULLET] = "> ",
5706 return draw_table[!is_locale_utf8()][ch];
5709 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5712 size_t l, old_len, new_len;
5718 old_len = strlen(old_string);
5719 new_len = strlen(new_string);
5732 if (!startswith(f, old_string)) {
5738 nl = l - old_len + new_len;
5739 a = realloc(r, nl + 1);
5747 t = stpcpy(t, new_string);
5759 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5760 const char *i, *begin = NULL;
5765 } state = STATE_OTHER;
5767 size_t osz = 0, isz;
5773 /* Strips ANSI color and replaces TABs by 8 spaces */
5775 isz = _isz ? *_isz : strlen(*ibuf);
5777 f = open_memstream(&obuf, &osz);
5781 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5786 if (i >= *ibuf + isz) /* EOT */
5788 else if (*i == '\x1B')
5789 state = STATE_ESCAPE;
5790 else if (*i == '\t')
5797 if (i >= *ibuf + isz) { /* EOT */
5800 } else if (*i == '[') {
5801 state = STATE_BRACKET;
5806 state = STATE_OTHER;
5813 if (i >= *ibuf + isz || /* EOT */
5814 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5817 state = STATE_OTHER;
5819 } else if (*i == 'm')
5820 state = STATE_OTHER;
5842 int on_ac_power(void) {
5843 bool found_offline = false, found_online = false;
5844 _cleanup_closedir_ DIR *d = NULL;
5846 d = opendir("/sys/class/power_supply");
5852 union dirent_storage buf;
5853 _cleanup_free_ char *p = NULL;
5854 _cleanup_close_ int fd = -1, device = -1;
5859 k = readdir_r(d, &buf.de, &de);
5866 if (ignore_file(de->d_name))
5869 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5871 if (errno == ENOENT || errno == ENOTDIR)
5877 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5879 if (errno == ENOENT)
5885 n = read(fd, contents, sizeof(contents));
5889 if (n != 6 || memcmp(contents, "Mains\n", 6))
5892 close_nointr_nofail(fd);
5893 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5895 if (errno == ENOENT)
5901 n = read(fd, contents, sizeof(contents));
5905 if (n != 2 || contents[1] != '\n')
5908 if (contents[0] == '1') {
5909 found_online = true;
5911 } else if (contents[0] == '0')
5912 found_offline = true;
5917 return found_online || !found_offline;
5920 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5927 if (!path_strv_canonicalize_uniq(search))
5930 STRV_FOREACH(i, search) {
5931 _cleanup_free_ char *p = NULL;
5934 p = strjoin(*i, "/", path, NULL);
5944 if (errno != ENOENT)
5951 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5952 _cleanup_strv_free_ char **copy = NULL;
5958 if (path_is_absolute(path)) {
5961 f = fopen(path, mode);
5970 copy = strv_copy((char**) search);
5974 return search_and_fopen_internal(path, mode, copy, _f);
5977 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5978 _cleanup_strv_free_ char **s = NULL;
5980 if (path_is_absolute(path)) {
5983 f = fopen(path, mode);
5992 s = strv_split_nulstr(search);
5996 return search_and_fopen_internal(path, mode, s, _f);