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");