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"
78 char **saved_argv = NULL;
80 static volatile unsigned cached_columns = 0;
81 static volatile unsigned cached_lines = 0;
83 #define PROCFS_PATH_LEN (sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t))
85 #define FORMAT_PROCFS_PATH(buffer, path, pid) \
87 assert_cc(sizeof(buffer) == (PROCFS_PATH_LEN + 1 + sizeof(path))); \
88 snprintf(buffer, sizeof(buffer) - 1, "/proc/%lu/%s", (unsigned long) pid, path); \
89 char_array_0(buffer); \
93 size_t page_size(void) {
94 static __thread size_t pgsz = 0;
97 if (_likely_(pgsz > 0))
100 r = sysconf(_SC_PAGESIZE);
107 bool streq_ptr(const char *a, const char *b) {
109 /* Like streq(), but tries to make sense of NULL pointers */
120 char* endswith(const char *s, const char *postfix) {
127 pl = strlen(postfix);
130 return (char*) s + sl;
135 if (memcmp(s + sl - pl, postfix, pl) != 0)
138 return (char*) s + sl - pl;
141 char* startswith(const char *s, const char *prefix) {
158 char* startswith_no_case(const char *s, const char *prefix) {
168 if (tolower(*a) != tolower(*b))
175 bool first_word(const char *s, const char *word) {
190 if (memcmp(s, word, wl) != 0)
194 strchr(WHITESPACE, s[wl]);
197 int close_nointr(int fd) {
203 /* Just ignore EINTR; a retry loop is the wrong
204 * thing to do on Linux.
206 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
207 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
208 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
209 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
211 if (_unlikely_(r < 0 && errno == EINTR))
219 void close_nointr_nofail(int fd) {
222 /* like close_nointr() but cannot fail, and guarantees errno
225 assert_se(close_nointr(fd) == 0);
228 void close_many(const int fds[], unsigned n_fd) {
231 assert(fds || n_fd <= 0);
233 for (i = 0; i < n_fd; i++)
234 close_nointr_nofail(fds[i]);
237 int unlink_noerrno(const char *path) {
248 int parse_boolean(const char *v) {
251 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
253 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
259 int parse_pid(const char *s, pid_t* ret_pid) {
260 unsigned long ul = 0;
267 r = safe_atolu(s, &ul);
273 if ((unsigned long) pid != ul)
283 int parse_uid(const char *s, uid_t* ret_uid) {
284 unsigned long ul = 0;
291 r = safe_atolu(s, &ul);
297 if ((unsigned long) uid != ul)
304 int safe_atou(const char *s, unsigned *ret_u) {
312 l = strtoul(s, &x, 0);
314 if (!x || x == s || *x || errno)
315 return errno > 0 ? -errno : -EINVAL;
317 if ((unsigned long) (unsigned) l != l)
320 *ret_u = (unsigned) l;
324 int safe_atoi(const char *s, int *ret_i) {
332 l = strtol(s, &x, 0);
334 if (!x || x == s || *x || errno)
335 return errno > 0 ? -errno : -EINVAL;
337 if ((long) (int) l != l)
344 int safe_atollu(const char *s, long long unsigned *ret_llu) {
346 unsigned long long l;
352 l = strtoull(s, &x, 0);
354 if (!x || x == s || *x || errno)
355 return errno ? -errno : -EINVAL;
361 int safe_atolli(const char *s, long long int *ret_lli) {
369 l = strtoll(s, &x, 0);
371 if (!x || x == s || *x || errno)
372 return errno ? -errno : -EINVAL;
378 int safe_atod(const char *s, double *ret_d) {
388 if (!x || x == s || *x || errno)
389 return errno ? -errno : -EINVAL;
395 /* Split a string into words. */
396 char *split(const char *c, size_t *l, const char *separator, char **state) {
399 current = *state ? *state : (char*) c;
401 if (!*current || *c == 0)
404 current += strspn(current, separator);
405 *l = strcspn(current, separator);
408 return (char*) current;
411 /* Split a string into words, but consider strings enclosed in '' and
412 * "" as words even if they include spaces. */
413 char *split_quoted(const char *c, size_t *l, char **state) {
415 bool escaped = false;
417 current = *state ? *state : (char*) c;
419 if (!*current || *c == 0)
422 current += strspn(current, WHITESPACE);
424 if (*current == '\'') {
427 for (e = current; *e; e++) {
437 *state = *e == 0 ? e : e+1;
438 } else if (*current == '\"') {
441 for (e = current; *e; e++) {
451 *state = *e == 0 ? e : e+1;
453 for (e = current; *e; e++) {
458 else if (strchr(WHITESPACE, *e))
465 return (char*) current;
468 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
470 _cleanup_fclose_ FILE *f = NULL;
471 char fn[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/stat")], line[LINE_MAX], *p;
477 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
483 if (!fgets(line, sizeof(line), f)) {
484 r = feof(f) ? -EIO : -errno;
488 /* Let's skip the pid and comm fields. The latter is enclosed
489 * in () but does not escape any () in its value, so let's
490 * skip over it manually */
492 p = strrchr(line, ')');
504 if ((long unsigned) (pid_t) ppid != ppid)
507 *_ppid = (pid_t) ppid;
512 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
513 _cleanup_fclose_ FILE *f = NULL;
514 char fn[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/stat")], line[LINE_MAX], *p;
519 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
525 if (!fgets(line, sizeof(line), f)) {
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_comm(pid_t pid, char **name) {
593 r = read_one_line_file("/proc/self/comm", name);
595 char path[PROCFS_PATH_LEN + sizeof("/comm")];
596 FORMAT_PROCFS_PATH(path, "comm", pid);
597 r = read_one_line_file(path, name);
603 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
611 f = fopen("/proc/self/cmdline", "re");
613 char path[PROCFS_PATH_LEN + sizeof("/cmdline")];
614 FORMAT_PROCFS_PATH(path, "cmdline", pid);
615 f = fopen(path, "re");
620 if (max_length == 0) {
622 while ((c = getc(f)) != EOF) {
623 k = realloc(r, len+1);
630 r[len-1] = isprint(c) ? c : ' ';
637 r = new(char, max_length);
645 while ((c = getc(f)) != EOF) {
667 size_t n = MIN(left-1, 3U);
676 /* Kernel threads have no argv[] */
677 if (r == NULL || r[0] == 0) {
686 h = get_process_comm(pid, &t);
690 r = strjoin("[", t, "]", NULL);
701 int is_kernel_thread(pid_t pid) {
702 char path[PROCFS_PATH_LEN + sizeof("/cmdline")];
711 FORMAT_PROCFS_PATH(path, "cmdline", pid);
712 f = fopen(path, "re");
717 count = fread(&c, 1, 1, f);
721 /* Kernel threads have an empty cmdline */
724 return eof ? 1 : -errno;
729 int get_process_exe(pid_t pid, char **name) {
735 r = readlink_malloc("/proc/self/exe", name);
737 char path[PROCFS_PATH_LEN + sizeof("/exe")];
738 FORMAT_PROCFS_PATH(path, "exe", pid);
739 r = readlink_malloc(path, name);
745 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
746 _cleanup_fclose_ FILE *f = NULL;
747 char path[PROCFS_PATH_LEN + sizeof("/status")];
756 FORMAT_PROCFS_PATH(path, "status", pid);
757 f = fopen(path, "re");
761 FOREACH_LINE(line, f, return -errno) {
766 if (startswith(l, field)) {
768 l += strspn(l, WHITESPACE);
770 l[strcspn(l, WHITESPACE)] = 0;
772 return parse_uid(l, uid);
779 int get_process_uid(pid_t pid, uid_t *uid) {
780 return get_process_id(pid, "Uid:", uid);
783 int get_process_gid(pid_t pid, gid_t *gid) {
784 return get_process_id(pid, "Gid:", gid);
787 char *strnappend(const char *s, const char *suffix, size_t b) {
795 return strndup(suffix, b);
804 if (b > ((size_t) -1) - a)
807 r = new(char, a+b+1);
812 memcpy(r+a, suffix, b);
818 char *strappend(const char *s, const char *suffix) {
819 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
822 int readlink_malloc(const char *p, char **r) {
832 if (!(c = new(char, l)))
835 if ((n = readlink(p, c, l-1)) < 0) {
841 if ((size_t) n < l-1) {
852 int readlink_and_make_absolute(const char *p, char **r) {
859 if ((j = readlink_malloc(p, &target)) < 0)
862 k = file_in_same_dir(p, target);
872 int readlink_and_canonicalize(const char *p, char **r) {
879 j = readlink_and_make_absolute(p, &t);
883 s = canonicalize_file_name(t);
890 path_kill_slashes(*r);
895 int reset_all_signal_handlers(void) {
898 for (sig = 1; sig < _NSIG; sig++) {
899 struct sigaction sa = {
900 .sa_handler = SIG_DFL,
901 .sa_flags = SA_RESTART,
904 if (sig == SIGKILL || sig == SIGSTOP)
907 /* On Linux the first two RT signals are reserved by
908 * glibc, and sigaction() will return EINVAL for them. */
909 if ((sigaction(sig, &sa, NULL) < 0))
917 char *strstrip(char *s) {
920 /* Drops trailing whitespace. Modifies the string in
921 * place. Returns pointer to first non-space character */
923 s += strspn(s, WHITESPACE);
925 for (e = strchr(s, 0); e > s; e --)
926 if (!strchr(WHITESPACE, e[-1]))
934 char *delete_chars(char *s, const char *bad) {
937 /* Drops all whitespace, regardless where in the string */
939 for (f = s, t = s; *f; f++) {
951 bool in_charset(const char *s, const char* charset) {
958 if (!strchr(charset, *i))
964 char *file_in_same_dir(const char *path, const char *filename) {
971 /* This removes the last component of path and appends
972 * filename, unless the latter is absolute anyway or the
975 if (path_is_absolute(filename))
976 return strdup(filename);
978 if (!(e = strrchr(path, '/')))
979 return strdup(filename);
981 k = strlen(filename);
982 if (!(r = new(char, e-path+1+k+1)))
985 memcpy(r, path, e-path+1);
986 memcpy(r+(e-path)+1, filename, k+1);
991 int rmdir_parents(const char *path, const char *stop) {
1000 /* Skip trailing slashes */
1001 while (l > 0 && path[l-1] == '/')
1007 /* Skip last component */
1008 while (l > 0 && path[l-1] != '/')
1011 /* Skip trailing slashes */
1012 while (l > 0 && path[l-1] == '/')
1018 if (!(t = strndup(path, l)))
1021 if (path_startswith(stop, t)) {
1030 if (errno != ENOENT)
1037 char hexchar(int x) {
1038 static const char table[16] = "0123456789abcdef";
1040 return table[x & 15];
1043 int unhexchar(char c) {
1045 if (c >= '0' && c <= '9')
1048 if (c >= 'a' && c <= 'f')
1049 return c - 'a' + 10;
1051 if (c >= 'A' && c <= 'F')
1052 return c - 'A' + 10;
1057 char *hexmem(const void *p, size_t l) {
1061 z = r = malloc(l * 2 + 1);
1065 for (x = p; x < (const uint8_t*) p + l; x++) {
1066 *(z++) = hexchar(*x >> 4);
1067 *(z++) = hexchar(*x & 15);
1074 void *unhexmem(const char *p, size_t l) {
1080 z = r = malloc((l + 1) / 2 + 1);
1084 for (x = p; x < p + l; x += 2) {
1087 a = unhexchar(x[0]);
1089 b = unhexchar(x[1]);
1093 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1100 char octchar(int x) {
1101 return '0' + (x & 7);
1104 int unoctchar(char c) {
1106 if (c >= '0' && c <= '7')
1112 char decchar(int x) {
1113 return '0' + (x % 10);
1116 int undecchar(char c) {
1118 if (c >= '0' && c <= '9')
1124 char *cescape(const char *s) {
1130 /* Does C style string escaping. */
1132 r = new(char, strlen(s)*4 + 1);
1136 for (f = s, t = r; *f; f++)
1182 /* For special chars we prefer octal over
1183 * hexadecimal encoding, simply because glib's
1184 * g_strescape() does the same */
1185 if ((*f < ' ') || (*f >= 127)) {
1187 *(t++) = octchar((unsigned char) *f >> 6);
1188 *(t++) = octchar((unsigned char) *f >> 3);
1189 *(t++) = octchar((unsigned char) *f);
1200 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1207 /* Undoes C style string escaping, and optionally prefixes it. */
1209 pl = prefix ? strlen(prefix) : 0;
1211 r = new(char, pl+length+1);
1216 memcpy(r, prefix, pl);
1218 for (f = s, t = r + pl; f < s + length; f++) {
1261 /* This is an extension of the XDG syntax files */
1266 /* hexadecimal encoding */
1269 a = unhexchar(f[1]);
1270 b = unhexchar(f[2]);
1272 if (a < 0 || b < 0) {
1273 /* Invalid escape code, let's take it literal then */
1277 *(t++) = (char) ((a << 4) | b);
1292 /* octal encoding */
1295 a = unoctchar(f[0]);
1296 b = unoctchar(f[1]);
1297 c = unoctchar(f[2]);
1299 if (a < 0 || b < 0 || c < 0) {
1300 /* Invalid escape code, let's take it literal then */
1304 *(t++) = (char) ((a << 6) | (b << 3) | c);
1312 /* premature end of string.*/
1317 /* Invalid escape code, let's take it literal then */
1329 char *cunescape_length(const char *s, size_t length) {
1330 return cunescape_length_with_prefix(s, length, NULL);
1333 char *cunescape(const char *s) {
1336 return cunescape_length(s, strlen(s));
1339 char *xescape(const char *s, const char *bad) {
1343 /* Escapes all chars in bad, in addition to \ and all special
1344 * chars, in \xFF style escaping. May be reversed with
1347 r = new(char, strlen(s) * 4 + 1);
1351 for (f = s, t = r; *f; f++) {
1353 if ((*f < ' ') || (*f >= 127) ||
1354 (*f == '\\') || strchr(bad, *f)) {
1357 *(t++) = hexchar(*f >> 4);
1358 *(t++) = hexchar(*f);
1368 char *bus_path_escape(const char *s) {
1374 /* Escapes all chars that D-Bus' object path cannot deal
1375 * with. Can be reverse with bus_path_unescape(). We special
1376 * case the empty string. */
1381 r = new(char, strlen(s)*3 + 1);
1385 for (f = s, t = r; *f; f++) {
1387 /* Escape everything that is not a-zA-Z0-9. We also
1388 * escape 0-9 if it's the first character */
1390 if (!(*f >= 'A' && *f <= 'Z') &&
1391 !(*f >= 'a' && *f <= 'z') &&
1392 !(f > s && *f >= '0' && *f <= '9')) {
1394 *(t++) = hexchar(*f >> 4);
1395 *(t++) = hexchar(*f);
1405 char *bus_path_unescape(const char *f) {
1410 /* Special case for the empty string */
1414 r = new(char, strlen(f) + 1);
1418 for (t = r; *f; f++) {
1423 if ((a = unhexchar(f[1])) < 0 ||
1424 (b = unhexchar(f[2])) < 0) {
1425 /* Invalid escape code, let's take it literal then */
1428 *(t++) = (char) ((a << 4) | b);
1440 char *ascii_strlower(char *t) {
1445 for (p = t; *p; p++)
1446 if (*p >= 'A' && *p <= 'Z')
1447 *p = *p - 'A' + 'a';
1452 static bool ignore_file_allow_backup(const char *filename) {
1456 filename[0] == '.' ||
1457 streq(filename, "lost+found") ||
1458 streq(filename, "aquota.user") ||
1459 streq(filename, "aquota.group") ||
1460 endswith(filename, ".rpmnew") ||
1461 endswith(filename, ".rpmsave") ||
1462 endswith(filename, ".rpmorig") ||
1463 endswith(filename, ".dpkg-old") ||
1464 endswith(filename, ".dpkg-new") ||
1465 endswith(filename, ".swp");
1468 bool ignore_file(const char *filename) {
1471 if (endswith(filename, "~"))
1474 return ignore_file_allow_backup(filename);
1477 int fd_nonblock(int fd, bool nonblock) {
1482 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1486 flags |= O_NONBLOCK;
1488 flags &= ~O_NONBLOCK;
1490 if (fcntl(fd, F_SETFL, flags) < 0)
1496 int fd_cloexec(int fd, bool cloexec) {
1501 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1505 flags |= FD_CLOEXEC;
1507 flags &= ~FD_CLOEXEC;
1509 if (fcntl(fd, F_SETFD, flags) < 0)
1515 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1518 assert(n_fdset == 0 || fdset);
1520 for (i = 0; i < n_fdset; i++)
1527 int close_all_fds(const int except[], unsigned n_except) {
1532 assert(n_except == 0 || except);
1534 d = opendir("/proc/self/fd");
1539 /* When /proc isn't available (for example in chroots)
1540 * the fallback is brute forcing through the fd
1543 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1544 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1546 if (fd_in_set(fd, except, n_except))
1549 if (close_nointr(fd) < 0)
1550 if (errno != EBADF && r == 0)
1557 while ((de = readdir(d))) {
1560 if (ignore_file(de->d_name))
1563 if (safe_atoi(de->d_name, &fd) < 0)
1564 /* Let's better ignore this, just in case */
1573 if (fd_in_set(fd, except, n_except))
1576 if (close_nointr(fd) < 0) {
1577 /* Valgrind has its own FD and doesn't want to have it closed */
1578 if (errno != EBADF && r == 0)
1587 bool chars_intersect(const char *a, const char *b) {
1590 /* Returns true if any of the chars in a are in b. */
1591 for (p = a; *p; p++)
1598 bool fstype_is_network(const char *fstype) {
1599 static const char table[] =
1608 return nulstr_contains(table, fstype);
1612 _cleanup_close_ int fd;
1614 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1620 TIOCL_GETKMSGREDIRECT,
1624 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1627 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1630 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1636 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1637 struct termios old_termios, new_termios;
1639 char line[LINE_MAX];
1644 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1645 new_termios = old_termios;
1647 new_termios.c_lflag &= ~ICANON;
1648 new_termios.c_cc[VMIN] = 1;
1649 new_termios.c_cc[VTIME] = 0;
1651 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1654 if (t != (usec_t) -1) {
1655 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1656 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1661 k = fread(&c, 1, 1, f);
1663 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1669 *need_nl = c != '\n';
1676 if (t != (usec_t) -1)
1677 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1680 if (!fgets(line, sizeof(line), f))
1685 if (strlen(line) != 1)
1695 int ask(char *ret, const char *replies, const char *text, ...) {
1705 bool need_nl = true;
1708 fputs(ANSI_HIGHLIGHT_ON, stdout);
1715 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1719 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1722 if (r == -EBADMSG) {
1723 puts("Bad input, please try again.");
1734 if (strchr(replies, c)) {
1739 puts("Read unexpected character, please try again.");
1743 int reset_terminal_fd(int fd, bool switch_to_text) {
1744 struct termios termios;
1747 /* Set terminal to some sane defaults */
1751 /* We leave locked terminal attributes untouched, so that
1752 * Plymouth may set whatever it wants to set, and we don't
1753 * interfere with that. */
1755 /* Disable exclusive mode, just in case */
1756 ioctl(fd, TIOCNXCL);
1758 /* Switch to text mode */
1760 ioctl(fd, KDSETMODE, KD_TEXT);
1762 /* Enable console unicode mode */
1763 ioctl(fd, KDSKBMODE, K_UNICODE);
1765 if (tcgetattr(fd, &termios) < 0) {
1770 /* We only reset the stuff that matters to the software. How
1771 * hardware is set up we don't touch assuming that somebody
1772 * else will do that for us */
1774 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1775 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1776 termios.c_oflag |= ONLCR;
1777 termios.c_cflag |= CREAD;
1778 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1780 termios.c_cc[VINTR] = 03; /* ^C */
1781 termios.c_cc[VQUIT] = 034; /* ^\ */
1782 termios.c_cc[VERASE] = 0177;
1783 termios.c_cc[VKILL] = 025; /* ^X */
1784 termios.c_cc[VEOF] = 04; /* ^D */
1785 termios.c_cc[VSTART] = 021; /* ^Q */
1786 termios.c_cc[VSTOP] = 023; /* ^S */
1787 termios.c_cc[VSUSP] = 032; /* ^Z */
1788 termios.c_cc[VLNEXT] = 026; /* ^V */
1789 termios.c_cc[VWERASE] = 027; /* ^W */
1790 termios.c_cc[VREPRINT] = 022; /* ^R */
1791 termios.c_cc[VEOL] = 0;
1792 termios.c_cc[VEOL2] = 0;
1794 termios.c_cc[VTIME] = 0;
1795 termios.c_cc[VMIN] = 1;
1797 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1801 /* Just in case, flush all crap out */
1802 tcflush(fd, TCIOFLUSH);
1807 int reset_terminal(const char *name) {
1810 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1814 r = reset_terminal_fd(fd, true);
1815 close_nointr_nofail(fd);
1820 int open_terminal(const char *name, int mode) {
1825 * If a TTY is in the process of being closed opening it might
1826 * cause EIO. This is horribly awful, but unlikely to be
1827 * changed in the kernel. Hence we work around this problem by
1828 * retrying a couple of times.
1830 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1834 fd = open(name, mode);
1841 /* Max 1s in total */
1845 usleep(50 * USEC_PER_MSEC);
1854 close_nointr_nofail(fd);
1859 close_nointr_nofail(fd);
1866 int flush_fd(int fd) {
1867 struct pollfd pollfd = {
1877 r = poll(&pollfd, 1, 0);
1887 l = read(fd, buf, sizeof(buf));
1893 if (errno == EAGAIN)
1902 int acquire_terminal(
1906 bool ignore_tiocstty_eperm,
1909 int fd = -1, notify = -1, r = 0, wd = -1;
1914 /* We use inotify to be notified when the tty is closed. We
1915 * create the watch before checking if we can actually acquire
1916 * it, so that we don't lose any event.
1918 * Note: strictly speaking this actually watches for the
1919 * device being closed, it does *not* really watch whether a
1920 * tty loses its controlling process. However, unless some
1921 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1922 * its tty otherwise this will not become a problem. As long
1923 * as the administrator makes sure not configure any service
1924 * on the same tty as an untrusted user this should not be a
1925 * problem. (Which he probably should not do anyway.) */
1927 if (timeout != (usec_t) -1)
1928 ts = now(CLOCK_MONOTONIC);
1930 if (!fail && !force) {
1931 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1937 wd = inotify_add_watch(notify, name, IN_CLOSE);
1945 struct sigaction sa_old, sa_new = {
1946 .sa_handler = SIG_IGN,
1947 .sa_flags = SA_RESTART,
1951 r = flush_fd(notify);
1956 /* We pass here O_NOCTTY only so that we can check the return
1957 * value TIOCSCTTY and have a reliable way to figure out if we
1958 * successfully became the controlling process of the tty */
1959 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1963 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1964 * if we already own the tty. */
1965 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1967 /* First, try to get the tty */
1968 if (ioctl(fd, TIOCSCTTY, force) < 0)
1971 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1973 /* Sometimes it makes sense to ignore TIOCSCTTY
1974 * returning EPERM, i.e. when very likely we already
1975 * are have this controlling terminal. */
1976 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1979 if (r < 0 && (force || fail || r != -EPERM)) {
1988 assert(notify >= 0);
1991 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1993 struct inotify_event *e;
1995 if (timeout != (usec_t) -1) {
1998 n = now(CLOCK_MONOTONIC);
1999 if (ts + timeout < n) {
2004 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2014 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2017 if (errno == EINTR || errno == EAGAIN)
2024 e = (struct inotify_event*) inotify_buffer;
2029 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2034 step = sizeof(struct inotify_event) + e->len;
2035 assert(step <= (size_t) l);
2037 e = (struct inotify_event*) ((uint8_t*) e + step);
2044 /* We close the tty fd here since if the old session
2045 * ended our handle will be dead. It's important that
2046 * we do this after sleeping, so that we don't enter
2047 * an endless loop. */
2048 close_nointr_nofail(fd);
2052 close_nointr_nofail(notify);
2054 r = reset_terminal_fd(fd, true);
2056 log_warning("Failed to reset terminal: %s", strerror(-r));
2062 close_nointr_nofail(fd);
2065 close_nointr_nofail(notify);
2070 int release_terminal(void) {
2072 struct sigaction sa_old, sa_new = {
2073 .sa_handler = SIG_IGN,
2074 .sa_flags = SA_RESTART,
2076 int _cleanup_close_ fd;
2078 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2082 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2083 * by our own TIOCNOTTY */
2084 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2086 if (ioctl(fd, TIOCNOTTY) < 0)
2089 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2094 int sigaction_many(const struct sigaction *sa, ...) {
2099 while ((sig = va_arg(ap, int)) > 0)
2100 if (sigaction(sig, sa, NULL) < 0)
2107 int ignore_signals(int sig, ...) {
2108 struct sigaction sa = {
2109 .sa_handler = SIG_IGN,
2110 .sa_flags = SA_RESTART,
2116 if (sigaction(sig, &sa, NULL) < 0)
2120 while ((sig = va_arg(ap, int)) > 0)
2121 if (sigaction(sig, &sa, NULL) < 0)
2128 int default_signals(int sig, ...) {
2129 struct sigaction sa = {
2130 .sa_handler = SIG_DFL,
2131 .sa_flags = SA_RESTART,
2136 if (sigaction(sig, &sa, NULL) < 0)
2140 while ((sig = va_arg(ap, int)) > 0)
2141 if (sigaction(sig, &sa, NULL) < 0)
2148 int close_pipe(int p[]) {
2154 a = close_nointr(p[0]);
2159 b = close_nointr(p[1]);
2163 return a < 0 ? a : b;
2166 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2175 while (nbytes > 0) {
2178 if ((k = read(fd, p, nbytes)) <= 0) {
2180 if (k < 0 && errno == EINTR)
2183 if (k < 0 && errno == EAGAIN && do_poll) {
2184 struct pollfd pollfd = {
2189 if (poll(&pollfd, 1, -1) < 0) {
2193 return n > 0 ? n : -errno;
2196 if (pollfd.revents != POLLIN)
2197 return n > 0 ? n : -EIO;
2202 return n > 0 ? n : (k < 0 ? -errno : 0);
2213 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2222 while (nbytes > 0) {
2225 k = write(fd, p, nbytes);
2228 if (k < 0 && errno == EINTR)
2231 if (k < 0 && errno == EAGAIN && do_poll) {
2232 struct pollfd pollfd = {
2237 if (poll(&pollfd, 1, -1) < 0) {
2241 return n > 0 ? n : -errno;
2244 if (pollfd.revents != POLLOUT)
2245 return n > 0 ? n : -EIO;
2250 return n > 0 ? n : (k < 0 ? -errno : 0);
2261 int parse_bytes(const char *t, off_t *bytes) {
2262 static const struct {
2268 { "M", 1024ULL*1024ULL },
2269 { "G", 1024ULL*1024ULL*1024ULL },
2270 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2271 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2272 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2289 l = strtoll(p, &e, 10);
2300 e += strspn(e, WHITESPACE);
2302 for (i = 0; i < ELEMENTSOF(table); i++)
2303 if (startswith(e, table[i].suffix)) {
2304 r += (off_t) l * table[i].factor;
2305 p = e + strlen(table[i].suffix);
2309 if (i >= ELEMENTSOF(table))
2319 int make_stdio(int fd) {
2324 r = dup3(fd, STDIN_FILENO, 0);
2325 s = dup3(fd, STDOUT_FILENO, 0);
2326 t = dup3(fd, STDERR_FILENO, 0);
2329 close_nointr_nofail(fd);
2331 if (r < 0 || s < 0 || t < 0)
2334 /* We rely here that the new fd has O_CLOEXEC not set */
2339 int make_null_stdio(void) {
2342 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2346 return make_stdio(null_fd);
2349 bool is_device_path(const char *path) {
2351 /* Returns true on paths that refer to a device, either in
2352 * sysfs or in /dev */
2355 path_startswith(path, "/dev/") ||
2356 path_startswith(path, "/sys/");
2359 int dir_is_empty(const char *path) {
2360 _cleanup_closedir_ DIR *d;
2369 union dirent_storage buf;
2371 r = readdir_r(d, &buf.de, &de);
2378 if (!ignore_file(de->d_name))
2383 char* dirname_malloc(const char *path) {
2384 char *d, *dir, *dir2;
2401 unsigned long long random_ull(void) {
2402 _cleanup_close_ int fd;
2406 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2410 r = loop_read(fd, &ull, sizeof(ull), true);
2411 if (r != sizeof(ull))
2417 return random() * RAND_MAX + random();
2420 void rename_process(const char name[8]) {
2423 /* This is a like a poor man's setproctitle(). It changes the
2424 * comm field, argv[0], and also the glibc's internally used
2425 * name of the process. For the first one a limit of 16 chars
2426 * applies, to the second one usually one of 10 (i.e. length
2427 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2428 * "systemd"). If you pass a longer string it will be
2431 prctl(PR_SET_NAME, name);
2433 if (program_invocation_name)
2434 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2436 if (saved_argc > 0) {
2440 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2442 for (i = 1; i < saved_argc; i++) {
2446 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2451 void sigset_add_many(sigset_t *ss, ...) {
2458 while ((sig = va_arg(ap, int)) > 0)
2459 assert_se(sigaddset(ss, sig) == 0);
2463 char* gethostname_malloc(void) {
2466 assert_se(uname(&u) >= 0);
2468 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2469 return strdup(u.nodename);
2471 return strdup(u.sysname);
2474 bool hostname_is_set(void) {
2477 assert_se(uname(&u) >= 0);
2479 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2482 static char *lookup_uid(uid_t uid) {
2485 _cleanup_free_ char *buf = NULL;
2486 struct passwd pwbuf, *pw = NULL;
2488 /* Shortcut things to avoid NSS lookups */
2490 return strdup("root");
2492 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2496 buf = malloc(bufsize);
2500 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2501 return strdup(pw->pw_name);
2503 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2509 char* getlogname_malloc(void) {
2513 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2518 return lookup_uid(uid);
2521 char *getusername_malloc(void) {
2528 return lookup_uid(getuid());
2531 int getttyname_malloc(int fd, char **r) {
2532 char path[PATH_MAX], *c;
2537 k = ttyname_r(fd, path, sizeof(path));
2543 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2551 int getttyname_harder(int fd, char **r) {
2555 k = getttyname_malloc(fd, &s);
2559 if (streq(s, "tty")) {
2561 return get_ctty(0, NULL, r);
2568 int get_ctty_devnr(pid_t pid, dev_t *d) {
2570 char line[LINE_MAX], *p, *fn;
2571 unsigned long ttynr;
2574 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2577 f = fopen(fn, "re");
2582 if (!fgets(line, sizeof(line), f)) {
2583 k = feof(f) ? -EIO : -errno;
2590 p = strrchr(line, ')');
2600 "%*d " /* session */
2605 if (major(ttynr) == 0 && minor(ttynr) == 0)
2612 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2614 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2619 k = get_ctty_devnr(pid, &devnr);
2623 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2625 k = readlink_malloc(fn, &s);
2631 /* This is an ugly hack */
2632 if (major(devnr) == 136) {
2633 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2643 /* Probably something like the ptys which have no
2644 * symlink in /dev/char. Let's return something
2645 * vaguely useful. */
2658 if (startswith(s, "/dev/"))
2660 else if (startswith(s, "../"))
2678 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2684 /* This returns the first error we run into, but nevertheless
2685 * tries to go on. This closes the passed fd. */
2689 close_nointr_nofail(fd);
2691 return errno == ENOENT ? 0 : -errno;
2696 union dirent_storage buf;
2697 bool is_dir, keep_around;
2701 r = readdir_r(d, &buf.de, &de);
2702 if (r != 0 && ret == 0) {
2710 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2713 if (de->d_type == DT_UNKNOWN ||
2715 (de->d_type == DT_DIR && root_dev)) {
2716 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2717 if (ret == 0 && errno != ENOENT)
2722 is_dir = S_ISDIR(st.st_mode);
2725 (st.st_uid == 0 || st.st_uid == getuid()) &&
2726 (st.st_mode & S_ISVTX);
2728 is_dir = de->d_type == DT_DIR;
2729 keep_around = false;
2735 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2736 if (root_dev && st.st_dev != root_dev->st_dev)
2739 subdir_fd = openat(fd, de->d_name,
2740 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2741 if (subdir_fd < 0) {
2742 if (ret == 0 && errno != ENOENT)
2747 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2748 if (r < 0 && ret == 0)
2752 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2753 if (ret == 0 && errno != ENOENT)
2757 } else if (!only_dirs && !keep_around) {
2759 if (unlinkat(fd, de->d_name, 0) < 0) {
2760 if (ret == 0 && errno != ENOENT)
2771 static int is_temporary_fs(struct statfs *s) {
2773 return s->f_type == TMPFS_MAGIC ||
2774 (long)s->f_type == (long)RAMFS_MAGIC;
2777 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2782 if (fstatfs(fd, &s) < 0) {
2783 close_nointr_nofail(fd);
2787 /* We refuse to clean disk file systems with this call. This
2788 * is extra paranoia just to be sure we never ever remove
2790 if (!is_temporary_fs(&s)) {
2791 log_error("Attempted to remove disk file system, and we can't allow that.");
2792 close_nointr_nofail(fd);
2796 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2799 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2805 /* We refuse to clean the root file system with this
2806 * call. This is extra paranoia to never cause a really
2807 * seriously broken system. */
2808 if (path_equal(path, "/")) {
2809 log_error("Attempted to remove entire root file system, and we can't allow that.");
2813 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2816 if (errno != ENOTDIR)
2820 if (statfs(path, &s) < 0)
2823 if (!is_temporary_fs(&s)) {
2824 log_error("Attempted to remove disk file system, and we can't allow that.");
2829 if (delete_root && !only_dirs)
2830 if (unlink(path) < 0 && errno != ENOENT)
2837 if (fstatfs(fd, &s) < 0) {
2838 close_nointr_nofail(fd);
2842 if (!is_temporary_fs(&s)) {
2843 log_error("Attempted to remove disk file system, and we can't allow that.");
2844 close_nointr_nofail(fd);
2849 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2852 if (honour_sticky && file_is_priv_sticky(path) > 0)
2855 if (rmdir(path) < 0 && errno != ENOENT) {
2864 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2865 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2868 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2869 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2872 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2875 /* Under the assumption that we are running privileged we
2876 * first change the access mode and only then hand out
2877 * ownership to avoid a window where access is too open. */
2879 if (mode != (mode_t) -1)
2880 if (chmod(path, mode) < 0)
2883 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2884 if (chown(path, uid, gid) < 0)
2890 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2893 /* Under the assumption that we are running privileged we
2894 * first change the access mode and only then hand out
2895 * ownership to avoid a window where access is too open. */
2897 if (fchmod(fd, mode) < 0)
2900 if (fchown(fd, uid, gid) < 0)
2906 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2910 /* Allocates the cpuset in the right size */
2913 if (!(r = CPU_ALLOC(n)))
2916 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2917 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2927 if (errno != EINVAL)
2934 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2935 static const char status_indent[] = " "; /* "[" STATUS "] " */
2936 _cleanup_free_ char *s = NULL;
2937 _cleanup_close_ int fd = -1;
2938 struct iovec iovec[6] = {};
2940 static bool prev_ephemeral;
2944 /* This is independent of logging, as status messages are
2945 * optional and go exclusively to the console. */
2947 if (vasprintf(&s, format, ap) < 0)
2950 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2963 sl = status ? sizeof(status_indent)-1 : 0;
2969 e = ellipsize(s, emax, 75);
2977 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2978 prev_ephemeral = ephemeral;
2981 if (!isempty(status)) {
2982 IOVEC_SET_STRING(iovec[n++], "[");
2983 IOVEC_SET_STRING(iovec[n++], status);
2984 IOVEC_SET_STRING(iovec[n++], "] ");
2986 IOVEC_SET_STRING(iovec[n++], status_indent);
2989 IOVEC_SET_STRING(iovec[n++], s);
2991 IOVEC_SET_STRING(iovec[n++], "\n");
2993 if (writev(fd, iovec, n) < 0)
2999 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3005 va_start(ap, format);
3006 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3012 int status_welcome(void) {
3014 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3016 r = parse_env_file("/etc/os-release", NEWLINE,
3017 "PRETTY_NAME", &pretty_name,
3018 "ANSI_COLOR", &ansi_color,
3020 if (r < 0 && r != -ENOENT)
3021 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3023 return status_printf(NULL, false, false,
3024 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3025 isempty(ansi_color) ? "1" : ansi_color,
3026 isempty(pretty_name) ? "Linux" : pretty_name);
3029 char *replace_env(const char *format, char **env) {
3036 const char *e, *word = format;
3041 for (e = format; *e; e ++) {
3052 if (!(k = strnappend(r, word, e-word-1)))
3061 } else if (*e == '$') {
3062 if (!(k = strnappend(r, word, e-word)))
3078 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3080 k = strappend(r, t);
3094 if (!(k = strnappend(r, word, e-word)))
3105 char **replace_env_argv(char **argv, char **env) {
3107 unsigned k = 0, l = 0;
3109 l = strv_length(argv);
3111 if (!(r = new(char*, l+1)))
3114 STRV_FOREACH(i, argv) {
3116 /* If $FOO appears as single word, replace it by the split up variable */
3117 if ((*i)[0] == '$' && (*i)[1] != '{') {
3122 e = strv_env_get(env, *i+1);
3125 if (!(m = strv_split_quoted(e))) {
3136 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3145 memcpy(r + k, m, q * sizeof(char*));
3153 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3154 if (!(r[k++] = replace_env(*i, env))) {
3164 int fd_columns(int fd) {
3165 struct winsize ws = {};
3167 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3176 unsigned columns(void) {
3180 if (_likely_(cached_columns > 0))
3181 return cached_columns;
3184 e = getenv("COLUMNS");
3189 c = fd_columns(STDOUT_FILENO);
3198 int fd_lines(int fd) {
3199 struct winsize ws = {};
3201 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3210 unsigned lines(void) {
3214 if (_likely_(cached_lines > 0))
3215 return cached_lines;
3218 e = getenv("LINES");
3223 l = fd_lines(STDOUT_FILENO);
3229 return cached_lines;
3232 /* intended to be used as a SIGWINCH sighandler */
3233 void columns_lines_cache_reset(int signum) {
3239 static int cached_on_tty = -1;
3241 if (_unlikely_(cached_on_tty < 0))
3242 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3244 return cached_on_tty;
3247 int running_in_chroot(void) {
3248 struct stat a = {}, b = {};
3250 /* Only works as root */
3251 if (stat("/proc/1/root", &a) < 0)
3254 if (stat("/", &b) < 0)
3258 a.st_dev != b.st_dev ||
3259 a.st_ino != b.st_ino;
3262 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3267 assert(percent <= 100);
3268 assert(new_length >= 3);
3270 if (old_length <= 3 || old_length <= new_length)
3271 return strndup(s, old_length);
3273 r = new0(char, new_length+1);
3277 x = (new_length * percent) / 100;
3279 if (x > new_length - 3)
3287 s + old_length - (new_length - x - 3),
3288 new_length - x - 3);
3293 char *ellipsize(const char *s, size_t length, unsigned percent) {
3294 return ellipsize_mem(s, strlen(s), length, percent);
3297 int touch(const char *path) {
3302 /* This just opens the file for writing, ensuring it
3303 * exists. It doesn't call utimensat() the way /usr/bin/touch
3306 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3310 close_nointr_nofail(fd);
3314 char *unquote(const char *s, const char* quotes) {
3318 /* This is rather stupid, simply removes the heading and
3319 * trailing quotes if there is one. Doesn't care about
3320 * escaping or anything. We should make this smarter one
3327 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3328 return strndup(s+1, l-2);
3333 char *normalize_env_assignment(const char *s) {
3334 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3337 eq = strchr(s, '=');
3349 memmove(r, t, strlen(t) + 1);
3353 name = strndup(s, eq - s);
3361 value = unquote(strstrip(p), QUOTES);
3365 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3371 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3382 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3394 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3401 r = wait_for_terminate(pid, &status);
3403 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3407 if (status.si_code == CLD_EXITED) {
3408 if (status.si_status != 0) {
3409 log_warning("%s failed with error code %i.", name, status.si_status);
3410 return status.si_status;
3413 log_debug("%s succeeded.", name);
3416 } else if (status.si_code == CLD_KILLED ||
3417 status.si_code == CLD_DUMPED) {
3419 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3423 log_warning("%s failed due to unknown reason.", name);
3427 _noreturn_ void freeze(void) {
3429 /* Make sure nobody waits for us on a socket anymore */
3430 close_all_fds(NULL, 0);
3438 bool null_or_empty(struct stat *st) {
3441 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3444 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3450 int null_or_empty_path(const char *fn) {
3455 if (stat(fn, &st) < 0)
3458 return null_or_empty(&st);
3461 DIR *xopendirat(int fd, const char *name, int flags) {
3465 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3471 close_nointr_nofail(nfd);
3478 int signal_from_string_try_harder(const char *s) {
3482 signo = signal_from_string(s);
3484 if (startswith(s, "SIG"))
3485 return signal_from_string(s+3);
3490 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3494 /* FIXME: to follow udev's logic 100% we need to leave valid
3495 * UTF8 chars unescaped */
3497 u = unquote(tagvalue, "\"\'");
3501 t = xescape(u, "/ ");
3507 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3516 char *fstab_node_to_udev_node(const char *p) {
3519 if (startswith(p, "LABEL="))
3520 return tag_to_udev_node(p+6, "label");
3522 if (startswith(p, "UUID="))
3523 return tag_to_udev_node(p+5, "uuid");
3525 if (startswith(p, "PARTUUID="))
3526 return tag_to_udev_node(p+9, "partuuid");
3528 if (startswith(p, "PARTLABEL="))
3529 return tag_to_udev_node(p+10, "partlabel");
3534 bool tty_is_vc(const char *tty) {
3537 if (startswith(tty, "/dev/"))
3540 return vtnr_from_tty(tty) >= 0;
3543 bool tty_is_console(const char *tty) {
3546 if (startswith(tty, "/dev/"))
3549 return streq(tty, "console");
3552 int vtnr_from_tty(const char *tty) {
3557 if (startswith(tty, "/dev/"))
3560 if (!startswith(tty, "tty") )
3563 if (tty[3] < '0' || tty[3] > '9')
3566 r = safe_atoi(tty+3, &i);
3570 if (i < 0 || i > 63)
3576 char *resolve_dev_console(char **active) {
3579 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3580 * (i.e. not read-only-mounted which is a sign for container setups) */
3582 if (path_is_read_only_fs("/sys") > 0)
3585 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3588 /* If multiple log outputs are configured the last one is what
3589 * /dev/console points to */
3590 tty = strrchr(*active, ' ');
3599 bool tty_is_vc_resolve(const char *tty) {
3600 char *active = NULL;
3605 if (startswith(tty, "/dev/"))
3608 if (streq(tty, "console")) {
3609 tty = resolve_dev_console(&active);
3620 const char *default_term_for_tty(const char *tty) {
3623 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3626 bool dirent_is_file(const struct dirent *de) {
3629 if (ignore_file(de->d_name))
3632 if (de->d_type != DT_REG &&
3633 de->d_type != DT_LNK &&
3634 de->d_type != DT_UNKNOWN)
3640 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3643 if (de->d_type != DT_REG &&
3644 de->d_type != DT_LNK &&
3645 de->d_type != DT_UNKNOWN)
3648 if (ignore_file_allow_backup(de->d_name))
3651 return endswith(de->d_name, suffix);
3654 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3657 Hashmap *pids = NULL;
3661 /* Executes all binaries in a directory in parallel and
3662 * waits for them to finish. */
3665 if (!(_d = opendir(directory))) {
3667 if (errno == ENOENT)
3670 log_error("Failed to enumerate directory %s: %m", directory);
3677 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3678 log_error("Failed to allocate set.");
3682 while ((de = readdir(d))) {
3687 if (!dirent_is_file(de))
3690 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3695 if ((pid = fork()) < 0) {
3696 log_error("Failed to fork: %m");
3714 log_error("Failed to execute %s: %m", path);
3715 _exit(EXIT_FAILURE);
3718 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3720 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3721 log_error("Failed to add PID to set: %s", strerror(-k));
3726 while (!hashmap_isempty(pids)) {
3727 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3731 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3736 log_error("waitid() failed: %m");
3740 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3741 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3742 if (si.si_code == CLD_EXITED)
3743 log_error("%s exited with exit status %i.", path, si.si_status);
3745 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3747 log_debug("%s exited successfully.", path);
3758 hashmap_free_free(pids);
3761 int kill_and_sigcont(pid_t pid, int sig) {
3764 r = kill(pid, sig) < 0 ? -errno : 0;
3772 bool nulstr_contains(const char*nulstr, const char *needle) {
3778 NULSTR_FOREACH(i, nulstr)
3779 if (streq(i, needle))
3785 bool plymouth_running(void) {
3786 return access("/run/plymouth/pid", F_OK) >= 0;
3789 char* strshorten(char *s, size_t l) {
3798 static bool hostname_valid_char(char c) {
3800 (c >= 'a' && c <= 'z') ||
3801 (c >= 'A' && c <= 'Z') ||
3802 (c >= '0' && c <= '9') ||
3808 bool hostname_is_valid(const char *s) {
3815 for (p = s, dot = true; *p; p++) {
3822 if (!hostname_valid_char(*p))
3832 if (p-s > HOST_NAME_MAX)
3838 char* hostname_cleanup(char *s) {
3841 for (p = s, d = s; *p; p++)
3842 if ((*p >= 'a' && *p <= 'z') ||
3843 (*p >= 'A' && *p <= 'Z') ||
3844 (*p >= '0' && *p <= '9') ||
3852 strshorten(s, HOST_NAME_MAX);
3856 int pipe_eof(int fd) {
3858 struct pollfd pollfd = {
3860 .events = POLLIN|POLLHUP,
3863 r = poll(&pollfd, 1, 0);
3870 return pollfd.revents & POLLHUP;
3873 int fd_wait_for_event(int fd, int event, usec_t t) {
3875 struct pollfd pollfd = {
3880 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3887 return pollfd.revents;
3890 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3901 t = new(char, strlen(path) + 1 + 6 + 1);
3905 fn = path_get_file_name(path);
3909 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3911 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3917 f = fdopen(fd, "we");
3930 int terminal_vhangup_fd(int fd) {
3933 if (ioctl(fd, TIOCVHANGUP) < 0)
3939 int terminal_vhangup(const char *name) {
3942 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3946 r = terminal_vhangup_fd(fd);
3947 close_nointr_nofail(fd);
3952 int vt_disallocate(const char *name) {
3956 /* Deallocate the VT if possible. If not possible
3957 * (i.e. because it is the active one), at least clear it
3958 * entirely (including the scrollback buffer) */
3960 if (!startswith(name, "/dev/"))
3963 if (!tty_is_vc(name)) {
3964 /* So this is not a VT. I guess we cannot deallocate
3965 * it then. But let's at least clear the screen */
3967 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3972 "\033[r" /* clear scrolling region */
3973 "\033[H" /* move home */
3974 "\033[2J", /* clear screen */
3976 close_nointr_nofail(fd);
3981 if (!startswith(name, "/dev/tty"))
3984 r = safe_atou(name+8, &u);
3991 /* Try to deallocate */
3992 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3996 r = ioctl(fd, VT_DISALLOCATE, u);
3997 close_nointr_nofail(fd);
4005 /* Couldn't deallocate, so let's clear it fully with
4007 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4012 "\033[r" /* clear scrolling region */
4013 "\033[H" /* move home */
4014 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4016 close_nointr_nofail(fd);
4021 int copy_file(const char *from, const char *to) {
4027 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4031 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4033 close_nointr_nofail(fdf);
4041 n = read(fdf, buf, sizeof(buf));
4045 close_nointr_nofail(fdf);
4056 k = loop_write(fdt, buf, n, false);
4058 r = k < 0 ? k : (errno ? -errno : -EIO);
4060 close_nointr_nofail(fdf);
4068 close_nointr_nofail(fdf);
4069 r = close_nointr(fdt);
4079 int symlink_atomic(const char *from, const char *to) {
4081 _cleanup_free_ char *t;
4084 unsigned long long ull;
4091 t = new(char, strlen(to) + 1 + 16 + 1);
4095 fn = path_get_file_name(to);
4099 x = stpcpy(t+k+1, fn);
4102 for (i = 0; i < 16; i++) {
4103 *(x++) = hexchar(ull & 0xF);
4109 if (symlink(from, t) < 0)
4112 if (rename(t, to) < 0) {
4121 bool display_is_local(const char *display) {
4125 display[0] == ':' &&
4126 display[1] >= '0' &&
4130 int socket_from_display(const char *display, char **path) {
4137 if (!display_is_local(display))
4140 k = strspn(display+1, "0123456789");
4142 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4146 c = stpcpy(f, "/tmp/.X11-unix/X");
4147 memcpy(c, display+1, k);
4156 const char **username,
4157 uid_t *uid, gid_t *gid,
4159 const char **shell) {
4167 /* We enforce some special rules for uid=0: in order to avoid
4168 * NSS lookups for root we hardcode its data. */
4170 if (streq(*username, "root") || streq(*username, "0")) {
4188 if (parse_uid(*username, &u) >= 0) {
4192 /* If there are multiple users with the same id, make
4193 * sure to leave $USER to the configured value instead
4194 * of the first occurrence in the database. However if
4195 * the uid was configured by a numeric uid, then let's
4196 * pick the real username from /etc/passwd. */
4198 *username = p->pw_name;
4201 p = getpwnam(*username);
4205 return errno > 0 ? -errno : -ESRCH;
4217 *shell = p->pw_shell;
4222 char* uid_to_name(uid_t uid) {
4227 return strdup("root");
4231 return strdup(p->pw_name);
4233 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4239 char* gid_to_name(gid_t gid) {
4244 return strdup("root");
4248 return strdup(p->gr_name);
4250 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4256 int get_group_creds(const char **groupname, gid_t *gid) {
4262 /* We enforce some special rules for gid=0: in order to avoid
4263 * NSS lookups for root we hardcode its data. */
4265 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4266 *groupname = "root";
4274 if (parse_gid(*groupname, &id) >= 0) {
4279 *groupname = g->gr_name;
4282 g = getgrnam(*groupname);
4286 return errno > 0 ? -errno : -ESRCH;
4294 int in_gid(gid_t gid) {
4296 int ngroups_max, r, i;
4298 if (getgid() == gid)
4301 if (getegid() == gid)
4304 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4305 assert(ngroups_max > 0);
4307 gids = alloca(sizeof(gid_t) * ngroups_max);
4309 r = getgroups(ngroups_max, gids);
4313 for (i = 0; i < r; i++)
4320 int in_group(const char *name) {
4324 r = get_group_creds(&name, &gid);
4331 int glob_exists(const char *path) {
4332 glob_t _cleanup_globfree_ g = {};
4338 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4340 if (k == GLOB_NOMATCH)
4342 else if (k == GLOB_NOSPACE)
4345 r = !strv_isempty(g.gl_pathv);
4347 r = errno ? -errno : -EIO;
4352 int dirent_ensure_type(DIR *d, struct dirent *de) {
4358 if (de->d_type != DT_UNKNOWN)
4361 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4365 S_ISREG(st.st_mode) ? DT_REG :
4366 S_ISDIR(st.st_mode) ? DT_DIR :
4367 S_ISLNK(st.st_mode) ? DT_LNK :
4368 S_ISFIFO(st.st_mode) ? DT_FIFO :
4369 S_ISSOCK(st.st_mode) ? DT_SOCK :
4370 S_ISCHR(st.st_mode) ? DT_CHR :
4371 S_ISBLK(st.st_mode) ? DT_BLK :
4377 int in_search_path(const char *path, char **search) {
4381 r = path_get_parent(path, &parent);
4387 STRV_FOREACH(i, search) {
4388 if (path_equal(parent, *i)) {
4399 int get_files_in_directory(const char *path, char ***list) {
4407 /* Returns all files in a directory in *list, and the number
4408 * of files as return value. If list is NULL returns only the
4417 union dirent_storage buf;
4420 k = readdir_r(d, &buf.de, &de);
4429 dirent_ensure_type(d, de);
4431 if (!dirent_is_file(de))
4435 if ((unsigned) r >= n) {
4439 t = realloc(l, sizeof(char*) * n);
4448 assert((unsigned) r < n);
4450 l[r] = strdup(de->d_name);
4474 char *strjoin(const char *x, ...) {
4488 t = va_arg(ap, const char *);
4493 if (n > ((size_t) -1) - l) {
4517 t = va_arg(ap, const char *);
4531 bool is_main_thread(void) {
4532 static __thread int cached = 0;
4534 if (_unlikely_(cached == 0))
4535 cached = getpid() == gettid() ? 1 : -1;
4540 int block_get_whole_disk(dev_t d, dev_t *ret) {
4547 /* If it has a queue this is good enough for us */
4548 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4551 r = access(p, F_OK);
4559 /* If it is a partition find the originating device */
4560 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4563 r = access(p, F_OK);
4569 /* Get parent dev_t */
4570 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4573 r = read_one_line_file(p, &s);
4579 r = sscanf(s, "%u:%u", &m, &n);
4585 /* Only return this if it is really good enough for us. */
4586 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4589 r = access(p, F_OK);
4593 *ret = makedev(m, n);
4600 int file_is_priv_sticky(const char *p) {
4605 if (lstat(p, &st) < 0)
4609 (st.st_uid == 0 || st.st_uid == getuid()) &&
4610 (st.st_mode & S_ISVTX);
4613 static const char *const ioprio_class_table[] = {
4614 [IOPRIO_CLASS_NONE] = "none",
4615 [IOPRIO_CLASS_RT] = "realtime",
4616 [IOPRIO_CLASS_BE] = "best-effort",
4617 [IOPRIO_CLASS_IDLE] = "idle"
4620 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4622 static const char *const sigchld_code_table[] = {
4623 [CLD_EXITED] = "exited",
4624 [CLD_KILLED] = "killed",
4625 [CLD_DUMPED] = "dumped",
4626 [CLD_TRAPPED] = "trapped",
4627 [CLD_STOPPED] = "stopped",
4628 [CLD_CONTINUED] = "continued",
4631 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4633 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4634 [LOG_FAC(LOG_KERN)] = "kern",
4635 [LOG_FAC(LOG_USER)] = "user",
4636 [LOG_FAC(LOG_MAIL)] = "mail",
4637 [LOG_FAC(LOG_DAEMON)] = "daemon",
4638 [LOG_FAC(LOG_AUTH)] = "auth",
4639 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4640 [LOG_FAC(LOG_LPR)] = "lpr",
4641 [LOG_FAC(LOG_NEWS)] = "news",
4642 [LOG_FAC(LOG_UUCP)] = "uucp",
4643 [LOG_FAC(LOG_CRON)] = "cron",
4644 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4645 [LOG_FAC(LOG_FTP)] = "ftp",
4646 [LOG_FAC(LOG_LOCAL0)] = "local0",
4647 [LOG_FAC(LOG_LOCAL1)] = "local1",
4648 [LOG_FAC(LOG_LOCAL2)] = "local2",
4649 [LOG_FAC(LOG_LOCAL3)] = "local3",
4650 [LOG_FAC(LOG_LOCAL4)] = "local4",
4651 [LOG_FAC(LOG_LOCAL5)] = "local5",
4652 [LOG_FAC(LOG_LOCAL6)] = "local6",
4653 [LOG_FAC(LOG_LOCAL7)] = "local7"
4656 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4658 static const char *const log_level_table[] = {
4659 [LOG_EMERG] = "emerg",
4660 [LOG_ALERT] = "alert",
4661 [LOG_CRIT] = "crit",
4663 [LOG_WARNING] = "warning",
4664 [LOG_NOTICE] = "notice",
4665 [LOG_INFO] = "info",
4666 [LOG_DEBUG] = "debug"
4669 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4671 static const char* const sched_policy_table[] = {
4672 [SCHED_OTHER] = "other",
4673 [SCHED_BATCH] = "batch",
4674 [SCHED_IDLE] = "idle",
4675 [SCHED_FIFO] = "fifo",
4679 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4681 static const char* const rlimit_table[] = {
4682 [RLIMIT_CPU] = "LimitCPU",
4683 [RLIMIT_FSIZE] = "LimitFSIZE",
4684 [RLIMIT_DATA] = "LimitDATA",
4685 [RLIMIT_STACK] = "LimitSTACK",
4686 [RLIMIT_CORE] = "LimitCORE",
4687 [RLIMIT_RSS] = "LimitRSS",
4688 [RLIMIT_NOFILE] = "LimitNOFILE",
4689 [RLIMIT_AS] = "LimitAS",
4690 [RLIMIT_NPROC] = "LimitNPROC",
4691 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4692 [RLIMIT_LOCKS] = "LimitLOCKS",
4693 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4694 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4695 [RLIMIT_NICE] = "LimitNICE",
4696 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4697 [RLIMIT_RTTIME] = "LimitRTTIME"
4700 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4702 static const char* const ip_tos_table[] = {
4703 [IPTOS_LOWDELAY] = "low-delay",
4704 [IPTOS_THROUGHPUT] = "throughput",
4705 [IPTOS_RELIABILITY] = "reliability",
4706 [IPTOS_LOWCOST] = "low-cost",
4709 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4711 static const char *const __signal_table[] = {
4728 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4739 [SIGVTALRM] = "VTALRM",
4741 [SIGWINCH] = "WINCH",
4747 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4749 const char *signal_to_string(int signo) {
4750 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4753 name = __signal_to_string(signo);
4757 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4758 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4760 snprintf(buf, sizeof(buf), "%d", signo);
4765 int signal_from_string(const char *s) {
4770 signo = __signal_from_string(s);
4774 if (startswith(s, "RTMIN+")) {
4778 if (safe_atou(s, &u) >= 0) {
4779 signo = (int) u + offset;
4780 if (signo > 0 && signo < _NSIG)
4786 bool kexec_loaded(void) {
4787 bool loaded = false;
4790 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4798 int strdup_or_null(const char *a, char **b) {
4816 int prot_from_flags(int flags) {
4818 switch (flags & O_ACCMODE) {
4827 return PROT_READ|PROT_WRITE;
4834 char *format_bytes(char *buf, size_t l, off_t t) {
4837 static const struct {
4841 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4842 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4843 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4844 { "G", 1024ULL*1024ULL*1024ULL },
4845 { "M", 1024ULL*1024ULL },
4849 for (i = 0; i < ELEMENTSOF(table); i++) {
4851 if (t >= table[i].factor) {
4854 (unsigned long long) (t / table[i].factor),
4855 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4862 snprintf(buf, l, "%lluB", (unsigned long long) t);
4870 void* memdup(const void *p, size_t l) {
4883 int fd_inc_sndbuf(int fd, size_t n) {
4885 socklen_t l = sizeof(value);
4887 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4889 l == sizeof(value) &&
4890 (size_t) value >= n*2)
4894 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4901 int fd_inc_rcvbuf(int fd, size_t n) {
4903 socklen_t l = sizeof(value);
4905 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4907 l == sizeof(value) &&
4908 (size_t) value >= n*2)
4912 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4919 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4920 pid_t parent_pid, agent_pid;
4922 bool stdout_is_tty, stderr_is_tty;
4930 parent_pid = getpid();
4932 /* Spawns a temporary TTY agent, making sure it goes away when
4939 if (agent_pid != 0) {
4946 * Make sure the agent goes away when the parent dies */
4947 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4948 _exit(EXIT_FAILURE);
4950 /* Check whether our parent died before we were able
4951 * to set the death signal */
4952 if (getppid() != parent_pid)
4953 _exit(EXIT_SUCCESS);
4955 /* Don't leak fds to the agent */
4956 close_all_fds(except, n_except);
4958 stdout_is_tty = isatty(STDOUT_FILENO);
4959 stderr_is_tty = isatty(STDERR_FILENO);
4961 if (!stdout_is_tty || !stderr_is_tty) {
4962 /* Detach from stdout/stderr. and reopen
4963 * /dev/tty for them. This is important to
4964 * ensure that when systemctl is started via
4965 * popen() or a similar call that expects to
4966 * read EOF we actually do generate EOF and
4967 * not delay this indefinitely by because we
4968 * keep an unused copy of stdin around. */
4969 fd = open("/dev/tty", O_WRONLY);
4971 log_error("Failed to open /dev/tty: %m");
4972 _exit(EXIT_FAILURE);
4976 dup2(fd, STDOUT_FILENO);
4979 dup2(fd, STDERR_FILENO);
4985 /* Count arguments */
4987 for (n = 0; va_arg(ap, char*); n++)
4992 l = alloca(sizeof(char *) * (n + 1));
4994 /* Fill in arguments */
4996 for (i = 0; i <= n; i++)
4997 l[i] = va_arg(ap, char*);
5001 _exit(EXIT_FAILURE);
5004 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5005 struct rlimit highest, fixed;
5009 if (setrlimit(resource, rlim) >= 0)
5015 /* So we failed to set the desired setrlimit, then let's try
5016 * to get as close as we can */
5017 assert_se(getrlimit(resource, &highest) == 0);
5019 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5020 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5022 if (setrlimit(resource, &fixed) < 0)
5028 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5029 char path[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/environ")], *value = NULL;
5041 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5043 f = fopen(path, "re");
5051 char line[LINE_MAX];
5054 for (i = 0; i < sizeof(line)-1; i++) {
5058 if (_unlikely_(c == EOF)) {
5068 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5069 value = strdup(line + l + 1);
5089 int can_sleep(const char *type) {
5093 _cleanup_free_ char *p = NULL;
5097 /* If /sys is read-only we cannot sleep */
5098 if (access("/sys/power/state", W_OK) < 0)
5101 r = read_one_line_file("/sys/power/state", &p);
5106 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5107 if (l == k && memcmp(w, type, l) == 0)
5113 int can_sleep_disk(const char *type) {
5117 _cleanup_free_ char *p = NULL;
5121 /* If /sys is read-only we cannot sleep */
5122 if (access("/sys/power/state", W_OK) < 0 ||
5123 access("/sys/power/disk", W_OK) < 0)
5126 r = read_one_line_file("/sys/power/disk", &p);
5131 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5132 if (l == k && memcmp(w, type, l) == 0)
5135 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5142 bool is_valid_documentation_url(const char *url) {
5145 if (startswith(url, "http://") && url[7])
5148 if (startswith(url, "https://") && url[8])
5151 if (startswith(url, "file:") && url[5])
5154 if (startswith(url, "info:") && url[5])
5157 if (startswith(url, "man:") && url[4])
5163 bool in_initrd(void) {
5164 static __thread int saved = -1;
5170 /* We make two checks here:
5172 * 1. the flag file /etc/initrd-release must exist
5173 * 2. the root file system must be a memory file system
5175 * The second check is extra paranoia, since misdetecting an
5176 * initrd can have bad bad consequences due the initrd
5177 * emptying when transititioning to the main systemd.
5180 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5181 statfs("/", &s) >= 0 &&
5182 is_temporary_fs(&s);
5187 void warn_melody(void) {
5188 _cleanup_close_ int fd = -1;
5190 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5194 /* Yeah, this is synchronous. Kinda sucks. But well... */
5196 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5197 usleep(125*USEC_PER_MSEC);
5199 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5200 usleep(125*USEC_PER_MSEC);
5202 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5203 usleep(125*USEC_PER_MSEC);
5205 ioctl(fd, KIOCSOUND, 0);
5208 int make_console_stdio(void) {
5211 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5213 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5215 log_error("Failed to acquire terminal: %s", strerror(-fd));
5221 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5228 int get_home_dir(char **_h) {
5236 /* Take the user specified one */
5247 /* Hardcode home directory for root to avoid NSS */
5250 h = strdup("/root");
5258 /* Check the database... */
5262 return errno ? -errno : -ESRCH;
5264 if (!path_is_absolute(p->pw_dir))
5267 h = strdup(p->pw_dir);
5275 void fclosep(FILE **f) {
5280 void pclosep(FILE **f) {
5285 void closep(int *fd) {
5287 close_nointr_nofail(*fd);
5290 void closedirp(DIR **d) {
5295 bool filename_is_safe(const char *p) {
5309 if (strlen(p) > FILENAME_MAX)
5315 bool string_is_safe(const char *p) {
5320 for (t = p; *t; t++) {
5321 if (*t > 0 && *t < ' ')
5324 if (strchr("\\\"\'", *t))
5331 bool string_has_cc(const char *p) {
5336 for (t = p; *t; t++)
5337 if (*t > 0 && *t < ' ')
5343 bool path_is_safe(const char *p) {
5348 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5351 if (strlen(p) > PATH_MAX)
5354 /* The following two checks are not really dangerous, but hey, they still are confusing */
5355 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5358 if (strstr(p, "//"))
5364 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5365 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5366 int (*compar) (const void *, const void *, void *), void *arg) {
5375 p = (void *)(((const char *) base) + (idx * size));
5376 comparison = compar(key, p, arg);
5379 else if (comparison > 0)
5387 bool is_locale_utf8(void) {
5389 static int cached_answer = -1;
5391 if (cached_answer >= 0)
5394 if (!setlocale(LC_ALL, "")) {
5395 cached_answer = true;
5399 set = nl_langinfo(CODESET);
5401 cached_answer = true;
5405 cached_answer = streq(set, "UTF-8");
5407 return (bool)cached_answer;
5410 const char *draw_special_char(DrawSpecialChar ch) {
5411 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5413 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5414 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5415 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5416 [DRAW_TREE_SPACE] = " ", /* */
5417 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5419 /* ASCII fallback */ {
5420 [DRAW_TREE_VERT] = "| ",
5421 [DRAW_TREE_BRANCH] = "|-",
5422 [DRAW_TREE_RIGHT] = "`-",
5423 [DRAW_TREE_SPACE] = " ",
5424 [DRAW_TRIANGULAR_BULLET] = "> ",
5428 return draw_table[!is_locale_utf8()][ch];
5431 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5434 size_t l, old_len, new_len;
5440 old_len = strlen(old_string);
5441 new_len = strlen(new_string);
5454 if (!startswith(f, old_string)) {
5460 nl = l - old_len + new_len;
5461 a = realloc(r, nl + 1);
5469 t = stpcpy(t, new_string);
5481 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5482 const char *i, *begin = NULL;
5487 } state = STATE_OTHER;
5489 size_t osz = 0, isz;
5495 /* Strips ANSI color and replaces TABs by 8 spaces */
5497 isz = _isz ? *_isz : strlen(*ibuf);
5499 f = open_memstream(&obuf, &osz);
5503 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5508 if (i >= *ibuf + isz) /* EOT */
5510 else if (*i == '\x1B')
5511 state = STATE_ESCAPE;
5512 else if (*i == '\t')
5519 if (i >= *ibuf + isz) { /* EOT */
5522 } else if (*i == '[') {
5523 state = STATE_BRACKET;
5528 state = STATE_OTHER;
5535 if (i >= *ibuf + isz || /* EOT */
5536 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5539 state = STATE_OTHER;
5541 } else if (*i == 'm')
5542 state = STATE_OTHER;
5564 int on_ac_power(void) {
5565 bool found_offline = false, found_online = false;
5566 _cleanup_closedir_ DIR *d = NULL;
5568 d = opendir("/sys/class/power_supply");
5574 union dirent_storage buf;
5575 _cleanup_close_ int fd = -1, device = -1;
5580 k = readdir_r(d, &buf.de, &de);
5587 if (ignore_file(de->d_name))
5590 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5592 if (errno == ENOENT || errno == ENOTDIR)
5598 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5600 if (errno == ENOENT)
5606 n = read(fd, contents, sizeof(contents));
5610 if (n != 6 || memcmp(contents, "Mains\n", 6))
5613 close_nointr_nofail(fd);
5614 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5616 if (errno == ENOENT)
5622 n = read(fd, contents, sizeof(contents));
5626 if (n != 2 || contents[1] != '\n')
5629 if (contents[0] == '1') {
5630 found_online = true;
5632 } else if (contents[0] == '0')
5633 found_offline = true;
5638 return found_online || !found_offline;
5641 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5648 if (!path_strv_canonicalize_uniq(search))
5651 STRV_FOREACH(i, search) {
5652 _cleanup_free_ char *p = NULL;
5655 p = strjoin(*i, "/", path, NULL);
5665 if (errno != ENOENT)
5672 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5673 _cleanup_strv_free_ char **copy = NULL;
5679 if (path_is_absolute(path)) {
5682 f = fopen(path, mode);
5691 copy = strv_copy((char**) search);
5695 return search_and_fopen_internal(path, mode, copy, _f);
5698 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5699 _cleanup_strv_free_ char **s = NULL;
5701 if (path_is_absolute(path)) {
5704 f = fopen(path, mode);
5713 s = strv_split_nulstr(search);
5717 return search_and_fopen_internal(path, mode, s, _f);
5720 int create_tmp_dir(char template[], char** dir_name) {
5726 RUN_WITH_UMASK(0077) {
5727 d = mkdtemp(template);
5730 log_error("Can't create directory %s: %m", template);
5734 dt = strjoin(d, "/tmp", NULL);
5740 RUN_WITH_UMASK(0000) {
5741 r = mkdir(dt, 0777);
5744 log_error("Can't create directory %s: %m", dt);
5748 log_debug("Created temporary directory %s", dt);
5750 r = chmod(dt, 0777 | S_ISVTX);
5752 log_error("Failed to chmod %s: %m", dt);
5756 log_debug("Set sticky bit on %s", dt);
5770 char *strextend(char **x, ...) {
5777 l = f = *x ? strlen(*x) : 0;
5784 t = va_arg(ap, const char *);
5789 if (n > ((size_t) -1) - l) {
5798 r = realloc(*x, l+1);
5808 t = va_arg(ap, const char *);
5822 char *strrep(const char *s, unsigned n) {
5830 p = r = malloc(l * n + 1);
5834 for (i = 0; i < n; i++)
5841 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5845 if (*allocated >= need)
5848 a = MAX(64u, need * 2);