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);
2223 log_error("Failed to add watch on %s: %m", name);
2230 r = flush_fd(notify);
2235 /* We pass here O_NOCTTY only so that we can check the return
2236 * value TIOCSCTTY and have a reliable way to figure out if we
2237 * successfully became the controlling process of the tty */
2238 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2242 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2243 * if we already own the tty. */
2245 sa_new.sa_handler = SIG_IGN;
2246 sa_new.sa_flags = SA_RESTART;
2247 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2249 /* First, try to get the tty */
2250 if (ioctl(fd, TIOCSCTTY, force) < 0)
2253 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2255 /* Sometimes it makes sense to ignore TIOCSCTTY
2256 * returning EPERM, i.e. when very likely we already
2257 * are have this controlling terminal. */
2258 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2261 if (r < 0 && (force || fail || r != -EPERM)) {
2270 assert(notify >= 0);
2273 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2275 struct inotify_event *e;
2277 if (timeout != (usec_t) -1) {
2280 n = now(CLOCK_MONOTONIC);
2281 if (ts + timeout < n) {
2286 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2296 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2299 if (errno == EINTR || errno == EAGAIN)
2306 e = (struct inotify_event*) inotify_buffer;
2311 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2316 step = sizeof(struct inotify_event) + e->len;
2317 assert(step <= (size_t) l);
2319 e = (struct inotify_event*) ((uint8_t*) e + step);
2326 /* We close the tty fd here since if the old session
2327 * ended our handle will be dead. It's important that
2328 * we do this after sleeping, so that we don't enter
2329 * an endless loop. */
2330 close_nointr_nofail(fd);
2334 close_nointr_nofail(notify);
2336 r = reset_terminal_fd(fd, true);
2338 log_warning("Failed to reset terminal: %s", strerror(-r));
2344 close_nointr_nofail(fd);
2347 close_nointr_nofail(notify);
2352 int release_terminal(void) {
2354 struct sigaction sa_old, sa_new;
2356 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2359 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2360 * by our own TIOCNOTTY */
2363 sa_new.sa_handler = SIG_IGN;
2364 sa_new.sa_flags = SA_RESTART;
2365 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2367 if (ioctl(fd, TIOCNOTTY) < 0)
2370 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2372 close_nointr_nofail(fd);
2376 int sigaction_many(const struct sigaction *sa, ...) {
2381 while ((sig = va_arg(ap, int)) > 0)
2382 if (sigaction(sig, sa, NULL) < 0)
2389 int ignore_signals(int sig, ...) {
2390 struct sigaction sa;
2395 sa.sa_handler = SIG_IGN;
2396 sa.sa_flags = SA_RESTART;
2398 if (sigaction(sig, &sa, NULL) < 0)
2402 while ((sig = va_arg(ap, int)) > 0)
2403 if (sigaction(sig, &sa, NULL) < 0)
2410 int default_signals(int sig, ...) {
2411 struct sigaction sa;
2416 sa.sa_handler = SIG_DFL;
2417 sa.sa_flags = SA_RESTART;
2419 if (sigaction(sig, &sa, NULL) < 0)
2423 while ((sig = va_arg(ap, int)) > 0)
2424 if (sigaction(sig, &sa, NULL) < 0)
2431 int close_pipe(int p[]) {
2437 a = close_nointr(p[0]);
2442 b = close_nointr(p[1]);
2446 return a < 0 ? a : b;
2449 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2458 while (nbytes > 0) {
2461 if ((k = read(fd, p, nbytes)) <= 0) {
2463 if (k < 0 && errno == EINTR)
2466 if (k < 0 && errno == EAGAIN && do_poll) {
2467 struct pollfd pollfd;
2471 pollfd.events = POLLIN;
2473 if (poll(&pollfd, 1, -1) < 0) {
2477 return n > 0 ? n : -errno;
2480 if (pollfd.revents != POLLIN)
2481 return n > 0 ? n : -EIO;
2486 return n > 0 ? n : (k < 0 ? -errno : 0);
2497 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2506 while (nbytes > 0) {
2509 k = write(fd, p, nbytes);
2512 if (k < 0 && errno == EINTR)
2515 if (k < 0 && errno == EAGAIN && do_poll) {
2516 struct pollfd pollfd;
2520 pollfd.events = POLLOUT;
2522 if (poll(&pollfd, 1, -1) < 0) {
2526 return n > 0 ? n : -errno;
2529 if (pollfd.revents != POLLOUT)
2530 return n > 0 ? n : -EIO;
2535 return n > 0 ? n : (k < 0 ? -errno : 0);
2546 int parse_bytes(const char *t, off_t *bytes) {
2547 static const struct {
2553 { "M", 1024ULL*1024ULL },
2554 { "G", 1024ULL*1024ULL*1024ULL },
2555 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2556 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2557 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2574 l = strtoll(p, &e, 10);
2585 e += strspn(e, WHITESPACE);
2587 for (i = 0; i < ELEMENTSOF(table); i++)
2588 if (startswith(e, table[i].suffix)) {
2589 r += (off_t) l * table[i].factor;
2590 p = e + strlen(table[i].suffix);
2594 if (i >= ELEMENTSOF(table))
2604 int make_stdio(int fd) {
2609 r = dup3(fd, STDIN_FILENO, 0);
2610 s = dup3(fd, STDOUT_FILENO, 0);
2611 t = dup3(fd, STDERR_FILENO, 0);
2614 close_nointr_nofail(fd);
2616 if (r < 0 || s < 0 || t < 0)
2619 /* We rely here that the new fd has O_CLOEXEC not set */
2624 int make_null_stdio(void) {
2627 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2631 return make_stdio(null_fd);
2634 bool is_device_path(const char *path) {
2636 /* Returns true on paths that refer to a device, either in
2637 * sysfs or in /dev */
2640 path_startswith(path, "/dev/") ||
2641 path_startswith(path, "/sys/");
2644 int dir_is_empty(const char *path) {
2645 _cleanup_closedir_ DIR *d;
2654 union dirent_storage buf;
2656 r = readdir_r(d, &buf.de, &de);
2663 if (!ignore_file(de->d_name))
2668 unsigned long long random_ull(void) {
2669 _cleanup_close_ int fd;
2673 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2677 r = loop_read(fd, &ull, sizeof(ull), true);
2678 if (r != sizeof(ull))
2684 return random() * RAND_MAX + random();
2687 void rename_process(const char name[8]) {
2690 /* This is a like a poor man's setproctitle(). It changes the
2691 * comm field, argv[0], and also the glibc's internally used
2692 * name of the process. For the first one a limit of 16 chars
2693 * applies, to the second one usually one of 10 (i.e. length
2694 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2695 * "systemd"). If you pass a longer string it will be
2698 prctl(PR_SET_NAME, name);
2700 if (program_invocation_name)
2701 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2703 if (saved_argc > 0) {
2707 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2709 for (i = 1; i < saved_argc; i++) {
2713 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2718 void sigset_add_many(sigset_t *ss, ...) {
2725 while ((sig = va_arg(ap, int)) > 0)
2726 assert_se(sigaddset(ss, sig) == 0);
2730 char* gethostname_malloc(void) {
2733 assert_se(uname(&u) >= 0);
2735 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2736 return strdup(u.nodename);
2738 return strdup(u.sysname);
2741 bool hostname_is_set(void) {
2744 assert_se(uname(&u) >= 0);
2746 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2749 static char *lookup_uid(uid_t uid) {
2752 _cleanup_free_ char *buf = NULL;
2753 struct passwd pwbuf, *pw = NULL;
2755 /* Shortcut things to avoid NSS lookups */
2757 return strdup("root");
2759 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2763 buf = malloc(bufsize);
2767 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2768 return strdup(pw->pw_name);
2770 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2776 char* getlogname_malloc(void) {
2780 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2785 return lookup_uid(uid);
2788 char *getusername_malloc(void) {
2795 return lookup_uid(getuid());
2798 int getttyname_malloc(int fd, char **r) {
2799 char path[PATH_MAX], *c;
2804 k = ttyname_r(fd, path, sizeof(path));
2810 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2818 int getttyname_harder(int fd, char **r) {
2822 k = getttyname_malloc(fd, &s);
2826 if (streq(s, "tty")) {
2828 return get_ctty(0, NULL, r);
2835 int get_ctty_devnr(pid_t pid, dev_t *d) {
2837 char line[LINE_MAX], *p, *fn;
2838 unsigned long ttynr;
2841 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2844 f = fopen(fn, "re");
2849 if (!fgets(line, sizeof(line), f)) {
2850 k = feof(f) ? -EIO : -errno;
2857 p = strrchr(line, ')');
2867 "%*d " /* session */
2872 if (major(ttynr) == 0 && minor(ttynr) == 0)
2879 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2881 char fn[PATH_MAX], *s, *b, *p;
2886 k = get_ctty_devnr(pid, &devnr);
2890 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2893 k = readlink_malloc(fn, &s);
2899 /* This is an ugly hack */
2900 if (major(devnr) == 136) {
2901 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2911 /* Probably something like the ptys which have no
2912 * symlink in /dev/char. Let's return something
2913 * vaguely useful. */
2926 if (startswith(s, "/dev/"))
2928 else if (startswith(s, "../"))
2946 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2952 /* This returns the first error we run into, but nevertheless
2953 * tries to go on. This closes the passed fd. */
2957 close_nointr_nofail(fd);
2959 return errno == ENOENT ? 0 : -errno;
2964 union dirent_storage buf;
2965 bool is_dir, keep_around;
2969 r = readdir_r(d, &buf.de, &de);
2970 if (r != 0 && ret == 0) {
2978 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2981 if (de->d_type == DT_UNKNOWN ||
2983 (de->d_type == DT_DIR && root_dev)) {
2984 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2985 if (ret == 0 && errno != ENOENT)
2990 is_dir = S_ISDIR(st.st_mode);
2993 (st.st_uid == 0 || st.st_uid == getuid()) &&
2994 (st.st_mode & S_ISVTX);
2996 is_dir = de->d_type == DT_DIR;
2997 keep_around = false;
3003 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3004 if (root_dev && st.st_dev != root_dev->st_dev)
3007 subdir_fd = openat(fd, de->d_name,
3008 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3009 if (subdir_fd < 0) {
3010 if (ret == 0 && errno != ENOENT)
3015 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
3016 if (r < 0 && ret == 0)
3020 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3021 if (ret == 0 && errno != ENOENT)
3025 } else if (!only_dirs && !keep_around) {
3027 if (unlinkat(fd, de->d_name, 0) < 0) {
3028 if (ret == 0 && errno != ENOENT)
3039 static int is_temporary_fs(struct statfs *s) {
3041 return s->f_type == TMPFS_MAGIC ||
3042 (long)s->f_type == (long)RAMFS_MAGIC;
3045 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3050 if (fstatfs(fd, &s) < 0) {
3051 close_nointr_nofail(fd);
3055 /* We refuse to clean disk file systems with this call. This
3056 * is extra paranoia just to be sure we never ever remove
3058 if (!is_temporary_fs(&s)) {
3059 log_error("Attempted to remove disk file system, and we can't allow that.");
3060 close_nointr_nofail(fd);
3064 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3067 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3073 /* We refuse to clean the root file system with this
3074 * call. This is extra paranoia to never cause a really
3075 * seriously broken system. */
3076 if (path_equal(path, "/")) {
3077 log_error("Attempted to remove entire root file system, and we can't allow that.");
3081 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3084 if (errno != ENOTDIR)
3088 if (statfs(path, &s) < 0)
3091 if (!is_temporary_fs(&s)) {
3092 log_error("Attempted to remove disk file system, and we can't allow that.");
3097 if (delete_root && !only_dirs)
3098 if (unlink(path) < 0 && errno != ENOENT)
3105 if (fstatfs(fd, &s) < 0) {
3106 close_nointr_nofail(fd);
3110 if (!is_temporary_fs(&s)) {
3111 log_error("Attempted to remove disk file system, and we can't allow that.");
3112 close_nointr_nofail(fd);
3117 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3120 if (honour_sticky && file_is_priv_sticky(path) > 0)
3123 if (rmdir(path) < 0 && errno != ENOENT) {
3132 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3133 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3136 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3137 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3140 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3143 /* Under the assumption that we are running privileged we
3144 * first change the access mode and only then hand out
3145 * ownership to avoid a window where access is too open. */
3147 if (mode != (mode_t) -1)
3148 if (chmod(path, mode) < 0)
3151 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3152 if (chown(path, uid, gid) < 0)
3158 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3161 /* Under the assumption that we are running privileged we
3162 * first change the access mode and only then hand out
3163 * ownership to avoid a window where access is too open. */
3165 if (fchmod(fd, mode) < 0)
3168 if (fchown(fd, uid, gid) < 0)
3174 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3178 /* Allocates the cpuset in the right size */
3181 if (!(r = CPU_ALLOC(n)))
3184 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3185 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3195 if (errno != EINVAL)
3202 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3203 static const char status_indent[] = " "; /* "[" STATUS "] " */
3204 _cleanup_free_ char *s = NULL;
3205 _cleanup_close_ int fd = -1;
3206 struct iovec iovec[5];
3211 /* This is independent of logging, as status messages are
3212 * optional and go exclusively to the console. */
3214 if (vasprintf(&s, format, ap) < 0)
3217 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3230 sl = status ? sizeof(status_indent)-1 : 0;
3236 e = ellipsize(s, emax, 75);
3246 if (!isempty(status)) {
3247 IOVEC_SET_STRING(iovec[n++], "[");
3248 IOVEC_SET_STRING(iovec[n++], status);
3249 IOVEC_SET_STRING(iovec[n++], "] ");
3251 IOVEC_SET_STRING(iovec[n++], status_indent);
3254 IOVEC_SET_STRING(iovec[n++], s);
3255 IOVEC_SET_STRING(iovec[n++], "\n");
3257 if (writev(fd, iovec, n) < 0)
3263 int status_printf(const char *status, bool ellipse, const char *format, ...) {
3269 va_start(ap, format);
3270 r = status_vprintf(status, ellipse, format, ap);
3276 int status_welcome(void) {
3278 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3280 r = parse_env_file("/etc/os-release", NEWLINE,
3281 "PRETTY_NAME", &pretty_name,
3282 "ANSI_COLOR", &ansi_color,
3284 if (r < 0 && r != -ENOENT)
3285 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3287 return status_printf(NULL, false,
3288 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3289 isempty(ansi_color) ? "1" : ansi_color,
3290 isempty(pretty_name) ? "Linux" : pretty_name);
3293 char *replace_env(const char *format, char **env) {
3300 const char *e, *word = format;
3305 for (e = format; *e; e ++) {
3316 if (!(k = strnappend(r, word, e-word-1)))
3325 } else if (*e == '$') {
3326 if (!(k = strnappend(r, word, e-word)))
3342 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3344 k = strappend(r, t);
3358 if (!(k = strnappend(r, word, e-word)))
3369 char **replace_env_argv(char **argv, char **env) {
3371 unsigned k = 0, l = 0;
3373 l = strv_length(argv);
3375 if (!(r = new(char*, l+1)))