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 size_t page_size(void) {
84 static __thread size_t pgsz = 0;
87 if (_likely_(pgsz > 0))
90 r = sysconf(_SC_PAGESIZE);
97 bool streq_ptr(const char *a, const char *b) {
99 /* Like streq(), but tries to make sense of NULL pointers */
110 char* endswith(const char *s, const char *postfix) {
117 pl = strlen(postfix);
120 return (char*) s + sl;
125 if (memcmp(s + sl - pl, postfix, pl) != 0)
128 return (char*) s + sl - pl;
131 char* startswith(const char *s, const char *prefix) {
148 char* startswith_no_case(const char *s, const char *prefix) {
158 if (tolower(*a) != tolower(*b))
165 bool first_word(const char *s, const char *word) {
180 if (memcmp(s, word, wl) != 0)
184 strchr(WHITESPACE, s[wl]);
187 int close_nointr(int fd) {
193 /* Just ignore EINTR; a retry loop is the wrong
194 * thing to do on Linux.
196 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
197 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
198 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
199 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
201 if (_unlikely_(r < 0 && errno == EINTR))
209 void close_nointr_nofail(int fd) {
212 /* like close_nointr() but cannot fail, and guarantees errno
215 assert_se(close_nointr(fd) == 0);
218 void close_many(const int fds[], unsigned n_fd) {
221 assert(fds || n_fd <= 0);
223 for (i = 0; i < n_fd; i++)
224 close_nointr_nofail(fds[i]);
227 int unlink_noerrno(const char *path) {
238 int parse_boolean(const char *v) {
241 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
243 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
249 int parse_pid(const char *s, pid_t* ret_pid) {
250 unsigned long ul = 0;
257 r = safe_atolu(s, &ul);
263 if ((unsigned long) pid != ul)
273 int parse_uid(const char *s, uid_t* ret_uid) {
274 unsigned long ul = 0;
281 r = safe_atolu(s, &ul);
287 if ((unsigned long) uid != ul)
294 int safe_atou(const char *s, unsigned *ret_u) {
302 l = strtoul(s, &x, 0);
304 if (!x || x == s || *x || errno)
305 return errno > 0 ? -errno : -EINVAL;
307 if ((unsigned long) (unsigned) l != l)
310 *ret_u = (unsigned) l;
314 int safe_atoi(const char *s, int *ret_i) {
322 l = strtol(s, &x, 0);
324 if (!x || x == s || *x || errno)
325 return errno > 0 ? -errno : -EINVAL;
327 if ((long) (int) l != l)
334 int safe_atollu(const char *s, long long unsigned *ret_llu) {
336 unsigned long long l;
342 l = strtoull(s, &x, 0);
344 if (!x || x == s || *x || errno)
345 return errno ? -errno : -EINVAL;
351 int safe_atolli(const char *s, long long int *ret_lli) {
359 l = strtoll(s, &x, 0);
361 if (!x || x == s || *x || errno)
362 return errno ? -errno : -EINVAL;
368 int safe_atod(const char *s, double *ret_d) {
375 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
380 if (!x || x == s || *x || errno)
381 return errno ? -errno : -EINVAL;
387 /* Split a string into words. */
388 char *split(const char *c, size_t *l, const char *separator, char **state) {
391 current = *state ? *state : (char*) c;
393 if (!*current || *c == 0)
396 current += strspn(current, separator);
397 *l = strcspn(current, separator);
400 return (char*) current;
403 /* Split a string into words, but consider strings enclosed in '' and
404 * "" as words even if they include spaces. */
405 char *split_quoted(const char *c, size_t *l, char **state) {
407 bool escaped = false;
409 current = *state ? *state : (char*) c;
411 if (!*current || *c == 0)
414 current += strspn(current, WHITESPACE);
416 if (*current == '\'') {
419 for (e = current; *e; e++) {
429 *state = *e == 0 ? e : e+1;
430 } else if (*current == '\"') {
433 for (e = current; *e; e++) {
443 *state = *e == 0 ? e : e+1;
445 for (e = current; *e; e++) {
450 else if (strchr(WHITESPACE, *e))
457 return (char*) current;
460 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
462 _cleanup_fclose_ FILE *f = NULL;
475 p = procfs_file_alloca(pid, "stat");
480 if (!fgets(line, sizeof(line), f)) {
481 r = feof(f) ? -EIO : -errno;
485 /* Let's skip the pid and comm fields. The latter is enclosed
486 * in () but does not escape any () in its value, so let's
487 * skip over it manually */
489 p = strrchr(line, ')');
501 if ((long unsigned) (pid_t) ppid != ppid)
504 *_ppid = (pid_t) ppid;
509 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
510 _cleanup_fclose_ FILE *f = NULL;
518 p = "/proc/self/stat";
520 p = procfs_file_alloca(pid, "stat");
526 if (!fgets(line, sizeof(line), f)) {
533 /* Let's skip the pid and comm fields. The latter is enclosed
534 * in () but does not escape any () in its value, so let's
535 * skip over it manually */
537 p = strrchr(line, ')');
559 "%*d " /* priority */
561 "%*d " /* num_threads */
562 "%*d " /* itrealvalue */
563 "%llu " /* starttime */,
570 int fchmod_umask(int fd, mode_t m) {
575 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
581 char *truncate_nl(char *s) {
584 s[strcspn(s, NEWLINE)] = 0;
588 int get_process_comm(pid_t pid, char **name) {
595 p = "/proc/self/comm";
597 p = procfs_file_alloca(pid, "comm");
599 return read_one_line_file(p, name);
602 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
603 _cleanup_fclose_ FILE *f = NULL;
612 p = "/proc/self/cmdline";
614 p = procfs_file_alloca(pid, "cmdline");
620 if (max_length == 0) {
621 size_t len = 0, allocated = 0;
623 while ((c = getc(f)) != EOF) {
625 if (!GREEDY_REALLOC(r, allocated, len+2)) {
630 r[len++] = isprint(c) ? c : ' ';
640 r = new(char, max_length);
646 while ((c = getc(f)) != EOF) {
668 size_t n = MIN(left-1, 3U);
675 /* Kernel threads have no argv[] */
676 if (r == NULL || r[0] == 0) {
685 h = get_process_comm(pid, &t);
689 r = strjoin("[", t, "]", NULL);
700 int is_kernel_thread(pid_t pid) {
712 p = procfs_file_alloca(pid, "cmdline");
717 count = fread(&c, 1, 1, f);
721 /* Kernel threads have an empty cmdline */
724 return eof ? 1 : -errno;
729 int get_process_capeff(pid_t pid, char **capeff) {
731 _cleanup_free_ char *status = NULL;
739 p = "/proc/self/status";
741 p = procfs_file_alloca(pid, "status");
743 r = read_full_file(p, &status, NULL);
747 t = strstr(status, "\nCapEff:\t");
751 for (t += strlen("\nCapEff:\t"); t[0] == '0'; t++)
757 *capeff = strndup(t, strchr(t, '\n') - t);
764 int get_process_exe(pid_t pid, char **name) {
773 p = "/proc/self/exe";
775 p = procfs_file_alloca(pid, "exe");
777 r = readlink_malloc(p, name);
781 d = endswith(*name, " (deleted)");
788 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
789 _cleanup_fclose_ FILE *f = NULL;
799 p = procfs_file_alloca(pid, "status");
804 FOREACH_LINE(line, f, return -errno) {
809 if (startswith(l, field)) {
811 l += strspn(l, WHITESPACE);
813 l[strcspn(l, WHITESPACE)] = 0;
815 return parse_uid(l, uid);
822 int get_process_uid(pid_t pid, uid_t *uid) {
823 return get_process_id(pid, "Uid:", uid);
826 int get_process_gid(pid_t pid, gid_t *gid) {
827 assert_cc(sizeof(uid_t) == sizeof(gid_t));
828 return get_process_id(pid, "Gid:", gid);
831 char *strnappend(const char *s, const char *suffix, size_t b) {
839 return strndup(suffix, b);
848 if (b > ((size_t) -1) - a)
851 r = new(char, a+b+1);
856 memcpy(r+a, suffix, b);
862 char *strappend(const char *s, const char *suffix) {
863 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
866 int readlink_malloc(const char *p, char **r) {
876 if (!(c = new(char, l)))
879 if ((n = readlink(p, c, l-1)) < 0) {
885 if ((size_t) n < l-1) {
896 int readlink_and_make_absolute(const char *p, char **r) {
897 _cleanup_free_ char *target = NULL;
904 j = readlink_malloc(p, &target);
908 k = file_in_same_dir(p, target);
916 int readlink_and_canonicalize(const char *p, char **r) {
923 j = readlink_and_make_absolute(p, &t);
927 s = canonicalize_file_name(t);
934 path_kill_slashes(*r);
939 int reset_all_signal_handlers(void) {
942 for (sig = 1; sig < _NSIG; sig++) {
943 struct sigaction sa = {
944 .sa_handler = SIG_DFL,
945 .sa_flags = SA_RESTART,
948 if (sig == SIGKILL || sig == SIGSTOP)
951 /* On Linux the first two RT signals are reserved by
952 * glibc, and sigaction() will return EINVAL for them. */
953 if ((sigaction(sig, &sa, NULL) < 0))
961 char *strstrip(char *s) {
964 /* Drops trailing whitespace. Modifies the string in
965 * place. Returns pointer to first non-space character */
967 s += strspn(s, WHITESPACE);
969 for (e = strchr(s, 0); e > s; e --)
970 if (!strchr(WHITESPACE, e[-1]))
978 char *delete_chars(char *s, const char *bad) {
981 /* Drops all whitespace, regardless where in the string */
983 for (f = s, t = s; *f; f++) {
995 bool in_charset(const char *s, const char* charset) {
1001 for (i = s; *i; i++)
1002 if (!strchr(charset, *i))
1008 char *file_in_same_dir(const char *path, const char *filename) {
1015 /* This removes the last component of path and appends
1016 * filename, unless the latter is absolute anyway or the
1019 if (path_is_absolute(filename))
1020 return strdup(filename);
1022 if (!(e = strrchr(path, '/')))
1023 return strdup(filename);
1025 k = strlen(filename);
1026 if (!(r = new(char, e-path+1+k+1)))
1029 memcpy(r, path, e-path+1);
1030 memcpy(r+(e-path)+1, filename, k+1);
1035 int rmdir_parents(const char *path, const char *stop) {
1044 /* Skip trailing slashes */
1045 while (l > 0 && path[l-1] == '/')
1051 /* Skip last component */
1052 while (l > 0 && path[l-1] != '/')
1055 /* Skip trailing slashes */
1056 while (l > 0 && path[l-1] == '/')
1062 if (!(t = strndup(path, l)))
1065 if (path_startswith(stop, t)) {
1074 if (errno != ENOENT)
1081 char hexchar(int x) {
1082 static const char table[16] = "0123456789abcdef";
1084 return table[x & 15];
1087 int unhexchar(char c) {
1089 if (c >= '0' && c <= '9')
1092 if (c >= 'a' && c <= 'f')
1093 return c - 'a' + 10;
1095 if (c >= 'A' && c <= 'F')
1096 return c - 'A' + 10;
1101 char *hexmem(const void *p, size_t l) {
1105 z = r = malloc(l * 2 + 1);
1109 for (x = p; x < (const uint8_t*) p + l; x++) {
1110 *(z++) = hexchar(*x >> 4);
1111 *(z++) = hexchar(*x & 15);
1118 void *unhexmem(const char *p, size_t l) {
1124 z = r = malloc((l + 1) / 2 + 1);
1128 for (x = p; x < p + l; x += 2) {
1131 a = unhexchar(x[0]);
1133 b = unhexchar(x[1]);
1137 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1144 char octchar(int x) {
1145 return '0' + (x & 7);
1148 int unoctchar(char c) {
1150 if (c >= '0' && c <= '7')
1156 char decchar(int x) {
1157 return '0' + (x % 10);
1160 int undecchar(char c) {
1162 if (c >= '0' && c <= '9')
1168 char *cescape(const char *s) {
1174 /* Does C style string escaping. */
1176 r = new(char, strlen(s)*4 + 1);
1180 for (f = s, t = r; *f; f++)
1226 /* For special chars we prefer octal over
1227 * hexadecimal encoding, simply because glib's
1228 * g_strescape() does the same */
1229 if ((*f < ' ') || (*f >= 127)) {
1231 *(t++) = octchar((unsigned char) *f >> 6);
1232 *(t++) = octchar((unsigned char) *f >> 3);
1233 *(t++) = octchar((unsigned char) *f);
1244 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1251 /* Undoes C style string escaping, and optionally prefixes it. */
1253 pl = prefix ? strlen(prefix) : 0;
1255 r = new(char, pl+length+1);
1260 memcpy(r, prefix, pl);
1262 for (f = s, t = r + pl; f < s + length; f++) {
1305 /* This is an extension of the XDG syntax files */
1310 /* hexadecimal encoding */
1313 a = unhexchar(f[1]);
1314 b = unhexchar(f[2]);
1316 if (a < 0 || b < 0) {
1317 /* Invalid escape code, let's take it literal then */
1321 *(t++) = (char) ((a << 4) | b);
1336 /* octal encoding */
1339 a = unoctchar(f[0]);
1340 b = unoctchar(f[1]);
1341 c = unoctchar(f[2]);
1343 if (a < 0 || b < 0 || c < 0) {
1344 /* Invalid escape code, let's take it literal then */
1348 *(t++) = (char) ((a << 6) | (b << 3) | c);
1356 /* premature end of string.*/
1361 /* Invalid escape code, let's take it literal then */
1373 char *cunescape_length(const char *s, size_t length) {
1374 return cunescape_length_with_prefix(s, length, NULL);
1377 char *cunescape(const char *s) {
1380 return cunescape_length(s, strlen(s));
1383 char *xescape(const char *s, const char *bad) {
1387 /* Escapes all chars in bad, in addition to \ and all special
1388 * chars, in \xFF style escaping. May be reversed with
1391 r = new(char, strlen(s) * 4 + 1);
1395 for (f = s, t = r; *f; f++) {
1397 if ((*f < ' ') || (*f >= 127) ||
1398 (*f == '\\') || strchr(bad, *f)) {
1401 *(t++) = hexchar(*f >> 4);
1402 *(t++) = hexchar(*f);
1412 char *bus_path_escape(const char *s) {
1418 /* Escapes all chars that D-Bus' object path cannot deal
1419 * with. Can be reverse with bus_path_unescape(). We special
1420 * case the empty string. */
1425 r = new(char, strlen(s)*3 + 1);
1429 for (f = s, t = r; *f; f++) {
1431 /* Escape everything that is not a-zA-Z0-9. We also
1432 * escape 0-9 if it's the first character */
1434 if (!(*f >= 'A' && *f <= 'Z') &&
1435 !(*f >= 'a' && *f <= 'z') &&
1436 !(f > s && *f >= '0' && *f <= '9')) {
1438 *(t++) = hexchar(*f >> 4);
1439 *(t++) = hexchar(*f);
1449 char *bus_path_unescape(const char *f) {
1454 /* Special case for the empty string */
1458 r = new(char, strlen(f) + 1);
1462 for (t = r; *f; f++) {
1467 if ((a = unhexchar(f[1])) < 0 ||
1468 (b = unhexchar(f[2])) < 0) {
1469 /* Invalid escape code, let's take it literal then */
1472 *(t++) = (char) ((a << 4) | b);
1484 char *ascii_strlower(char *t) {
1489 for (p = t; *p; p++)
1490 if (*p >= 'A' && *p <= 'Z')
1491 *p = *p - 'A' + 'a';
1496 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1500 filename[0] == '.' ||
1501 streq(filename, "lost+found") ||
1502 streq(filename, "aquota.user") ||
1503 streq(filename, "aquota.group") ||
1504 endswith(filename, ".rpmnew") ||
1505 endswith(filename, ".rpmsave") ||
1506 endswith(filename, ".rpmorig") ||
1507 endswith(filename, ".dpkg-old") ||
1508 endswith(filename, ".dpkg-new") ||
1509 endswith(filename, ".swp");
1512 bool ignore_file(const char *filename) {
1515 if (endswith(filename, "~"))
1518 return ignore_file_allow_backup(filename);
1521 int fd_nonblock(int fd, bool nonblock) {
1526 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1530 flags |= O_NONBLOCK;
1532 flags &= ~O_NONBLOCK;
1534 if (fcntl(fd, F_SETFL, flags) < 0)
1540 int fd_cloexec(int fd, bool cloexec) {
1545 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1549 flags |= FD_CLOEXEC;
1551 flags &= ~FD_CLOEXEC;
1553 if (fcntl(fd, F_SETFD, flags) < 0)
1559 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1562 assert(n_fdset == 0 || fdset);
1564 for (i = 0; i < n_fdset; i++)
1571 int close_all_fds(const int except[], unsigned n_except) {
1576 assert(n_except == 0 || except);
1578 d = opendir("/proc/self/fd");
1583 /* When /proc isn't available (for example in chroots)
1584 * the fallback is brute forcing through the fd
1587 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1588 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1590 if (fd_in_set(fd, except, n_except))
1593 if (close_nointr(fd) < 0)
1594 if (errno != EBADF && r == 0)
1601 while ((de = readdir(d))) {
1604 if (ignore_file(de->d_name))
1607 if (safe_atoi(de->d_name, &fd) < 0)
1608 /* Let's better ignore this, just in case */
1617 if (fd_in_set(fd, except, n_except))
1620 if (close_nointr(fd) < 0) {
1621 /* Valgrind has its own FD and doesn't want to have it closed */
1622 if (errno != EBADF && r == 0)
1631 bool chars_intersect(const char *a, const char *b) {
1634 /* Returns true if any of the chars in a are in b. */
1635 for (p = a; *p; p++)
1642 bool fstype_is_network(const char *fstype) {
1643 static const char table[] =
1653 return nulstr_contains(table, fstype);
1657 _cleanup_close_ int fd;
1659 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1665 TIOCL_GETKMSGREDIRECT,
1669 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1672 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1675 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1681 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1682 struct termios old_termios, new_termios;
1684 char line[LINE_MAX];
1689 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1690 new_termios = old_termios;
1692 new_termios.c_lflag &= ~ICANON;
1693 new_termios.c_cc[VMIN] = 1;
1694 new_termios.c_cc[VTIME] = 0;
1696 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1699 if (t != (usec_t) -1) {
1700 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1701 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1706 k = fread(&c, 1, 1, f);
1708 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1714 *need_nl = c != '\n';
1721 if (t != (usec_t) -1)
1722 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1725 if (!fgets(line, sizeof(line), f))
1730 if (strlen(line) != 1)
1740 int ask(char *ret, const char *replies, const char *text, ...) {
1750 bool need_nl = true;
1753 fputs(ANSI_HIGHLIGHT_ON, stdout);
1760 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1764 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1767 if (r == -EBADMSG) {
1768 puts("Bad input, please try again.");
1779 if (strchr(replies, c)) {
1784 puts("Read unexpected character, please try again.");
1788 int reset_terminal_fd(int fd, bool switch_to_text) {
1789 struct termios termios;
1792 /* Set terminal to some sane defaults */
1796 /* We leave locked terminal attributes untouched, so that
1797 * Plymouth may set whatever it wants to set, and we don't
1798 * interfere with that. */
1800 /* Disable exclusive mode, just in case */
1801 ioctl(fd, TIOCNXCL);
1803 /* Switch to text mode */
1805 ioctl(fd, KDSETMODE, KD_TEXT);
1807 /* Enable console unicode mode */
1808 ioctl(fd, KDSKBMODE, K_UNICODE);
1810 if (tcgetattr(fd, &termios) < 0) {
1815 /* We only reset the stuff that matters to the software. How
1816 * hardware is set up we don't touch assuming that somebody
1817 * else will do that for us */
1819 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1820 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1821 termios.c_oflag |= ONLCR;
1822 termios.c_cflag |= CREAD;
1823 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1825 termios.c_cc[VINTR] = 03; /* ^C */
1826 termios.c_cc[VQUIT] = 034; /* ^\ */
1827 termios.c_cc[VERASE] = 0177;
1828 termios.c_cc[VKILL] = 025; /* ^X */
1829 termios.c_cc[VEOF] = 04; /* ^D */
1830 termios.c_cc[VSTART] = 021; /* ^Q */
1831 termios.c_cc[VSTOP] = 023; /* ^S */
1832 termios.c_cc[VSUSP] = 032; /* ^Z */
1833 termios.c_cc[VLNEXT] = 026; /* ^V */
1834 termios.c_cc[VWERASE] = 027; /* ^W */
1835 termios.c_cc[VREPRINT] = 022; /* ^R */
1836 termios.c_cc[VEOL] = 0;
1837 termios.c_cc[VEOL2] = 0;
1839 termios.c_cc[VTIME] = 0;
1840 termios.c_cc[VMIN] = 1;
1842 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1846 /* Just in case, flush all crap out */
1847 tcflush(fd, TCIOFLUSH);
1852 int reset_terminal(const char *name) {
1855 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1859 r = reset_terminal_fd(fd, true);
1860 close_nointr_nofail(fd);
1865 int open_terminal(const char *name, int mode) {
1870 * If a TTY is in the process of being closed opening it might
1871 * cause EIO. This is horribly awful, but unlikely to be
1872 * changed in the kernel. Hence we work around this problem by
1873 * retrying a couple of times.
1875 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1878 assert(!(mode & O_CREAT));
1881 fd = open(name, mode, 0);
1888 /* Max 1s in total */
1892 usleep(50 * USEC_PER_MSEC);
1901 close_nointr_nofail(fd);
1906 close_nointr_nofail(fd);
1913 int flush_fd(int fd) {
1914 struct pollfd pollfd = {
1924 r = poll(&pollfd, 1, 0);
1934 l = read(fd, buf, sizeof(buf));
1940 if (errno == EAGAIN)
1949 int acquire_terminal(
1953 bool ignore_tiocstty_eperm,
1956 int fd = -1, notify = -1, r = 0, wd = -1;
1961 /* We use inotify to be notified when the tty is closed. We
1962 * create the watch before checking if we can actually acquire
1963 * it, so that we don't lose any event.
1965 * Note: strictly speaking this actually watches for the
1966 * device being closed, it does *not* really watch whether a
1967 * tty loses its controlling process. However, unless some
1968 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1969 * its tty otherwise this will not become a problem. As long
1970 * as the administrator makes sure not configure any service
1971 * on the same tty as an untrusted user this should not be a
1972 * problem. (Which he probably should not do anyway.) */
1974 if (timeout != (usec_t) -1)
1975 ts = now(CLOCK_MONOTONIC);
1977 if (!fail && !force) {
1978 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1984 wd = inotify_add_watch(notify, name, IN_CLOSE);
1992 struct sigaction sa_old, sa_new = {
1993 .sa_handler = SIG_IGN,
1994 .sa_flags = SA_RESTART,
1998 r = flush_fd(notify);
2003 /* We pass here O_NOCTTY only so that we can check the return
2004 * value TIOCSCTTY and have a reliable way to figure out if we
2005 * successfully became the controlling process of the tty */
2006 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2010 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2011 * if we already own the tty. */
2012 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2014 /* First, try to get the tty */
2015 if (ioctl(fd, TIOCSCTTY, force) < 0)
2018 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2020 /* Sometimes it makes sense to ignore TIOCSCTTY
2021 * returning EPERM, i.e. when very likely we already
2022 * are have this controlling terminal. */
2023 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2026 if (r < 0 && (force || fail || r != -EPERM)) {
2035 assert(notify >= 0);
2038 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2040 struct inotify_event *e;
2042 if (timeout != (usec_t) -1) {
2045 n = now(CLOCK_MONOTONIC);
2046 if (ts + timeout < n) {
2051 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2061 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2064 if (errno == EINTR || errno == EAGAIN)
2071 e = (struct inotify_event*) inotify_buffer;
2076 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2081 step = sizeof(struct inotify_event) + e->len;
2082 assert(step <= (size_t) l);
2084 e = (struct inotify_event*) ((uint8_t*) e + step);
2091 /* We close the tty fd here since if the old session
2092 * ended our handle will be dead. It's important that
2093 * we do this after sleeping, so that we don't enter
2094 * an endless loop. */
2095 close_nointr_nofail(fd);
2099 close_nointr_nofail(notify);
2101 r = reset_terminal_fd(fd, true);
2103 log_warning("Failed to reset terminal: %s", strerror(-r));
2109 close_nointr_nofail(fd);
2112 close_nointr_nofail(notify);
2117 int release_terminal(void) {
2119 struct sigaction sa_old, sa_new = {
2120 .sa_handler = SIG_IGN,
2121 .sa_flags = SA_RESTART,
2123 _cleanup_close_ int fd;
2125 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2129 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2130 * by our own TIOCNOTTY */
2131 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2133 if (ioctl(fd, TIOCNOTTY) < 0)
2136 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2141 int sigaction_many(const struct sigaction *sa, ...) {
2146 while ((sig = va_arg(ap, int)) > 0)
2147 if (sigaction(sig, sa, NULL) < 0)
2154 int ignore_signals(int sig, ...) {
2155 struct sigaction sa = {
2156 .sa_handler = SIG_IGN,
2157 .sa_flags = SA_RESTART,
2163 if (sigaction(sig, &sa, NULL) < 0)
2167 while ((sig = va_arg(ap, int)) > 0)
2168 if (sigaction(sig, &sa, NULL) < 0)
2175 int default_signals(int sig, ...) {
2176 struct sigaction sa = {
2177 .sa_handler = SIG_DFL,
2178 .sa_flags = SA_RESTART,
2183 if (sigaction(sig, &sa, NULL) < 0)
2187 while ((sig = va_arg(ap, int)) > 0)
2188 if (sigaction(sig, &sa, NULL) < 0)
2195 int close_pipe(int p[]) {
2201 a = close_nointr(p[0]);
2206 b = close_nointr(p[1]);
2210 return a < 0 ? a : b;
2213 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2222 while (nbytes > 0) {
2225 if ((k = read(fd, p, nbytes)) <= 0) {
2227 if (k < 0 && errno == EINTR)
2230 if (k < 0 && errno == EAGAIN && do_poll) {
2231 struct pollfd pollfd = {
2236 if (poll(&pollfd, 1, -1) < 0) {
2240 return n > 0 ? n : -errno;
2243 if (pollfd.revents != POLLIN)
2244 return n > 0 ? n : -EIO;
2249 return n > 0 ? n : (k < 0 ? -errno : 0);
2260 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2269 while (nbytes > 0) {
2272 k = write(fd, p, nbytes);
2275 if (k < 0 && errno == EINTR)
2278 if (k < 0 && errno == EAGAIN && do_poll) {
2279 struct pollfd pollfd = {
2284 if (poll(&pollfd, 1, -1) < 0) {
2288 return n > 0 ? n : -errno;
2291 if (pollfd.revents != POLLOUT)
2292 return n > 0 ? n : -EIO;
2297 return n > 0 ? n : (k < 0 ? -errno : 0);
2308 int parse_bytes(const char *t, off_t *bytes) {
2309 static const struct {
2311 unsigned long long factor;
2315 { "M", 1024ULL*1024ULL },
2316 { "G", 1024ULL*1024ULL*1024ULL },
2317 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2318 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2319 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2324 unsigned long long r = 0;
2336 l = strtoll(p, &e, 10);
2347 e += strspn(e, WHITESPACE);
2349 for (i = 0; i < ELEMENTSOF(table); i++)
2350 if (startswith(e, table[i].suffix)) {
2351 unsigned long long tmp;
2352 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2354 tmp = l * table[i].factor;
2355 if (tmp > ULLONG_MAX - r)
2359 if ((unsigned long long) (off_t) r != r)
2362 p = e + strlen(table[i].suffix);
2366 if (i >= ELEMENTSOF(table))
2376 int make_stdio(int fd) {
2381 r = dup3(fd, STDIN_FILENO, 0);
2382 s = dup3(fd, STDOUT_FILENO, 0);
2383 t = dup3(fd, STDERR_FILENO, 0);
2386 close_nointr_nofail(fd);
2388 if (r < 0 || s < 0 || t < 0)
2391 /* We rely here that the new fd has O_CLOEXEC not set */
2396 int make_null_stdio(void) {
2399 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2403 return make_stdio(null_fd);
2406 bool is_device_path(const char *path) {
2408 /* Returns true on paths that refer to a device, either in
2409 * sysfs or in /dev */
2412 path_startswith(path, "/dev/") ||
2413 path_startswith(path, "/sys/");
2416 int dir_is_empty(const char *path) {
2417 _cleanup_closedir_ DIR *d;
2426 union dirent_storage buf;
2428 r = readdir_r(d, &buf.de, &de);
2435 if (!ignore_file(de->d_name))
2440 char* dirname_malloc(const char *path) {
2441 char *d, *dir, *dir2;
2458 unsigned long long random_ull(void) {
2459 _cleanup_close_ int fd;
2463 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2467 r = loop_read(fd, &ull, sizeof(ull), true);
2468 if (r != sizeof(ull))
2474 return random() * RAND_MAX + random();
2477 void rename_process(const char name[8]) {
2480 /* This is a like a poor man's setproctitle(). It changes the
2481 * comm field, argv[0], and also the glibc's internally used
2482 * name of the process. For the first one a limit of 16 chars
2483 * applies, to the second one usually one of 10 (i.e. length
2484 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2485 * "systemd"). If you pass a longer string it will be
2488 prctl(PR_SET_NAME, name);
2490 if (program_invocation_name)
2491 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2493 if (saved_argc > 0) {
2497 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2499 for (i = 1; i < saved_argc; i++) {
2503 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2508 void sigset_add_many(sigset_t *ss, ...) {
2515 while ((sig = va_arg(ap, int)) > 0)
2516 assert_se(sigaddset(ss, sig) == 0);
2520 char* gethostname_malloc(void) {
2523 assert_se(uname(&u) >= 0);
2525 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2526 return strdup(u.nodename);
2528 return strdup(u.sysname);
2531 bool hostname_is_set(void) {
2534 assert_se(uname(&u) >= 0);
2536 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2539 static char *lookup_uid(uid_t uid) {
2542 _cleanup_free_ char *buf = NULL;
2543 struct passwd pwbuf, *pw = NULL;
2545 /* Shortcut things to avoid NSS lookups */
2547 return strdup("root");
2549 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2553 buf = malloc(bufsize);
2557 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2558 return strdup(pw->pw_name);
2560 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2566 char* getlogname_malloc(void) {
2570 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2575 return lookup_uid(uid);
2578 char *getusername_malloc(void) {
2585 return lookup_uid(getuid());
2588 int getttyname_malloc(int fd, char **r) {
2589 char path[PATH_MAX], *c;
2594 k = ttyname_r(fd, path, sizeof(path));
2600 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2608 int getttyname_harder(int fd, char **r) {
2612 k = getttyname_malloc(fd, &s);
2616 if (streq(s, "tty")) {
2618 return get_ctty(0, NULL, r);
2625 int get_ctty_devnr(pid_t pid, dev_t *d) {
2626 _cleanup_fclose_ FILE *f = NULL;
2627 char line[LINE_MAX], *p;
2628 unsigned long ttynr;
2636 fn = "/proc/self/stat";
2638 fn = procfs_file_alloca(pid, "stat");
2640 f = fopen(fn, "re");
2644 if (!fgets(line, sizeof(line), f)) {
2645 k = feof(f) ? -EIO : -errno;
2649 p = strrchr(line, ')');
2659 "%*d " /* session */
2664 if (major(ttynr) == 0 && minor(ttynr) == 0)
2671 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2673 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2678 k = get_ctty_devnr(pid, &devnr);
2682 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2684 k = readlink_malloc(fn, &s);
2690 /* This is an ugly hack */
2691 if (major(devnr) == 136) {
2692 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2702 /* Probably something like the ptys which have no
2703 * symlink in /dev/char. Let's return something
2704 * vaguely useful. */
2717 if (startswith(s, "/dev/"))
2719 else if (startswith(s, "../"))
2737 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2743 /* This returns the first error we run into, but nevertheless
2744 * tries to go on. This closes the passed fd. */
2748 close_nointr_nofail(fd);
2750 return errno == ENOENT ? 0 : -errno;
2755 union dirent_storage buf;
2756 bool is_dir, keep_around;
2760 r = readdir_r(d, &buf.de, &de);
2761 if (r != 0 && ret == 0) {
2769 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2772 if (de->d_type == DT_UNKNOWN ||
2774 (de->d_type == DT_DIR && root_dev)) {
2775 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2776 if (ret == 0 && errno != ENOENT)
2781 is_dir = S_ISDIR(st.st_mode);
2784 (st.st_uid == 0 || st.st_uid == getuid()) &&
2785 (st.st_mode & S_ISVTX);
2787 is_dir = de->d_type == DT_DIR;
2788 keep_around = false;
2794 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2795 if (root_dev && st.st_dev != root_dev->st_dev)
2798 subdir_fd = openat(fd, de->d_name,
2799 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2800 if (subdir_fd < 0) {
2801 if (ret == 0 && errno != ENOENT)
2806 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2807 if (r < 0 && ret == 0)
2811 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2812 if (ret == 0 && errno != ENOENT)
2816 } else if (!only_dirs && !keep_around) {
2818 if (unlinkat(fd, de->d_name, 0) < 0) {
2819 if (ret == 0 && errno != ENOENT)
2830 _pure_ static int is_temporary_fs(struct statfs *s) {
2833 F_TYPE_CMP(s->f_type, TMPFS_MAGIC) ||
2834 F_TYPE_CMP(s->f_type, RAMFS_MAGIC);
2837 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2842 if (fstatfs(fd, &s) < 0) {
2843 close_nointr_nofail(fd);
2847 /* We refuse to clean disk file systems with this call. This
2848 * is extra paranoia just to be sure we never ever remove
2850 if (!is_temporary_fs(&s)) {
2851 log_error("Attempted to remove disk file system, and we can't allow that.");
2852 close_nointr_nofail(fd);
2856 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2859 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2865 /* We refuse to clean the root file system with this
2866 * call. This is extra paranoia to never cause a really
2867 * seriously broken system. */
2868 if (path_equal(path, "/")) {
2869 log_error("Attempted to remove entire root file system, and we can't allow that.");
2873 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2876 if (errno != ENOTDIR)
2880 if (statfs(path, &s) < 0)
2883 if (!is_temporary_fs(&s)) {
2884 log_error("Attempted to remove disk file system, and we can't allow that.");
2889 if (delete_root && !only_dirs)
2890 if (unlink(path) < 0 && errno != ENOENT)
2897 if (fstatfs(fd, &s) < 0) {
2898 close_nointr_nofail(fd);
2902 if (!is_temporary_fs(&s)) {
2903 log_error("Attempted to remove disk file system, and we can't allow that.");
2904 close_nointr_nofail(fd);
2909 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2912 if (honour_sticky && file_is_priv_sticky(path) > 0)
2915 if (rmdir(path) < 0 && errno != ENOENT) {
2924 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2925 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2928 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2929 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2932 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2935 /* Under the assumption that we are running privileged we
2936 * first change the access mode and only then hand out
2937 * ownership to avoid a window where access is too open. */
2939 if (mode != (mode_t) -1)
2940 if (chmod(path, mode) < 0)
2943 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2944 if (chown(path, uid, gid) < 0)
2950 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2953 /* Under the assumption that we are running privileged we
2954 * first change the access mode and only then hand out
2955 * ownership to avoid a window where access is too open. */
2957 if (fchmod(fd, mode) < 0)
2960 if (fchown(fd, uid, gid) < 0)
2966 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2970 /* Allocates the cpuset in the right size */
2973 if (!(r = CPU_ALLOC(n)))
2976 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2977 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2987 if (errno != EINVAL)
2994 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2995 static const char status_indent[] = " "; /* "[" STATUS "] " */
2996 _cleanup_free_ char *s = NULL;
2997 _cleanup_close_ int fd = -1;
2998 struct iovec iovec[6] = {};
3000 static bool prev_ephemeral;
3004 /* This is independent of logging, as status messages are
3005 * optional and go exclusively to the console. */
3007 if (vasprintf(&s, format, ap) < 0)
3010 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3023 sl = status ? sizeof(status_indent)-1 : 0;
3029 e = ellipsize(s, emax, 75);
3037 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3038 prev_ephemeral = ephemeral;
3041 if (!isempty(status)) {
3042 IOVEC_SET_STRING(iovec[n++], "[");
3043 IOVEC_SET_STRING(iovec[n++], status);
3044 IOVEC_SET_STRING(iovec[n++], "] ");
3046 IOVEC_SET_STRING(iovec[n++], status_indent);
3049 IOVEC_SET_STRING(iovec[n++], s);
3051 IOVEC_SET_STRING(iovec[n++], "\n");
3053 if (writev(fd, iovec, n) < 0)
3059 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3065 va_start(ap, format);
3066 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3072 int status_welcome(void) {
3074 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3076 r = parse_env_file("/etc/os-release", NEWLINE,
3077 "PRETTY_NAME", &pretty_name,
3078 "ANSI_COLOR", &ansi_color,
3080 if (r < 0 && r != -ENOENT)
3081 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3083 return status_printf(NULL, false, false,
3084 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3085 isempty(ansi_color) ? "1" : ansi_color,
3086 isempty(pretty_name) ? "Linux" : pretty_name);
3089 char *replace_env(const char *format, char **env) {
3096 const char *e, *word = format;
3101 for (e = format; *e; e ++) {
3112 if (!(k = strnappend(r, word, e-word-1)))
3121 } else if (*e == '$') {
3122 if (!(k = strnappend(r, word, e-word)))
3138 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3140 k = strappend(r, t);
3154 if (!(k = strnappend(r, word, e-word)))
3165 char **replace_env_argv(char **argv, char **env) {
3167 unsigned k = 0, l = 0;
3169 l = strv_length(argv);
3171 if (!(r = new(char*, l+1)))
3174 STRV_FOREACH(i, argv) {
3176 /* If $FOO appears as single word, replace it by the split up variable */
3177 if ((*i)[0] == '$' && (*i)[1] != '{') {
3182 e = strv_env_get(env, *i+1);
3185 if (!(m = strv_split_quoted(e))) {
3196 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3205 memcpy(r + k, m, q * sizeof(char*));
3213 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3214 if (!(r[k++] = replace_env(*i, env))) {
3224 int fd_columns(int fd) {
3225 struct winsize ws = {};
3227 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3236 unsigned columns(void) {
3240 if (_likely_(cached_columns > 0))
3241 return cached_columns;
3244 e = getenv("COLUMNS");
3249 c = fd_columns(STDOUT_FILENO);
3258 int fd_lines(int fd) {
3259 struct winsize ws = {};
3261 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3270 unsigned lines(void) {
3274 if (_likely_(cached_lines > 0))
3275 return cached_lines;
3278 e = getenv("LINES");
3283 l = fd_lines(STDOUT_FILENO);
3289 return cached_lines;
3292 /* intended to be used as a SIGWINCH sighandler */
3293 void columns_lines_cache_reset(int signum) {
3299 static int cached_on_tty = -1;
3301 if (_unlikely_(cached_on_tty < 0))
3302 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3304 return cached_on_tty;
3307 int running_in_chroot(void) {
3308 struct stat a = {}, b = {};
3310 /* Only works as root */
3311 if (stat("/proc/1/root", &a) < 0)
3314 if (stat("/", &b) < 0)
3318 a.st_dev != b.st_dev ||
3319 a.st_ino != b.st_ino;
3322 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3327 assert(percent <= 100);
3328 assert(new_length >= 3);
3330 if (old_length <= 3 || old_length <= new_length)
3331 return strndup(s, old_length);
3333 r = new0(char, new_length+1);
3337 x = (new_length * percent) / 100;
3339 if (x > new_length - 3)
3347 s + old_length - (new_length - x - 3),
3348 new_length - x - 3);
3353 char *ellipsize(const char *s, size_t length, unsigned percent) {
3354 return ellipsize_mem(s, strlen(s), length, percent);
3357 int touch(const char *path) {
3362 /* This just opens the file for writing, ensuring it
3363 * exists. It doesn't call utimensat() the way /usr/bin/touch
3366 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3370 close_nointr_nofail(fd);
3374 char *unquote(const char *s, const char* quotes) {
3378 /* This is rather stupid, simply removes the heading and
3379 * trailing quotes if there is one. Doesn't care about
3380 * escaping or anything. We should make this smarter one
3387 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3388 return strndup(s+1, l-2);
3393 char *normalize_env_assignment(const char *s) {
3394 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3397 eq = strchr(s, '=');
3409 memmove(r, t, strlen(t) + 1);
3413 name = strndup(s, eq - s);
3421 value = unquote(strstrip(p), QUOTES);
3425 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3431 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3442 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3454 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3461 r = wait_for_terminate(pid, &status);
3463 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3467 if (status.si_code == CLD_EXITED) {
3468 if (status.si_status != 0) {
3469 log_warning("%s failed with error code %i.", name, status.si_status);
3470 return status.si_status;
3473 log_debug("%s succeeded.", name);
3476 } else if (status.si_code == CLD_KILLED ||
3477 status.si_code == CLD_DUMPED) {
3479 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3483 log_warning("%s failed due to unknown reason.", name);
3487 _noreturn_ void freeze(void) {
3489 /* Make sure nobody waits for us on a socket anymore */
3490 close_all_fds(NULL, 0);
3498 bool null_or_empty(struct stat *st) {
3501 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3504 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3510 int null_or_empty_path(const char *fn) {
3515 if (stat(fn, &st) < 0)
3518 return null_or_empty(&st);
3521 DIR *xopendirat(int fd, const char *name, int flags) {
3525 assert(!(flags & O_CREAT));
3527 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3533 close_nointr_nofail(nfd);
3540 int signal_from_string_try_harder(const char *s) {
3544 signo = signal_from_string(s);
3546 if (startswith(s, "SIG"))
3547 return signal_from_string(s+3);
3552 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3556 /* FIXME: to follow udev's logic 100% we need to leave valid
3557 * UTF8 chars unescaped */
3559 u = unquote(tagvalue, "\"\'");
3563 t = xescape(u, "/ ");
3569 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3578 char *fstab_node_to_udev_node(const char *p) {
3581 if (startswith(p, "LABEL="))
3582 return tag_to_udev_node(p+6, "label");
3584 if (startswith(p, "UUID="))
3585 return tag_to_udev_node(p+5, "uuid");
3587 if (startswith(p, "PARTUUID="))
3588 return tag_to_udev_node(p+9, "partuuid");
3590 if (startswith(p, "PARTLABEL="))
3591 return tag_to_udev_node(p+10, "partlabel");
3596 bool tty_is_vc(const char *tty) {
3599 if (startswith(tty, "/dev/"))
3602 return vtnr_from_tty(tty) >= 0;
3605 bool tty_is_console(const char *tty) {
3608 if (startswith(tty, "/dev/"))
3611 return streq(tty, "console");
3614 int vtnr_from_tty(const char *tty) {
3619 if (startswith(tty, "/dev/"))
3622 if (!startswith(tty, "tty") )
3625 if (tty[3] < '0' || tty[3] > '9')
3628 r = safe_atoi(tty+3, &i);
3632 if (i < 0 || i > 63)
3638 char *resolve_dev_console(char **active) {
3641 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3642 * (i.e. not read-only-mounted which is a sign for container setups) */
3644 if (path_is_read_only_fs("/sys") > 0)
3647 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3650 /* If multiple log outputs are configured the last one is what
3651 * /dev/console points to */
3652 tty = strrchr(*active, ' ');
3661 bool tty_is_vc_resolve(const char *tty) {
3662 char *active = NULL;
3667 if (startswith(tty, "/dev/"))
3670 if (streq(tty, "console")) {
3671 tty = resolve_dev_console(&active);
3682 const char *default_term_for_tty(const char *tty) {
3685 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3688 bool dirent_is_file(const struct dirent *de) {
3691 if (ignore_file(de->d_name))
3694 if (de->d_type != DT_REG &&
3695 de->d_type != DT_LNK &&
3696 de->d_type != DT_UNKNOWN)
3702 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3705 if (de->d_type != DT_REG &&
3706 de->d_type != DT_LNK &&
3707 de->d_type != DT_UNKNOWN)
3710 if (ignore_file_allow_backup(de->d_name))
3713 return endswith(de->d_name, suffix);
3716 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3719 Hashmap *pids = NULL;
3723 /* Executes all binaries in a directory in parallel and
3724 * waits for them to finish. */
3727 if (!(_d = opendir(directory))) {
3729 if (errno == ENOENT)
3732 log_error("Failed to enumerate directory %s: %m", directory);
3739 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3740 log_error("Failed to allocate set.");
3744 while ((de = readdir(d))) {
3749 if (!dirent_is_file(de))
3752 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3757 if ((pid = fork()) < 0) {
3758 log_error("Failed to fork: %m");
3776 log_error("Failed to execute %s: %m", path);
3777 _exit(EXIT_FAILURE);
3780 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3782 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3783 log_error("Failed to add PID to set: %s", strerror(-k));
3788 while (!hashmap_isempty(pids)) {
3789 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3793 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3798 log_error("waitid() failed: %m");
3802 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3803 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3804 if (si.si_code == CLD_EXITED)
3805 log_error("%s exited with exit status %i.", path, si.si_status);
3807 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3809 log_debug("%s exited successfully.", path);
3820 hashmap_free_free(pids);
3823 int kill_and_sigcont(pid_t pid, int sig) {
3826 r = kill(pid, sig) < 0 ? -errno : 0;
3834 bool nulstr_contains(const char*nulstr, const char *needle) {
3840 NULSTR_FOREACH(i, nulstr)
3841 if (streq(i, needle))
3847 bool plymouth_running(void) {
3848 return access("/run/plymouth/pid", F_OK) >= 0;
3851 char* strshorten(char *s, size_t l) {
3860 static bool hostname_valid_char(char c) {
3862 (c >= 'a' && c <= 'z') ||
3863 (c >= 'A' && c <= 'Z') ||
3864 (c >= '0' && c <= '9') ||
3870 bool hostname_is_valid(const char *s) {
3877 for (p = s, dot = true; *p; p++) {
3884 if (!hostname_valid_char(*p))
3894 if (p-s > HOST_NAME_MAX)
3900 char* hostname_cleanup(char *s, bool lowercase) {
3904 for (p = s, d = s, dot = true; *p; p++) {
3911 } else if (hostname_valid_char(*p)) {
3912 *(d++) = lowercase ? tolower(*p) : *p;
3923 strshorten(s, HOST_NAME_MAX);
3928 int pipe_eof(int fd) {
3930 struct pollfd pollfd = {
3932 .events = POLLIN|POLLHUP,
3935 r = poll(&pollfd, 1, 0);
3942 return pollfd.revents & POLLHUP;
3945 int fd_wait_for_event(int fd, int event, usec_t t) {
3947 struct pollfd pollfd = {
3952 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3959 return pollfd.revents;
3962 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3973 t = new(char, strlen(path) + 1 + 6 + 1);
3977 fn = path_get_file_name(path);
3981 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3983 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3989 f = fdopen(fd, "we");
4002 int terminal_vhangup_fd(int fd) {
4005 if (ioctl(fd, TIOCVHANGUP) < 0)
4011 int terminal_vhangup(const char *name) {
4014 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4018 r = terminal_vhangup_fd(fd);
4019 close_nointr_nofail(fd);
4024 int vt_disallocate(const char *name) {
4028 /* Deallocate the VT if possible. If not possible
4029 * (i.e. because it is the active one), at least clear it
4030 * entirely (including the scrollback buffer) */
4032 if (!startswith(name, "/dev/"))
4035 if (!tty_is_vc(name)) {
4036 /* So this is not a VT. I guess we cannot deallocate
4037 * it then. But let's at least clear the screen */
4039 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4044 "\033[r" /* clear scrolling region */
4045 "\033[H" /* move home */
4046 "\033[2J", /* clear screen */
4048 close_nointr_nofail(fd);
4053 if (!startswith(name, "/dev/tty"))
4056 r = safe_atou(name+8, &u);
4063 /* Try to deallocate */
4064 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4068 r = ioctl(fd, VT_DISALLOCATE, u);
4069 close_nointr_nofail(fd);
4077 /* Couldn't deallocate, so let's clear it fully with
4079 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4084 "\033[r" /* clear scrolling region */
4085 "\033[H" /* move home */
4086 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4088 close_nointr_nofail(fd);
4093 int copy_file(const char *from, const char *to) {
4099 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4103 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4105 close_nointr_nofail(fdf);
4113 n = read(fdf, buf, sizeof(buf));
4117 close_nointr_nofail(fdf);
4128 k = loop_write(fdt, buf, n, false);
4130 r = k < 0 ? k : (errno ? -errno : -EIO);
4132 close_nointr_nofail(fdf);
4140 close_nointr_nofail(fdf);
4141 r = close_nointr(fdt);
4151 int symlink_atomic(const char *from, const char *to) {
4153 _cleanup_free_ char *t;
4156 unsigned long long ull;
4163 t = new(char, strlen(to) + 1 + 16 + 1);
4167 fn = path_get_file_name(to);
4171 x = stpcpy(t+k+1, fn);
4174 for (i = 0; i < 16; i++) {
4175 *(x++) = hexchar(ull & 0xF);
4181 if (symlink(from, t) < 0)
4184 if (rename(t, to) < 0) {
4193 bool display_is_local(const char *display) {
4197 display[0] == ':' &&
4198 display[1] >= '0' &&
4202 int socket_from_display(const char *display, char **path) {
4209 if (!display_is_local(display))
4212 k = strspn(display+1, "0123456789");
4214 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4218 c = stpcpy(f, "/tmp/.X11-unix/X");
4219 memcpy(c, display+1, k);
4228 const char **username,
4229 uid_t *uid, gid_t *gid,
4231 const char **shell) {
4239 /* We enforce some special rules for uid=0: in order to avoid
4240 * NSS lookups for root we hardcode its data. */
4242 if (streq(*username, "root") || streq(*username, "0")) {
4260 if (parse_uid(*username, &u) >= 0) {
4264 /* If there are multiple users with the same id, make
4265 * sure to leave $USER to the configured value instead
4266 * of the first occurrence in the database. However if
4267 * the uid was configured by a numeric uid, then let's
4268 * pick the real username from /etc/passwd. */
4270 *username = p->pw_name;
4273 p = getpwnam(*username);
4277 return errno > 0 ? -errno : -ESRCH;
4289 *shell = p->pw_shell;
4294 char* uid_to_name(uid_t uid) {
4299 return strdup("root");
4303 return strdup(p->pw_name);
4305 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4311 char* gid_to_name(gid_t gid) {
4316 return strdup("root");
4320 return strdup(p->gr_name);
4322 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4328 int get_group_creds(const char **groupname, gid_t *gid) {
4334 /* We enforce some special rules for gid=0: in order to avoid
4335 * NSS lookups for root we hardcode its data. */
4337 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4338 *groupname = "root";
4346 if (parse_gid(*groupname, &id) >= 0) {
4351 *groupname = g->gr_name;
4354 g = getgrnam(*groupname);
4358 return errno > 0 ? -errno : -ESRCH;
4366 int in_gid(gid_t gid) {
4368 int ngroups_max, r, i;
4370 if (getgid() == gid)
4373 if (getegid() == gid)
4376 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4377 assert(ngroups_max > 0);
4379 gids = alloca(sizeof(gid_t) * ngroups_max);
4381 r = getgroups(ngroups_max, gids);
4385 for (i = 0; i < r; i++)
4392 int in_group(const char *name) {
4396 r = get_group_creds(&name, &gid);
4403 int glob_exists(const char *path) {
4404 _cleanup_globfree_ glob_t g = {};
4410 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4412 if (k == GLOB_NOMATCH)
4414 else if (k == GLOB_NOSPACE)
4417 return !strv_isempty(g.gl_pathv);
4419 return errno ? -errno : -EIO;
4422 int glob_extend(char ***strv, const char *path) {
4423 _cleanup_globfree_ glob_t g = {};
4428 k = glob(optarg, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4430 if (k == GLOB_NOMATCH)
4432 else if (k == GLOB_NOSPACE)
4434 else if (k != 0 || strv_isempty(g.gl_pathv))
4435 return errno ? -errno : -EIO;
4437 STRV_FOREACH(p, g.gl_pathv) {
4438 k = strv_extend(strv, *p);
4446 int dirent_ensure_type(DIR *d, struct dirent *de) {
4452 if (de->d_type != DT_UNKNOWN)
4455 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4459 S_ISREG(st.st_mode) ? DT_REG :
4460 S_ISDIR(st.st_mode) ? DT_DIR :
4461 S_ISLNK(st.st_mode) ? DT_LNK :
4462 S_ISFIFO(st.st_mode) ? DT_FIFO :
4463 S_ISSOCK(st.st_mode) ? DT_SOCK :
4464 S_ISCHR(st.st_mode) ? DT_CHR :
4465 S_ISBLK(st.st_mode) ? DT_BLK :
4471 int in_search_path(const char *path, char **search) {
4475 r = path_get_parent(path, &parent);
4481 STRV_FOREACH(i, search) {
4482 if (path_equal(parent, *i)) {
4493 int get_files_in_directory(const char *path, char ***list) {
4501 /* Returns all files in a directory in *list, and the number
4502 * of files as return value. If list is NULL returns only the
4511 union dirent_storage buf;
4514 k = readdir_r(d, &buf.de, &de);
4523 dirent_ensure_type(d, de);
4525 if (!dirent_is_file(de))
4529 if ((unsigned) r >= n) {
4533 t = realloc(l, sizeof(char*) * n);
4542 assert((unsigned) r < n);
4544 l[r] = strdup(de->d_name);
4568 char *strjoin(const char *x, ...) {
4582 t = va_arg(ap, const char *);
4587 if (n > ((size_t) -1) - l) {
4611 t = va_arg(ap, const char *);
4625 bool is_main_thread(void) {
4626 static __thread int cached = 0;
4628 if (_unlikely_(cached == 0))
4629 cached = getpid() == gettid() ? 1 : -1;
4634 int block_get_whole_disk(dev_t d, dev_t *ret) {
4641 /* If it has a queue this is good enough for us */
4642 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4645 r = access(p, F_OK);
4653 /* If it is a partition find the originating device */
4654 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4657 r = access(p, F_OK);
4663 /* Get parent dev_t */
4664 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4667 r = read_one_line_file(p, &s);
4673 r = sscanf(s, "%u:%u", &m, &n);
4679 /* Only return this if it is really good enough for us. */
4680 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4683 r = access(p, F_OK);
4687 *ret = makedev(m, n);
4694 int file_is_priv_sticky(const char *p) {
4699 if (lstat(p, &st) < 0)
4703 (st.st_uid == 0 || st.st_uid == getuid()) &&
4704 (st.st_mode & S_ISVTX);
4707 static const char *const ioprio_class_table[] = {
4708 [IOPRIO_CLASS_NONE] = "none",
4709 [IOPRIO_CLASS_RT] = "realtime",
4710 [IOPRIO_CLASS_BE] = "best-effort",
4711 [IOPRIO_CLASS_IDLE] = "idle"
4714 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4716 static const char *const sigchld_code_table[] = {
4717 [CLD_EXITED] = "exited",
4718 [CLD_KILLED] = "killed",
4719 [CLD_DUMPED] = "dumped",
4720 [CLD_TRAPPED] = "trapped",
4721 [CLD_STOPPED] = "stopped",
4722 [CLD_CONTINUED] = "continued",
4725 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4727 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4728 [LOG_FAC(LOG_KERN)] = "kern",
4729 [LOG_FAC(LOG_USER)] = "user",
4730 [LOG_FAC(LOG_MAIL)] = "mail",
4731 [LOG_FAC(LOG_DAEMON)] = "daemon",
4732 [LOG_FAC(LOG_AUTH)] = "auth",
4733 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4734 [LOG_FAC(LOG_LPR)] = "lpr",
4735 [LOG_FAC(LOG_NEWS)] = "news",
4736 [LOG_FAC(LOG_UUCP)] = "uucp",
4737 [LOG_FAC(LOG_CRON)] = "cron",
4738 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4739 [LOG_FAC(LOG_FTP)] = "ftp",
4740 [LOG_FAC(LOG_LOCAL0)] = "local0",
4741 [LOG_FAC(LOG_LOCAL1)] = "local1",
4742 [LOG_FAC(LOG_LOCAL2)] = "local2",
4743 [LOG_FAC(LOG_LOCAL3)] = "local3",
4744 [LOG_FAC(LOG_LOCAL4)] = "local4",
4745 [LOG_FAC(LOG_LOCAL5)] = "local5",
4746 [LOG_FAC(LOG_LOCAL6)] = "local6",
4747 [LOG_FAC(LOG_LOCAL7)] = "local7"
4750 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4752 static const char *const log_level_table[] = {
4753 [LOG_EMERG] = "emerg",
4754 [LOG_ALERT] = "alert",
4755 [LOG_CRIT] = "crit",
4757 [LOG_WARNING] = "warning",
4758 [LOG_NOTICE] = "notice",
4759 [LOG_INFO] = "info",
4760 [LOG_DEBUG] = "debug"
4763 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4765 static const char* const sched_policy_table[] = {
4766 [SCHED_OTHER] = "other",
4767 [SCHED_BATCH] = "batch",
4768 [SCHED_IDLE] = "idle",
4769 [SCHED_FIFO] = "fifo",
4773 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4775 static const char* const rlimit_table[] = {
4776 [RLIMIT_CPU] = "LimitCPU",
4777 [RLIMIT_FSIZE] = "LimitFSIZE",
4778 [RLIMIT_DATA] = "LimitDATA",
4779 [RLIMIT_STACK] = "LimitSTACK",
4780 [RLIMIT_CORE] = "LimitCORE",
4781 [RLIMIT_RSS] = "LimitRSS",
4782 [RLIMIT_NOFILE] = "LimitNOFILE",
4783 [RLIMIT_AS] = "LimitAS",
4784 [RLIMIT_NPROC] = "LimitNPROC",
4785 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4786 [RLIMIT_LOCKS] = "LimitLOCKS",
4787 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4788 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4789 [RLIMIT_NICE] = "LimitNICE",
4790 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4791 [RLIMIT_RTTIME] = "LimitRTTIME"
4794 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4796 static const char* const ip_tos_table[] = {
4797 [IPTOS_LOWDELAY] = "low-delay",
4798 [IPTOS_THROUGHPUT] = "throughput",
4799 [IPTOS_RELIABILITY] = "reliability",
4800 [IPTOS_LOWCOST] = "low-cost",
4803 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4805 static const char *const __signal_table[] = {
4822 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4833 [SIGVTALRM] = "VTALRM",
4835 [SIGWINCH] = "WINCH",
4841 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4843 const char *signal_to_string(int signo) {
4844 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4847 name = __signal_to_string(signo);
4851 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4852 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4854 snprintf(buf, sizeof(buf), "%d", signo);
4859 int signal_from_string(const char *s) {
4864 signo = __signal_from_string(s);
4868 if (startswith(s, "RTMIN+")) {
4872 if (safe_atou(s, &u) >= 0) {
4873 signo = (int) u + offset;
4874 if (signo > 0 && signo < _NSIG)
4880 bool kexec_loaded(void) {
4881 bool loaded = false;
4884 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4892 int strdup_or_null(const char *a, char **b) {
4910 int prot_from_flags(int flags) {
4912 switch (flags & O_ACCMODE) {
4921 return PROT_READ|PROT_WRITE;
4928 char *format_bytes(char *buf, size_t l, off_t t) {
4931 static const struct {
4935 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4936 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4937 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4938 { "G", 1024ULL*1024ULL*1024ULL },
4939 { "M", 1024ULL*1024ULL },
4943 for (i = 0; i < ELEMENTSOF(table); i++) {
4945 if (t >= table[i].factor) {
4948 (unsigned long long) (t / table[i].factor),
4949 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4956 snprintf(buf, l, "%lluB", (unsigned long long) t);
4964 void* memdup(const void *p, size_t l) {
4977 int fd_inc_sndbuf(int fd, size_t n) {
4979 socklen_t l = sizeof(value);
4981 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4983 l == sizeof(value) &&
4984 (size_t) value >= n*2)
4988 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4995 int fd_inc_rcvbuf(int fd, size_t n) {
4997 socklen_t l = sizeof(value);
4999 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5001 l == sizeof(value) &&
5002 (size_t) value >= n*2)
5006 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5013 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5014 pid_t parent_pid, agent_pid;
5016 bool stdout_is_tty, stderr_is_tty;
5024 parent_pid = getpid();
5026 /* Spawns a temporary TTY agent, making sure it goes away when
5033 if (agent_pid != 0) {
5040 * Make sure the agent goes away when the parent dies */
5041 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5042 _exit(EXIT_FAILURE);
5044 /* Check whether our parent died before we were able
5045 * to set the death signal */
5046 if (getppid() != parent_pid)
5047 _exit(EXIT_SUCCESS);
5049 /* Don't leak fds to the agent */
5050 close_all_fds(except, n_except);
5052 stdout_is_tty = isatty(STDOUT_FILENO);
5053 stderr_is_tty = isatty(STDERR_FILENO);
5055 if (!stdout_is_tty || !stderr_is_tty) {
5056 /* Detach from stdout/stderr. and reopen
5057 * /dev/tty for them. This is important to
5058 * ensure that when systemctl is started via
5059 * popen() or a similar call that expects to
5060 * read EOF we actually do generate EOF and
5061 * not delay this indefinitely by because we
5062 * keep an unused copy of stdin around. */
5063 fd = open("/dev/tty", O_WRONLY);
5065 log_error("Failed to open /dev/tty: %m");
5066 _exit(EXIT_FAILURE);
5070 dup2(fd, STDOUT_FILENO);
5073 dup2(fd, STDERR_FILENO);
5079 /* Count arguments */
5081 for (n = 0; va_arg(ap, char*); n++)
5086 l = alloca(sizeof(char *) * (n + 1));
5088 /* Fill in arguments */
5090 for (i = 0; i <= n; i++)
5091 l[i] = va_arg(ap, char*);
5095 _exit(EXIT_FAILURE);
5098 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5099 struct rlimit highest, fixed;
5103 if (setrlimit(resource, rlim) >= 0)
5109 /* So we failed to set the desired setrlimit, then let's try
5110 * to get as close as we can */
5111 assert_se(getrlimit(resource, &highest) == 0);
5113 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5114 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5116 if (setrlimit(resource, &fixed) < 0)
5122 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5123 _cleanup_fclose_ FILE *f = NULL;
5135 path = "/proc/self/environ";
5137 path = procfs_file_alloca(pid, "environ");
5139 f = fopen(path, "re");
5147 char line[LINE_MAX];
5150 for (i = 0; i < sizeof(line)-1; i++) {
5154 if (_unlikely_(c == EOF)) {
5164 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5165 value = strdup(line + l + 1);
5179 bool is_valid_documentation_url(const char *url) {
5182 if (startswith(url, "http://") && url[7])
5185 if (startswith(url, "https://") && url[8])
5188 if (startswith(url, "file:") && url[5])
5191 if (startswith(url, "info:") && url[5])
5194 if (startswith(url, "man:") && url[4])
5200 bool in_initrd(void) {
5201 static __thread int saved = -1;
5207 /* We make two checks here:
5209 * 1. the flag file /etc/initrd-release must exist
5210 * 2. the root file system must be a memory file system
5212 * The second check is extra paranoia, since misdetecting an
5213 * initrd can have bad bad consequences due the initrd
5214 * emptying when transititioning to the main systemd.
5217 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5218 statfs("/", &s) >= 0 &&
5219 is_temporary_fs(&s);
5224 void warn_melody(void) {
5225 _cleanup_close_ int fd = -1;
5227 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5231 /* Yeah, this is synchronous. Kinda sucks. But well... */
5233 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5234 usleep(125*USEC_PER_MSEC);
5236 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5237 usleep(125*USEC_PER_MSEC);
5239 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5240 usleep(125*USEC_PER_MSEC);
5242 ioctl(fd, KIOCSOUND, 0);
5245 int make_console_stdio(void) {
5248 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5250 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5252 log_error("Failed to acquire terminal: %s", strerror(-fd));
5258 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5265 int get_home_dir(char **_h) {
5273 /* Take the user specified one */
5284 /* Hardcode home directory for root to avoid NSS */
5287 h = strdup("/root");
5295 /* Check the database... */
5299 return errno > 0 ? -errno : -ESRCH;
5301 if (!path_is_absolute(p->pw_dir))
5304 h = strdup(p->pw_dir);
5312 bool filename_is_safe(const char *p) {
5326 if (strlen(p) > FILENAME_MAX)
5332 bool string_is_safe(const char *p) {
5337 for (t = p; *t; t++) {
5338 if (*t > 0 && *t < ' ')
5341 if (strchr("\\\"\'", *t))
5348 bool string_has_cc(const char *p) {
5353 for (t = p; *t; t++)
5354 if (*t > 0 && *t < ' ')
5360 bool path_is_safe(const char *p) {
5365 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5368 if (strlen(p) > PATH_MAX)
5371 /* The following two checks are not really dangerous, but hey, they still are confusing */
5372 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5375 if (strstr(p, "//"))
5381 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5382 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5383 int (*compar) (const void *, const void *, void *), void *arg) {
5392 p = (void *)(((const char *) base) + (idx * size));
5393 comparison = compar(key, p, arg);
5396 else if (comparison > 0)
5404 bool is_locale_utf8(void) {
5406 static int cached_answer = -1;
5408 if (cached_answer >= 0)
5411 if (!setlocale(LC_ALL, "")) {
5412 cached_answer = true;
5416 set = nl_langinfo(CODESET);
5418 cached_answer = true;
5422 if(streq(set, "UTF-8")) {
5423 cached_answer = true;
5427 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5428 * unset and everything can do to UTF-8 nowadays. */
5429 set = setlocale(LC_CTYPE, NULL);
5431 cached_answer = true;
5435 /* Check result, but ignore the result if C was set
5439 !getenv("LC_ALL") &&
5440 !getenv("LC_CTYPE") &&
5444 return (bool) cached_answer;
5447 const char *draw_special_char(DrawSpecialChar ch) {
5448 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5450 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5451 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5452 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5453 [DRAW_TREE_SPACE] = " ", /* */
5454 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5456 /* ASCII fallback */ {
5457 [DRAW_TREE_VERT] = "| ",
5458 [DRAW_TREE_BRANCH] = "|-",
5459 [DRAW_TREE_RIGHT] = "`-",
5460 [DRAW_TREE_SPACE] = " ",
5461 [DRAW_TRIANGULAR_BULLET] = "> ",
5465 return draw_table[!is_locale_utf8()][ch];
5468 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5471 size_t l, old_len, new_len;
5477 old_len = strlen(old_string);
5478 new_len = strlen(new_string);
5491 if (!startswith(f, old_string)) {
5497 nl = l - old_len + new_len;
5498 a = realloc(r, nl + 1);
5506 t = stpcpy(t, new_string);
5518 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5519 const char *i, *begin = NULL;
5524 } state = STATE_OTHER;
5526 size_t osz = 0, isz;
5532 /* Strips ANSI color and replaces TABs by 8 spaces */
5534 isz = _isz ? *_isz : strlen(*ibuf);
5536 f = open_memstream(&obuf, &osz);
5540 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5545 if (i >= *ibuf + isz) /* EOT */
5547 else if (*i == '\x1B')
5548 state = STATE_ESCAPE;
5549 else if (*i == '\t')
5556 if (i >= *ibuf + isz) { /* EOT */
5559 } else if (*i == '[') {
5560 state = STATE_BRACKET;
5565 state = STATE_OTHER;
5572 if (i >= *ibuf + isz || /* EOT */
5573 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5576 state = STATE_OTHER;
5578 } else if (*i == 'm')
5579 state = STATE_OTHER;
5601 int on_ac_power(void) {
5602 bool found_offline = false, found_online = false;
5603 _cleanup_closedir_ DIR *d = NULL;
5605 d = opendir("/sys/class/power_supply");
5611 union dirent_storage buf;
5612 _cleanup_close_ int fd = -1, device = -1;
5617 k = readdir_r(d, &buf.de, &de);
5624 if (ignore_file(de->d_name))
5627 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5629 if (errno == ENOENT || errno == ENOTDIR)
5635 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5637 if (errno == ENOENT)
5643 n = read(fd, contents, sizeof(contents));
5647 if (n != 6 || memcmp(contents, "Mains\n", 6))
5650 close_nointr_nofail(fd);
5651 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5653 if (errno == ENOENT)
5659 n = read(fd, contents, sizeof(contents));
5663 if (n != 2 || contents[1] != '\n')
5666 if (contents[0] == '1') {
5667 found_online = true;
5669 } else if (contents[0] == '0')
5670 found_offline = true;
5675 return found_online || !found_offline;
5678 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5685 if (!path_strv_canonicalize_uniq(search))
5688 STRV_FOREACH(i, search) {
5689 _cleanup_free_ char *p = NULL;
5692 p = strjoin(*i, "/", path, NULL);
5702 if (errno != ENOENT)
5709 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5710 _cleanup_strv_free_ char **copy = NULL;
5716 if (path_is_absolute(path)) {
5719 f = fopen(path, mode);
5728 copy = strv_copy((char**) search);
5732 return search_and_fopen_internal(path, mode, copy, _f);
5735 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5736 _cleanup_strv_free_ char **s = NULL;
5738 if (path_is_absolute(path)) {
5741 f = fopen(path, mode);
5750 s = strv_split_nulstr(search);
5754 return search_and_fopen_internal(path, mode, s, _f);
5757 int create_tmp_dir(char template[], char** dir_name) {
5759 char *d = NULL, *dt;
5763 RUN_WITH_UMASK(0077) {
5764 d = mkdtemp(template);
5767 log_error("Can't create directory %s: %m", template);
5771 dt = strjoin(d, "/tmp", NULL);
5777 RUN_WITH_UMASK(0000) {
5778 r = mkdir(dt, 0777);
5781 log_error("Can't create directory %s: %m", dt);
5785 log_debug("Created temporary directory %s", dt);
5787 r = chmod(dt, 0777 | S_ISVTX);
5789 log_error("Failed to chmod %s: %m", dt);
5793 log_debug("Set sticky bit on %s", dt);
5807 char *strextend(char **x, ...) {
5814 l = f = *x ? strlen(*x) : 0;
5821 t = va_arg(ap, const char *);
5826 if (n > ((size_t) -1) - l) {
5835 r = realloc(*x, l+1);
5845 t = va_arg(ap, const char *);
5859 char *strrep(const char *s, unsigned n) {
5867 p = r = malloc(l * n + 1);
5871 for (i = 0; i < n; i++)
5878 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5882 if (*allocated >= need)
5885 a = MAX(64u, need * 2);
5895 bool id128_is_valid(const char *s) {
5901 /* Simple formatted 128bit hex string */
5903 for (i = 0; i < l; i++) {
5906 if (!(c >= '0' && c <= '9') &&
5907 !(c >= 'a' && c <= 'z') &&
5908 !(c >= 'A' && c <= 'Z'))
5912 } else if (l == 36) {
5914 /* Formatted UUID */
5916 for (i = 0; i < l; i++) {
5919 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5923 if (!(c >= '0' && c <= '9') &&
5924 !(c >= 'a' && c <= 'z') &&
5925 !(c >= 'A' && c <= 'Z'))
5936 void parse_user_at_host(char *arg, char **user, char **host) {
5941 *host = strchr(arg, '@');
5950 int split_pair(const char *s, const char *sep, char **l, char **r) {
5965 a = strndup(s, x - s);
5969 b = strdup(x + strlen(sep));