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>
45 #include <sys/prctl.h>
46 #include <sys/utsname.h>
48 #include <netinet/ip.h>
57 #include <sys/mount.h>
58 #include <linux/magic.h>
62 #include <sys/personality.h>
66 #ifdef HAVE_SYS_AUXV_H
78 #include "path-util.h"
79 #include "exit-status.h"
83 #include "device-nodes.h"
90 char **saved_argv = NULL;
92 static volatile unsigned cached_columns = 0;
93 static volatile unsigned cached_lines = 0;
95 size_t page_size(void) {
96 static thread_local size_t pgsz = 0;
99 if (_likely_(pgsz > 0))
102 r = sysconf(_SC_PAGESIZE);
109 bool streq_ptr(const char *a, const char *b) {
111 /* Like streq(), but tries to make sense of NULL pointers */
122 char* endswith(const char *s, const char *postfix) {
129 pl = strlen(postfix);
132 return (char*) s + sl;
137 if (memcmp(s + sl - pl, postfix, pl) != 0)
140 return (char*) s + sl - pl;
143 char* first_word(const char *s, const char *word) {
150 /* Checks if the string starts with the specified word, either
151 * followed by NUL or by whitespace. Returns a pointer to the
152 * NUL or the first character after the whitespace. */
163 if (memcmp(s, word, wl) != 0)
170 if (!strchr(WHITESPACE, *p))
173 p += strspn(p, WHITESPACE);
177 int close_nointr(int fd) {
184 else if (errno == EINTR)
186 * Just ignore EINTR; a retry loop is the wrong
187 * thing to do on Linux.
189 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
190 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
191 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
192 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
199 int safe_close(int fd) {
202 * Like close_nointr() but cannot fail. Guarantees errno is
203 * unchanged. Is a NOP with negative fds passed, and returns
204 * -1, so that it can be used in this syntax:
206 * fd = safe_close(fd);
212 /* The kernel might return pretty much any error code
213 * via close(), but the fd will be closed anyway. The
214 * only condition we want to check for here is whether
215 * the fd was invalid at all... */
217 assert_se(close_nointr(fd) != -EBADF);
223 void close_many(const int fds[], unsigned n_fd) {
226 assert(fds || n_fd <= 0);
228 for (i = 0; i < n_fd; i++)
232 int unlink_noerrno(const char *path) {
243 int parse_boolean(const char *v) {
246 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
248 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
254 int parse_pid(const char *s, pid_t* ret_pid) {
255 unsigned long ul = 0;
262 r = safe_atolu(s, &ul);
268 if ((unsigned long) pid != ul)
278 int parse_uid(const char *s, uid_t* ret_uid) {
279 unsigned long ul = 0;
286 r = safe_atolu(s, &ul);
292 if ((unsigned long) uid != ul)
295 /* Some libc APIs use (uid_t) -1 as special placeholder */
296 if (uid == (uid_t) 0xFFFFFFFF)
299 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
300 if (uid == (uid_t) 0xFFFF)
307 int safe_atou(const char *s, unsigned *ret_u) {
315 l = strtoul(s, &x, 0);
317 if (!x || x == s || *x || errno)
318 return errno > 0 ? -errno : -EINVAL;
320 if ((unsigned long) (unsigned) l != l)
323 *ret_u = (unsigned) l;
327 int safe_atoi(const char *s, int *ret_i) {
335 l = strtol(s, &x, 0);
337 if (!x || x == s || *x || errno)
338 return errno > 0 ? -errno : -EINVAL;
340 if ((long) (int) l != l)
347 int safe_atou8(const char *s, uint8_t *ret) {
355 l = strtoul(s, &x, 0);
357 if (!x || x == s || *x || errno)
358 return errno > 0 ? -errno : -EINVAL;
360 if ((unsigned long) (uint8_t) l != l)
367 int safe_atollu(const char *s, long long unsigned *ret_llu) {
369 unsigned long long l;
375 l = strtoull(s, &x, 0);
377 if (!x || x == s || *x || errno)
378 return errno ? -errno : -EINVAL;
384 int safe_atolli(const char *s, long long int *ret_lli) {
392 l = strtoll(s, &x, 0);
394 if (!x || x == s || *x || errno)
395 return errno ? -errno : -EINVAL;
401 int safe_atod(const char *s, double *ret_d) {
408 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
413 if (!x || x == s || *x || errno)
414 return errno ? -errno : -EINVAL;
420 static size_t strcspn_escaped(const char *s, const char *reject) {
421 bool escaped = false;
424 for (n=0; s[n]; n++) {
427 else if (s[n] == '\\')
429 else if (strchr(reject, s[n]))
432 /* if s ends in \, return index of previous char */
436 /* Split a string into words. */
437 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
443 assert(**state == '\0');
447 current += strspn(current, separator);
453 if (quoted && strchr("\'\"", *current)) {
454 char quotechars[2] = {*current, '\0'};
456 *l = strcspn_escaped(current + 1, quotechars);
457 if (current[*l + 1] == '\0' ||
458 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
459 /* right quote missing or garbage at the end*/
463 assert(current[*l + 1] == quotechars[0]);
464 *state = current++ + *l + 2;
466 *l = strcspn_escaped(current, separator);
467 *state = current + *l;
469 *l = strcspn(current, separator);
470 *state = current + *l;
476 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
478 _cleanup_free_ char *line = NULL;
490 p = procfs_file_alloca(pid, "stat");
491 r = read_one_line_file(p, &line);
495 /* Let's skip the pid and comm fields. The latter is enclosed
496 * in () but does not escape any () in its value, so let's
497 * skip over it manually */
499 p = strrchr(line, ')');
511 if ((long unsigned) (pid_t) ppid != ppid)
514 *_ppid = (pid_t) ppid;
519 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
521 _cleanup_free_ char *line = NULL;
527 p = procfs_file_alloca(pid, "stat");
528 r = read_one_line_file(p, &line);
532 /* Let's skip the pid and comm fields. The latter is enclosed
533 * in () but does not escape any () in its value, so let's
534 * skip over it manually */
536 p = strrchr(line, ')');
558 "%*d " /* priority */
560 "%*d " /* num_threads */
561 "%*d " /* itrealvalue */
562 "%llu " /* starttime */,
569 int fchmod_umask(int fd, mode_t m) {
574 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
580 char *truncate_nl(char *s) {
583 s[strcspn(s, NEWLINE)] = 0;
587 int get_process_state(pid_t pid) {
591 _cleanup_free_ char *line = NULL;
595 p = procfs_file_alloca(pid, "stat");
596 r = read_one_line_file(p, &line);
600 p = strrchr(line, ')');
606 if (sscanf(p, " %c", &state) != 1)
609 return (unsigned char) state;
612 int get_process_comm(pid_t pid, char **name) {
619 p = procfs_file_alloca(pid, "comm");
621 r = read_one_line_file(p, name);
628 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
629 _cleanup_fclose_ FILE *f = NULL;
637 p = procfs_file_alloca(pid, "cmdline");
643 if (max_length == 0) {
644 size_t len = 0, allocated = 0;
646 while ((c = getc(f)) != EOF) {
648 if (!GREEDY_REALLOC(r, allocated, len+2)) {
653 r[len++] = isprint(c) ? c : ' ';
663 r = new(char, max_length);
669 while ((c = getc(f)) != EOF) {
691 size_t n = MIN(left-1, 3U);
698 /* Kernel threads have no argv[] */
699 if (r == NULL || r[0] == 0) {
700 _cleanup_free_ char *t = NULL;
708 h = get_process_comm(pid, &t);
712 r = strjoin("[", t, "]", NULL);
721 int is_kernel_thread(pid_t pid) {
733 p = procfs_file_alloca(pid, "cmdline");
738 count = fread(&c, 1, 1, f);
742 /* Kernel threads have an empty cmdline */
745 return eof ? 1 : -errno;
750 int get_process_capeff(pid_t pid, char **capeff) {
756 p = procfs_file_alloca(pid, "status");
758 return get_status_field(p, "\nCapEff:", capeff);
761 int get_process_exe(pid_t pid, char **name) {
769 p = procfs_file_alloca(pid, "exe");
771 r = readlink_malloc(p, name);
773 return r == -ENOENT ? -ESRCH : r;
775 d = endswith(*name, " (deleted)");
782 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
783 _cleanup_fclose_ FILE *f = NULL;
793 p = procfs_file_alloca(pid, "status");
798 FOREACH_LINE(line, f, return -errno) {
803 if (startswith(l, field)) {
805 l += strspn(l, WHITESPACE);
807 l[strcspn(l, WHITESPACE)] = 0;
809 return parse_uid(l, uid);
816 int get_process_uid(pid_t pid, uid_t *uid) {
817 return get_process_id(pid, "Uid:", uid);
820 int get_process_gid(pid_t pid, gid_t *gid) {
821 assert_cc(sizeof(uid_t) == sizeof(gid_t));
822 return get_process_id(pid, "Gid:", gid);
825 char *strnappend(const char *s, const char *suffix, size_t b) {
833 return strndup(suffix, b);
842 if (b > ((size_t) -1) - a)
845 r = new(char, a+b+1);
850 memcpy(r+a, suffix, b);
856 char *strappend(const char *s, const char *suffix) {
857 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
860 int readlinkat_malloc(int fd, const char *p, char **ret) {
875 n = readlinkat(fd, p, c, l-1);
882 if ((size_t) n < l-1) {
893 int readlink_malloc(const char *p, char **ret) {
894 return readlinkat_malloc(AT_FDCWD, p, ret);
897 int readlink_and_make_absolute(const char *p, char **r) {
898 _cleanup_free_ char *target = NULL;
905 j = readlink_malloc(p, &target);
909 k = file_in_same_dir(p, target);
917 int readlink_and_canonicalize(const char *p, char **r) {
924 j = readlink_and_make_absolute(p, &t);
928 s = canonicalize_file_name(t);
935 path_kill_slashes(*r);
940 int reset_all_signal_handlers(void) {
943 for (sig = 1; sig < _NSIG; sig++) {
944 struct sigaction sa = {
945 .sa_handler = SIG_DFL,
946 .sa_flags = SA_RESTART,
949 if (sig == SIGKILL || sig == SIGSTOP)
952 /* On Linux the first two RT signals are reserved by
953 * glibc, and sigaction() will return EINVAL for them. */
954 if ((sigaction(sig, &sa, NULL) < 0))
962 char *strstrip(char *s) {
965 /* Drops trailing whitespace. Modifies the string in
966 * place. Returns pointer to first non-space character */
968 s += strspn(s, WHITESPACE);
970 for (e = strchr(s, 0); e > s; e --)
971 if (!strchr(WHITESPACE, e[-1]))
979 char *delete_chars(char *s, const char *bad) {
982 /* Drops all whitespace, regardless where in the string */
984 for (f = s, t = s; *f; f++) {
996 char *file_in_same_dir(const char *path, const char *filename) {
1003 /* This removes the last component of path and appends
1004 * filename, unless the latter is absolute anyway or the
1007 if (path_is_absolute(filename))
1008 return strdup(filename);
1010 if (!(e = strrchr(path, '/')))
1011 return strdup(filename);
1013 k = strlen(filename);
1014 if (!(r = new(char, e-path+1+k+1)))
1017 memcpy(r, path, e-path+1);
1018 memcpy(r+(e-path)+1, filename, k+1);
1023 int rmdir_parents(const char *path, const char *stop) {
1032 /* Skip trailing slashes */
1033 while (l > 0 && path[l-1] == '/')
1039 /* Skip last component */
1040 while (l > 0 && path[l-1] != '/')
1043 /* Skip trailing slashes */
1044 while (l > 0 && path[l-1] == '/')
1050 if (!(t = strndup(path, l)))
1053 if (path_startswith(stop, t)) {
1062 if (errno != ENOENT)
1069 char hexchar(int x) {
1070 static const char table[16] = "0123456789abcdef";
1072 return table[x & 15];
1075 int unhexchar(char c) {
1077 if (c >= '0' && c <= '9')
1080 if (c >= 'a' && c <= 'f')
1081 return c - 'a' + 10;
1083 if (c >= 'A' && c <= 'F')
1084 return c - 'A' + 10;
1089 char *hexmem(const void *p, size_t l) {
1093 z = r = malloc(l * 2 + 1);
1097 for (x = p; x < (const uint8_t*) p + l; x++) {
1098 *(z++) = hexchar(*x >> 4);
1099 *(z++) = hexchar(*x & 15);
1106 void *unhexmem(const char *p, size_t l) {
1112 z = r = malloc((l + 1) / 2 + 1);
1116 for (x = p; x < p + l; x += 2) {
1119 a = unhexchar(x[0]);
1121 b = unhexchar(x[1]);
1125 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1132 char octchar(int x) {
1133 return '0' + (x & 7);
1136 int unoctchar(char c) {
1138 if (c >= '0' && c <= '7')
1144 char decchar(int x) {
1145 return '0' + (x % 10);
1148 int undecchar(char c) {
1150 if (c >= '0' && c <= '9')
1156 char *cescape(const char *s) {
1162 /* Does C style string escaping. */
1164 r = new(char, strlen(s)*4 + 1);
1168 for (f = s, t = r; *f; f++)
1214 /* For special chars we prefer octal over
1215 * hexadecimal encoding, simply because glib's
1216 * g_strescape() does the same */
1217 if ((*f < ' ') || (*f >= 127)) {
1219 *(t++) = octchar((unsigned char) *f >> 6);
1220 *(t++) = octchar((unsigned char) *f >> 3);
1221 *(t++) = octchar((unsigned char) *f);
1232 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1239 /* Undoes C style string escaping, and optionally prefixes it. */
1241 pl = prefix ? strlen(prefix) : 0;
1243 r = new(char, pl+length+1);
1248 memcpy(r, prefix, pl);
1250 for (f = s, t = r + pl; f < s + length; f++) {
1293 /* This is an extension of the XDG syntax files */
1298 /* hexadecimal encoding */
1301 a = unhexchar(f[1]);
1302 b = unhexchar(f[2]);
1304 if (a < 0 || b < 0 || (a == 0 && b == 0)) {
1305 /* Invalid escape code, let's take it literal then */
1309 *(t++) = (char) ((a << 4) | b);
1324 /* octal encoding */
1327 a = unoctchar(f[0]);
1328 b = unoctchar(f[1]);
1329 c = unoctchar(f[2]);
1331 if (a < 0 || b < 0 || c < 0 || (a == 0 && b == 0 && c == 0)) {
1332 /* Invalid escape code, let's take it literal then */
1336 *(t++) = (char) ((a << 6) | (b << 3) | c);
1344 /* premature end of string.*/
1349 /* Invalid escape code, let's take it literal then */
1361 char *cunescape_length(const char *s, size_t length) {
1362 return cunescape_length_with_prefix(s, length, NULL);
1365 char *cunescape(const char *s) {
1368 return cunescape_length(s, strlen(s));
1371 char *xescape(const char *s, const char *bad) {
1375 /* Escapes all chars in bad, in addition to \ and all special
1376 * chars, in \xFF style escaping. May be reversed with
1379 r = new(char, strlen(s) * 4 + 1);
1383 for (f = s, t = r; *f; f++) {
1385 if ((*f < ' ') || (*f >= 127) ||
1386 (*f == '\\') || strchr(bad, *f)) {
1389 *(t++) = hexchar(*f >> 4);
1390 *(t++) = hexchar(*f);
1400 char *ascii_strlower(char *t) {
1405 for (p = t; *p; p++)
1406 if (*p >= 'A' && *p <= 'Z')
1407 *p = *p - 'A' + 'a';
1412 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1416 filename[0] == '.' ||
1417 streq(filename, "lost+found") ||
1418 streq(filename, "aquota.user") ||
1419 streq(filename, "aquota.group") ||
1420 endswith(filename, ".rpmnew") ||
1421 endswith(filename, ".rpmsave") ||
1422 endswith(filename, ".rpmorig") ||
1423 endswith(filename, ".dpkg-old") ||
1424 endswith(filename, ".dpkg-new") ||
1425 endswith(filename, ".swp");
1428 bool ignore_file(const char *filename) {
1431 if (endswith(filename, "~"))
1434 return ignore_file_allow_backup(filename);
1437 int fd_nonblock(int fd, bool nonblock) {
1442 flags = fcntl(fd, F_GETFL, 0);
1447 nflags = flags | O_NONBLOCK;
1449 nflags = flags & ~O_NONBLOCK;
1451 if (nflags == flags)
1454 if (fcntl(fd, F_SETFL, nflags) < 0)
1460 int fd_cloexec(int fd, bool cloexec) {
1465 flags = fcntl(fd, F_GETFD, 0);
1470 nflags = flags | FD_CLOEXEC;
1472 nflags = flags & ~FD_CLOEXEC;
1474 if (nflags == flags)
1477 if (fcntl(fd, F_SETFD, nflags) < 0)
1483 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1486 assert(n_fdset == 0 || fdset);
1488 for (i = 0; i < n_fdset; i++)
1495 int close_all_fds(const int except[], unsigned n_except) {
1496 _cleanup_closedir_ DIR *d = NULL;
1500 assert(n_except == 0 || except);
1502 d = opendir("/proc/self/fd");
1507 /* When /proc isn't available (for example in chroots)
1508 * the fallback is brute forcing through the fd
1511 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1512 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1514 if (fd_in_set(fd, except, n_except))
1517 if (close_nointr(fd) < 0)
1518 if (errno != EBADF && r == 0)
1525 while ((de = readdir(d))) {
1528 if (ignore_file(de->d_name))
1531 if (safe_atoi(de->d_name, &fd) < 0)
1532 /* Let's better ignore this, just in case */
1541 if (fd_in_set(fd, except, n_except))
1544 if (close_nointr(fd) < 0) {
1545 /* Valgrind has its own FD and doesn't want to have it closed */
1546 if (errno != EBADF && r == 0)
1554 bool chars_intersect(const char *a, const char *b) {
1557 /* Returns true if any of the chars in a are in b. */
1558 for (p = a; *p; p++)
1565 bool fstype_is_network(const char *fstype) {
1566 static const char table[] =
1580 x = startswith(fstype, "fuse.");
1584 return nulstr_contains(table, fstype);
1588 _cleanup_close_ int fd;
1590 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1596 TIOCL_GETKMSGREDIRECT,
1600 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1603 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1606 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1612 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1613 struct termios old_termios, new_termios;
1614 char c, line[LINE_MAX];
1619 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1620 new_termios = old_termios;
1622 new_termios.c_lflag &= ~ICANON;
1623 new_termios.c_cc[VMIN] = 1;
1624 new_termios.c_cc[VTIME] = 0;
1626 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1629 if (t != USEC_INFINITY) {
1630 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1631 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1636 k = fread(&c, 1, 1, f);
1638 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1644 *need_nl = c != '\n';
1651 if (t != USEC_INFINITY) {
1652 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1657 if (!fgets(line, sizeof(line), f))
1658 return errno ? -errno : -EIO;
1662 if (strlen(line) != 1)
1672 int ask_char(char *ret, const char *replies, const char *text, ...) {
1682 bool need_nl = true;
1685 fputs(ANSI_HIGHLIGHT_ON, stdout);
1692 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1696 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1699 if (r == -EBADMSG) {
1700 puts("Bad input, please try again.");
1711 if (strchr(replies, c)) {
1716 puts("Read unexpected character, please try again.");
1720 int ask_string(char **ret, const char *text, ...) {
1725 char line[LINE_MAX];
1729 fputs(ANSI_HIGHLIGHT_ON, stdout);
1736 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1741 if (!fgets(line, sizeof(line), stdin))
1742 return errno ? -errno : -EIO;
1744 if (!endswith(line, "\n"))
1763 int reset_terminal_fd(int fd, bool switch_to_text) {
1764 struct termios termios;
1767 /* Set terminal to some sane defaults */
1771 /* We leave locked terminal attributes untouched, so that
1772 * Plymouth may set whatever it wants to set, and we don't
1773 * interfere with that. */
1775 /* Disable exclusive mode, just in case */
1776 ioctl(fd, TIOCNXCL);
1778 /* Switch to text mode */
1780 ioctl(fd, KDSETMODE, KD_TEXT);
1782 /* Enable console unicode mode */
1783 ioctl(fd, KDSKBMODE, K_UNICODE);
1785 if (tcgetattr(fd, &termios) < 0) {
1790 /* We only reset the stuff that matters to the software. How
1791 * hardware is set up we don't touch assuming that somebody
1792 * else will do that for us */
1794 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1795 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1796 termios.c_oflag |= ONLCR;
1797 termios.c_cflag |= CREAD;
1798 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1800 termios.c_cc[VINTR] = 03; /* ^C */
1801 termios.c_cc[VQUIT] = 034; /* ^\ */
1802 termios.c_cc[VERASE] = 0177;
1803 termios.c_cc[VKILL] = 025; /* ^X */
1804 termios.c_cc[VEOF] = 04; /* ^D */
1805 termios.c_cc[VSTART] = 021; /* ^Q */
1806 termios.c_cc[VSTOP] = 023; /* ^S */
1807 termios.c_cc[VSUSP] = 032; /* ^Z */
1808 termios.c_cc[VLNEXT] = 026; /* ^V */
1809 termios.c_cc[VWERASE] = 027; /* ^W */
1810 termios.c_cc[VREPRINT] = 022; /* ^R */
1811 termios.c_cc[VEOL] = 0;
1812 termios.c_cc[VEOL2] = 0;
1814 termios.c_cc[VTIME] = 0;
1815 termios.c_cc[VMIN] = 1;
1817 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1821 /* Just in case, flush all crap out */
1822 tcflush(fd, TCIOFLUSH);
1827 int reset_terminal(const char *name) {
1828 _cleanup_close_ int fd = -1;
1830 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1834 return reset_terminal_fd(fd, true);
1837 int open_terminal(const char *name, int mode) {
1842 * If a TTY is in the process of being closed opening it might
1843 * cause EIO. This is horribly awful, but unlikely to be
1844 * changed in the kernel. Hence we work around this problem by
1845 * retrying a couple of times.
1847 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1850 assert(!(mode & O_CREAT));
1853 fd = open(name, mode, 0);
1860 /* Max 1s in total */
1864 usleep(50 * USEC_PER_MSEC);
1885 int flush_fd(int fd) {
1886 struct pollfd pollfd = {
1896 r = poll(&pollfd, 1, 0);
1906 l = read(fd, buf, sizeof(buf));
1912 if (errno == EAGAIN)
1921 int acquire_terminal(
1925 bool ignore_tiocstty_eperm,
1928 int fd = -1, notify = -1, r = 0, wd = -1;
1933 /* We use inotify to be notified when the tty is closed. We
1934 * create the watch before checking if we can actually acquire
1935 * it, so that we don't lose any event.
1937 * Note: strictly speaking this actually watches for the
1938 * device being closed, it does *not* really watch whether a
1939 * tty loses its controlling process. However, unless some
1940 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1941 * its tty otherwise this will not become a problem. As long
1942 * as the administrator makes sure not configure any service
1943 * on the same tty as an untrusted user this should not be a
1944 * problem. (Which he probably should not do anyway.) */
1946 if (timeout != USEC_INFINITY)
1947 ts = now(CLOCK_MONOTONIC);
1949 if (!fail && !force) {
1950 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
1956 wd = inotify_add_watch(notify, name, IN_CLOSE);
1964 struct sigaction sa_old, sa_new = {
1965 .sa_handler = SIG_IGN,
1966 .sa_flags = SA_RESTART,
1970 r = flush_fd(notify);
1975 /* We pass here O_NOCTTY only so that we can check the return
1976 * value TIOCSCTTY and have a reliable way to figure out if we
1977 * successfully became the controlling process of the tty */
1978 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1982 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1983 * if we already own the tty. */
1984 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1986 /* First, try to get the tty */
1987 if (ioctl(fd, TIOCSCTTY, force) < 0)
1990 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1992 /* Sometimes it makes sense to ignore TIOCSCTTY
1993 * returning EPERM, i.e. when very likely we already
1994 * are have this controlling terminal. */
1995 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1998 if (r < 0 && (force || fail || r != -EPERM)) {
2007 assert(notify >= 0);
2010 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2012 struct inotify_event *e;
2014 if (timeout != USEC_INFINITY) {
2017 n = now(CLOCK_MONOTONIC);
2018 if (ts + timeout < n) {
2023 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2033 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2036 if (errno == EINTR || errno == EAGAIN)
2043 e = (struct inotify_event*) inotify_buffer;
2048 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2053 step = sizeof(struct inotify_event) + e->len;
2054 assert(step <= (size_t) l);
2056 e = (struct inotify_event*) ((uint8_t*) e + step);
2063 /* We close the tty fd here since if the old session
2064 * ended our handle will be dead. It's important that
2065 * we do this after sleeping, so that we don't enter
2066 * an endless loop. */
2072 r = reset_terminal_fd(fd, true);
2074 log_warning("Failed to reset terminal: %s", strerror(-r));
2085 int release_terminal(void) {
2087 struct sigaction sa_old, sa_new = {
2088 .sa_handler = SIG_IGN,
2089 .sa_flags = SA_RESTART,
2091 _cleanup_close_ int fd;
2093 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2097 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2098 * by our own TIOCNOTTY */
2099 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2101 if (ioctl(fd, TIOCNOTTY) < 0)
2104 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2109 int sigaction_many(const struct sigaction *sa, ...) {
2114 while ((sig = va_arg(ap, int)) > 0)
2115 if (sigaction(sig, sa, NULL) < 0)
2122 int ignore_signals(int sig, ...) {
2123 struct sigaction sa = {
2124 .sa_handler = SIG_IGN,
2125 .sa_flags = SA_RESTART,
2130 if (sigaction(sig, &sa, NULL) < 0)
2134 while ((sig = va_arg(ap, int)) > 0)
2135 if (sigaction(sig, &sa, NULL) < 0)
2142 int default_signals(int sig, ...) {
2143 struct sigaction sa = {
2144 .sa_handler = SIG_DFL,
2145 .sa_flags = SA_RESTART,
2150 if (sigaction(sig, &sa, NULL) < 0)
2154 while ((sig = va_arg(ap, int)) > 0)
2155 if (sigaction(sig, &sa, NULL) < 0)
2162 void safe_close_pair(int p[]) {
2166 /* Special case pairs which use the same fd in both
2168 p[0] = p[1] = safe_close(p[0]);
2172 p[0] = safe_close(p[0]);
2173 p[1] = safe_close(p[1]);
2176 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2183 while (nbytes > 0) {
2186 k = read(fd, p, nbytes);
2187 if (k < 0 && errno == EINTR)
2190 if (k < 0 && errno == EAGAIN && do_poll) {
2192 /* We knowingly ignore any return value here,
2193 * and expect that any error/EOF is reported
2196 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2201 return n > 0 ? n : (k < 0 ? -errno : 0);
2211 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2212 const uint8_t *p = buf;
2218 while (nbytes > 0) {
2221 k = write(fd, p, nbytes);
2222 if (k < 0 && errno == EINTR)
2225 if (k < 0 && errno == EAGAIN && do_poll) {
2227 /* We knowingly ignore any return value here,
2228 * and expect that any error/EOF is reported
2231 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2236 return n > 0 ? n : (k < 0 ? -errno : 0);
2246 int parse_size(const char *t, off_t base, off_t *size) {
2248 /* Soo, sometimes we want to parse IEC binary suffxies, and
2249 * sometimes SI decimal suffixes. This function can parse
2250 * both. Which one is the right way depends on the
2251 * context. Wikipedia suggests that SI is customary for
2252 * hardrware metrics and network speeds, while IEC is
2253 * customary for most data sizes used by software and volatile
2254 * (RAM) memory. Hence be careful which one you pick!
2256 * In either case we use just K, M, G as suffix, and not Ki,
2257 * Mi, Gi or so (as IEC would suggest). That's because that's
2258 * frickin' ugly. But this means you really need to make sure
2259 * to document which base you are parsing when you use this
2264 unsigned long long factor;
2267 static const struct table iec[] = {
2268 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2269 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2270 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2271 { "G", 1024ULL*1024ULL*1024ULL },
2272 { "M", 1024ULL*1024ULL },
2278 static const struct table si[] = {
2279 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2280 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2281 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2282 { "G", 1000ULL*1000ULL*1000ULL },
2283 { "M", 1000ULL*1000ULL },
2289 const struct table *table;
2291 unsigned long long r = 0;
2292 unsigned n_entries, start_pos = 0;
2295 assert(base == 1000 || base == 1024);
2300 n_entries = ELEMENTSOF(si);
2303 n_entries = ELEMENTSOF(iec);
2309 unsigned long long l2;
2315 l = strtoll(p, &e, 10);
2328 if (*e >= '0' && *e <= '9') {
2331 /* strotoull itself would accept space/+/- */
2332 l2 = strtoull(e, &e2, 10);
2334 if (errno == ERANGE)
2337 /* Ignore failure. E.g. 10.M is valid */
2344 e += strspn(e, WHITESPACE);
2346 for (i = start_pos; i < n_entries; i++)
2347 if (startswith(e, table[i].suffix)) {
2348 unsigned long long tmp;
2349 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2351 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2352 if (tmp > ULLONG_MAX - r)
2356 if ((unsigned long long) (off_t) r != r)
2359 p = e + strlen(table[i].suffix);
2375 int make_stdio(int fd) {
2380 r = dup3(fd, STDIN_FILENO, 0);
2381 s = dup3(fd, STDOUT_FILENO, 0);
2382 t = dup3(fd, STDERR_FILENO, 0);
2387 if (r < 0 || s < 0 || t < 0)
2390 /* We rely here that the new fd has O_CLOEXEC not set */
2395 int make_null_stdio(void) {
2398 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2402 return make_stdio(null_fd);
2405 bool is_device_path(const char *path) {
2407 /* Returns true on paths that refer to a device, either in
2408 * sysfs or in /dev */
2411 path_startswith(path, "/dev/") ||
2412 path_startswith(path, "/sys/");
2415 int dir_is_empty(const char *path) {
2416 _cleanup_closedir_ DIR *d;
2427 if (!de && errno != 0)
2433 if (!ignore_file(de->d_name))
2438 char* dirname_malloc(const char *path) {
2439 char *d, *dir, *dir2;
2456 int dev_urandom(void *p, size_t n) {
2457 _cleanup_close_ int fd;
2460 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2462 return errno == ENOENT ? -ENOSYS : -errno;
2464 k = loop_read(fd, p, n, true);
2467 if ((size_t) k != n)
2473 void random_bytes(void *p, size_t n) {
2474 static bool srand_called = false;
2478 r = dev_urandom(p, n);
2482 /* If some idiot made /dev/urandom unavailable to us, he'll
2483 * get a PRNG instead. */
2485 if (!srand_called) {
2488 #ifdef HAVE_SYS_AUXV_H
2489 /* The kernel provides us with a bit of entropy in
2490 * auxv, so let's try to make use of that to seed the
2491 * pseudo-random generator. It's better than
2496 auxv = (void*) getauxval(AT_RANDOM);
2498 x ^= *(unsigned*) auxv;
2501 x ^= (unsigned) now(CLOCK_REALTIME);
2502 x ^= (unsigned) gettid();
2505 srand_called = true;
2508 for (q = p; q < (uint8_t*) p + n; q ++)
2512 void rename_process(const char name[8]) {
2515 /* This is a like a poor man's setproctitle(). It changes the
2516 * comm field, argv[0], and also the glibc's internally used
2517 * name of the process. For the first one a limit of 16 chars
2518 * applies, to the second one usually one of 10 (i.e. length
2519 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2520 * "systemd"). If you pass a longer string it will be
2523 prctl(PR_SET_NAME, name);
2525 if (program_invocation_name)
2526 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2528 if (saved_argc > 0) {
2532 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2534 for (i = 1; i < saved_argc; i++) {
2538 memzero(saved_argv[i], strlen(saved_argv[i]));
2543 void sigset_add_many(sigset_t *ss, ...) {
2550 while ((sig = va_arg(ap, int)) > 0)
2551 assert_se(sigaddset(ss, sig) == 0);
2555 int sigprocmask_many(int how, ...) {
2560 assert_se(sigemptyset(&ss) == 0);
2563 while ((sig = va_arg(ap, int)) > 0)
2564 assert_se(sigaddset(&ss, sig) == 0);
2567 if (sigprocmask(how, &ss, NULL) < 0)
2573 char* gethostname_malloc(void) {
2576 assert_se(uname(&u) >= 0);
2578 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2579 return strdup(u.nodename);
2581 return strdup(u.sysname);
2584 bool hostname_is_set(void) {
2587 assert_se(uname(&u) >= 0);
2589 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2592 static char *lookup_uid(uid_t uid) {
2595 _cleanup_free_ char *buf = NULL;
2596 struct passwd pwbuf, *pw = NULL;
2598 /* Shortcut things to avoid NSS lookups */
2600 return strdup("root");
2602 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2606 buf = malloc(bufsize);
2610 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2611 return strdup(pw->pw_name);
2613 if (asprintf(&name, UID_FMT, uid) < 0)
2619 char* getlogname_malloc(void) {
2623 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2628 return lookup_uid(uid);
2631 char *getusername_malloc(void) {
2638 return lookup_uid(getuid());
2641 int getttyname_malloc(int fd, char **r) {
2642 char path[PATH_MAX], *c;
2647 k = ttyname_r(fd, path, sizeof(path));
2653 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2661 int getttyname_harder(int fd, char **r) {
2665 k = getttyname_malloc(fd, &s);
2669 if (streq(s, "tty")) {
2671 return get_ctty(0, NULL, r);
2678 int get_ctty_devnr(pid_t pid, dev_t *d) {
2680 _cleanup_free_ char *line = NULL;
2682 unsigned long ttynr;
2686 p = procfs_file_alloca(pid, "stat");
2687 r = read_one_line_file(p, &line);
2691 p = strrchr(line, ')');
2701 "%*d " /* session */
2706 if (major(ttynr) == 0 && minor(ttynr) == 0)
2715 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2716 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2717 _cleanup_free_ char *s = NULL;
2724 k = get_ctty_devnr(pid, &devnr);
2728 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2730 k = readlink_malloc(fn, &s);
2736 /* This is an ugly hack */
2737 if (major(devnr) == 136) {
2738 asprintf(&b, "pts/%u", minor(devnr));
2742 /* Probably something like the ptys which have no
2743 * symlink in /dev/char. Let's return something
2744 * vaguely useful. */
2750 if (startswith(s, "/dev/"))
2752 else if (startswith(s, "../"))
2770 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2771 _cleanup_closedir_ DIR *d = NULL;
2776 /* This returns the first error we run into, but nevertheless
2777 * tries to go on. This closes the passed fd. */
2783 return errno == ENOENT ? 0 : -errno;
2788 bool is_dir, keep_around;
2795 if (errno != 0 && ret == 0)
2800 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2803 if (de->d_type == DT_UNKNOWN ||
2805 (de->d_type == DT_DIR && root_dev)) {
2806 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2807 if (ret == 0 && errno != ENOENT)
2812 is_dir = S_ISDIR(st.st_mode);
2815 (st.st_uid == 0 || st.st_uid == getuid()) &&
2816 (st.st_mode & S_ISVTX);
2818 is_dir = de->d_type == DT_DIR;
2819 keep_around = false;
2825 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2826 if (root_dev && st.st_dev != root_dev->st_dev)
2829 subdir_fd = openat(fd, de->d_name,
2830 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2831 if (subdir_fd < 0) {
2832 if (ret == 0 && errno != ENOENT)
2837 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2838 if (r < 0 && ret == 0)
2842 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2843 if (ret == 0 && errno != ENOENT)
2847 } else if (!only_dirs && !keep_around) {
2849 if (unlinkat(fd, de->d_name, 0) < 0) {
2850 if (ret == 0 && errno != ENOENT)
2857 _pure_ static int is_temporary_fs(struct statfs *s) {
2860 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2861 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2864 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2869 if (fstatfs(fd, &s) < 0) {
2874 /* We refuse to clean disk file systems with this call. This
2875 * is extra paranoia just to be sure we never ever remove
2877 if (!is_temporary_fs(&s)) {
2878 log_error("Attempted to remove disk file system, and we can't allow that.");
2883 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2886 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2892 /* We refuse to clean the root file system with this
2893 * call. This is extra paranoia to never cause a really
2894 * seriously broken system. */
2895 if (path_equal(path, "/")) {
2896 log_error("Attempted to remove entire root file system, and we can't allow that.");
2900 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2903 if (errno != ENOTDIR)
2907 if (statfs(path, &s) < 0)
2910 if (!is_temporary_fs(&s)) {
2911 log_error("Attempted to remove disk file system, and we can't allow that.");
2916 if (delete_root && !only_dirs)
2917 if (unlink(path) < 0 && errno != ENOENT)
2924 if (fstatfs(fd, &s) < 0) {
2929 if (!is_temporary_fs(&s)) {
2930 log_error("Attempted to remove disk file system, and we can't allow that.");
2936 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2939 if (honour_sticky && file_is_priv_sticky(path) > 0)
2942 if (rmdir(path) < 0 && errno != ENOENT) {
2951 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2952 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2955 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2956 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2959 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2962 /* Under the assumption that we are running privileged we
2963 * first change the access mode and only then hand out
2964 * ownership to avoid a window where access is too open. */
2966 if (mode != (mode_t) -1)
2967 if (chmod(path, mode) < 0)
2970 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2971 if (chown(path, uid, gid) < 0)
2977 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2980 /* Under the assumption that we are running privileged we
2981 * first change the access mode and only then hand out
2982 * ownership to avoid a window where access is too open. */
2984 if (mode != (mode_t) -1)
2985 if (fchmod(fd, mode) < 0)
2988 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2989 if (fchown(fd, uid, gid) < 0)
2995 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2999 /* Allocates the cpuset in the right size */
3002 if (!(r = CPU_ALLOC(n)))
3005 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3006 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3016 if (errno != EINVAL)
3023 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
3024 static const char status_indent[] = " "; /* "[" STATUS "] " */
3025 _cleanup_free_ char *s = NULL;
3026 _cleanup_close_ int fd = -1;
3027 struct iovec iovec[6] = {};
3029 static bool prev_ephemeral;
3033 /* This is independent of logging, as status messages are
3034 * optional and go exclusively to the console. */
3036 if (vasprintf(&s, format, ap) < 0)
3039 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3052 sl = status ? sizeof(status_indent)-1 : 0;
3058 e = ellipsize(s, emax, 75);
3066 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3067 prev_ephemeral = ephemeral;
3070 if (!isempty(status)) {
3071 IOVEC_SET_STRING(iovec[n++], "[");
3072 IOVEC_SET_STRING(iovec[n++], status);
3073 IOVEC_SET_STRING(iovec[n++], "] ");
3075 IOVEC_SET_STRING(iovec[n++], status_indent);
3078 IOVEC_SET_STRING(iovec[n++], s);
3080 IOVEC_SET_STRING(iovec[n++], "\n");
3082 if (writev(fd, iovec, n) < 0)
3088 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3094 va_start(ap, format);
3095 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3101 char *replace_env(const char *format, char **env) {
3108 const char *e, *word = format;
3113 for (e = format; *e; e ++) {
3124 if (!(k = strnappend(r, word, e-word-1)))
3133 } else if (*e == '$') {
3134 if (!(k = strnappend(r, word, e-word)))
3150 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3152 k = strappend(r, t);
3166 if (!(k = strnappend(r, word, e-word)))
3177 char **replace_env_argv(char **argv, char **env) {
3179 unsigned k = 0, l = 0;
3181 l = strv_length(argv);
3183 ret = new(char*, l+1);
3187 STRV_FOREACH(i, argv) {
3189 /* If $FOO appears as single word, replace it by the split up variable */
3190 if ((*i)[0] == '$' && (*i)[1] != '{') {
3195 e = strv_env_get(env, *i+1);
3199 r = strv_split_quoted(&m, e);
3211 w = realloc(ret, sizeof(char*) * (l+1));
3221 memcpy(ret + k, m, q * sizeof(char*));
3229 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3230 ret[k] = replace_env(*i, env);
3242 int fd_columns(int fd) {
3243 struct winsize ws = {};
3245 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3254 unsigned columns(void) {
3258 if (_likely_(cached_columns > 0))
3259 return cached_columns;
3262 e = getenv("COLUMNS");
3267 c = fd_columns(STDOUT_FILENO);
3276 int fd_lines(int fd) {
3277 struct winsize ws = {};
3279 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3288 unsigned lines(void) {
3292 if (_likely_(cached_lines > 0))
3293 return cached_lines;
3296 e = getenv("LINES");
3301 l = fd_lines(STDOUT_FILENO);
3307 return cached_lines;
3310 /* intended to be used as a SIGWINCH sighandler */
3311 void columns_lines_cache_reset(int signum) {
3317 static int cached_on_tty = -1;
3319 if (_unlikely_(cached_on_tty < 0))
3320 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3322 return cached_on_tty;
3325 int files_same(const char *filea, const char *fileb) {
3328 if (stat(filea, &a) < 0)
3331 if (stat(fileb, &b) < 0)
3334 return a.st_dev == b.st_dev &&
3335 a.st_ino == b.st_ino;
3338 int running_in_chroot(void) {
3341 ret = files_same("/proc/1/root", "/");
3348 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3353 assert(percent <= 100);
3354 assert(new_length >= 3);
3356 if (old_length <= 3 || old_length <= new_length)
3357 return strndup(s, old_length);
3359 r = new0(char, new_length+1);
3363 x = (new_length * percent) / 100;
3365 if (x > new_length - 3)
3373 s + old_length - (new_length - x - 3),
3374 new_length - x - 3);
3379 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3383 unsigned k, len, len2;
3386 assert(percent <= 100);
3387 assert(new_length >= 3);
3389 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3390 if (ascii_is_valid(s))
3391 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3393 if (old_length <= 3 || old_length <= new_length)
3394 return strndup(s, old_length);
3396 x = (new_length * percent) / 100;