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
1879 fd = open(name, mode);
1886 /* Max 1s in total */
1890 usleep(50 * USEC_PER_MSEC);
1899 close_nointr_nofail(fd);
1904 close_nointr_nofail(fd);
1911 int flush_fd(int fd) {
1912 struct pollfd pollfd = {
1922 r = poll(&pollfd, 1, 0);
1932 l = read(fd, buf, sizeof(buf));
1938 if (errno == EAGAIN)
1947 int acquire_terminal(
1951 bool ignore_tiocstty_eperm,
1954 int fd = -1, notify = -1, r = 0, wd = -1;
1959 /* We use inotify to be notified when the tty is closed. We
1960 * create the watch before checking if we can actually acquire
1961 * it, so that we don't lose any event.
1963 * Note: strictly speaking this actually watches for the
1964 * device being closed, it does *not* really watch whether a
1965 * tty loses its controlling process. However, unless some
1966 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1967 * its tty otherwise this will not become a problem. As long
1968 * as the administrator makes sure not configure any service
1969 * on the same tty as an untrusted user this should not be a
1970 * problem. (Which he probably should not do anyway.) */
1972 if (timeout != (usec_t) -1)
1973 ts = now(CLOCK_MONOTONIC);
1975 if (!fail && !force) {
1976 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1982 wd = inotify_add_watch(notify, name, IN_CLOSE);
1990 struct sigaction sa_old, sa_new = {
1991 .sa_handler = SIG_IGN,
1992 .sa_flags = SA_RESTART,
1996 r = flush_fd(notify);
2001 /* We pass here O_NOCTTY only so that we can check the return
2002 * value TIOCSCTTY and have a reliable way to figure out if we
2003 * successfully became the controlling process of the tty */
2004 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2008 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2009 * if we already own the tty. */
2010 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2012 /* First, try to get the tty */
2013 if (ioctl(fd, TIOCSCTTY, force) < 0)
2016 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2018 /* Sometimes it makes sense to ignore TIOCSCTTY
2019 * returning EPERM, i.e. when very likely we already
2020 * are have this controlling terminal. */
2021 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2024 if (r < 0 && (force || fail || r != -EPERM)) {
2033 assert(notify >= 0);
2036 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2038 struct inotify_event *e;
2040 if (timeout != (usec_t) -1) {
2043 n = now(CLOCK_MONOTONIC);
2044 if (ts + timeout < n) {
2049 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2059 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2062 if (errno == EINTR || errno == EAGAIN)
2069 e = (struct inotify_event*) inotify_buffer;
2074 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2079 step = sizeof(struct inotify_event) + e->len;
2080 assert(step <= (size_t) l);
2082 e = (struct inotify_event*) ((uint8_t*) e + step);
2089 /* We close the tty fd here since if the old session
2090 * ended our handle will be dead. It's important that
2091 * we do this after sleeping, so that we don't enter
2092 * an endless loop. */
2093 close_nointr_nofail(fd);
2097 close_nointr_nofail(notify);
2099 r = reset_terminal_fd(fd, true);
2101 log_warning("Failed to reset terminal: %s", strerror(-r));
2107 close_nointr_nofail(fd);
2110 close_nointr_nofail(notify);
2115 int release_terminal(void) {
2117 struct sigaction sa_old, sa_new = {
2118 .sa_handler = SIG_IGN,
2119 .sa_flags = SA_RESTART,
2121 _cleanup_close_ int fd;
2123 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2127 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2128 * by our own TIOCNOTTY */
2129 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2131 if (ioctl(fd, TIOCNOTTY) < 0)
2134 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2139 int sigaction_many(const struct sigaction *sa, ...) {
2144 while ((sig = va_arg(ap, int)) > 0)
2145 if (sigaction(sig, sa, NULL) < 0)
2152 int ignore_signals(int sig, ...) {
2153 struct sigaction sa = {
2154 .sa_handler = SIG_IGN,
2155 .sa_flags = SA_RESTART,
2161 if (sigaction(sig, &sa, NULL) < 0)
2165 while ((sig = va_arg(ap, int)) > 0)
2166 if (sigaction(sig, &sa, NULL) < 0)
2173 int default_signals(int sig, ...) {
2174 struct sigaction sa = {
2175 .sa_handler = SIG_DFL,
2176 .sa_flags = SA_RESTART,
2181 if (sigaction(sig, &sa, NULL) < 0)
2185 while ((sig = va_arg(ap, int)) > 0)
2186 if (sigaction(sig, &sa, NULL) < 0)
2193 int close_pipe(int p[]) {
2199 a = close_nointr(p[0]);
2204 b = close_nointr(p[1]);
2208 return a < 0 ? a : b;
2211 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2220 while (nbytes > 0) {
2223 if ((k = read(fd, p, nbytes)) <= 0) {
2225 if (k < 0 && errno == EINTR)
2228 if (k < 0 && errno == EAGAIN && do_poll) {
2229 struct pollfd pollfd = {
2234 if (poll(&pollfd, 1, -1) < 0) {
2238 return n > 0 ? n : -errno;
2241 if (pollfd.revents != POLLIN)
2242 return n > 0 ? n : -EIO;
2247 return n > 0 ? n : (k < 0 ? -errno : 0);
2258 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2267 while (nbytes > 0) {
2270 k = write(fd, p, nbytes);
2273 if (k < 0 && errno == EINTR)
2276 if (k < 0 && errno == EAGAIN && do_poll) {
2277 struct pollfd pollfd = {
2282 if (poll(&pollfd, 1, -1) < 0) {
2286 return n > 0 ? n : -errno;
2289 if (pollfd.revents != POLLOUT)
2290 return n > 0 ? n : -EIO;
2295 return n > 0 ? n : (k < 0 ? -errno : 0);
2306 int parse_bytes(const char *t, off_t *bytes) {
2307 static const struct {
2309 unsigned long long factor;
2313 { "M", 1024ULL*1024ULL },
2314 { "G", 1024ULL*1024ULL*1024ULL },
2315 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2316 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2317 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2322 unsigned long long r = 0;
2334 l = strtoll(p, &e, 10);
2345 e += strspn(e, WHITESPACE);
2347 for (i = 0; i < ELEMENTSOF(table); i++)
2348 if (startswith(e, table[i].suffix)) {
2349 unsigned long long tmp;
2350 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2352 tmp = l * table[i].factor;
2353 if (tmp > ULLONG_MAX - r)
2357 if ((unsigned long long) (off_t) r != r)
2360 p = e + strlen(table[i].suffix);
2364 if (i >= ELEMENTSOF(table))
2374 int make_stdio(int fd) {
2379 r = dup3(fd, STDIN_FILENO, 0);
2380 s = dup3(fd, STDOUT_FILENO, 0);
2381 t = dup3(fd, STDERR_FILENO, 0);
2384 close_nointr_nofail(fd);
2386 if (r < 0 || s < 0 || t < 0)
2389 /* We rely here that the new fd has O_CLOEXEC not set */
2394 int make_null_stdio(void) {
2397 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2401 return make_stdio(null_fd);
2404 bool is_device_path(const char *path) {
2406 /* Returns true on paths that refer to a device, either in
2407 * sysfs or in /dev */
2410 path_startswith(path, "/dev/") ||
2411 path_startswith(path, "/sys/");
2414 int dir_is_empty(const char *path) {
2415 _cleanup_closedir_ DIR *d;
2424 union dirent_storage buf;
2426 r = readdir_r(d, &buf.de, &de);
2433 if (!ignore_file(de->d_name))
2438 char* dirname_malloc(const char *path) {
2439 char *d, *dir, *dir2;
2456 unsigned long long random_ull(void) {
2457 _cleanup_close_ int fd;
2461 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2465 r = loop_read(fd, &ull, sizeof(ull), true);
2466 if (r != sizeof(ull))
2472 return random() * RAND_MAX + random();
2475 void rename_process(const char name[8]) {
2478 /* This is a like a poor man's setproctitle(). It changes the
2479 * comm field, argv[0], and also the glibc's internally used
2480 * name of the process. For the first one a limit of 16 chars
2481 * applies, to the second one usually one of 10 (i.e. length
2482 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2483 * "systemd"). If you pass a longer string it will be
2486 prctl(PR_SET_NAME, name);
2488 if (program_invocation_name)
2489 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2491 if (saved_argc > 0) {
2495 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2497 for (i = 1; i < saved_argc; i++) {
2501 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2506 void sigset_add_many(sigset_t *ss, ...) {
2513 while ((sig = va_arg(ap, int)) > 0)
2514 assert_se(sigaddset(ss, sig) == 0);
2518 char* gethostname_malloc(void) {
2521 assert_se(uname(&u) >= 0);
2523 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2524 return strdup(u.nodename);
2526 return strdup(u.sysname);
2529 bool hostname_is_set(void) {
2532 assert_se(uname(&u) >= 0);
2534 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2537 static char *lookup_uid(uid_t uid) {
2540 _cleanup_free_ char *buf = NULL;
2541 struct passwd pwbuf, *pw = NULL;
2543 /* Shortcut things to avoid NSS lookups */
2545 return strdup("root");
2547 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2551 buf = malloc(bufsize);
2555 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2556 return strdup(pw->pw_name);
2558 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2564 char* getlogname_malloc(void) {
2568 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2573 return lookup_uid(uid);
2576 char *getusername_malloc(void) {
2583 return lookup_uid(getuid());
2586 int getttyname_malloc(int fd, char **r) {
2587 char path[PATH_MAX], *c;
2592 k = ttyname_r(fd, path, sizeof(path));
2598 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2606 int getttyname_harder(int fd, char **r) {
2610 k = getttyname_malloc(fd, &s);
2614 if (streq(s, "tty")) {
2616 return get_ctty(0, NULL, r);
2623 int get_ctty_devnr(pid_t pid, dev_t *d) {
2624 _cleanup_fclose_ FILE *f = NULL;
2625 char line[LINE_MAX], *p;
2626 unsigned long ttynr;
2634 fn = "/proc/self/stat";
2636 fn = procfs_file_alloca(pid, "stat");
2638 f = fopen(fn, "re");
2642 if (!fgets(line, sizeof(line), f)) {
2643 k = feof(f) ? -EIO : -errno;
2647 p = strrchr(line, ')');
2657 "%*d " /* session */
2662 if (major(ttynr) == 0 && minor(ttynr) == 0)
2669 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2671 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2676 k = get_ctty_devnr(pid, &devnr);
2680 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2682 k = readlink_malloc(fn, &s);
2688 /* This is an ugly hack */
2689 if (major(devnr) == 136) {
2690 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2700 /* Probably something like the ptys which have no
2701 * symlink in /dev/char. Let's return something
2702 * vaguely useful. */
2715 if (startswith(s, "/dev/"))
2717 else if (startswith(s, "../"))
2735 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2741 /* This returns the first error we run into, but nevertheless
2742 * tries to go on. This closes the passed fd. */
2746 close_nointr_nofail(fd);
2748 return errno == ENOENT ? 0 : -errno;
2753 union dirent_storage buf;
2754 bool is_dir, keep_around;
2758 r = readdir_r(d, &buf.de, &de);
2759 if (r != 0 && ret == 0) {
2767 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2770 if (de->d_type == DT_UNKNOWN ||
2772 (de->d_type == DT_DIR && root_dev)) {
2773 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2774 if (ret == 0 && errno != ENOENT)
2779 is_dir = S_ISDIR(st.st_mode);
2782 (st.st_uid == 0 || st.st_uid == getuid()) &&
2783 (st.st_mode & S_ISVTX);
2785 is_dir = de->d_type == DT_DIR;
2786 keep_around = false;
2792 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2793 if (root_dev && st.st_dev != root_dev->st_dev)
2796 subdir_fd = openat(fd, de->d_name,
2797 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2798 if (subdir_fd < 0) {
2799 if (ret == 0 && errno != ENOENT)
2804 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2805 if (r < 0 && ret == 0)
2809 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2810 if (ret == 0 && errno != ENOENT)
2814 } else if (!only_dirs && !keep_around) {
2816 if (unlinkat(fd, de->d_name, 0) < 0) {
2817 if (ret == 0 && errno != ENOENT)
2828 _pure_ static int is_temporary_fs(struct statfs *s) {
2831 F_TYPE_CMP(s->f_type, TMPFS_MAGIC) ||
2832 F_TYPE_CMP(s->f_type, RAMFS_MAGIC);
2835 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2840 if (fstatfs(fd, &s) < 0) {
2841 close_nointr_nofail(fd);
2845 /* We refuse to clean disk file systems with this call. This
2846 * is extra paranoia just to be sure we never ever remove
2848 if (!is_temporary_fs(&s)) {
2849 log_error("Attempted to remove disk file system, and we can't allow that.");
2850 close_nointr_nofail(fd);
2854 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2857 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2863 /* We refuse to clean the root file system with this
2864 * call. This is extra paranoia to never cause a really
2865 * seriously broken system. */
2866 if (path_equal(path, "/")) {
2867 log_error("Attempted to remove entire root file system, and we can't allow that.");
2871 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2874 if (errno != ENOTDIR)
2878 if (statfs(path, &s) < 0)
2881 if (!is_temporary_fs(&s)) {
2882 log_error("Attempted to remove disk file system, and we can't allow that.");
2887 if (delete_root && !only_dirs)
2888 if (unlink(path) < 0 && errno != ENOENT)
2895 if (fstatfs(fd, &s) < 0) {
2896 close_nointr_nofail(fd);
2900 if (!is_temporary_fs(&s)) {
2901 log_error("Attempted to remove disk file system, and we can't allow that.");
2902 close_nointr_nofail(fd);
2907 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2910 if (honour_sticky && file_is_priv_sticky(path) > 0)
2913 if (rmdir(path) < 0 && errno != ENOENT) {
2922 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2923 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2926 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2927 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2930 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2933 /* Under the assumption that we are running privileged we
2934 * first change the access mode and only then hand out
2935 * ownership to avoid a window where access is too open. */
2937 if (mode != (mode_t) -1)
2938 if (chmod(path, mode) < 0)
2941 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2942 if (chown(path, uid, gid) < 0)
2948 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2951 /* Under the assumption that we are running privileged we
2952 * first change the access mode and only then hand out
2953 * ownership to avoid a window where access is too open. */
2955 if (fchmod(fd, mode) < 0)
2958 if (fchown(fd, uid, gid) < 0)
2964 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2968 /* Allocates the cpuset in the right size */
2971 if (!(r = CPU_ALLOC(n)))
2974 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2975 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2985 if (errno != EINVAL)
2992 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2993 static const char status_indent[] = " "; /* "[" STATUS "] " */
2994 _cleanup_free_ char *s = NULL;
2995 _cleanup_close_ int fd = -1;
2996 struct iovec iovec[6] = {};
2998 static bool prev_ephemeral;
3002 /* This is independent of logging, as status messages are
3003 * optional and go exclusively to the console. */
3005 if (vasprintf(&s, format, ap) < 0)
3008 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3021 sl = status ? sizeof(status_indent)-1 : 0;
3027 e = ellipsize(s, emax, 75);
3035 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3036 prev_ephemeral = ephemeral;
3039 if (!isempty(status)) {
3040 IOVEC_SET_STRING(iovec[n++], "[");
3041 IOVEC_SET_STRING(iovec[n++], status);
3042 IOVEC_SET_STRING(iovec[n++], "] ");
3044 IOVEC_SET_STRING(iovec[n++], status_indent);
3047 IOVEC_SET_STRING(iovec[n++], s);
3049 IOVEC_SET_STRING(iovec[n++], "\n");
3051 if (writev(fd, iovec, n) < 0)
3057 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3063 va_start(ap, format);
3064 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3070 int status_welcome(void) {
3072 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3074 r = parse_env_file("/etc/os-release", NEWLINE,
3075 "PRETTY_NAME", &pretty_name,
3076 "ANSI_COLOR", &ansi_color,
3078 if (r < 0 && r != -ENOENT)
3079 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3081 return status_printf(NULL, false, false,
3082 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3083 isempty(ansi_color) ? "1" : ansi_color,
3084 isempty(pretty_name) ? "Linux" : pretty_name);
3087 char *replace_env(const char *format, char **env) {
3094 const char *e, *word = format;
3099 for (e = format; *e; e ++) {
3110 if (!(k = strnappend(r, word, e-word-1)))
3119 } else if (*e == '$') {
3120 if (!(k = strnappend(r, word, e-word)))
3136 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3138 k = strappend(r, t);
3152 if (!(k = strnappend(r, word, e-word)))
3163 char **replace_env_argv(char **argv, char **env) {
3165 unsigned k = 0, l = 0;
3167 l = strv_length(argv);
3169 if (!(r = new(char*, l+1)))
3172 STRV_FOREACH(i, argv) {
3174 /* If $FOO appears as single word, replace it by the split up variable */
3175 if ((*i)[0] == '$' && (*i)[1] != '{') {
3180 e = strv_env_get(env, *i+1);
3183 if (!(m = strv_split_quoted(e))) {
3194 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3203 memcpy(r + k, m, q * sizeof(char*));
3211 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3212 if (!(r[k++] = replace_env(*i, env))) {
3222 int fd_columns(int fd) {
3223 struct winsize ws = {};
3225 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3234 unsigned columns(void) {
3238 if (_likely_(cached_columns > 0))
3239 return cached_columns;
3242 e = getenv("COLUMNS");
3247 c = fd_columns(STDOUT_FILENO);
3256 int fd_lines(int fd) {
3257 struct winsize ws = {};
3259 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3268 unsigned lines(void) {
3272 if (_likely_(cached_lines > 0))
3273 return cached_lines;
3276 e = getenv("LINES");
3281 l = fd_lines(STDOUT_FILENO);
3287 return cached_lines;
3290 /* intended to be used as a SIGWINCH sighandler */
3291 void columns_lines_cache_reset(int signum) {
3297 static int cached_on_tty = -1;
3299 if (_unlikely_(cached_on_tty < 0))
3300 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3302 return cached_on_tty;
3305 int running_in_chroot(void) {
3306 struct stat a = {}, b = {};
3308 /* Only works as root */
3309 if (stat("/proc/1/root", &a) < 0)
3312 if (stat("/", &b) < 0)
3316 a.st_dev != b.st_dev ||
3317 a.st_ino != b.st_ino;
3320 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3325 assert(percent <= 100);
3326 assert(new_length >= 3);
3328 if (old_length <= 3 || old_length <= new_length)
3329 return strndup(s, old_length);
3331 r = new0(char, new_length+1);
3335 x = (new_length * percent) / 100;
3337 if (x > new_length - 3)
3345 s + old_length - (new_length - x - 3),
3346 new_length - x - 3);
3351 char *ellipsize(const char *s, size_t length, unsigned percent) {
3352 return ellipsize_mem(s, strlen(s), length, percent);
3355 int touch(const char *path) {
3360 /* This just opens the file for writing, ensuring it
3361 * exists. It doesn't call utimensat() the way /usr/bin/touch
3364 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3368 close_nointr_nofail(fd);
3372 char *unquote(const char *s, const char* quotes) {
3376 /* This is rather stupid, simply removes the heading and
3377 * trailing quotes if there is one. Doesn't care about
3378 * escaping or anything. We should make this smarter one
3385 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3386 return strndup(s+1, l-2);
3391 char *normalize_env_assignment(const char *s) {
3392 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3395 eq = strchr(s, '=');
3407 memmove(r, t, strlen(t) + 1);
3411 name = strndup(s, eq - s);
3419 value = unquote(strstrip(p), QUOTES);
3423 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3429 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3440 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3452 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3459 r = wait_for_terminate(pid, &status);
3461 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3465 if (status.si_code == CLD_EXITED) {
3466 if (status.si_status != 0) {
3467 log_warning("%s failed with error code %i.", name, status.si_status);
3468 return status.si_status;
3471 log_debug("%s succeeded.", name);
3474 } else if (status.si_code == CLD_KILLED ||
3475 status.si_code == CLD_DUMPED) {
3477 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3481 log_warning("%s failed due to unknown reason.", name);
3485 _noreturn_ void freeze(void) {
3487 /* Make sure nobody waits for us on a socket anymore */
3488 close_all_fds(NULL, 0);
3496 bool null_or_empty(struct stat *st) {
3499 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3502 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3508 int null_or_empty_path(const char *fn) {
3513 if (stat(fn, &st) < 0)
3516 return null_or_empty(&st);
3519 DIR *xopendirat(int fd, const char *name, int flags) {
3523 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3529 close_nointr_nofail(nfd);
3536 int signal_from_string_try_harder(const char *s) {
3540 signo = signal_from_string(s);
3542 if (startswith(s, "SIG"))
3543 return signal_from_string(s+3);
3548 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3552 /* FIXME: to follow udev's logic 100% we need to leave valid
3553 * UTF8 chars unescaped */
3555 u = unquote(tagvalue, "\"\'");
3559 t = xescape(u, "/ ");
3565 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3574 char *fstab_node_to_udev_node(const char *p) {
3577 if (startswith(p, "LABEL="))
3578 return tag_to_udev_node(p+6, "label");
3580 if (startswith(p, "UUID="))
3581 return tag_to_udev_node(p+5, "uuid");
3583 if (startswith(p, "PARTUUID="))
3584 return tag_to_udev_node(p+9, "partuuid");
3586 if (startswith(p, "PARTLABEL="))
3587 return tag_to_udev_node(p+10, "partlabel");
3592 bool tty_is_vc(const char *tty) {
3595 if (startswith(tty, "/dev/"))
3598 return vtnr_from_tty(tty) >= 0;
3601 bool tty_is_console(const char *tty) {
3604 if (startswith(tty, "/dev/"))
3607 return streq(tty, "console");
3610 int vtnr_from_tty(const char *tty) {
3615 if (startswith(tty, "/dev/"))
3618 if (!startswith(tty, "tty") )
3621 if (tty[3] < '0' || tty[3] > '9')
3624 r = safe_atoi(tty+3, &i);
3628 if (i < 0 || i > 63)
3634 char *resolve_dev_console(char **active) {
3637 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3638 * (i.e. not read-only-mounted which is a sign for container setups) */
3640 if (path_is_read_only_fs("/sys") > 0)
3643 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3646 /* If multiple log outputs are configured the last one is what
3647 * /dev/console points to */
3648 tty = strrchr(*active, ' ');
3657 bool tty_is_vc_resolve(const char *tty) {
3658 char *active = NULL;
3663 if (startswith(tty, "/dev/"))
3666 if (streq(tty, "console")) {
3667 tty = resolve_dev_console(&active);
3678 const char *default_term_for_tty(const char *tty) {
3681 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3684 bool dirent_is_file(const struct dirent *de) {
3687 if (ignore_file(de->d_name))
3690 if (de->d_type != DT_REG &&
3691 de->d_type != DT_LNK &&
3692 de->d_type != DT_UNKNOWN)
3698 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3701 if (de->d_type != DT_REG &&
3702 de->d_type != DT_LNK &&
3703 de->d_type != DT_UNKNOWN)
3706 if (ignore_file_allow_backup(de->d_name))
3709 return endswith(de->d_name, suffix);
3712 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3715 Hashmap *pids = NULL;
3719 /* Executes all binaries in a directory in parallel and
3720 * waits for them to finish. */
3723 if (!(_d = opendir(directory))) {
3725 if (errno == ENOENT)
3728 log_error("Failed to enumerate directory %s: %m", directory);
3735 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3736 log_error("Failed to allocate set.");
3740 while ((de = readdir(d))) {
3745 if (!dirent_is_file(de))
3748 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3753 if ((pid = fork()) < 0) {
3754 log_error("Failed to fork: %m");
3772 log_error("Failed to execute %s: %m", path);
3773 _exit(EXIT_FAILURE);
3776 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3778 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3779 log_error("Failed to add PID to set: %s", strerror(-k));
3784 while (!hashmap_isempty(pids)) {
3785 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3789 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3794 log_error("waitid() failed: %m");
3798 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3799 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3800 if (si.si_code == CLD_EXITED)
3801 log_error("%s exited with exit status %i.", path, si.si_status);
3803 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3805 log_debug("%s exited successfully.", path);
3816 hashmap_free_free(pids);
3819 int kill_and_sigcont(pid_t pid, int sig) {
3822 r = kill(pid, sig) < 0 ? -errno : 0;
3830 bool nulstr_contains(const char*nulstr, const char *needle) {
3836 NULSTR_FOREACH(i, nulstr)
3837 if (streq(i, needle))
3843 bool plymouth_running(void) {
3844 return access("/run/plymouth/pid", F_OK) >= 0;
3847 char* strshorten(char *s, size_t l) {
3856 static bool hostname_valid_char(char c) {
3858 (c >= 'a' && c <= 'z') ||
3859 (c >= 'A' && c <= 'Z') ||
3860 (c >= '0' && c <= '9') ||
3866 bool hostname_is_valid(const char *s) {
3873 for (p = s, dot = true; *p; p++) {
3880 if (!hostname_valid_char(*p))
3890 if (p-s > HOST_NAME_MAX)
3896 char* hostname_cleanup(char *s, bool lowercase) {
3900 for (p = s, d = s, dot = true; *p; p++) {
3907 } else if (hostname_valid_char(*p)) {
3908 *(d++) = lowercase ? tolower(*p) : *p;
3919 strshorten(s, HOST_NAME_MAX);
3924 int pipe_eof(int fd) {
3926 struct pollfd pollfd = {
3928 .events = POLLIN|POLLHUP,
3931 r = poll(&pollfd, 1, 0);
3938 return pollfd.revents & POLLHUP;
3941 int fd_wait_for_event(int fd, int event, usec_t t) {
3943 struct pollfd pollfd = {
3948 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3955 return pollfd.revents;
3958 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3969 t = new(char, strlen(path) + 1 + 6 + 1);
3973 fn = path_get_file_name(path);
3977 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3979 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3985 f = fdopen(fd, "we");
3998 int terminal_vhangup_fd(int fd) {
4001 if (ioctl(fd, TIOCVHANGUP) < 0)
4007 int terminal_vhangup(const char *name) {
4010 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4014 r = terminal_vhangup_fd(fd);
4015 close_nointr_nofail(fd);
4020 int vt_disallocate(const char *name) {
4024 /* Deallocate the VT if possible. If not possible
4025 * (i.e. because it is the active one), at least clear it
4026 * entirely (including the scrollback buffer) */
4028 if (!startswith(name, "/dev/"))
4031 if (!tty_is_vc(name)) {
4032 /* So this is not a VT. I guess we cannot deallocate
4033 * it then. But let's at least clear the screen */
4035 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4040 "\033[r" /* clear scrolling region */
4041 "\033[H" /* move home */
4042 "\033[2J", /* clear screen */
4044 close_nointr_nofail(fd);
4049 if (!startswith(name, "/dev/tty"))
4052 r = safe_atou(name+8, &u);
4059 /* Try to deallocate */
4060 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4064 r = ioctl(fd, VT_DISALLOCATE, u);
4065 close_nointr_nofail(fd);
4073 /* Couldn't deallocate, so let's clear it fully with
4075 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4080 "\033[r" /* clear scrolling region */
4081 "\033[H" /* move home */
4082 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4084 close_nointr_nofail(fd);
4089 int copy_file(const char *from, const char *to) {
4095 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4099 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4101 close_nointr_nofail(fdf);
4109 n = read(fdf, buf, sizeof(buf));
4113 close_nointr_nofail(fdf);
4124 k = loop_write(fdt, buf, n, false);
4126 r = k < 0 ? k : (errno ? -errno : -EIO);
4128 close_nointr_nofail(fdf);
4136 close_nointr_nofail(fdf);
4137 r = close_nointr(fdt);
4147 int symlink_atomic(const char *from, const char *to) {
4149 _cleanup_free_ char *t;
4152 unsigned long long ull;
4159 t = new(char, strlen(to) + 1 + 16 + 1);
4163 fn = path_get_file_name(to);
4167 x = stpcpy(t+k+1, fn);
4170 for (i = 0; i < 16; i++) {
4171 *(x++) = hexchar(ull & 0xF);
4177 if (symlink(from, t) < 0)
4180 if (rename(t, to) < 0) {
4189 bool display_is_local(const char *display) {
4193 display[0] == ':' &&
4194 display[1] >= '0' &&
4198 int socket_from_display(const char *display, char **path) {
4205 if (!display_is_local(display))
4208 k = strspn(display+1, "0123456789");
4210 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4214 c = stpcpy(f, "/tmp/.X11-unix/X");
4215 memcpy(c, display+1, k);
4224 const char **username,
4225 uid_t *uid, gid_t *gid,
4227 const char **shell) {
4235 /* We enforce some special rules for uid=0: in order to avoid
4236 * NSS lookups for root we hardcode its data. */
4238 if (streq(*username, "root") || streq(*username, "0")) {
4256 if (parse_uid(*username, &u) >= 0) {
4260 /* If there are multiple users with the same id, make
4261 * sure to leave $USER to the configured value instead
4262 * of the first occurrence in the database. However if
4263 * the uid was configured by a numeric uid, then let's
4264 * pick the real username from /etc/passwd. */
4266 *username = p->pw_name;
4269 p = getpwnam(*username);
4273 return errno > 0 ? -errno : -ESRCH;
4285 *shell = p->pw_shell;
4290 char* uid_to_name(uid_t uid) {
4295 return strdup("root");
4299 return strdup(p->pw_name);
4301 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4307 char* gid_to_name(gid_t gid) {
4312 return strdup("root");
4316 return strdup(p->gr_name);
4318 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4324 int get_group_creds(const char **groupname, gid_t *gid) {
4330 /* We enforce some special rules for gid=0: in order to avoid
4331 * NSS lookups for root we hardcode its data. */
4333 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4334 *groupname = "root";
4342 if (parse_gid(*groupname, &id) >= 0) {
4347 *groupname = g->gr_name;
4350 g = getgrnam(*groupname);
4354 return errno > 0 ? -errno : -ESRCH;
4362 int in_gid(gid_t gid) {
4364 int ngroups_max, r, i;
4366 if (getgid() == gid)
4369 if (getegid() == gid)
4372 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4373 assert(ngroups_max > 0);
4375 gids = alloca(sizeof(gid_t) * ngroups_max);
4377 r = getgroups(ngroups_max, gids);
4381 for (i = 0; i < r; i++)
4388 int in_group(const char *name) {
4392 r = get_group_creds(&name, &gid);
4399 int glob_exists(const char *path) {
4400 _cleanup_globfree_ glob_t g = {};
4406 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4408 if (k == GLOB_NOMATCH)
4410 else if (k == GLOB_NOSPACE)
4413 return !strv_isempty(g.gl_pathv);
4415 return errno ? -errno : -EIO;
4418 int glob_extend(char ***strv, const char *path) {
4419 _cleanup_globfree_ glob_t g = {};
4424 k = glob(optarg, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4426 if (k == GLOB_NOMATCH)
4428 else if (k == GLOB_NOSPACE)
4430 else if (k != 0 || strv_isempty(g.gl_pathv))
4431 return errno ? -errno : -EIO;
4433 STRV_FOREACH(p, g.gl_pathv) {
4434 k = strv_extend(strv, *p);
4442 int dirent_ensure_type(DIR *d, struct dirent *de) {
4448 if (de->d_type != DT_UNKNOWN)
4451 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4455 S_ISREG(st.st_mode) ? DT_REG :
4456 S_ISDIR(st.st_mode) ? DT_DIR :
4457 S_ISLNK(st.st_mode) ? DT_LNK :
4458 S_ISFIFO(st.st_mode) ? DT_FIFO :
4459 S_ISSOCK(st.st_mode) ? DT_SOCK :
4460 S_ISCHR(st.st_mode) ? DT_CHR :
4461 S_ISBLK(st.st_mode) ? DT_BLK :
4467 int in_search_path(const char *path, char **search) {
4471 r = path_get_parent(path, &parent);
4477 STRV_FOREACH(i, search) {
4478 if (path_equal(parent, *i)) {
4489 int get_files_in_directory(const char *path, char ***list) {
4497 /* Returns all files in a directory in *list, and the number
4498 * of files as return value. If list is NULL returns only the
4507 union dirent_storage buf;
4510 k = readdir_r(d, &buf.de, &de);
4519 dirent_ensure_type(d, de);
4521 if (!dirent_is_file(de))
4525 if ((unsigned) r >= n) {
4529 t = realloc(l, sizeof(char*) * n);
4538 assert((unsigned) r < n);
4540 l[r] = strdup(de->d_name);
4564 char *strjoin(const char *x, ...) {
4578 t = va_arg(ap, const char *);
4583 if (n > ((size_t) -1) - l) {
4607 t = va_arg(ap, const char *);
4621 bool is_main_thread(void) {
4622 static __thread int cached = 0;
4624 if (_unlikely_(cached == 0))
4625 cached = getpid() == gettid() ? 1 : -1;
4630 int block_get_whole_disk(dev_t d, dev_t *ret) {
4637 /* If it has a queue this is good enough for us */
4638 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4641 r = access(p, F_OK);
4649 /* If it is a partition find the originating device */
4650 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4653 r = access(p, F_OK);
4659 /* Get parent dev_t */
4660 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4663 r = read_one_line_file(p, &s);
4669 r = sscanf(s, "%u:%u", &m, &n);
4675 /* Only return this if it is really good enough for us. */
4676 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4679 r = access(p, F_OK);
4683 *ret = makedev(m, n);
4690 int file_is_priv_sticky(const char *p) {
4695 if (lstat(p, &st) < 0)
4699 (st.st_uid == 0 || st.st_uid == getuid()) &&
4700 (st.st_mode & S_ISVTX);
4703 static const char *const ioprio_class_table[] = {
4704 [IOPRIO_CLASS_NONE] = "none",
4705 [IOPRIO_CLASS_RT] = "realtime",
4706 [IOPRIO_CLASS_BE] = "best-effort",
4707 [IOPRIO_CLASS_IDLE] = "idle"
4710 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4712 static const char *const sigchld_code_table[] = {
4713 [CLD_EXITED] = "exited",
4714 [CLD_KILLED] = "killed",
4715 [CLD_DUMPED] = "dumped",
4716 [CLD_TRAPPED] = "trapped",
4717 [CLD_STOPPED] = "stopped",
4718 [CLD_CONTINUED] = "continued",
4721 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4723 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4724 [LOG_FAC(LOG_KERN)] = "kern",
4725 [LOG_FAC(LOG_USER)] = "user",
4726 [LOG_FAC(LOG_MAIL)] = "mail",
4727 [LOG_FAC(LOG_DAEMON)] = "daemon",
4728 [LOG_FAC(LOG_AUTH)] = "auth",
4729 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4730 [LOG_FAC(LOG_LPR)] = "lpr",
4731 [LOG_FAC(LOG_NEWS)] = "news",
4732 [LOG_FAC(LOG_UUCP)] = "uucp",
4733 [LOG_FAC(LOG_CRON)] = "cron",
4734 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4735 [LOG_FAC(LOG_FTP)] = "ftp",
4736 [LOG_FAC(LOG_LOCAL0)] = "local0",
4737 [LOG_FAC(LOG_LOCAL1)] = "local1",
4738 [LOG_FAC(LOG_LOCAL2)] = "local2",
4739 [LOG_FAC(LOG_LOCAL3)] = "local3",
4740 [LOG_FAC(LOG_LOCAL4)] = "local4",
4741 [LOG_FAC(LOG_LOCAL5)] = "local5",
4742 [LOG_FAC(LOG_LOCAL6)] = "local6",
4743 [LOG_FAC(LOG_LOCAL7)] = "local7"
4746 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4748 static const char *const log_level_table[] = {
4749 [LOG_EMERG] = "emerg",
4750 [LOG_ALERT] = "alert",
4751 [LOG_CRIT] = "crit",
4753 [LOG_WARNING] = "warning",
4754 [LOG_NOTICE] = "notice",
4755 [LOG_INFO] = "info",
4756 [LOG_DEBUG] = "debug"
4759 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4761 static const char* const sched_policy_table[] = {
4762 [SCHED_OTHER] = "other",
4763 [SCHED_BATCH] = "batch",
4764 [SCHED_IDLE] = "idle",
4765 [SCHED_FIFO] = "fifo",
4769 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4771 static const char* const rlimit_table[] = {
4772 [RLIMIT_CPU] = "LimitCPU",
4773 [RLIMIT_FSIZE] = "LimitFSIZE",
4774 [RLIMIT_DATA] = "LimitDATA",
4775 [RLIMIT_STACK] = "LimitSTACK",
4776 [RLIMIT_CORE] = "LimitCORE",
4777 [RLIMIT_RSS] = "LimitRSS",
4778 [RLIMIT_NOFILE] = "LimitNOFILE",
4779 [RLIMIT_AS] = "LimitAS",
4780 [RLIMIT_NPROC] = "LimitNPROC",
4781 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4782 [RLIMIT_LOCKS] = "LimitLOCKS",
4783 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4784 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4785 [RLIMIT_NICE] = "LimitNICE",
4786 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4787 [RLIMIT_RTTIME] = "LimitRTTIME"
4790 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4792 static const char* const ip_tos_table[] = {
4793 [IPTOS_LOWDELAY] = "low-delay",
4794 [IPTOS_THROUGHPUT] = "throughput",
4795 [IPTOS_RELIABILITY] = "reliability",
4796 [IPTOS_LOWCOST] = "low-cost",
4799 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4801 static const char *const __signal_table[] = {
4818 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4829 [SIGVTALRM] = "VTALRM",
4831 [SIGWINCH] = "WINCH",
4837 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4839 const char *signal_to_string(int signo) {
4840 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4843 name = __signal_to_string(signo);
4847 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4848 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4850 snprintf(buf, sizeof(buf), "%d", signo);
4855 int signal_from_string(const char *s) {
4860 signo = __signal_from_string(s);
4864 if (startswith(s, "RTMIN+")) {
4868 if (safe_atou(s, &u) >= 0) {
4869 signo = (int) u + offset;
4870 if (signo > 0 && signo < _NSIG)
4876 bool kexec_loaded(void) {
4877 bool loaded = false;
4880 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4888 int strdup_or_null(const char *a, char **b) {
4906 int prot_from_flags(int flags) {
4908 switch (flags & O_ACCMODE) {
4917 return PROT_READ|PROT_WRITE;
4924 char *format_bytes(char *buf, size_t l, off_t t) {
4927 static const struct {
4931 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4932 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4933 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4934 { "G", 1024ULL*1024ULL*1024ULL },
4935 { "M", 1024ULL*1024ULL },
4939 for (i = 0; i < ELEMENTSOF(table); i++) {
4941 if (t >= table[i].factor) {
4944 (unsigned long long) (t / table[i].factor),
4945 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4952 snprintf(buf, l, "%lluB", (unsigned long long) t);
4960 void* memdup(const void *p, size_t l) {
4973 int fd_inc_sndbuf(int fd, size_t n) {
4975 socklen_t l = sizeof(value);
4977 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4979 l == sizeof(value) &&
4980 (size_t) value >= n*2)
4984 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4991 int fd_inc_rcvbuf(int fd, size_t n) {
4993 socklen_t l = sizeof(value);
4995 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4997 l == sizeof(value) &&
4998 (size_t) value >= n*2)
5002 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5009 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5010 pid_t parent_pid, agent_pid;
5012 bool stdout_is_tty, stderr_is_tty;
5020 parent_pid = getpid();
5022 /* Spawns a temporary TTY agent, making sure it goes away when
5029 if (agent_pid != 0) {
5036 * Make sure the agent goes away when the parent dies */
5037 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5038 _exit(EXIT_FAILURE);
5040 /* Check whether our parent died before we were able
5041 * to set the death signal */
5042 if (getppid() != parent_pid)
5043 _exit(EXIT_SUCCESS);
5045 /* Don't leak fds to the agent */
5046 close_all_fds(except, n_except);
5048 stdout_is_tty = isatty(STDOUT_FILENO);
5049 stderr_is_tty = isatty(STDERR_FILENO);
5051 if (!stdout_is_tty || !stderr_is_tty) {
5052 /* Detach from stdout/stderr. and reopen
5053 * /dev/tty for them. This is important to
5054 * ensure that when systemctl is started via
5055 * popen() or a similar call that expects to
5056 * read EOF we actually do generate EOF and
5057 * not delay this indefinitely by because we
5058 * keep an unused copy of stdin around. */
5059 fd = open("/dev/tty", O_WRONLY);
5061 log_error("Failed to open /dev/tty: %m");
5062 _exit(EXIT_FAILURE);
5066 dup2(fd, STDOUT_FILENO);
5069 dup2(fd, STDERR_FILENO);
5075 /* Count arguments */
5077 for (n = 0; va_arg(ap, char*); n++)
5082 l = alloca(sizeof(char *) * (n + 1));
5084 /* Fill in arguments */
5086 for (i = 0; i <= n; i++)
5087 l[i] = va_arg(ap, char*);
5091 _exit(EXIT_FAILURE);
5094 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5095 struct rlimit highest, fixed;
5099 if (setrlimit(resource, rlim) >= 0)
5105 /* So we failed to set the desired setrlimit, then let's try
5106 * to get as close as we can */
5107 assert_se(getrlimit(resource, &highest) == 0);
5109 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5110 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5112 if (setrlimit(resource, &fixed) < 0)
5118 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5119 _cleanup_fclose_ FILE *f = NULL;
5131 path = "/proc/self/environ";
5133 path = procfs_file_alloca(pid, "environ");
5135 f = fopen(path, "re");
5143 char line[LINE_MAX];
5146 for (i = 0; i < sizeof(line)-1; i++) {
5150 if (_unlikely_(c == EOF)) {
5160 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5161 value = strdup(line + l + 1);
5175 bool is_valid_documentation_url(const char *url) {
5178 if (startswith(url, "http://") && url[7])
5181 if (startswith(url, "https://") && url[8])
5184 if (startswith(url, "file:") && url[5])
5187 if (startswith(url, "info:") && url[5])
5190 if (startswith(url, "man:") && url[4])
5196 bool in_initrd(void) {
5197 static __thread int saved = -1;
5203 /* We make two checks here:
5205 * 1. the flag file /etc/initrd-release must exist
5206 * 2. the root file system must be a memory file system
5208 * The second check is extra paranoia, since misdetecting an
5209 * initrd can have bad bad consequences due the initrd
5210 * emptying when transititioning to the main systemd.
5213 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5214 statfs("/", &s) >= 0 &&
5215 is_temporary_fs(&s);
5220 void warn_melody(void) {
5221 _cleanup_close_ int fd = -1;
5223 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5227 /* Yeah, this is synchronous. Kinda sucks. But well... */
5229 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5230 usleep(125*USEC_PER_MSEC);
5232 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5233 usleep(125*USEC_PER_MSEC);
5235 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5236 usleep(125*USEC_PER_MSEC);
5238 ioctl(fd, KIOCSOUND, 0);
5241 int make_console_stdio(void) {
5244 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5246 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5248 log_error("Failed to acquire terminal: %s", strerror(-fd));
5254 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5261 int get_home_dir(char **_h) {
5269 /* Take the user specified one */
5280 /* Hardcode home directory for root to avoid NSS */
5283 h = strdup("/root");
5291 /* Check the database... */
5295 return errno > 0 ? -errno : -ESRCH;
5297 if (!path_is_absolute(p->pw_dir))
5300 h = strdup(p->pw_dir);
5308 bool filename_is_safe(const char *p) {
5322 if (strlen(p) > FILENAME_MAX)
5328 bool string_is_safe(const char *p) {
5333 for (t = p; *t; t++) {
5334 if (*t > 0 && *t < ' ')
5337 if (strchr("\\\"\'", *t))
5344 bool string_has_cc(const char *p) {
5349 for (t = p; *t; t++)
5350 if (*t > 0 && *t < ' ')
5356 bool path_is_safe(const char *p) {
5361 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5364 if (strlen(p) > PATH_MAX)
5367 /* The following two checks are not really dangerous, but hey, they still are confusing */
5368 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5371 if (strstr(p, "//"))
5377 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5378 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5379 int (*compar) (const void *, const void *, void *), void *arg) {
5388 p = (void *)(((const char *) base) + (idx * size));
5389 comparison = compar(key, p, arg);
5392 else if (comparison > 0)
5400 bool is_locale_utf8(void) {
5402 static int cached_answer = -1;
5404 if (cached_answer >= 0)
5407 if (!setlocale(LC_ALL, "")) {
5408 cached_answer = true;
5412 set = nl_langinfo(CODESET);
5414 cached_answer = true;
5418 if(streq(set, "UTF-8")) {
5419 cached_answer = true;
5423 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5424 * unset and everything can do to UTF-8 nowadays. */
5425 set = setlocale(LC_CTYPE, NULL);
5427 cached_answer = true;
5431 /* Check result, but ignore the result if C was set
5435 !getenv("LC_ALL") &&
5436 !getenv("LC_CTYPE") &&
5440 return (bool) cached_answer;
5443 const char *draw_special_char(DrawSpecialChar ch) {
5444 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5446 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5447 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5448 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5449 [DRAW_TREE_SPACE] = " ", /* */
5450 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5452 /* ASCII fallback */ {
5453 [DRAW_TREE_VERT] = "| ",
5454 [DRAW_TREE_BRANCH] = "|-",
5455 [DRAW_TREE_RIGHT] = "`-",
5456 [DRAW_TREE_SPACE] = " ",
5457 [DRAW_TRIANGULAR_BULLET] = "> ",
5461 return draw_table[!is_locale_utf8()][ch];
5464 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5467 size_t l, old_len, new_len;
5473 old_len = strlen(old_string);
5474 new_len = strlen(new_string);
5487 if (!startswith(f, old_string)) {
5493 nl = l - old_len + new_len;
5494 a = realloc(r, nl + 1);
5502 t = stpcpy(t, new_string);
5514 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5515 const char *i, *begin = NULL;
5520 } state = STATE_OTHER;
5522 size_t osz = 0, isz;
5528 /* Strips ANSI color and replaces TABs by 8 spaces */
5530 isz = _isz ? *_isz : strlen(*ibuf);
5532 f = open_memstream(&obuf, &osz);
5536 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5541 if (i >= *ibuf + isz) /* EOT */
5543 else if (*i == '\x1B')
5544 state = STATE_ESCAPE;
5545 else if (*i == '\t')
5552 if (i >= *ibuf + isz) { /* EOT */
5555 } else if (*i == '[') {
5556 state = STATE_BRACKET;
5561 state = STATE_OTHER;
5568 if (i >= *ibuf + isz || /* EOT */
5569 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5572 state = STATE_OTHER;
5574 } else if (*i == 'm')
5575 state = STATE_OTHER;
5597 int on_ac_power(void) {
5598 bool found_offline = false, found_online = false;
5599 _cleanup_closedir_ DIR *d = NULL;
5601 d = opendir("/sys/class/power_supply");
5607 union dirent_storage buf;
5608 _cleanup_close_ int fd = -1, device = -1;
5613 k = readdir_r(d, &buf.de, &de);
5620 if (ignore_file(de->d_name))
5623 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5625 if (errno == ENOENT || errno == ENOTDIR)
5631 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5633 if (errno == ENOENT)
5639 n = read(fd, contents, sizeof(contents));
5643 if (n != 6 || memcmp(contents, "Mains\n", 6))
5646 close_nointr_nofail(fd);
5647 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5649 if (errno == ENOENT)
5655 n = read(fd, contents, sizeof(contents));
5659 if (n != 2 || contents[1] != '\n')
5662 if (contents[0] == '1') {
5663 found_online = true;
5665 } else if (contents[0] == '0')
5666 found_offline = true;
5671 return found_online || !found_offline;
5674 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5681 if (!path_strv_canonicalize_uniq(search))
5684 STRV_FOREACH(i, search) {
5685 _cleanup_free_ char *p = NULL;
5688 p = strjoin(*i, "/", path, NULL);
5698 if (errno != ENOENT)
5705 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5706 _cleanup_strv_free_ char **copy = NULL;
5712 if (path_is_absolute(path)) {
5715 f = fopen(path, mode);
5724 copy = strv_copy((char**) search);
5728 return search_and_fopen_internal(path, mode, copy, _f);
5731 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5732 _cleanup_strv_free_ char **s = NULL;
5734 if (path_is_absolute(path)) {
5737 f = fopen(path, mode);
5746 s = strv_split_nulstr(search);
5750 return search_and_fopen_internal(path, mode, s, _f);
5753 int create_tmp_dir(char template[], char** dir_name) {
5759 RUN_WITH_UMASK(0077) {
5760 d = mkdtemp(template);
5763 log_error("Can't create directory %s: %m", template);
5767 dt = strjoin(d, "/tmp", NULL);
5773 RUN_WITH_UMASK(0000) {
5774 r = mkdir(dt, 0777);
5777 log_error("Can't create directory %s: %m", dt);
5781 log_debug("Created temporary directory %s", dt);
5783 r = chmod(dt, 0777 | S_ISVTX);
5785 log_error("Failed to chmod %s: %m", dt);
5789 log_debug("Set sticky bit on %s", dt);
5803 char *strextend(char **x, ...) {
5810 l = f = *x ? strlen(*x) : 0;
5817 t = va_arg(ap, const char *);
5822 if (n > ((size_t) -1) - l) {
5831 r = realloc(*x, l+1);
5841 t = va_arg(ap, const char *);
5855 char *strrep(const char *s, unsigned n) {
5863 p = r = malloc(l * n + 1);
5867 for (i = 0; i < n; i++)
5874 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5878 if (*allocated >= need)
5881 a = MAX(64u, need * 2);
5891 bool id128_is_valid(const char *s) {
5897 /* Simple formatted 128bit hex string */
5899 for (i = 0; i < l; i++) {
5902 if (!(c >= '0' && c <= '9') &&
5903 !(c >= 'a' && c <= 'z') &&
5904 !(c >= 'A' && c <= 'Z'))
5908 } else if (l == 36) {
5910 /* Formatted UUID */
5912 for (i = 0; i < l; i++) {
5915 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5919 if (!(c >= '0' && c <= '9') &&
5920 !(c >= 'a' && c <= 'z') &&
5921 !(c >= 'A' && c <= 'Z'))
5932 void parse_user_at_host(char *arg, char **user, char **host) {
5937 *host = strchr(arg, '@');