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 bool first_word(const char *s, const char *word) {
158 if (memcmp(s, word, wl) != 0)
162 strchr(WHITESPACE, s[wl]);
165 int close_nointr(int fd) {
172 else if (errno == EINTR)
174 * Just ignore EINTR; a retry loop is the wrong
175 * thing to do on Linux.
177 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
178 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
179 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
180 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
187 int safe_close(int fd) {
190 * Like close_nointr() but cannot fail. Guarantees errno is
191 * unchanged. Is a NOP with negative fds passed, and returns
192 * -1, so that it can be used in this syntax:
194 * fd = safe_close(fd);
200 /* The kernel might return pretty much any error code
201 * via close(), but the fd will be closed anyway. The
202 * only condition we want to check for here is whether
203 * the fd was invalid at all... */
205 assert_se(close_nointr(fd) != -EBADF);
211 void close_many(const int fds[], unsigned n_fd) {
214 assert(fds || n_fd <= 0);
216 for (i = 0; i < n_fd; i++)
220 int unlink_noerrno(const char *path) {
231 int parse_boolean(const char *v) {
234 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
236 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
242 int parse_pid(const char *s, pid_t* ret_pid) {
243 unsigned long ul = 0;
250 r = safe_atolu(s, &ul);
256 if ((unsigned long) pid != ul)
266 int parse_uid(const char *s, uid_t* ret_uid) {
267 unsigned long ul = 0;
274 r = safe_atolu(s, &ul);
280 if ((unsigned long) uid != ul)
287 int safe_atou(const char *s, unsigned *ret_u) {
295 l = strtoul(s, &x, 0);
297 if (!x || x == s || *x || errno)
298 return errno > 0 ? -errno : -EINVAL;
300 if ((unsigned long) (unsigned) l != l)
303 *ret_u = (unsigned) l;
307 int safe_atoi(const char *s, int *ret_i) {
315 l = strtol(s, &x, 0);
317 if (!x || x == s || *x || errno)
318 return errno > 0 ? -errno : -EINVAL;
320 if ((long) (int) l != l)
327 int safe_atollu(const char *s, long long unsigned *ret_llu) {
329 unsigned long long l;
335 l = strtoull(s, &x, 0);
337 if (!x || x == s || *x || errno)
338 return errno ? -errno : -EINVAL;
344 int safe_atolli(const char *s, long long int *ret_lli) {
352 l = strtoll(s, &x, 0);
354 if (!x || x == s || *x || errno)
355 return errno ? -errno : -EINVAL;
361 int safe_atod(const char *s, double *ret_d) {
368 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
373 if (!x || x == s || *x || errno)
374 return errno ? -errno : -EINVAL;
380 static size_t strcspn_escaped(const char *s, const char *reject) {
381 bool escaped = false;
384 for (n=0; s[n]; n++) {
387 else if (s[n] == '\\')
389 else if (strchr(reject, s[n]))
395 /* Split a string into words. */
396 char *split(const char *c, size_t *l, const char *separator, bool quoted, char **state) {
399 current = *state ? *state : (char*) c;
401 if (!*current || *c == 0)
404 current += strspn(current, separator);
408 if (quoted && strchr("\'\"", *current)) {
409 char quotechar = *(current++);
410 *l = strcspn_escaped(current, (char[]){quotechar, '\0'});
411 *state = current+*l+1;
413 *l = strcspn_escaped(current, separator);
416 *l = strcspn(current, separator);
420 return (char*) current;
423 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
425 _cleanup_free_ char *line = NULL;
437 p = procfs_file_alloca(pid, "stat");
438 r = read_one_line_file(p, &line);
442 /* Let's skip the pid and comm fields. The latter is enclosed
443 * in () but does not escape any () in its value, so let's
444 * skip over it manually */
446 p = strrchr(line, ')');
458 if ((long unsigned) (pid_t) ppid != ppid)
461 *_ppid = (pid_t) ppid;
466 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
468 _cleanup_free_ char *line = NULL;
474 p = procfs_file_alloca(pid, "stat");
475 r = read_one_line_file(p, &line);
479 /* Let's skip the pid and comm fields. The latter is enclosed
480 * in () but does not escape any () in its value, so let's
481 * skip over it manually */
483 p = strrchr(line, ')');
505 "%*d " /* priority */
507 "%*d " /* num_threads */
508 "%*d " /* itrealvalue */
509 "%llu " /* starttime */,
516 int fchmod_umask(int fd, mode_t m) {
521 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
527 char *truncate_nl(char *s) {
530 s[strcspn(s, NEWLINE)] = 0;
534 int get_process_state(pid_t pid) {
538 _cleanup_free_ char *line = NULL;
542 p = procfs_file_alloca(pid, "stat");
543 r = read_one_line_file(p, &line);
547 p = strrchr(line, ')');
553 if (sscanf(p, " %c", &state) != 1)
556 return (unsigned char) state;
559 int get_process_comm(pid_t pid, char **name) {
566 p = procfs_file_alloca(pid, "comm");
568 r = read_one_line_file(p, name);
575 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
576 _cleanup_fclose_ FILE *f = NULL;
584 p = procfs_file_alloca(pid, "cmdline");
590 if (max_length == 0) {
591 size_t len = 0, allocated = 0;
593 while ((c = getc(f)) != EOF) {
595 if (!GREEDY_REALLOC(r, allocated, len+2)) {
600 r[len++] = isprint(c) ? c : ' ';
610 r = new(char, max_length);
616 while ((c = getc(f)) != EOF) {
638 size_t n = MIN(left-1, 3U);
645 /* Kernel threads have no argv[] */
646 if (r == NULL || r[0] == 0) {
647 _cleanup_free_ char *t = NULL;
655 h = get_process_comm(pid, &t);
659 r = strjoin("[", t, "]", NULL);
668 int is_kernel_thread(pid_t pid) {
680 p = procfs_file_alloca(pid, "cmdline");
685 count = fread(&c, 1, 1, f);
689 /* Kernel threads have an empty cmdline */
692 return eof ? 1 : -errno;
697 int get_process_capeff(pid_t pid, char **capeff) {
703 p = procfs_file_alloca(pid, "status");
705 return get_status_field(p, "\nCapEff:", capeff);
708 int get_process_exe(pid_t pid, char **name) {
716 p = procfs_file_alloca(pid, "exe");
718 r = readlink_malloc(p, name);
720 return r == -ENOENT ? -ESRCH : r;
722 d = endswith(*name, " (deleted)");
729 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
730 _cleanup_fclose_ FILE *f = NULL;
740 p = procfs_file_alloca(pid, "status");
745 FOREACH_LINE(line, f, return -errno) {
750 if (startswith(l, field)) {
752 l += strspn(l, WHITESPACE);
754 l[strcspn(l, WHITESPACE)] = 0;
756 return parse_uid(l, uid);
763 int get_process_uid(pid_t pid, uid_t *uid) {
764 return get_process_id(pid, "Uid:", uid);
767 int get_process_gid(pid_t pid, gid_t *gid) {
768 assert_cc(sizeof(uid_t) == sizeof(gid_t));
769 return get_process_id(pid, "Gid:", gid);
772 char *strnappend(const char *s, const char *suffix, size_t b) {
780 return strndup(suffix, b);
789 if (b > ((size_t) -1) - a)
792 r = new(char, a+b+1);
797 memcpy(r+a, suffix, b);
803 char *strappend(const char *s, const char *suffix) {
804 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
807 int readlinkat_malloc(int fd, const char *p, char **ret) {
822 n = readlinkat(fd, p, c, l-1);
829 if ((size_t) n < l-1) {
840 int readlink_malloc(const char *p, char **ret) {
841 return readlinkat_malloc(AT_FDCWD, p, ret);
844 int readlink_and_make_absolute(const char *p, char **r) {
845 _cleanup_free_ char *target = NULL;
852 j = readlink_malloc(p, &target);
856 k = file_in_same_dir(p, target);
864 int readlink_and_canonicalize(const char *p, char **r) {
871 j = readlink_and_make_absolute(p, &t);
875 s = canonicalize_file_name(t);
882 path_kill_slashes(*r);
887 int reset_all_signal_handlers(void) {
890 for (sig = 1; sig < _NSIG; sig++) {
891 struct sigaction sa = {
892 .sa_handler = SIG_DFL,
893 .sa_flags = SA_RESTART,
896 if (sig == SIGKILL || sig == SIGSTOP)
899 /* On Linux the first two RT signals are reserved by
900 * glibc, and sigaction() will return EINVAL for them. */
901 if ((sigaction(sig, &sa, NULL) < 0))
909 char *strstrip(char *s) {
912 /* Drops trailing whitespace. Modifies the string in
913 * place. Returns pointer to first non-space character */
915 s += strspn(s, WHITESPACE);
917 for (e = strchr(s, 0); e > s; e --)
918 if (!strchr(WHITESPACE, e[-1]))
926 char *delete_chars(char *s, const char *bad) {
929 /* Drops all whitespace, regardless where in the string */
931 for (f = s, t = s; *f; f++) {
943 char *file_in_same_dir(const char *path, const char *filename) {
950 /* This removes the last component of path and appends
951 * filename, unless the latter is absolute anyway or the
954 if (path_is_absolute(filename))
955 return strdup(filename);
957 if (!(e = strrchr(path, '/')))
958 return strdup(filename);
960 k = strlen(filename);
961 if (!(r = new(char, e-path+1+k+1)))
964 memcpy(r, path, e-path+1);
965 memcpy(r+(e-path)+1, filename, k+1);
970 int rmdir_parents(const char *path, const char *stop) {
979 /* Skip trailing slashes */
980 while (l > 0 && path[l-1] == '/')
986 /* Skip last component */
987 while (l > 0 && path[l-1] != '/')
990 /* Skip trailing slashes */
991 while (l > 0 && path[l-1] == '/')
997 if (!(t = strndup(path, l)))
1000 if (path_startswith(stop, t)) {
1009 if (errno != ENOENT)
1016 char hexchar(int x) {
1017 static const char table[16] = "0123456789abcdef";
1019 return table[x & 15];
1022 int unhexchar(char c) {
1024 if (c >= '0' && c <= '9')
1027 if (c >= 'a' && c <= 'f')
1028 return c - 'a' + 10;
1030 if (c >= 'A' && c <= 'F')
1031 return c - 'A' + 10;
1036 char *hexmem(const void *p, size_t l) {
1040 z = r = malloc(l * 2 + 1);
1044 for (x = p; x < (const uint8_t*) p + l; x++) {
1045 *(z++) = hexchar(*x >> 4);
1046 *(z++) = hexchar(*x & 15);
1053 void *unhexmem(const char *p, size_t l) {
1059 z = r = malloc((l + 1) / 2 + 1);
1063 for (x = p; x < p + l; x += 2) {
1066 a = unhexchar(x[0]);
1068 b = unhexchar(x[1]);
1072 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1079 char octchar(int x) {
1080 return '0' + (x & 7);
1083 int unoctchar(char c) {
1085 if (c >= '0' && c <= '7')
1091 char decchar(int x) {
1092 return '0' + (x % 10);
1095 int undecchar(char c) {
1097 if (c >= '0' && c <= '9')
1103 char *cescape(const char *s) {
1109 /* Does C style string escaping. */
1111 r = new(char, strlen(s)*4 + 1);
1115 for (f = s, t = r; *f; f++)
1161 /* For special chars we prefer octal over
1162 * hexadecimal encoding, simply because glib's
1163 * g_strescape() does the same */
1164 if ((*f < ' ') || (*f >= 127)) {
1166 *(t++) = octchar((unsigned char) *f >> 6);
1167 *(t++) = octchar((unsigned char) *f >> 3);
1168 *(t++) = octchar((unsigned char) *f);
1179 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1186 /* Undoes C style string escaping, and optionally prefixes it. */
1188 pl = prefix ? strlen(prefix) : 0;
1190 r = new(char, pl+length+1);
1195 memcpy(r, prefix, pl);
1197 for (f = s, t = r + pl; f < s + length; f++) {
1240 /* This is an extension of the XDG syntax files */
1245 /* hexadecimal encoding */
1248 a = unhexchar(f[1]);
1249 b = unhexchar(f[2]);
1251 if (a < 0 || b < 0) {
1252 /* Invalid escape code, let's take it literal then */
1256 *(t++) = (char) ((a << 4) | b);
1271 /* octal encoding */
1274 a = unoctchar(f[0]);
1275 b = unoctchar(f[1]);
1276 c = unoctchar(f[2]);
1278 if (a < 0 || b < 0 || c < 0) {
1279 /* Invalid escape code, let's take it literal then */
1283 *(t++) = (char) ((a << 6) | (b << 3) | c);
1291 /* premature end of string.*/
1296 /* Invalid escape code, let's take it literal then */
1308 char *cunescape_length(const char *s, size_t length) {
1309 return cunescape_length_with_prefix(s, length, NULL);
1312 char *cunescape(const char *s) {
1315 return cunescape_length(s, strlen(s));
1318 char *xescape(const char *s, const char *bad) {
1322 /* Escapes all chars in bad, in addition to \ and all special
1323 * chars, in \xFF style escaping. May be reversed with
1326 r = new(char, strlen(s) * 4 + 1);
1330 for (f = s, t = r; *f; f++) {
1332 if ((*f < ' ') || (*f >= 127) ||
1333 (*f == '\\') || strchr(bad, *f)) {
1336 *(t++) = hexchar(*f >> 4);
1337 *(t++) = hexchar(*f);
1347 char *ascii_strlower(char *t) {
1352 for (p = t; *p; p++)
1353 if (*p >= 'A' && *p <= 'Z')
1354 *p = *p - 'A' + 'a';
1359 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1363 filename[0] == '.' ||
1364 streq(filename, "lost+found") ||
1365 streq(filename, "aquota.user") ||
1366 streq(filename, "aquota.group") ||
1367 endswith(filename, ".rpmnew") ||
1368 endswith(filename, ".rpmsave") ||
1369 endswith(filename, ".rpmorig") ||
1370 endswith(filename, ".dpkg-old") ||
1371 endswith(filename, ".dpkg-new") ||
1372 endswith(filename, ".swp");
1375 bool ignore_file(const char *filename) {
1378 if (endswith(filename, "~"))
1381 return ignore_file_allow_backup(filename);
1384 int fd_nonblock(int fd, bool nonblock) {
1389 flags = fcntl(fd, F_GETFL, 0);
1394 nflags = flags | O_NONBLOCK;
1396 nflags = flags & ~O_NONBLOCK;
1398 if (nflags == flags)
1401 if (fcntl(fd, F_SETFL, nflags) < 0)
1407 int fd_cloexec(int fd, bool cloexec) {
1412 flags = fcntl(fd, F_GETFD, 0);
1417 nflags = flags | FD_CLOEXEC;
1419 nflags = flags & ~FD_CLOEXEC;
1421 if (nflags == flags)
1424 if (fcntl(fd, F_SETFD, nflags) < 0)
1430 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1433 assert(n_fdset == 0 || fdset);
1435 for (i = 0; i < n_fdset; i++)
1442 int close_all_fds(const int except[], unsigned n_except) {
1443 _cleanup_closedir_ DIR *d = NULL;
1447 assert(n_except == 0 || except);
1449 d = opendir("/proc/self/fd");
1454 /* When /proc isn't available (for example in chroots)
1455 * the fallback is brute forcing through the fd
1458 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1459 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1461 if (fd_in_set(fd, except, n_except))
1464 if (close_nointr(fd) < 0)
1465 if (errno != EBADF && r == 0)
1472 while ((de = readdir(d))) {
1475 if (ignore_file(de->d_name))
1478 if (safe_atoi(de->d_name, &fd) < 0)
1479 /* Let's better ignore this, just in case */
1488 if (fd_in_set(fd, except, n_except))
1491 if (close_nointr(fd) < 0) {
1492 /* Valgrind has its own FD and doesn't want to have it closed */
1493 if (errno != EBADF && r == 0)
1501 bool chars_intersect(const char *a, const char *b) {
1504 /* Returns true if any of the chars in a are in b. */
1505 for (p = a; *p; p++)
1512 bool fstype_is_network(const char *fstype) {
1513 static const char table[] =
1527 x = startswith(fstype, "fuse.");
1531 return nulstr_contains(table, fstype);
1535 _cleanup_close_ int fd;
1537 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1543 TIOCL_GETKMSGREDIRECT,
1547 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1550 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1553 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1559 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1560 struct termios old_termios, new_termios;
1562 char line[LINE_MAX];
1567 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1568 new_termios = old_termios;
1570 new_termios.c_lflag &= ~ICANON;
1571 new_termios.c_cc[VMIN] = 1;
1572 new_termios.c_cc[VTIME] = 0;
1574 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1577 if (t != (usec_t) -1) {
1578 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1579 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1584 k = fread(&c, 1, 1, f);
1586 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1592 *need_nl = c != '\n';
1599 if (t != (usec_t) -1)
1600 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1603 if (!fgets(line, sizeof(line), f))
1608 if (strlen(line) != 1)
1618 int ask(char *ret, const char *replies, const char *text, ...) {
1628 bool need_nl = true;
1631 fputs(ANSI_HIGHLIGHT_ON, stdout);
1638 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1642 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1645 if (r == -EBADMSG) {
1646 puts("Bad input, please try again.");
1657 if (strchr(replies, c)) {
1662 puts("Read unexpected character, please try again.");
1666 int reset_terminal_fd(int fd, bool switch_to_text) {
1667 struct termios termios;
1670 /* Set terminal to some sane defaults */
1674 /* We leave locked terminal attributes untouched, so that
1675 * Plymouth may set whatever it wants to set, and we don't
1676 * interfere with that. */
1678 /* Disable exclusive mode, just in case */
1679 ioctl(fd, TIOCNXCL);
1681 /* Switch to text mode */
1683 ioctl(fd, KDSETMODE, KD_TEXT);
1685 /* Enable console unicode mode */
1686 ioctl(fd, KDSKBMODE, K_UNICODE);
1688 if (tcgetattr(fd, &termios) < 0) {
1693 /* We only reset the stuff that matters to the software. How
1694 * hardware is set up we don't touch assuming that somebody
1695 * else will do that for us */
1697 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1698 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1699 termios.c_oflag |= ONLCR;
1700 termios.c_cflag |= CREAD;
1701 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1703 termios.c_cc[VINTR] = 03; /* ^C */
1704 termios.c_cc[VQUIT] = 034; /* ^\ */
1705 termios.c_cc[VERASE] = 0177;
1706 termios.c_cc[VKILL] = 025; /* ^X */
1707 termios.c_cc[VEOF] = 04; /* ^D */
1708 termios.c_cc[VSTART] = 021; /* ^Q */
1709 termios.c_cc[VSTOP] = 023; /* ^S */
1710 termios.c_cc[VSUSP] = 032; /* ^Z */
1711 termios.c_cc[VLNEXT] = 026; /* ^V */
1712 termios.c_cc[VWERASE] = 027; /* ^W */
1713 termios.c_cc[VREPRINT] = 022; /* ^R */
1714 termios.c_cc[VEOL] = 0;
1715 termios.c_cc[VEOL2] = 0;
1717 termios.c_cc[VTIME] = 0;
1718 termios.c_cc[VMIN] = 1;
1720 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1724 /* Just in case, flush all crap out */
1725 tcflush(fd, TCIOFLUSH);
1730 int reset_terminal(const char *name) {
1731 _cleanup_close_ int fd = -1;
1733 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1737 return reset_terminal_fd(fd, true);
1740 int open_terminal(const char *name, int mode) {
1745 * If a TTY is in the process of being closed opening it might
1746 * cause EIO. This is horribly awful, but unlikely to be
1747 * changed in the kernel. Hence we work around this problem by
1748 * retrying a couple of times.
1750 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1753 assert(!(mode & O_CREAT));
1756 fd = open(name, mode, 0);
1763 /* Max 1s in total */
1767 usleep(50 * USEC_PER_MSEC);
1788 int flush_fd(int fd) {
1789 struct pollfd pollfd = {
1799 r = poll(&pollfd, 1, 0);
1809 l = read(fd, buf, sizeof(buf));
1815 if (errno == EAGAIN)
1824 int acquire_terminal(
1828 bool ignore_tiocstty_eperm,
1831 int fd = -1, notify = -1, r = 0, wd = -1;
1836 /* We use inotify to be notified when the tty is closed. We
1837 * create the watch before checking if we can actually acquire
1838 * it, so that we don't lose any event.
1840 * Note: strictly speaking this actually watches for the
1841 * device being closed, it does *not* really watch whether a
1842 * tty loses its controlling process. However, unless some
1843 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1844 * its tty otherwise this will not become a problem. As long
1845 * as the administrator makes sure not configure any service
1846 * on the same tty as an untrusted user this should not be a
1847 * problem. (Which he probably should not do anyway.) */
1849 if (timeout != (usec_t) -1)
1850 ts = now(CLOCK_MONOTONIC);
1852 if (!fail && !force) {
1853 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1859 wd = inotify_add_watch(notify, name, IN_CLOSE);
1867 struct sigaction sa_old, sa_new = {
1868 .sa_handler = SIG_IGN,
1869 .sa_flags = SA_RESTART,
1873 r = flush_fd(notify);
1878 /* We pass here O_NOCTTY only so that we can check the return
1879 * value TIOCSCTTY and have a reliable way to figure out if we
1880 * successfully became the controlling process of the tty */
1881 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1885 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1886 * if we already own the tty. */
1887 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1889 /* First, try to get the tty */
1890 if (ioctl(fd, TIOCSCTTY, force) < 0)
1893 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1895 /* Sometimes it makes sense to ignore TIOCSCTTY
1896 * returning EPERM, i.e. when very likely we already
1897 * are have this controlling terminal. */
1898 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1901 if (r < 0 && (force || fail || r != -EPERM)) {
1910 assert(notify >= 0);
1913 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1915 struct inotify_event *e;
1917 if (timeout != (usec_t) -1) {
1920 n = now(CLOCK_MONOTONIC);
1921 if (ts + timeout < n) {
1926 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1936 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1939 if (errno == EINTR || errno == EAGAIN)
1946 e = (struct inotify_event*) inotify_buffer;
1951 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1956 step = sizeof(struct inotify_event) + e->len;
1957 assert(step <= (size_t) l);
1959 e = (struct inotify_event*) ((uint8_t*) e + step);
1966 /* We close the tty fd here since if the old session
1967 * ended our handle will be dead. It's important that
1968 * we do this after sleeping, so that we don't enter
1969 * an endless loop. */
1975 r = reset_terminal_fd(fd, true);
1977 log_warning("Failed to reset terminal: %s", strerror(-r));
1988 int release_terminal(void) {
1990 struct sigaction sa_old, sa_new = {
1991 .sa_handler = SIG_IGN,
1992 .sa_flags = SA_RESTART,
1994 _cleanup_close_ int fd;
1996 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2000 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2001 * by our own TIOCNOTTY */
2002 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2004 if (ioctl(fd, TIOCNOTTY) < 0)
2007 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2012 int sigaction_many(const struct sigaction *sa, ...) {
2017 while ((sig = va_arg(ap, int)) > 0)
2018 if (sigaction(sig, sa, NULL) < 0)
2025 int ignore_signals(int sig, ...) {
2026 struct sigaction sa = {
2027 .sa_handler = SIG_IGN,
2028 .sa_flags = SA_RESTART,
2033 if (sigaction(sig, &sa, NULL) < 0)
2037 while ((sig = va_arg(ap, int)) > 0)
2038 if (sigaction(sig, &sa, NULL) < 0)
2045 int default_signals(int sig, ...) {
2046 struct sigaction sa = {
2047 .sa_handler = SIG_DFL,
2048 .sa_flags = SA_RESTART,
2053 if (sigaction(sig, &sa, NULL) < 0)
2057 while ((sig = va_arg(ap, int)) > 0)
2058 if (sigaction(sig, &sa, NULL) < 0)
2065 void safe_close_pair(int p[]) {
2069 /* Special case pairs which use the same fd in both
2071 p[0] = p[1] = safe_close(p[0]);
2075 p[0] = safe_close(p[0]);
2076 p[1] = safe_close(p[1]);
2079 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2086 while (nbytes > 0) {
2089 k = read(fd, p, nbytes);
2090 if (k < 0 && errno == EINTR)
2093 if (k < 0 && errno == EAGAIN && do_poll) {
2095 /* We knowingly ignore any return value here,
2096 * and expect that any error/EOF is reported
2099 fd_wait_for_event(fd, POLLIN, (usec_t) -1);
2104 return n > 0 ? n : (k < 0 ? -errno : 0);
2114 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2115 const uint8_t *p = buf;
2121 while (nbytes > 0) {
2124 k = write(fd, p, nbytes);
2125 if (k < 0 && errno == EINTR)
2128 if (k < 0 && errno == EAGAIN && do_poll) {
2130 /* We knowingly ignore any return value here,
2131 * and expect that any error/EOF is reported
2134 fd_wait_for_event(fd, POLLOUT, (usec_t) -1);
2139 return n > 0 ? n : (k < 0 ? -errno : 0);
2149 int parse_size(const char *t, off_t base, off_t *size) {
2151 /* Soo, sometimes we want to parse IEC binary suffxies, and
2152 * sometimes SI decimal suffixes. This function can parse
2153 * both. Which one is the right way depends on the
2154 * context. Wikipedia suggests that SI is customary for
2155 * hardrware metrics and network speeds, while IEC is
2156 * customary for most data sizes used by software and volatile
2157 * (RAM) memory. Hence be careful which one you pick!
2159 * In either case we use just K, M, G as suffix, and not Ki,
2160 * Mi, Gi or so (as IEC would suggest). That's because that's
2161 * frickin' ugly. But this means you really need to make sure
2162 * to document which base you are parsing when you use this
2167 unsigned long long factor;
2170 static const struct table iec[] = {
2171 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2172 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2173 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2174 { "G", 1024ULL*1024ULL*1024ULL },
2175 { "M", 1024ULL*1024ULL },
2181 static const struct table si[] = {
2182 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2183 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2184 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2185 { "G", 1000ULL*1000ULL*1000ULL },
2186 { "M", 1000ULL*1000ULL },
2192 const struct table *table;
2194 unsigned long long r = 0;
2195 unsigned n_entries, start_pos = 0;
2198 assert(base == 1000 || base == 1024);
2203 n_entries = ELEMENTSOF(si);
2206 n_entries = ELEMENTSOF(iec);
2212 unsigned long long l2;
2218 l = strtoll(p, &e, 10);
2231 if (*e >= '0' && *e <= '9') {
2234 /* strotoull itself would accept space/+/- */
2235 l2 = strtoull(e, &e2, 10);
2237 if (errno == ERANGE)
2240 /* Ignore failure. E.g. 10.M is valid */
2247 e += strspn(e, WHITESPACE);
2249 for (i = start_pos; i < n_entries; i++)
2250 if (startswith(e, table[i].suffix)) {
2251 unsigned long long tmp;
2252 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2254 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2255 if (tmp > ULLONG_MAX - r)
2259 if ((unsigned long long) (off_t) r != r)
2262 p = e + strlen(table[i].suffix);
2278 int make_stdio(int fd) {
2283 r = dup3(fd, STDIN_FILENO, 0);
2284 s = dup3(fd, STDOUT_FILENO, 0);
2285 t = dup3(fd, STDERR_FILENO, 0);
2290 if (r < 0 || s < 0 || t < 0)
2293 /* We rely here that the new fd has O_CLOEXEC not set */
2298 int make_null_stdio(void) {
2301 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2305 return make_stdio(null_fd);
2308 bool is_device_path(const char *path) {
2310 /* Returns true on paths that refer to a device, either in
2311 * sysfs or in /dev */
2314 path_startswith(path, "/dev/") ||
2315 path_startswith(path, "/sys/");
2318 int dir_is_empty(const char *path) {
2319 _cleanup_closedir_ DIR *d;
2330 if (!de && errno != 0)
2336 if (!ignore_file(de->d_name))
2341 char* dirname_malloc(const char *path) {
2342 char *d, *dir, *dir2;
2359 int dev_urandom(void *p, size_t n) {
2360 _cleanup_close_ int fd;
2363 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2365 return errno == ENOENT ? -ENOSYS : -errno;
2367 k = loop_read(fd, p, n, true);
2370 if ((size_t) k != n)
2376 void random_bytes(void *p, size_t n) {
2377 static bool srand_called = false;
2381 r = dev_urandom(p, n);
2385 /* If some idiot made /dev/urandom unavailable to us, he'll
2386 * get a PRNG instead. */
2388 if (!srand_called) {
2391 #ifdef HAVE_SYS_AUXV_H
2392 /* The kernel provides us with a bit of entropy in
2393 * auxv, so let's try to make use of that to seed the
2394 * pseudo-random generator. It's better than
2399 auxv = (void*) getauxval(AT_RANDOM);
2401 x ^= *(unsigned*) auxv;
2404 x ^= (unsigned) now(CLOCK_REALTIME);
2405 x ^= (unsigned) gettid();
2408 srand_called = true;
2411 for (q = p; q < (uint8_t*) p + n; q ++)
2415 void rename_process(const char name[8]) {
2418 /* This is a like a poor man's setproctitle(). It changes the
2419 * comm field, argv[0], and also the glibc's internally used
2420 * name of the process. For the first one a limit of 16 chars
2421 * applies, to the second one usually one of 10 (i.e. length
2422 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2423 * "systemd"). If you pass a longer string it will be
2426 prctl(PR_SET_NAME, name);
2428 if (program_invocation_name)
2429 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2431 if (saved_argc > 0) {
2435 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2437 for (i = 1; i < saved_argc; i++) {
2441 memzero(saved_argv[i], strlen(saved_argv[i]));
2446 void sigset_add_many(sigset_t *ss, ...) {
2453 while ((sig = va_arg(ap, int)) > 0)
2454 assert_se(sigaddset(ss, sig) == 0);
2458 int sigprocmask_many(int how, ...) {
2463 assert_se(sigemptyset(&ss) == 0);
2466 while ((sig = va_arg(ap, int)) > 0)
2467 assert_se(sigaddset(&ss, sig) == 0);
2470 if (sigprocmask(how, &ss, NULL) < 0)
2476 char* gethostname_malloc(void) {
2479 assert_se(uname(&u) >= 0);
2481 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2482 return strdup(u.nodename);
2484 return strdup(u.sysname);
2487 bool hostname_is_set(void) {
2490 assert_se(uname(&u) >= 0);
2492 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2495 static char *lookup_uid(uid_t uid) {
2498 _cleanup_free_ char *buf = NULL;
2499 struct passwd pwbuf, *pw = NULL;
2501 /* Shortcut things to avoid NSS lookups */
2503 return strdup("root");
2505 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2509 buf = malloc(bufsize);
2513 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2514 return strdup(pw->pw_name);
2516 if (asprintf(&name, UID_FMT, uid) < 0)
2522 char* getlogname_malloc(void) {
2526 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2531 return lookup_uid(uid);
2534 char *getusername_malloc(void) {
2541 return lookup_uid(getuid());
2544 int getttyname_malloc(int fd, char **r) {
2545 char path[PATH_MAX], *c;
2550 k = ttyname_r(fd, path, sizeof(path));
2556 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2564 int getttyname_harder(int fd, char **r) {
2568 k = getttyname_malloc(fd, &s);
2572 if (streq(s, "tty")) {
2574 return get_ctty(0, NULL, r);
2581 int get_ctty_devnr(pid_t pid, dev_t *d) {
2583 _cleanup_free_ char *line = NULL;
2585 unsigned long ttynr;
2589 p = procfs_file_alloca(pid, "stat");
2590 r = read_one_line_file(p, &line);
2594 p = strrchr(line, ')');
2604 "%*d " /* session */
2609 if (major(ttynr) == 0 && minor(ttynr) == 0)
2618 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2619 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2620 _cleanup_free_ char *s = NULL;
2627 k = get_ctty_devnr(pid, &devnr);
2631 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2633 k = readlink_malloc(fn, &s);
2639 /* This is an ugly hack */
2640 if (major(devnr) == 136) {
2641 asprintf(&b, "pts/%u", minor(devnr));
2645 /* Probably something like the ptys which have no
2646 * symlink in /dev/char. Let's return something
2647 * vaguely useful. */
2653 if (startswith(s, "/dev/"))
2655 else if (startswith(s, "../"))
2673 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2674 _cleanup_closedir_ DIR *d = NULL;
2679 /* This returns the first error we run into, but nevertheless
2680 * tries to go on. This closes the passed fd. */
2686 return errno == ENOENT ? 0 : -errno;
2691 bool is_dir, keep_around;
2698 if (errno != 0 && ret == 0)
2703 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2706 if (de->d_type == DT_UNKNOWN ||
2708 (de->d_type == DT_DIR && root_dev)) {
2709 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2710 if (ret == 0 && errno != ENOENT)
2715 is_dir = S_ISDIR(st.st_mode);
2718 (st.st_uid == 0 || st.st_uid == getuid()) &&
2719 (st.st_mode & S_ISVTX);
2721 is_dir = de->d_type == DT_DIR;
2722 keep_around = false;
2728 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2729 if (root_dev && st.st_dev != root_dev->st_dev)
2732 subdir_fd = openat(fd, de->d_name,
2733 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2734 if (subdir_fd < 0) {
2735 if (ret == 0 && errno != ENOENT)
2740 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2741 if (r < 0 && ret == 0)
2745 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2746 if (ret == 0 && errno != ENOENT)
2750 } else if (!only_dirs && !keep_around) {
2752 if (unlinkat(fd, de->d_name, 0) < 0) {
2753 if (ret == 0 && errno != ENOENT)
2760 _pure_ static int is_temporary_fs(struct statfs *s) {
2763 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2764 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2767 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2772 if (fstatfs(fd, &s) < 0) {
2777 /* We refuse to clean disk file systems with this call. This
2778 * is extra paranoia just to be sure we never ever remove
2780 if (!is_temporary_fs(&s)) {
2781 log_error("Attempted to remove disk file system, and we can't allow that.");
2786 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2789 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2795 /* We refuse to clean the root file system with this
2796 * call. This is extra paranoia to never cause a really
2797 * seriously broken system. */
2798 if (path_equal(path, "/")) {
2799 log_error("Attempted to remove entire root file system, and we can't allow that.");
2803 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2806 if (errno != ENOTDIR)
2810 if (statfs(path, &s) < 0)
2813 if (!is_temporary_fs(&s)) {
2814 log_error("Attempted to remove disk file system, and we can't allow that.");
2819 if (delete_root && !only_dirs)
2820 if (unlink(path) < 0 && errno != ENOENT)
2827 if (fstatfs(fd, &s) < 0) {
2832 if (!is_temporary_fs(&s)) {
2833 log_error("Attempted to remove disk file system, and we can't allow that.");
2839 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2842 if (honour_sticky && file_is_priv_sticky(path) > 0)
2845 if (rmdir(path) < 0 && errno != ENOENT) {
2854 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2855 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2858 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2859 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2862 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2865 /* Under the assumption that we are running privileged we
2866 * first change the access mode and only then hand out
2867 * ownership to avoid a window where access is too open. */
2869 if (mode != (mode_t) -1)
2870 if (chmod(path, mode) < 0)
2873 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2874 if (chown(path, uid, gid) < 0)
2880 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2883 /* Under the assumption that we are running privileged we
2884 * first change the access mode and only then hand out
2885 * ownership to avoid a window where access is too open. */
2887 if (mode != (mode_t) -1)
2888 if (fchmod(fd, mode) < 0)
2891 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2892 if (fchown(fd, uid, gid) < 0)
2898 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2902 /* Allocates the cpuset in the right size */
2905 if (!(r = CPU_ALLOC(n)))
2908 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2909 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2919 if (errno != EINVAL)
2926 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2927 static const char status_indent[] = " "; /* "[" STATUS "] " */
2928 _cleanup_free_ char *s = NULL;
2929 _cleanup_close_ int fd = -1;
2930 struct iovec iovec[6] = {};
2932 static bool prev_ephemeral;
2936 /* This is independent of logging, as status messages are
2937 * optional and go exclusively to the console. */
2939 if (vasprintf(&s, format, ap) < 0)
2942 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2955 sl = status ? sizeof(status_indent)-1 : 0;
2961 e = ellipsize(s, emax, 75);
2969 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2970 prev_ephemeral = ephemeral;
2973 if (!isempty(status)) {
2974 IOVEC_SET_STRING(iovec[n++], "[");
2975 IOVEC_SET_STRING(iovec[n++], status);
2976 IOVEC_SET_STRING(iovec[n++], "] ");
2978 IOVEC_SET_STRING(iovec[n++], status_indent);
2981 IOVEC_SET_STRING(iovec[n++], s);
2983 IOVEC_SET_STRING(iovec[n++], "\n");
2985 if (writev(fd, iovec, n) < 0)
2991 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2997 va_start(ap, format);
2998 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3004 char *replace_env(const char *format, char **env) {
3011 const char *e, *word = format;
3016 for (e = format; *e; e ++) {
3027 if (!(k = strnappend(r, word, e-word-1)))
3036 } else if (*e == '$') {
3037 if (!(k = strnappend(r, word, e-word)))
3053 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3055 k = strappend(r, t);
3069 if (!(k = strnappend(r, word, e-word)))
3080 char **replace_env_argv(char **argv, char **env) {
3082 unsigned k = 0, l = 0;
3084 l = strv_length(argv);
3086 if (!(r = new(char*, l+1)))
3089 STRV_FOREACH(i, argv) {
3091 /* If $FOO appears as single word, replace it by the split up variable */
3092 if ((*i)[0] == '$' && (*i)[1] != '{') {
3097 e = strv_env_get(env, *i+1);
3100 if (!(m = strv_split_quoted(e))) {
3111 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3120 memcpy(r + k, m, q * sizeof(char*));
3128 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3129 if (!(r[k++] = replace_env(*i, env))) {
3139 int fd_columns(int fd) {
3140 struct winsize ws = {};
3142 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3151 unsigned columns(void) {
3155 if (_likely_(cached_columns > 0))
3156 return cached_columns;
3159 e = getenv("COLUMNS");
3164 c = fd_columns(STDOUT_FILENO);
3173 int fd_lines(int fd) {
3174 struct winsize ws = {};
3176 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3185 unsigned lines(void) {
3189 if (_likely_(cached_lines > 0))
3190 return cached_lines;
3193 e = getenv("LINES");
3198 l = fd_lines(STDOUT_FILENO);
3204 return cached_lines;
3207 /* intended to be used as a SIGWINCH sighandler */
3208 void columns_lines_cache_reset(int signum) {
3214 static int cached_on_tty = -1;
3216 if (_unlikely_(cached_on_tty < 0))
3217 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3219 return cached_on_tty;
3222 int files_same(const char *filea, const char *fileb) {
3225 if (stat(filea, &a) < 0)
3228 if (stat(fileb, &b) < 0)
3231 return a.st_dev == b.st_dev &&
3232 a.st_ino == b.st_ino;
3235 int running_in_chroot(void) {
3238 ret = files_same("/proc/1/root", "/");
3245 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3250 assert(percent <= 100);
3251 assert(new_length >= 3);
3253 if (old_length <= 3 || old_length <= new_length)
3254 return strndup(s, old_length);
3256 r = new0(char, new_length+1);
3260 x = (new_length * percent) / 100;
3262 if (x > new_length - 3)
3270 s + old_length - (new_length - x - 3),
3271 new_length - x - 3);
3276 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3280 unsigned k, len, len2;
3283 assert(percent <= 100);
3284 assert(new_length >= 3);
3286 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3287 if (ascii_is_valid(s))
3288 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3290 if (old_length <= 3 || old_length <= new_length)
3291 return strndup(s, old_length);
3293 x = (new_length * percent) / 100;
3295 if (x > new_length - 3)
3299 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3302 c = utf8_encoded_to_unichar(i);
3305 k += unichar_iswide(c) ? 2 : 1;
3308 if (k > x) /* last character was wide and went over quota */
3311 for (j = s + old_length; k < new_length && j > i; ) {
3314 j = utf8_prev_char(j);
3315 c = utf8_encoded_to_unichar(j);
3318 k += unichar_iswide(c) ? 2 : 1;
3322 /* we don't actually need to ellipsize */
3324 return memdup(s, old_length + 1);
3326 /* make space for ellipsis */
3327 j = utf8_next_char(j);
3330 len2 = s + old_length - j;
3331 e = new(char, len + 3 + len2 + 1);
3336 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3337 old_length, new_length, x, len, len2, k);
3341 e[len] = 0xe2; /* tri-dot ellipsis: … */
3345 memcpy(e + len + 3, j, len2 + 1);
3350 char *ellipsize(const char *s, size_t length, unsigned percent) {
3351 return ellipsize_mem(s, strlen(s), length, percent);
3354 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3355 _cleanup_close_ int fd;
3361 mkdir_parents(path, 0755);
3363 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3368 r = fchmod(fd, mode);
3373 if (uid != (uid_t) -1 || gid != (gid_t) -1) {
3374 r = fchown(fd, uid, gid);
3379 if (stamp != (usec_t) -1) {
3380 struct timespec ts[2];
3382 timespec_store(&ts[0], stamp);
3384 r = futimens(fd, ts);
3386 r = futimens(fd, NULL);
3393 int touch(const char *path) {
3394 return touch_file(path, false, (usec_t) -1, (uid_t) -1, (gid_t) -1, 0);
3397 char *unquote(const char *s, const char* quotes) {