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>
71 #include "path-util.h"
72 #include "exit-status.h"
76 #include "device-nodes.h"
81 char **saved_argv = NULL;
83 static volatile unsigned cached_columns = 0;
84 static volatile unsigned cached_lines = 0;
86 size_t page_size(void) {
87 static __thread size_t pgsz = 0;
90 if (_likely_(pgsz > 0))
93 r = sysconf(_SC_PAGESIZE);
100 bool streq_ptr(const char *a, const char *b) {
102 /* Like streq(), but tries to make sense of NULL pointers */
113 char* endswith(const char *s, const char *postfix) {
120 pl = strlen(postfix);
123 return (char*) s + sl;
128 if (memcmp(s + sl - pl, postfix, pl) != 0)
131 return (char*) s + sl - pl;
134 bool first_word(const char *s, const char *word) {
149 if (memcmp(s, word, wl) != 0)
153 strchr(WHITESPACE, s[wl]);
156 int close_nointr(int fd) {
162 /* Just ignore EINTR; a retry loop is the wrong
163 * thing to do on Linux.
165 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
166 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
167 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
168 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
170 if (_unlikely_(r < 0 && errno == EINTR))
178 void close_nointr_nofail(int fd) {
181 /* like close_nointr() but cannot fail, and guarantees errno
184 assert_se(close_nointr(fd) == 0);
187 void close_many(const int fds[], unsigned n_fd) {
190 assert(fds || n_fd <= 0);
192 for (i = 0; i < n_fd; i++)
193 close_nointr_nofail(fds[i]);
196 int unlink_noerrno(const char *path) {
207 int parse_boolean(const char *v) {
210 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
212 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
218 int parse_pid(const char *s, pid_t* ret_pid) {
219 unsigned long ul = 0;
226 r = safe_atolu(s, &ul);
232 if ((unsigned long) pid != ul)
242 int parse_uid(const char *s, uid_t* ret_uid) {
243 unsigned long ul = 0;
250 r = safe_atolu(s, &ul);
256 if ((unsigned long) uid != ul)
263 int safe_atou(const char *s, unsigned *ret_u) {
271 l = strtoul(s, &x, 0);
273 if (!x || x == s || *x || errno)
274 return errno > 0 ? -errno : -EINVAL;
276 if ((unsigned long) (unsigned) l != l)
279 *ret_u = (unsigned) l;
283 int safe_atoi(const char *s, int *ret_i) {
291 l = strtol(s, &x, 0);
293 if (!x || x == s || *x || errno)
294 return errno > 0 ? -errno : -EINVAL;
296 if ((long) (int) l != l)
303 int safe_atollu(const char *s, long long unsigned *ret_llu) {
305 unsigned long long l;
311 l = strtoull(s, &x, 0);
313 if (!x || x == s || *x || errno)
314 return errno ? -errno : -EINVAL;
320 int safe_atolli(const char *s, long long int *ret_lli) {
328 l = strtoll(s, &x, 0);
330 if (!x || x == s || *x || errno)
331 return errno ? -errno : -EINVAL;
337 int safe_atod(const char *s, double *ret_d) {
344 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
349 if (!x || x == s || *x || errno)
350 return errno ? -errno : -EINVAL;
356 /* Split a string into words. */
357 char *split(const char *c, size_t *l, const char *separator, char **state) {
360 current = *state ? *state : (char*) c;
362 if (!*current || *c == 0)
365 current += strspn(current, separator);
366 *l = strcspn(current, separator);
369 return (char*) current;
372 /* Split a string into words, but consider strings enclosed in '' and
373 * "" as words even if they include spaces. */
374 char *split_quoted(const char *c, size_t *l, char **state) {
376 bool escaped = false;
378 current = *state ? *state : (char*) c;
380 if (!*current || *c == 0)
383 current += strspn(current, WHITESPACE);
385 if (*current == '\'') {
388 for (e = current; *e; e++) {
398 *state = *e == 0 ? e : e+1;
399 } else if (*current == '\"') {
402 for (e = current; *e; e++) {
412 *state = *e == 0 ? e : e+1;
414 for (e = current; *e; e++) {
419 else if (strchr(WHITESPACE, *e))
426 return (char*) current;
429 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
431 _cleanup_fclose_ FILE *f = NULL;
444 p = procfs_file_alloca(pid, "stat");
449 if (!fgets(line, sizeof(line), f)) {
450 r = feof(f) ? -EIO : -errno;
454 /* Let's skip the pid and comm fields. The latter is enclosed
455 * in () but does not escape any () in its value, so let's
456 * skip over it manually */
458 p = strrchr(line, ')');
470 if ((long unsigned) (pid_t) ppid != ppid)
473 *_ppid = (pid_t) ppid;
478 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
479 _cleanup_fclose_ FILE *f = NULL;
487 p = "/proc/self/stat";
489 p = procfs_file_alloca(pid, "stat");
495 if (!fgets(line, sizeof(line), f)) {
502 /* Let's skip the pid and comm fields. The latter is enclosed
503 * in () but does not escape any () in its value, so let's
504 * skip over it manually */
506 p = strrchr(line, ')');
528 "%*d " /* priority */
530 "%*d " /* num_threads */
531 "%*d " /* itrealvalue */
532 "%llu " /* starttime */,
539 int fchmod_umask(int fd, mode_t m) {
544 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
550 char *truncate_nl(char *s) {
553 s[strcspn(s, NEWLINE)] = 0;
557 int get_process_comm(pid_t pid, char **name) {
564 p = "/proc/self/comm";
566 p = procfs_file_alloca(pid, "comm");
568 return read_one_line_file(p, name);
571 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
572 _cleanup_fclose_ FILE *f = NULL;
581 p = "/proc/self/cmdline";
583 p = procfs_file_alloca(pid, "cmdline");
589 if (max_length == 0) {
590 size_t len = 0, allocated = 0;
592 while ((c = getc(f)) != EOF) {
594 if (!GREEDY_REALLOC(r, allocated, len+2)) {
599 r[len++] = isprint(c) ? c : ' ';
609 r = new(char, max_length);
615 while ((c = getc(f)) != EOF) {
637 size_t n = MIN(left-1, 3U);
644 /* Kernel threads have no argv[] */
645 if (r == NULL || r[0] == 0) {
646 _cleanup_free_ char *t = NULL;
654 h = get_process_comm(pid, &t);
658 r = strjoin("[", t, "]", NULL);
667 int is_kernel_thread(pid_t pid) {
679 p = procfs_file_alloca(pid, "cmdline");
684 count = fread(&c, 1, 1, f);
688 /* Kernel threads have an empty cmdline */
691 return eof ? 1 : -errno;
696 int get_process_capeff(pid_t pid, char **capeff) {
703 p = "/proc/self/status";
705 p = procfs_file_alloca(pid, "status");
707 return get_status_field(p, "\nCapEff:", capeff);
710 int get_process_exe(pid_t pid, char **name) {
719 p = "/proc/self/exe";
721 p = procfs_file_alloca(pid, "exe");
723 r = readlink_malloc(p, name);
727 d = endswith(*name, " (deleted)");
734 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
735 _cleanup_fclose_ FILE *f = NULL;
745 p = procfs_file_alloca(pid, "status");
750 FOREACH_LINE(line, f, return -errno) {
755 if (startswith(l, field)) {
757 l += strspn(l, WHITESPACE);
759 l[strcspn(l, WHITESPACE)] = 0;
761 return parse_uid(l, uid);
768 int get_process_uid(pid_t pid, uid_t *uid) {
769 return get_process_id(pid, "Uid:", uid);
772 int get_process_gid(pid_t pid, gid_t *gid) {
773 assert_cc(sizeof(uid_t) == sizeof(gid_t));
774 return get_process_id(pid, "Gid:", gid);
777 char *strnappend(const char *s, const char *suffix, size_t b) {
785 return strndup(suffix, b);
794 if (b > ((size_t) -1) - a)
797 r = new(char, a+b+1);
802 memcpy(r+a, suffix, b);
808 char *strappend(const char *s, const char *suffix) {
809 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
812 int readlink_malloc(const char *p, char **r) {
822 if (!(c = new(char, l)))
825 if ((n = readlink(p, c, l-1)) < 0) {
831 if ((size_t) n < l-1) {
842 int readlink_and_make_absolute(const char *p, char **r) {
843 _cleanup_free_ char *target = NULL;
850 j = readlink_malloc(p, &target);
854 k = file_in_same_dir(p, target);
862 int readlink_and_canonicalize(const char *p, char **r) {
869 j = readlink_and_make_absolute(p, &t);
873 s = canonicalize_file_name(t);
880 path_kill_slashes(*r);
885 int reset_all_signal_handlers(void) {
888 for (sig = 1; sig < _NSIG; sig++) {
889 struct sigaction sa = {
890 .sa_handler = SIG_DFL,
891 .sa_flags = SA_RESTART,
894 if (sig == SIGKILL || sig == SIGSTOP)
897 /* On Linux the first two RT signals are reserved by
898 * glibc, and sigaction() will return EINVAL for them. */
899 if ((sigaction(sig, &sa, NULL) < 0))
907 char *strstrip(char *s) {
910 /* Drops trailing whitespace. Modifies the string in
911 * place. Returns pointer to first non-space character */
913 s += strspn(s, WHITESPACE);
915 for (e = strchr(s, 0); e > s; e --)
916 if (!strchr(WHITESPACE, e[-1]))
924 char *delete_chars(char *s, const char *bad) {
927 /* Drops all whitespace, regardless where in the string */
929 for (f = s, t = s; *f; f++) {
941 bool in_charset(const char *s, const char* charset) {
948 if (!strchr(charset, *i))
954 char *file_in_same_dir(const char *path, const char *filename) {
961 /* This removes the last component of path and appends
962 * filename, unless the latter is absolute anyway or the
965 if (path_is_absolute(filename))
966 return strdup(filename);
968 if (!(e = strrchr(path, '/')))
969 return strdup(filename);
971 k = strlen(filename);
972 if (!(r = new(char, e-path+1+k+1)))
975 memcpy(r, path, e-path+1);
976 memcpy(r+(e-path)+1, filename, k+1);
981 int rmdir_parents(const char *path, const char *stop) {
990 /* Skip trailing slashes */
991 while (l > 0 && path[l-1] == '/')
997 /* Skip last component */
998 while (l > 0 && path[l-1] != '/')
1001 /* Skip trailing slashes */
1002 while (l > 0 && path[l-1] == '/')
1008 if (!(t = strndup(path, l)))
1011 if (path_startswith(stop, t)) {
1020 if (errno != ENOENT)
1027 char hexchar(int x) {
1028 static const char table[16] = "0123456789abcdef";
1030 return table[x & 15];
1033 int unhexchar(char c) {
1035 if (c >= '0' && c <= '9')
1038 if (c >= 'a' && c <= 'f')
1039 return c - 'a' + 10;
1041 if (c >= 'A' && c <= 'F')
1042 return c - 'A' + 10;
1047 char *hexmem(const void *p, size_t l) {
1051 z = r = malloc(l * 2 + 1);
1055 for (x = p; x < (const uint8_t*) p + l; x++) {
1056 *(z++) = hexchar(*x >> 4);
1057 *(z++) = hexchar(*x & 15);
1064 void *unhexmem(const char *p, size_t l) {
1070 z = r = malloc((l + 1) / 2 + 1);
1074 for (x = p; x < p + l; x += 2) {
1077 a = unhexchar(x[0]);
1079 b = unhexchar(x[1]);
1083 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1090 char octchar(int x) {
1091 return '0' + (x & 7);
1094 int unoctchar(char c) {
1096 if (c >= '0' && c <= '7')
1102 char decchar(int x) {
1103 return '0' + (x % 10);
1106 int undecchar(char c) {
1108 if (c >= '0' && c <= '9')
1114 char *cescape(const char *s) {
1120 /* Does C style string escaping. */
1122 r = new(char, strlen(s)*4 + 1);
1126 for (f = s, t = r; *f; f++)
1172 /* For special chars we prefer octal over
1173 * hexadecimal encoding, simply because glib's
1174 * g_strescape() does the same */
1175 if ((*f < ' ') || (*f >= 127)) {
1177 *(t++) = octchar((unsigned char) *f >> 6);
1178 *(t++) = octchar((unsigned char) *f >> 3);
1179 *(t++) = octchar((unsigned char) *f);
1190 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1197 /* Undoes C style string escaping, and optionally prefixes it. */
1199 pl = prefix ? strlen(prefix) : 0;
1201 r = new(char, pl+length+1);
1206 memcpy(r, prefix, pl);
1208 for (f = s, t = r + pl; f < s + length; f++) {
1251 /* This is an extension of the XDG syntax files */
1256 /* hexadecimal encoding */
1259 a = unhexchar(f[1]);
1260 b = unhexchar(f[2]);
1262 if (a < 0 || b < 0) {
1263 /* Invalid escape code, let's take it literal then */
1267 *(t++) = (char) ((a << 4) | b);
1282 /* octal encoding */
1285 a = unoctchar(f[0]);
1286 b = unoctchar(f[1]);
1287 c = unoctchar(f[2]);
1289 if (a < 0 || b < 0 || c < 0) {
1290 /* Invalid escape code, let's take it literal then */
1294 *(t++) = (char) ((a << 6) | (b << 3) | c);
1302 /* premature end of string.*/
1307 /* Invalid escape code, let's take it literal then */
1319 char *cunescape_length(const char *s, size_t length) {
1320 return cunescape_length_with_prefix(s, length, NULL);
1323 char *cunescape(const char *s) {
1326 return cunescape_length(s, strlen(s));
1329 char *xescape(const char *s, const char *bad) {
1333 /* Escapes all chars in bad, in addition to \ and all special
1334 * chars, in \xFF style escaping. May be reversed with
1337 r = new(char, strlen(s) * 4 + 1);
1341 for (f = s, t = r; *f; f++) {
1343 if ((*f < ' ') || (*f >= 127) ||
1344 (*f == '\\') || strchr(bad, *f)) {
1347 *(t++) = hexchar(*f >> 4);
1348 *(t++) = hexchar(*f);
1358 char *bus_path_escape(const char *s) {
1364 /* Escapes all chars that D-Bus' object path cannot deal
1365 * with. Can be reverse with bus_path_unescape(). We special
1366 * case the empty string. */
1371 r = new(char, strlen(s)*3 + 1);
1375 for (f = s, t = r; *f; f++) {
1377 /* Escape everything that is not a-zA-Z0-9. We also
1378 * escape 0-9 if it's the first character */
1380 if (!(*f >= 'A' && *f <= 'Z') &&
1381 !(*f >= 'a' && *f <= 'z') &&
1382 !(f > s && *f >= '0' && *f <= '9')) {
1384 *(t++) = hexchar(*f >> 4);
1385 *(t++) = hexchar(*f);
1395 char *bus_path_unescape(const char *f) {
1400 /* Special case for the empty string */
1404 r = new(char, strlen(f) + 1);
1408 for (t = r; *f; f++) {
1413 if ((a = unhexchar(f[1])) < 0 ||
1414 (b = unhexchar(f[2])) < 0) {
1415 /* Invalid escape code, let's take it literal then */
1418 *(t++) = (char) ((a << 4) | b);
1430 char *ascii_strlower(char *t) {
1435 for (p = t; *p; p++)
1436 if (*p >= 'A' && *p <= 'Z')
1437 *p = *p - 'A' + 'a';
1442 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1446 filename[0] == '.' ||
1447 streq(filename, "lost+found") ||
1448 streq(filename, "aquota.user") ||
1449 streq(filename, "aquota.group") ||
1450 endswith(filename, ".rpmnew") ||
1451 endswith(filename, ".rpmsave") ||
1452 endswith(filename, ".rpmorig") ||
1453 endswith(filename, ".dpkg-old") ||
1454 endswith(filename, ".dpkg-new") ||
1455 endswith(filename, ".swp");
1458 bool ignore_file(const char *filename) {
1461 if (endswith(filename, "~"))
1464 return ignore_file_allow_backup(filename);
1467 int fd_nonblock(int fd, bool nonblock) {
1472 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1476 flags |= O_NONBLOCK;
1478 flags &= ~O_NONBLOCK;
1480 if (fcntl(fd, F_SETFL, flags) < 0)
1486 int fd_cloexec(int fd, bool cloexec) {
1491 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1495 flags |= FD_CLOEXEC;
1497 flags &= ~FD_CLOEXEC;
1499 if (fcntl(fd, F_SETFD, flags) < 0)
1505 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1508 assert(n_fdset == 0 || fdset);
1510 for (i = 0; i < n_fdset; i++)
1517 int close_all_fds(const int except[], unsigned n_except) {
1522 assert(n_except == 0 || except);
1524 d = opendir("/proc/self/fd");
1529 /* When /proc isn't available (for example in chroots)
1530 * the fallback is brute forcing through the fd
1533 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1534 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1536 if (fd_in_set(fd, except, n_except))
1539 if (close_nointr(fd) < 0)
1540 if (errno != EBADF && r == 0)
1547 while ((de = readdir(d))) {
1550 if (ignore_file(de->d_name))
1553 if (safe_atoi(de->d_name, &fd) < 0)
1554 /* Let's better ignore this, just in case */
1563 if (fd_in_set(fd, except, n_except))
1566 if (close_nointr(fd) < 0) {
1567 /* Valgrind has its own FD and doesn't want to have it closed */
1568 if (errno != EBADF && r == 0)
1577 bool chars_intersect(const char *a, const char *b) {
1580 /* Returns true if any of the chars in a are in b. */
1581 for (p = a; *p; p++)
1588 bool fstype_is_network(const char *fstype) {
1589 static const char table[] =
1599 return nulstr_contains(table, fstype);
1603 _cleanup_close_ int fd;
1605 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1611 TIOCL_GETKMSGREDIRECT,
1615 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1618 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1621 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1627 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1628 struct termios old_termios, new_termios;
1630 char line[LINE_MAX];
1635 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1636 new_termios = old_termios;
1638 new_termios.c_lflag &= ~ICANON;
1639 new_termios.c_cc[VMIN] = 1;
1640 new_termios.c_cc[VTIME] = 0;
1642 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1645 if (t != (usec_t) -1) {
1646 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1647 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1652 k = fread(&c, 1, 1, f);
1654 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1660 *need_nl = c != '\n';
1667 if (t != (usec_t) -1)
1668 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1671 if (!fgets(line, sizeof(line), f))
1676 if (strlen(line) != 1)
1686 int ask(char *ret, const char *replies, const char *text, ...) {
1696 bool need_nl = true;
1699 fputs(ANSI_HIGHLIGHT_ON, stdout);
1706 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1710 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1713 if (r == -EBADMSG) {
1714 puts("Bad input, please try again.");
1725 if (strchr(replies, c)) {
1730 puts("Read unexpected character, please try again.");
1734 int reset_terminal_fd(int fd, bool switch_to_text) {
1735 struct termios termios;
1738 /* Set terminal to some sane defaults */
1742 /* We leave locked terminal attributes untouched, so that
1743 * Plymouth may set whatever it wants to set, and we don't
1744 * interfere with that. */
1746 /* Disable exclusive mode, just in case */
1747 ioctl(fd, TIOCNXCL);
1749 /* Switch to text mode */
1751 ioctl(fd, KDSETMODE, KD_TEXT);
1753 /* Enable console unicode mode */
1754 ioctl(fd, KDSKBMODE, K_UNICODE);
1756 if (tcgetattr(fd, &termios) < 0) {
1761 /* We only reset the stuff that matters to the software. How
1762 * hardware is set up we don't touch assuming that somebody
1763 * else will do that for us */
1765 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1766 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1767 termios.c_oflag |= ONLCR;
1768 termios.c_cflag |= CREAD;
1769 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1771 termios.c_cc[VINTR] = 03; /* ^C */
1772 termios.c_cc[VQUIT] = 034; /* ^\ */
1773 termios.c_cc[VERASE] = 0177;
1774 termios.c_cc[VKILL] = 025; /* ^X */
1775 termios.c_cc[VEOF] = 04; /* ^D */
1776 termios.c_cc[VSTART] = 021; /* ^Q */
1777 termios.c_cc[VSTOP] = 023; /* ^S */
1778 termios.c_cc[VSUSP] = 032; /* ^Z */
1779 termios.c_cc[VLNEXT] = 026; /* ^V */
1780 termios.c_cc[VWERASE] = 027; /* ^W */
1781 termios.c_cc[VREPRINT] = 022; /* ^R */
1782 termios.c_cc[VEOL] = 0;
1783 termios.c_cc[VEOL2] = 0;
1785 termios.c_cc[VTIME] = 0;
1786 termios.c_cc[VMIN] = 1;
1788 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1792 /* Just in case, flush all crap out */
1793 tcflush(fd, TCIOFLUSH);
1798 int reset_terminal(const char *name) {
1801 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1805 r = reset_terminal_fd(fd, true);
1806 close_nointr_nofail(fd);
1811 int open_terminal(const char *name, int mode) {
1816 * If a TTY is in the process of being closed opening it might
1817 * cause EIO. This is horribly awful, but unlikely to be
1818 * changed in the kernel. Hence we work around this problem by
1819 * retrying a couple of times.
1821 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1824 assert(!(mode & O_CREAT));
1827 fd = open(name, mode, 0);
1834 /* Max 1s in total */
1838 usleep(50 * USEC_PER_MSEC);
1847 close_nointr_nofail(fd);
1852 close_nointr_nofail(fd);
1859 int flush_fd(int fd) {
1860 struct pollfd pollfd = {
1870 r = poll(&pollfd, 1, 0);
1880 l = read(fd, buf, sizeof(buf));
1886 if (errno == EAGAIN)
1895 int acquire_terminal(
1899 bool ignore_tiocstty_eperm,
1902 int fd = -1, notify = -1, r = 0, wd = -1;
1907 /* We use inotify to be notified when the tty is closed. We
1908 * create the watch before checking if we can actually acquire
1909 * it, so that we don't lose any event.
1911 * Note: strictly speaking this actually watches for the
1912 * device being closed, it does *not* really watch whether a
1913 * tty loses its controlling process. However, unless some
1914 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1915 * its tty otherwise this will not become a problem. As long
1916 * as the administrator makes sure not configure any service
1917 * on the same tty as an untrusted user this should not be a
1918 * problem. (Which he probably should not do anyway.) */
1920 if (timeout != (usec_t) -1)
1921 ts = now(CLOCK_MONOTONIC);
1923 if (!fail && !force) {
1924 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1930 wd = inotify_add_watch(notify, name, IN_CLOSE);
1938 struct sigaction sa_old, sa_new = {
1939 .sa_handler = SIG_IGN,
1940 .sa_flags = SA_RESTART,
1944 r = flush_fd(notify);
1949 /* We pass here O_NOCTTY only so that we can check the return
1950 * value TIOCSCTTY and have a reliable way to figure out if we
1951 * successfully became the controlling process of the tty */
1952 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1956 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1957 * if we already own the tty. */
1958 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1960 /* First, try to get the tty */
1961 if (ioctl(fd, TIOCSCTTY, force) < 0)
1964 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1966 /* Sometimes it makes sense to ignore TIOCSCTTY
1967 * returning EPERM, i.e. when very likely we already
1968 * are have this controlling terminal. */
1969 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1972 if (r < 0 && (force || fail || r != -EPERM)) {
1981 assert(notify >= 0);
1984 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1986 struct inotify_event *e;
1988 if (timeout != (usec_t) -1) {
1991 n = now(CLOCK_MONOTONIC);
1992 if (ts + timeout < n) {
1997 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2007 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2010 if (errno == EINTR || errno == EAGAIN)
2017 e = (struct inotify_event*) inotify_buffer;
2022 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2027 step = sizeof(struct inotify_event) + e->len;
2028 assert(step <= (size_t) l);
2030 e = (struct inotify_event*) ((uint8_t*) e + step);
2037 /* We close the tty fd here since if the old session
2038 * ended our handle will be dead. It's important that
2039 * we do this after sleeping, so that we don't enter
2040 * an endless loop. */
2041 close_nointr_nofail(fd);
2045 close_nointr_nofail(notify);
2047 r = reset_terminal_fd(fd, true);
2049 log_warning("Failed to reset terminal: %s", strerror(-r));
2055 close_nointr_nofail(fd);
2058 close_nointr_nofail(notify);
2063 int release_terminal(void) {
2065 struct sigaction sa_old, sa_new = {
2066 .sa_handler = SIG_IGN,
2067 .sa_flags = SA_RESTART,
2069 _cleanup_close_ int fd;
2071 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2075 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2076 * by our own TIOCNOTTY */
2077 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2079 if (ioctl(fd, TIOCNOTTY) < 0)
2082 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2087 int sigaction_many(const struct sigaction *sa, ...) {
2092 while ((sig = va_arg(ap, int)) > 0)
2093 if (sigaction(sig, sa, NULL) < 0)
2100 int ignore_signals(int sig, ...) {
2101 struct sigaction sa = {
2102 .sa_handler = SIG_IGN,
2103 .sa_flags = SA_RESTART,
2109 if (sigaction(sig, &sa, NULL) < 0)
2113 while ((sig = va_arg(ap, int)) > 0)
2114 if (sigaction(sig, &sa, NULL) < 0)
2121 int default_signals(int sig, ...) {
2122 struct sigaction sa = {
2123 .sa_handler = SIG_DFL,
2124 .sa_flags = SA_RESTART,
2129 if (sigaction(sig, &sa, NULL) < 0)
2133 while ((sig = va_arg(ap, int)) > 0)
2134 if (sigaction(sig, &sa, NULL) < 0)
2141 int close_pipe(int p[]) {
2147 a = close_nointr(p[0]);
2152 b = close_nointr(p[1]);
2156 return a < 0 ? a : b;
2159 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2168 while (nbytes > 0) {
2171 if ((k = read(fd, p, nbytes)) <= 0) {
2173 if (k < 0 && errno == EINTR)
2176 if (k < 0 && errno == EAGAIN && do_poll) {
2177 struct pollfd pollfd = {
2182 if (poll(&pollfd, 1, -1) < 0) {
2186 return n > 0 ? n : -errno;
2189 /* We knowingly ignore the revents value here,
2190 * and expect that any error/EOF is reported
2191 * via read()/write()
2197 return n > 0 ? n : (k < 0 ? -errno : 0);
2208 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2217 while (nbytes > 0) {
2220 k = write(fd, p, nbytes);
2223 if (k < 0 && errno == EINTR)
2226 if (k < 0 && errno == EAGAIN && do_poll) {
2227 struct pollfd pollfd = {
2232 if (poll(&pollfd, 1, -1) < 0) {
2236 return n > 0 ? n : -errno;
2239 /* We knowingly ignore the revents value here,
2240 * and expect that any error/EOF is reported
2241 * via read()/write()
2247 return n > 0 ? n : (k < 0 ? -errno : 0);
2258 int parse_bytes(const char *t, off_t *bytes) {
2259 static const struct {
2261 unsigned long long factor;
2265 { "M", 1024ULL*1024ULL },
2266 { "G", 1024ULL*1024ULL*1024ULL },
2267 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2268 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2269 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2274 unsigned long long r = 0;
2286 l = strtoll(p, &e, 10);
2297 e += strspn(e, WHITESPACE);
2299 for (i = 0; i < ELEMENTSOF(table); i++)
2300 if (startswith(e, table[i].suffix)) {
2301 unsigned long long tmp;
2302 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2304 tmp = l * table[i].factor;
2305 if (tmp > ULLONG_MAX - r)
2309 if ((unsigned long long) (off_t) r != r)
2312 p = e + strlen(table[i].suffix);
2316 if (i >= ELEMENTSOF(table))
2326 int make_stdio(int fd) {
2331 r = dup3(fd, STDIN_FILENO, 0);
2332 s = dup3(fd, STDOUT_FILENO, 0);
2333 t = dup3(fd, STDERR_FILENO, 0);
2336 close_nointr_nofail(fd);
2338 if (r < 0 || s < 0 || t < 0)
2341 /* We rely here that the new fd has O_CLOEXEC not set */
2346 int make_null_stdio(void) {
2349 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2353 return make_stdio(null_fd);
2356 bool is_device_path(const char *path) {
2358 /* Returns true on paths that refer to a device, either in
2359 * sysfs or in /dev */
2362 path_startswith(path, "/dev/") ||
2363 path_startswith(path, "/sys/");
2366 int dir_is_empty(const char *path) {
2367 _cleanup_closedir_ DIR *d;
2376 union dirent_storage buf;
2378 r = readdir_r(d, &buf.de, &de);
2385 if (!ignore_file(de->d_name))
2390 char* dirname_malloc(const char *path) {
2391 char *d, *dir, *dir2;
2408 unsigned long long random_ull(void) {
2409 _cleanup_close_ int fd;
2413 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2417 r = loop_read(fd, &ull, sizeof(ull), true);
2418 if (r != sizeof(ull))
2424 return random() * RAND_MAX + random();
2427 unsigned random_u(void) {
2428 _cleanup_close_ int fd;
2432 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2436 r = loop_read(fd, &u, sizeof(u), true);
2443 return random() * RAND_MAX + random();
2446 void rename_process(const char name[8]) {
2449 /* This is a like a poor man's setproctitle(). It changes the
2450 * comm field, argv[0], and also the glibc's internally used
2451 * name of the process. For the first one a limit of 16 chars
2452 * applies, to the second one usually one of 10 (i.e. length
2453 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2454 * "systemd"). If you pass a longer string it will be
2457 prctl(PR_SET_NAME, name);
2459 if (program_invocation_name)
2460 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2462 if (saved_argc > 0) {
2466 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2468 for (i = 1; i < saved_argc; i++) {
2472 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2477 void sigset_add_many(sigset_t *ss, ...) {
2484 while ((sig = va_arg(ap, int)) > 0)
2485 assert_se(sigaddset(ss, sig) == 0);
2489 char* gethostname_malloc(void) {
2492 assert_se(uname(&u) >= 0);
2494 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2495 return strdup(u.nodename);
2497 return strdup(u.sysname);
2500 bool hostname_is_set(void) {
2503 assert_se(uname(&u) >= 0);
2505 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2508 static char *lookup_uid(uid_t uid) {
2511 _cleanup_free_ char *buf = NULL;
2512 struct passwd pwbuf, *pw = NULL;
2514 /* Shortcut things to avoid NSS lookups */
2516 return strdup("root");
2518 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2522 buf = malloc(bufsize);
2526 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2527 return strdup(pw->pw_name);
2529 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2535 char* getlogname_malloc(void) {
2539 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2544 return lookup_uid(uid);
2547 char *getusername_malloc(void) {
2554 return lookup_uid(getuid());
2557 int getttyname_malloc(int fd, char **r) {
2558 char path[PATH_MAX], *c;
2563 k = ttyname_r(fd, path, sizeof(path));
2569 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2577 int getttyname_harder(int fd, char **r) {
2581 k = getttyname_malloc(fd, &s);
2585 if (streq(s, "tty")) {
2587 return get_ctty(0, NULL, r);
2594 int get_ctty_devnr(pid_t pid, dev_t *d) {
2595 _cleanup_fclose_ FILE *f = NULL;
2596 char line[LINE_MAX], *p;
2597 unsigned long ttynr;
2605 fn = "/proc/self/stat";
2607 fn = procfs_file_alloca(pid, "stat");
2609 f = fopen(fn, "re");
2613 if (!fgets(line, sizeof(line), f)) {
2614 k = feof(f) ? -EIO : -errno;
2618 p = strrchr(line, ')');
2628 "%*d " /* session */
2633 if (major(ttynr) == 0 && minor(ttynr) == 0)
2640 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2642 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2647 k = get_ctty_devnr(pid, &devnr);
2651 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2653 k = readlink_malloc(fn, &s);
2659 /* This is an ugly hack */
2660 if (major(devnr) == 136) {
2661 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2671 /* Probably something like the ptys which have no
2672 * symlink in /dev/char. Let's return something
2673 * vaguely useful. */
2686 if (startswith(s, "/dev/"))
2688 else if (startswith(s, "../"))
2706 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2712 /* This returns the first error we run into, but nevertheless
2713 * tries to go on. This closes the passed fd. */
2717 close_nointr_nofail(fd);
2719 return errno == ENOENT ? 0 : -errno;
2724 union dirent_storage buf;
2725 bool is_dir, keep_around;
2729 r = readdir_r(d, &buf.de, &de);
2730 if (r != 0 && ret == 0) {
2738 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2741 if (de->d_type == DT_UNKNOWN ||
2743 (de->d_type == DT_DIR && root_dev)) {
2744 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2745 if (ret == 0 && errno != ENOENT)
2750 is_dir = S_ISDIR(st.st_mode);
2753 (st.st_uid == 0 || st.st_uid == getuid()) &&
2754 (st.st_mode & S_ISVTX);
2756 is_dir = de->d_type == DT_DIR;
2757 keep_around = false;
2763 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2764 if (root_dev && st.st_dev != root_dev->st_dev)
2767 subdir_fd = openat(fd, de->d_name,
2768 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2769 if (subdir_fd < 0) {
2770 if (ret == 0 && errno != ENOENT)
2775 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2776 if (r < 0 && ret == 0)
2780 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2781 if (ret == 0 && errno != ENOENT)
2785 } else if (!only_dirs && !keep_around) {
2787 if (unlinkat(fd, de->d_name, 0) < 0) {
2788 if (ret == 0 && errno != ENOENT)
2799 _pure_ static int is_temporary_fs(struct statfs *s) {
2802 F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2803 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2806 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2811 if (fstatfs(fd, &s) < 0) {
2812 close_nointr_nofail(fd);
2816 /* We refuse to clean disk file systems with this call. This
2817 * is extra paranoia just to be sure we never ever remove
2819 if (!is_temporary_fs(&s)) {
2820 log_error("Attempted to remove disk file system, and we can't allow that.");
2821 close_nointr_nofail(fd);
2825 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2828 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2834 /* We refuse to clean the root file system with this
2835 * call. This is extra paranoia to never cause a really
2836 * seriously broken system. */
2837 if (path_equal(path, "/")) {
2838 log_error("Attempted to remove entire root file system, and we can't allow that.");
2842 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2845 if (errno != ENOTDIR)
2849 if (statfs(path, &s) < 0)
2852 if (!is_temporary_fs(&s)) {
2853 log_error("Attempted to remove disk file system, and we can't allow that.");
2858 if (delete_root && !only_dirs)
2859 if (unlink(path) < 0 && errno != ENOENT)
2866 if (fstatfs(fd, &s) < 0) {
2867 close_nointr_nofail(fd);
2871 if (!is_temporary_fs(&s)) {
2872 log_error("Attempted to remove disk file system, and we can't allow that.");
2873 close_nointr_nofail(fd);
2878 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2881 if (honour_sticky && file_is_priv_sticky(path) > 0)
2884 if (rmdir(path) < 0 && errno != ENOENT) {
2893 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2894 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2897 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2898 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2901 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2904 /* Under the assumption that we are running privileged we
2905 * first change the access mode and only then hand out
2906 * ownership to avoid a window where access is too open. */
2908 if (mode != (mode_t) -1)
2909 if (chmod(path, mode) < 0)
2912 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2913 if (chown(path, uid, gid) < 0)
2919 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2922 /* Under the assumption that we are running privileged we
2923 * first change the access mode and only then hand out
2924 * ownership to avoid a window where access is too open. */
2926 if (fchmod(fd, mode) < 0)
2929 if (fchown(fd, uid, gid) < 0)
2935 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2939 /* Allocates the cpuset in the right size */
2942 if (!(r = CPU_ALLOC(n)))
2945 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2946 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2956 if (errno != EINVAL)
2963 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2964 static const char status_indent[] = " "; /* "[" STATUS "] " */
2965 _cleanup_free_ char *s = NULL;
2966 _cleanup_close_ int fd = -1;
2967 struct iovec iovec[6] = {};
2969 static bool prev_ephemeral;
2973 /* This is independent of logging, as status messages are
2974 * optional and go exclusively to the console. */
2976 if (vasprintf(&s, format, ap) < 0)
2979 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2992 sl = status ? sizeof(status_indent)-1 : 0;
2998 e = ellipsize(s, emax, 75);
3006 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3007 prev_ephemeral = ephemeral;
3010 if (!isempty(status)) {
3011 IOVEC_SET_STRING(iovec[n++], "[");
3012 IOVEC_SET_STRING(iovec[n++], status);
3013 IOVEC_SET_STRING(iovec[n++], "] ");
3015 IOVEC_SET_STRING(iovec[n++], status_indent);
3018 IOVEC_SET_STRING(iovec[n++], s);
3020 IOVEC_SET_STRING(iovec[n++], "\n");
3022 if (writev(fd, iovec, n) < 0)
3028 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3034 va_start(ap, format);
3035 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3041 int status_welcome(void) {
3043 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3045 r = parse_env_file("/etc/os-release", NEWLINE,
3046 "PRETTY_NAME", &pretty_name,
3047 "ANSI_COLOR", &ansi_color,
3049 if (r < 0 && r != -ENOENT)
3050 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3052 return status_printf(NULL, false, false,
3053 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3054 isempty(ansi_color) ? "1" : ansi_color,
3055 isempty(pretty_name) ? "Linux" : pretty_name);
3058 char *replace_env(const char *format, char **env) {
3065 const char *e, *word = format;
3070 for (e = format; *e; e ++) {
3081 if (!(k = strnappend(r, word, e-word-1)))
3090 } else if (*e == '$') {
3091 if (!(k = strnappend(r, word, e-word)))
3107 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3109 k = strappend(r, t);
3123 if (!(k = strnappend(r, word, e-word)))
3134 char **replace_env_argv(char **argv, char **env) {
3136 unsigned k = 0, l = 0;
3138 l = strv_length(argv);
3140 if (!(r = new(char*, l+1)))
3143 STRV_FOREACH(i, argv) {
3145 /* If $FOO appears as single word, replace it by the split up variable */
3146 if ((*i)[0] == '$' && (*i)[1] != '{') {
3151 e = strv_env_get(env, *i+1);
3154 if (!(m = strv_split_quoted(e))) {
3165 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3174 memcpy(r + k, m, q * sizeof(char*));
3182 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3183 if (!(r[k++] = replace_env(*i, env))) {
3193 int fd_columns(int fd) {
3194 struct winsize ws = {};
3196 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3205 unsigned columns(void) {
3209 if (_likely_(cached_columns > 0))
3210 return cached_columns;
3213 e = getenv("COLUMNS");
3218 c = fd_columns(STDOUT_FILENO);
3227 int fd_lines(int fd) {
3228 struct winsize ws = {};
3230 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3239 unsigned lines(void) {
3243 if (_likely_(cached_lines > 0))
3244 return cached_lines;
3247 e = getenv("LINES");
3252 l = fd_lines(STDOUT_FILENO);
3258 return cached_lines;
3261 /* intended to be used as a SIGWINCH sighandler */
3262 void columns_lines_cache_reset(int signum) {
3268 static int cached_on_tty = -1;
3270 if (_unlikely_(cached_on_tty < 0))
3271 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3273 return cached_on_tty;
3276 int running_in_chroot(void) {
3277 struct stat a = {}, b = {};
3279 /* Only works as root */
3280 if (stat("/proc/1/root", &a) < 0)
3283 if (stat("/", &b) < 0)
3287 a.st_dev != b.st_dev ||
3288 a.st_ino != b.st_ino;
3291 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3296 assert(percent <= 100);
3297 assert(new_length >= 3);
3299 if (old_length <= 3 || old_length <= new_length)
3300 return strndup(s, old_length);
3302 r = new0(char, new_length+1);
3306 x = (new_length * percent) / 100;
3308 if (x > new_length - 3)
3316 s + old_length - (new_length - x - 3),
3317 new_length - x - 3);
3322 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3326 unsigned k, len, len2;
3329 assert(percent <= 100);
3330 assert(new_length >= 3);
3332 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3333 if (ascii_is_valid(s))
3334 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3336 if (old_length <= 3 || old_length <= new_length)
3337 return strndup(s, old_length);
3339 x = (new_length * percent) / 100;
3341 if (x > new_length - 3)
3345 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3348 c = utf8_encoded_to_unichar(i);
3351 k += unichar_iswide(c) ? 2 : 1;
3354 if (k > x) /* last character was wide and went over quota */
3357 for (j = s + old_length; k < new_length && j > i; ) {
3360 j = utf8_prev_char(j);
3361 c = utf8_encoded_to_unichar(j);
3364 k += unichar_iswide(c) ? 2 : 1;
3368 /* we don't actually need to ellipsize */
3370 return memdup(s, old_length + 1);
3372 /* make space for ellipsis */
3373 j = utf8_next_char(j);
3376 len2 = s + old_length - j;
3377 e = new(char, len + 3 + len2 + 1);
3382 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3383 old_length, new_length, x, len, len2, k);
3387 e[len] = 0xe2; /* tri-dot ellipsis: … */