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) {
210 int saved_errno = errno;
212 /* like close_nointr() but cannot fail, and guarantees errno
215 assert_se(close_nointr(fd) == 0);
220 void close_many(const int fds[], unsigned n_fd) {
223 assert(fds || n_fd <= 0);
225 for (i = 0; i < n_fd; i++)
226 close_nointr_nofail(fds[i]);
229 int parse_boolean(const char *v) {
232 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
234 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
240 int parse_pid(const char *s, pid_t* ret_pid) {
241 unsigned long ul = 0;
248 r = safe_atolu(s, &ul);
254 if ((unsigned long) pid != ul)
264 int parse_uid(const char *s, uid_t* ret_uid) {
265 unsigned long ul = 0;
272 r = safe_atolu(s, &ul);
278 if ((unsigned long) uid != ul)
285 int safe_atou(const char *s, unsigned *ret_u) {
293 l = strtoul(s, &x, 0);
295 if (!x || x == s || *x || errno)
296 return errno > 0 ? -errno : -EINVAL;
298 if ((unsigned long) (unsigned) l != l)
301 *ret_u = (unsigned) l;
305 int safe_atoi(const char *s, int *ret_i) {
313 l = strtol(s, &x, 0);
315 if (!x || x == s || *x || errno)
316 return errno > 0 ? -errno : -EINVAL;
318 if ((long) (int) l != l)
325 int safe_atollu(const char *s, long long unsigned *ret_llu) {
327 unsigned long long l;
333 l = strtoull(s, &x, 0);
335 if (!x || x == s || *x || errno)
336 return errno ? -errno : -EINVAL;
342 int safe_atolli(const char *s, long long int *ret_lli) {
350 l = strtoll(s, &x, 0);
352 if (!x || x == s || *x || errno)
353 return errno ? -errno : -EINVAL;
359 int safe_atod(const char *s, double *ret_d) {
369 if (!x || x == s || *x || errno)
370 return errno ? -errno : -EINVAL;
376 /* Split a string into words. */
377 char *split(const char *c, size_t *l, const char *separator, char **state) {
380 current = *state ? *state : (char*) c;
382 if (!*current || *c == 0)
385 current += strspn(current, separator);
386 *l = strcspn(current, separator);
389 return (char*) current;
392 /* Split a string into words, but consider strings enclosed in '' and
393 * "" as words even if they include spaces. */
394 char *split_quoted(const char *c, size_t *l, char **state) {
396 bool escaped = false;
398 current = *state ? *state : (char*) c;
400 if (!*current || *c == 0)
403 current += strspn(current, WHITESPACE);
405 if (*current == '\'') {
408 for (e = current; *e; e++) {
418 *state = *e == 0 ? e : e+1;
419 } else if (*current == '\"') {
422 for (e = current; *e; e++) {
432 *state = *e == 0 ? e : e+1;
434 for (e = current; *e; e++) {
439 else if (strchr(WHITESPACE, *e))
446 return (char*) current;
449 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
451 _cleanup_fclose_ FILE *f = NULL;
452 char fn[PATH_MAX], line[LINE_MAX], *p;
458 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
465 if (!fgets(line, sizeof(line), f)) {
466 r = feof(f) ? -EIO : -errno;
470 /* Let's skip the pid and comm fields. The latter is enclosed
471 * in () but does not escape any () in its value, so let's
472 * skip over it manually */
474 p = strrchr(line, ')');
486 if ((long unsigned) (pid_t) ppid != ppid)
489 *_ppid = (pid_t) ppid;
494 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
495 _cleanup_fclose_ FILE *f = NULL;
496 char fn[PATH_MAX], line[LINE_MAX], *p;
501 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
508 if (!fgets(line, sizeof(line), f)) {
515 /* Let's skip the pid and comm fields. The latter is enclosed
516 * in () but does not escape any () in its value, so let's
517 * skip over it manually */
519 p = strrchr(line, ')');
541 "%*d " /* priority */
543 "%*d " /* num_threads */
544 "%*d " /* itrealvalue */
545 "%llu " /* starttime */,
552 int fchmod_umask(int fd, mode_t m) {
557 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
563 char *truncate_nl(char *s) {
566 s[strcspn(s, NEWLINE)] = 0;
570 int get_process_comm(pid_t pid, char **name) {
576 r = read_one_line_file("/proc/self/comm", name);
579 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
582 r = read_one_line_file(p, name);
589 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
597 f = fopen("/proc/self/cmdline", "re");
600 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
609 if (max_length == 0) {
611 while ((c = getc(f)) != EOF) {
612 k = realloc(r, len+1);
619 r[len-1] = isprint(c) ? c : ' ';
626 r = new(char, max_length);
634 while ((c = getc(f)) != EOF) {
656 size_t n = MIN(left-1, 3U);
665 /* Kernel threads have no argv[] */
666 if (r == NULL || r[0] == 0) {
675 h = get_process_comm(pid, &t);
679 r = strjoin("[", t, "]", NULL);
690 int is_kernel_thread(pid_t pid) {
700 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
709 count = fread(&c, 1, 1, f);
713 /* Kernel threads have an empty cmdline */
716 return eof ? 1 : -errno;
721 int get_process_exe(pid_t pid, char **name) {
727 r = readlink_malloc("/proc/self/exe", name);
730 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
733 r = readlink_malloc(p, name);
740 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
741 _cleanup_fclose_ FILE *f = NULL;
742 _cleanup_free_ char *p = NULL;
751 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
758 FOREACH_LINE(line, f, return -errno) {
763 if (startswith(l, field)) {
765 l += strspn(l, WHITESPACE);
767 l[strcspn(l, WHITESPACE)] = 0;
769 return parse_uid(l, uid);
776 int get_process_uid(pid_t pid, uid_t *uid) {
777 return get_process_id(pid, "Uid:", uid);
780 int get_process_gid(pid_t pid, gid_t *gid) {
781 return get_process_id(pid, "Gid:", gid);
784 char *strnappend(const char *s, const char *suffix, size_t b) {
792 return strndup(suffix, b);
801 if (b > ((size_t) -1) - a)
804 r = new(char, a+b+1);
809 memcpy(r+a, suffix, b);
815 char *strappend(const char *s, const char *suffix) {
816 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
819 int readlink_malloc(const char *p, char **r) {
829 if (!(c = new(char, l)))
832 if ((n = readlink(p, c, l-1)) < 0) {
838 if ((size_t) n < l-1) {
849 int readlink_and_make_absolute(const char *p, char **r) {
856 if ((j = readlink_malloc(p, &target)) < 0)
859 k = file_in_same_dir(p, target);
869 int readlink_and_canonicalize(const char *p, char **r) {
876 j = readlink_and_make_absolute(p, &t);
880 s = canonicalize_file_name(t);
887 path_kill_slashes(*r);
892 int reset_all_signal_handlers(void) {
895 for (sig = 1; sig < _NSIG; sig++) {
898 if (sig == SIGKILL || sig == SIGSTOP)
902 sa.sa_handler = SIG_DFL;
903 sa.sa_flags = SA_RESTART;
905 /* On Linux the first two RT signals are reserved by
906 * glibc, and sigaction() will return EINVAL for them. */
907 if ((sigaction(sig, &sa, NULL) < 0))
915 char *strstrip(char *s) {
918 /* Drops trailing whitespace. Modifies the string in
919 * place. Returns pointer to first non-space character */
921 s += strspn(s, WHITESPACE);
923 for (e = strchr(s, 0); e > s; e --)
924 if (!strchr(WHITESPACE, e[-1]))
932 char *delete_chars(char *s, const char *bad) {
935 /* Drops all whitespace, regardless where in the string */
937 for (f = s, t = s; *f; f++) {
949 bool in_charset(const char *s, const char* charset) {
956 if (!strchr(charset, *i))
962 char *file_in_same_dir(const char *path, const char *filename) {
969 /* This removes the last component of path and appends
970 * filename, unless the latter is absolute anyway or the
973 if (path_is_absolute(filename))
974 return strdup(filename);
976 if (!(e = strrchr(path, '/')))
977 return strdup(filename);
979 k = strlen(filename);
980 if (!(r = new(char, e-path+1+k+1)))
983 memcpy(r, path, e-path+1);
984 memcpy(r+(e-path)+1, filename, k+1);
989 int rmdir_parents(const char *path, const char *stop) {
998 /* Skip trailing slashes */
999 while (l > 0 && path[l-1] == '/')
1005 /* Skip last component */
1006 while (l > 0 && path[l-1] != '/')
1009 /* Skip trailing slashes */
1010 while (l > 0 && path[l-1] == '/')
1016 if (!(t = strndup(path, l)))
1019 if (path_startswith(stop, t)) {
1028 if (errno != ENOENT)
1035 char hexchar(int x) {
1036 static const char table[16] = "0123456789abcdef";
1038 return table[x & 15];
1041 int unhexchar(char c) {
1043 if (c >= '0' && c <= '9')
1046 if (c >= 'a' && c <= 'f')
1047 return c - 'a' + 10;
1049 if (c >= 'A' && c <= 'F')
1050 return c - 'A' + 10;
1055 char *hexmem(const void *p, size_t l) {
1059 z = r = malloc(l * 2 + 1);
1063 for (x = p; x < (const uint8_t*) p + l; x++) {
1064 *(z++) = hexchar(*x >> 4);
1065 *(z++) = hexchar(*x & 15);
1072 void *unhexmem(const char *p, size_t l) {
1078 z = r = malloc((l + 1) / 2 + 1);
1082 for (x = p; x < p + l; x += 2) {
1085 a = unhexchar(x[0]);
1087 b = unhexchar(x[1]);
1091 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1098 char octchar(int x) {
1099 return '0' + (x & 7);
1102 int unoctchar(char c) {
1104 if (c >= '0' && c <= '7')
1110 char decchar(int x) {
1111 return '0' + (x % 10);
1114 int undecchar(char c) {
1116 if (c >= '0' && c <= '9')
1122 char *cescape(const char *s) {
1128 /* Does C style string escaping. */
1130 r = new(char, strlen(s)*4 + 1);
1134 for (f = s, t = r; *f; f++)
1180 /* For special chars we prefer octal over
1181 * hexadecimal encoding, simply because glib's
1182 * g_strescape() does the same */
1183 if ((*f < ' ') || (*f >= 127)) {
1185 *(t++) = octchar((unsigned char) *f >> 6);
1186 *(t++) = octchar((unsigned char) *f >> 3);
1187 *(t++) = octchar((unsigned char) *f);
1198 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1205 /* Undoes C style string escaping, and optionally prefixes it. */
1207 pl = prefix ? strlen(prefix) : 0;
1209 r = new(char, pl+length+1);
1214 memcpy(r, prefix, pl);
1216 for (f = s, t = r + pl; f < s + length; f++) {
1259 /* This is an extension of the XDG syntax files */
1264 /* hexadecimal encoding */
1267 a = unhexchar(f[1]);
1268 b = unhexchar(f[2]);
1270 if (a < 0 || b < 0) {
1271 /* Invalid escape code, let's take it literal then */
1275 *(t++) = (char) ((a << 4) | b);
1290 /* octal encoding */
1293 a = unoctchar(f[0]);
1294 b = unoctchar(f[1]);
1295 c = unoctchar(f[2]);
1297 if (a < 0 || b < 0 || c < 0) {
1298 /* Invalid escape code, let's take it literal then */
1302 *(t++) = (char) ((a << 6) | (b << 3) | c);
1310 /* premature end of string.*/
1315 /* Invalid escape code, let's take it literal then */
1327 char *cunescape_length(const char *s, size_t length) {
1328 return cunescape_length_with_prefix(s, length, NULL);
1331 char *cunescape(const char *s) {
1334 return cunescape_length(s, strlen(s));
1337 char *xescape(const char *s, const char *bad) {
1341 /* Escapes all chars in bad, in addition to \ and all special
1342 * chars, in \xFF style escaping. May be reversed with
1345 r = new(char, strlen(s) * 4 + 1);
1349 for (f = s, t = r; *f; f++) {
1351 if ((*f < ' ') || (*f >= 127) ||
1352 (*f == '\\') || strchr(bad, *f)) {
1355 *(t++) = hexchar(*f >> 4);
1356 *(t++) = hexchar(*f);
1366 char *bus_path_escape(const char *s) {
1372 /* Escapes all chars that D-Bus' object path cannot deal
1373 * with. Can be reverse with bus_path_unescape(). We special
1374 * case the empty string. */
1379 r = new(char, strlen(s)*3 + 1);
1383 for (f = s, t = r; *f; f++) {
1385 /* Escape everything that is not a-zA-Z0-9. We also
1386 * escape 0-9 if it's the first character */
1388 if (!(*f >= 'A' && *f <= 'Z') &&
1389 !(*f >= 'a' && *f <= 'z') &&
1390 !(f > s && *f >= '0' && *f <= '9')) {
1392 *(t++) = hexchar(*f >> 4);
1393 *(t++) = hexchar(*f);
1403 char *bus_path_unescape(const char *f) {
1408 /* Special case for the empty string */
1412 r = new(char, strlen(f) + 1);
1416 for (t = r; *f; f++) {
1421 if ((a = unhexchar(f[1])) < 0 ||
1422 (b = unhexchar(f[2])) < 0) {
1423 /* Invalid escape code, let's take it literal then */
1426 *(t++) = (char) ((a << 4) | b);
1438 char *ascii_strlower(char *t) {
1443 for (p = t; *p; p++)
1444 if (*p >= 'A' && *p <= 'Z')
1445 *p = *p - 'A' + 'a';
1450 static bool ignore_file_allow_backup(const char *filename) {
1454 filename[0] == '.' ||
1455 streq(filename, "lost+found") ||
1456 streq(filename, "aquota.user") ||
1457 streq(filename, "aquota.group") ||
1458 endswith(filename, ".rpmnew") ||
1459 endswith(filename, ".rpmsave") ||
1460 endswith(filename, ".rpmorig") ||
1461 endswith(filename, ".dpkg-old") ||
1462 endswith(filename, ".dpkg-new") ||
1463 endswith(filename, ".swp");
1466 bool ignore_file(const char *filename) {
1469 if (endswith(filename, "~"))
1472 return ignore_file_allow_backup(filename);
1475 int fd_nonblock(int fd, bool nonblock) {
1480 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1484 flags |= O_NONBLOCK;
1486 flags &= ~O_NONBLOCK;
1488 if (fcntl(fd, F_SETFL, flags) < 0)
1494 int fd_cloexec(int fd, bool cloexec) {
1499 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1503 flags |= FD_CLOEXEC;
1505 flags &= ~FD_CLOEXEC;
1507 if (fcntl(fd, F_SETFD, flags) < 0)
1513 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1516 assert(n_fdset == 0 || fdset);
1518 for (i = 0; i < n_fdset; i++)
1525 int close_all_fds(const int except[], unsigned n_except) {
1530 assert(n_except == 0 || except);
1532 d = opendir("/proc/self/fd");
1537 /* When /proc isn't available (for example in chroots)
1538 * the fallback is brute forcing through the fd
1541 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1542 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1544 if (fd_in_set(fd, except, n_except))
1547 if (close_nointr(fd) < 0)
1548 if (errno != EBADF && r == 0)
1555 while ((de = readdir(d))) {
1558 if (ignore_file(de->d_name))
1561 if (safe_atoi(de->d_name, &fd) < 0)
1562 /* Let's better ignore this, just in case */
1571 if (fd_in_set(fd, except, n_except))
1574 if (close_nointr(fd) < 0) {
1575 /* Valgrind has its own FD and doesn't want to have it closed */
1576 if (errno != EBADF && r == 0)
1585 bool chars_intersect(const char *a, const char *b) {
1588 /* Returns true if any of the chars in a are in b. */
1589 for (p = a; *p; p++)
1596 bool fstype_is_network(const char *fstype) {
1597 static const char table[] =
1606 return nulstr_contains(table, fstype);
1610 _cleanup_close_ int fd;
1612 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1618 TIOCL_GETKMSGREDIRECT,
1622 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1625 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1628 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1634 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1635 struct termios old_termios, new_termios;
1637 char line[LINE_MAX];
1642 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1643 new_termios = old_termios;
1645 new_termios.c_lflag &= ~ICANON;
1646 new_termios.c_cc[VMIN] = 1;
1647 new_termios.c_cc[VTIME] = 0;
1649 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1652 if (t != (usec_t) -1) {
1653 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1654 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1659 k = fread(&c, 1, 1, f);
1661 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1667 *need_nl = c != '\n';
1674 if (t != (usec_t) -1)
1675 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1678 if (!fgets(line, sizeof(line), f))
1683 if (strlen(line) != 1)
1693 int ask(char *ret, const char *replies, const char *text, ...) {
1703 bool need_nl = true;
1706 fputs(ANSI_HIGHLIGHT_ON, stdout);
1713 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1717 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1720 if (r == -EBADMSG) {
1721 puts("Bad input, please try again.");
1732 if (strchr(replies, c)) {
1737 puts("Read unexpected character, please try again.");
1741 int reset_terminal_fd(int fd, bool switch_to_text) {
1742 struct termios termios;
1745 /* Set terminal to some sane defaults */
1749 /* We leave locked terminal attributes untouched, so that
1750 * Plymouth may set whatever it wants to set, and we don't
1751 * interfere with that. */
1753 /* Disable exclusive mode, just in case */
1754 ioctl(fd, TIOCNXCL);
1756 /* Switch to text mode */
1758 ioctl(fd, KDSETMODE, KD_TEXT);
1760 /* Enable console unicode mode */
1761 ioctl(fd, KDSKBMODE, K_UNICODE);
1763 if (tcgetattr(fd, &termios) < 0) {
1768 /* We only reset the stuff that matters to the software. How
1769 * hardware is set up we don't touch assuming that somebody
1770 * else will do that for us */
1772 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1773 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1774 termios.c_oflag |= ONLCR;
1775 termios.c_cflag |= CREAD;
1776 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1778 termios.c_cc[VINTR] = 03; /* ^C */
1779 termios.c_cc[VQUIT] = 034; /* ^\ */
1780 termios.c_cc[VERASE] = 0177;
1781 termios.c_cc[VKILL] = 025; /* ^X */
1782 termios.c_cc[VEOF] = 04; /* ^D */
1783 termios.c_cc[VSTART] = 021; /* ^Q */
1784 termios.c_cc[VSTOP] = 023; /* ^S */
1785 termios.c_cc[VSUSP] = 032; /* ^Z */
1786 termios.c_cc[VLNEXT] = 026; /* ^V */
1787 termios.c_cc[VWERASE] = 027; /* ^W */
1788 termios.c_cc[VREPRINT] = 022; /* ^R */
1789 termios.c_cc[VEOL] = 0;
1790 termios.c_cc[VEOL2] = 0;
1792 termios.c_cc[VTIME] = 0;
1793 termios.c_cc[VMIN] = 1;
1795 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1799 /* Just in case, flush all crap out */
1800 tcflush(fd, TCIOFLUSH);
1805 int reset_terminal(const char *name) {
1808 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1812 r = reset_terminal_fd(fd, true);
1813 close_nointr_nofail(fd);
1818 int open_terminal(const char *name, int mode) {
1823 * If a TTY is in the process of being closed opening it might
1824 * cause EIO. This is horribly awful, but unlikely to be
1825 * changed in the kernel. Hence we work around this problem by
1826 * retrying a couple of times.
1828 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1832 fd = open(name, mode);
1839 /* Max 1s in total */
1843 usleep(50 * USEC_PER_MSEC);
1852 close_nointr_nofail(fd);
1857 close_nointr_nofail(fd);
1864 int flush_fd(int fd) {
1865 struct pollfd pollfd;
1869 pollfd.events = POLLIN;
1876 if ((r = poll(&pollfd, 1, 0)) < 0) {
1887 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1892 if (errno == EAGAIN)
1903 int acquire_terminal(
1907 bool ignore_tiocstty_eperm,
1910 int fd = -1, notify = -1, r = 0, wd = -1;
1912 struct sigaction sa_old, sa_new;
1916 /* We use inotify to be notified when the tty is closed. We
1917 * create the watch before checking if we can actually acquire
1918 * it, so that we don't lose any event.
1920 * Note: strictly speaking this actually watches for the
1921 * device being closed, it does *not* really watch whether a
1922 * tty loses its controlling process. However, unless some
1923 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1924 * its tty otherwise this will not become a problem. As long
1925 * as the administrator makes sure not configure any service
1926 * on the same tty as an untrusted user this should not be a
1927 * problem. (Which he probably should not do anyway.) */
1929 if (timeout != (usec_t) -1)
1930 ts = now(CLOCK_MONOTONIC);
1932 if (!fail && !force) {
1933 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1939 wd = inotify_add_watch(notify, name, IN_CLOSE);
1948 r = flush_fd(notify);
1953 /* We pass here O_NOCTTY only so that we can check the return
1954 * value TIOCSCTTY and have a reliable way to figure out if we
1955 * successfully became the controlling process of the tty */
1956 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1960 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1961 * if we already own the tty. */
1963 sa_new.sa_handler = SIG_IGN;
1964 sa_new.sa_flags = SA_RESTART;
1965 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1967 /* First, try to get the tty */
1968 if (ioctl(fd, TIOCSCTTY, force) < 0)
1971 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1973 /* Sometimes it makes sense to ignore TIOCSCTTY
1974 * returning EPERM, i.e. when very likely we already
1975 * are have this controlling terminal. */
1976 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1979 if (r < 0 && (force || fail || r != -EPERM)) {
1988 assert(notify >= 0);
1991 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1993 struct inotify_event *e;
1995 if (timeout != (usec_t) -1) {
1998 n = now(CLOCK_MONOTONIC);
1999 if (ts + timeout < n) {
2004 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2014 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2017 if (errno == EINTR || errno == EAGAIN)
2024 e = (struct inotify_event*) inotify_buffer;
2029 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2034 step = sizeof(struct inotify_event) + e->len;
2035 assert(step <= (size_t) l);
2037 e = (struct inotify_event*) ((uint8_t*) e + step);
2044 /* We close the tty fd here since if the old session
2045 * ended our handle will be dead. It's important that
2046 * we do this after sleeping, so that we don't enter
2047 * an endless loop. */
2048 close_nointr_nofail(fd);
2052 close_nointr_nofail(notify);
2054 r = reset_terminal_fd(fd, true);
2056 log_warning("Failed to reset terminal: %s", strerror(-r));
2062 close_nointr_nofail(fd);
2065 close_nointr_nofail(notify);
2070 int release_terminal(void) {
2072 struct sigaction sa_old, sa_new;
2074 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2077 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2078 * by our own TIOCNOTTY */
2081 sa_new.sa_handler = SIG_IGN;
2082 sa_new.sa_flags = SA_RESTART;
2083 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2085 if (ioctl(fd, TIOCNOTTY) < 0)
2088 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2090 close_nointr_nofail(fd);
2094 int sigaction_many(const struct sigaction *sa, ...) {
2099 while ((sig = va_arg(ap, int)) > 0)
2100 if (sigaction(sig, sa, NULL) < 0)
2107 int ignore_signals(int sig, ...) {
2108 struct sigaction sa;
2113 sa.sa_handler = SIG_IGN;
2114 sa.sa_flags = SA_RESTART;
2116 if (sigaction(sig, &sa, NULL) < 0)
2120 while ((sig = va_arg(ap, int)) > 0)
2121 if (sigaction(sig, &sa, NULL) < 0)
2128 int default_signals(int sig, ...) {
2129 struct sigaction sa;
2134 sa.sa_handler = SIG_DFL;
2135 sa.sa_flags = SA_RESTART;
2137 if (sigaction(sig, &sa, NULL) < 0)
2141 while ((sig = va_arg(ap, int)) > 0)
2142 if (sigaction(sig, &sa, NULL) < 0)
2149 int close_pipe(int p[]) {
2155 a = close_nointr(p[0]);
2160 b = close_nointr(p[1]);
2164 return a < 0 ? a : b;
2167 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2176 while (nbytes > 0) {
2179 if ((k = read(fd, p, nbytes)) <= 0) {
2181 if (k < 0 && errno == EINTR)
2184 if (k < 0 && errno == EAGAIN && do_poll) {
2185 struct pollfd pollfd;
2189 pollfd.events = POLLIN;
2191 if (poll(&pollfd, 1, -1) < 0) {
2195 return n > 0 ? n : -errno;
2198 if (pollfd.revents != POLLIN)
2199 return n > 0 ? n : -EIO;
2204 return n > 0 ? n : (k < 0 ? -errno : 0);
2215 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2224 while (nbytes > 0) {
2227 k = write(fd, p, nbytes);
2230 if (k < 0 && errno == EINTR)
2233 if (k < 0 && errno == EAGAIN && do_poll) {
2234 struct pollfd pollfd;
2238 pollfd.events = POLLOUT;
2240 if (poll(&pollfd, 1, -1) < 0) {
2244 return n > 0 ? n : -errno;
2247 if (pollfd.revents != POLLOUT)
2248 return n > 0 ? n : -EIO;
2253 return n > 0 ? n : (k < 0 ? -errno : 0);
2264 int parse_bytes(const char *t, off_t *bytes) {
2265 static const struct {
2271 { "M", 1024ULL*1024ULL },
2272 { "G", 1024ULL*1024ULL*1024ULL },
2273 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2274 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2275 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2292 l = strtoll(p, &e, 10);
2303 e += strspn(e, WHITESPACE);
2305 for (i = 0; i < ELEMENTSOF(table); i++)
2306 if (startswith(e, table[i].suffix)) {
2307 r += (off_t) l * table[i].factor;
2308 p = e + strlen(table[i].suffix);
2312 if (i >= ELEMENTSOF(table))
2322 int make_stdio(int fd) {
2327 r = dup3(fd, STDIN_FILENO, 0);
2328 s = dup3(fd, STDOUT_FILENO, 0);
2329 t = dup3(fd, STDERR_FILENO, 0);
2332 close_nointr_nofail(fd);
2334 if (r < 0 || s < 0 || t < 0)
2337 /* We rely here that the new fd has O_CLOEXEC not set */
2342 int make_null_stdio(void) {
2345 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2349 return make_stdio(null_fd);
2352 bool is_device_path(const char *path) {
2354 /* Returns true on paths that refer to a device, either in
2355 * sysfs or in /dev */
2358 path_startswith(path, "/dev/") ||
2359 path_startswith(path, "/sys/");
2362 int dir_is_empty(const char *path) {
2363 _cleanup_closedir_ DIR *d;
2372 union dirent_storage buf;
2374 r = readdir_r(d, &buf.de, &de);
2381 if (!ignore_file(de->d_name))
2386 char* dirname_malloc(const char *path) {
2387 char *d, *dir, *dir2;
2404 unsigned long long random_ull(void) {
2405 _cleanup_close_ int fd;
2409 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2413 r = loop_read(fd, &ull, sizeof(ull), true);
2414 if (r != sizeof(ull))
2420 return random() * RAND_MAX + random();
2423 void rename_process(const char name[8]) {
2426 /* This is a like a poor man's setproctitle(). It changes the
2427 * comm field, argv[0], and also the glibc's internally used
2428 * name of the process. For the first one a limit of 16 chars
2429 * applies, to the second one usually one of 10 (i.e. length
2430 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2431 * "systemd"). If you pass a longer string it will be
2434 prctl(PR_SET_NAME, name);
2436 if (program_invocation_name)
2437 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2439 if (saved_argc > 0) {
2443 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2445 for (i = 1; i < saved_argc; i++) {
2449 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2454 void sigset_add_many(sigset_t *ss, ...) {
2461 while ((sig = va_arg(ap, int)) > 0)
2462 assert_se(sigaddset(ss, sig) == 0);
2466 char* gethostname_malloc(void) {
2469 assert_se(uname(&u) >= 0);
2471 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2472 return strdup(u.nodename);
2474 return strdup(u.sysname);
2477 bool hostname_is_set(void) {
2480 assert_se(uname(&u) >= 0);
2482 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2485 static char *lookup_uid(uid_t uid) {
2488 _cleanup_free_ char *buf = NULL;
2489 struct passwd pwbuf, *pw = NULL;
2491 /* Shortcut things to avoid NSS lookups */
2493 return strdup("root");
2495 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2499 buf = malloc(bufsize);
2503 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2504 return strdup(pw->pw_name);
2506 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2512 char* getlogname_malloc(void) {
2516 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2521 return lookup_uid(uid);
2524 char *getusername_malloc(void) {
2531 return lookup_uid(getuid());
2534 int getttyname_malloc(int fd, char **r) {
2535 char path[PATH_MAX], *c;
2540 k = ttyname_r(fd, path, sizeof(path));
2546 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2554 int getttyname_harder(int fd, char **r) {
2558 k = getttyname_malloc(fd, &s);
2562 if (streq(s, "tty")) {
2564 return get_ctty(0, NULL, r);
2571 int get_ctty_devnr(pid_t pid, dev_t *d) {
2573 char line[LINE_MAX], *p, *fn;
2574 unsigned long ttynr;
2577 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2580 f = fopen(fn, "re");
2585 if (!fgets(line, sizeof(line), f)) {
2586 k = feof(f) ? -EIO : -errno;
2593 p = strrchr(line, ')');
2603 "%*d " /* session */
2608 if (major(ttynr) == 0 && minor(ttynr) == 0)
2615 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2617 char fn[PATH_MAX], *s, *b, *p;
2622 k = get_ctty_devnr(pid, &devnr);
2626 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2629 k = readlink_malloc(fn, &s);
2635 /* This is an ugly hack */
2636 if (major(devnr) == 136) {
2637 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2647 /* Probably something like the ptys which have no
2648 * symlink in /dev/char. Let's return something
2649 * vaguely useful. */
2662 if (startswith(s, "/dev/"))
2664 else if (startswith(s, "../"))
2682 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2688 /* This returns the first error we run into, but nevertheless
2689 * tries to go on. This closes the passed fd. */
2693 close_nointr_nofail(fd);
2695 return errno == ENOENT ? 0 : -errno;
2700 union dirent_storage buf;
2701 bool is_dir, keep_around;
2705 r = readdir_r(d, &buf.de, &de);
2706 if (r != 0 && ret == 0) {
2714 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2717 if (de->d_type == DT_UNKNOWN ||
2719 (de->d_type == DT_DIR && root_dev)) {
2720 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2721 if (ret == 0 && errno != ENOENT)
2726 is_dir = S_ISDIR(st.st_mode);
2729 (st.st_uid == 0 || st.st_uid == getuid()) &&
2730 (st.st_mode & S_ISVTX);
2732 is_dir = de->d_type == DT_DIR;
2733 keep_around = false;
2739 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2740 if (root_dev && st.st_dev != root_dev->st_dev)
2743 subdir_fd = openat(fd, de->d_name,
2744 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2745 if (subdir_fd < 0) {
2746 if (ret == 0 && errno != ENOENT)
2751 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2752 if (r < 0 && ret == 0)
2756 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2757 if (ret == 0 && errno != ENOENT)
2761 } else if (!only_dirs && !keep_around) {
2763 if (unlinkat(fd, de->d_name, 0) < 0) {
2764 if (ret == 0 && errno != ENOENT)
2775 static int is_temporary_fs(struct statfs *s) {
2777 return s->f_type == TMPFS_MAGIC ||
2778 (long)s->f_type == (long)RAMFS_MAGIC;
2781 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2786 if (fstatfs(fd, &s) < 0) {
2787 close_nointr_nofail(fd);
2791 /* We refuse to clean disk file systems with this call. This
2792 * is extra paranoia just to be sure we never ever remove
2794 if (!is_temporary_fs(&s)) {
2795 log_error("Attempted to remove disk file system, and we can't allow that.");
2796 close_nointr_nofail(fd);
2800 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2803 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2809 /* We refuse to clean the root file system with this
2810 * call. This is extra paranoia to never cause a really
2811 * seriously broken system. */
2812 if (path_equal(path, "/")) {
2813 log_error("Attempted to remove entire root file system, and we can't allow that.");
2817 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2820 if (errno != ENOTDIR)
2824 if (statfs(path, &s) < 0)
2827 if (!is_temporary_fs(&s)) {
2828 log_error("Attempted to remove disk file system, and we can't allow that.");
2833 if (delete_root && !only_dirs)
2834 if (unlink(path) < 0 && errno != ENOENT)
2841 if (fstatfs(fd, &s) < 0) {
2842 close_nointr_nofail(fd);
2846 if (!is_temporary_fs(&s)) {
2847 log_error("Attempted to remove disk file system, and we can't allow that.");
2848 close_nointr_nofail(fd);
2853 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2856 if (honour_sticky && file_is_priv_sticky(path) > 0)
2859 if (rmdir(path) < 0 && errno != ENOENT) {
2868 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2869 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2872 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2873 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2876 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2879 /* Under the assumption that we are running privileged we
2880 * first change the access mode and only then hand out
2881 * ownership to avoid a window where access is too open. */
2883 if (mode != (mode_t) -1)
2884 if (chmod(path, mode) < 0)
2887 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2888 if (chown(path, uid, gid) < 0)
2894 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2897 /* Under the assumption that we are running privileged we
2898 * first change the access mode and only then hand out
2899 * ownership to avoid a window where access is too open. */
2901 if (fchmod(fd, mode) < 0)
2904 if (fchown(fd, uid, gid) < 0)
2910 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2914 /* Allocates the cpuset in the right size */
2917 if (!(r = CPU_ALLOC(n)))
2920 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2921 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2931 if (errno != EINVAL)
2938 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2939 static const char status_indent[] = " "; /* "[" STATUS "] " */
2940 _cleanup_free_ char *s = NULL;
2941 _cleanup_close_ int fd = -1;
2942 struct iovec iovec[6];
2944 static bool prev_ephemeral;
2948 /* This is independent of logging, as status messages are
2949 * optional and go exclusively to the console. */
2951 if (vasprintf(&s, format, ap) < 0)
2954 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2967 sl = status ? sizeof(status_indent)-1 : 0;
2973 e = ellipsize(s, emax, 75);
2983 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2984 prev_ephemeral = ephemeral;
2987 if (!isempty(status)) {
2988 IOVEC_SET_STRING(iovec[n++], "[");
2989 IOVEC_SET_STRING(iovec[n++], status);
2990 IOVEC_SET_STRING(iovec[n++], "] ");
2992 IOVEC_SET_STRING(iovec[n++], status_indent);
2995 IOVEC_SET_STRING(iovec[n++], s);
2997 IOVEC_SET_STRING(iovec[n++], "\n");
2999 if (writev(fd, iovec, n) < 0)
3005 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3011 va_start(ap, format);
3012 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3018 int status_welcome(void) {
3020 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3022 r = parse_env_file("/etc/os-release", NEWLINE,
3023 "PRETTY_NAME", &pretty_name,
3024 "ANSI_COLOR", &ansi_color,
3026 if (r < 0 && r != -ENOENT)
3027 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3029 return status_printf(NULL, false, false,
3030 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3031 isempty(ansi_color) ? "1" : ansi_color,
3032 isempty(pretty_name) ? "Linux" : pretty_name);
3035 char *replace_env(const char *format, char **env) {
3042 const char *e, *word = format;
3047 for (e = format; *e; e ++) {
3058 if (!(k = strnappend(r, word, e-word-1)))
3067 } else if (*e == '$') {
3068 if (!(k = strnappend(r, word, e-word)))
3084 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3086 k = strappend(r, t);
3100 if (!(k = strnappend(r, word, e-word)))
3111 char **replace_env_argv(char **argv, char **env) {
3113 unsigned k = 0, l = 0;
3115 l = strv_length(argv);
3117 if (!(r = new(char*, l+1)))
3120 STRV_FOREACH(i, argv) {
3122 /* If $FOO appears as single word, replace it by the split up variable */
3123 if ((*i)[0] == '$' && (*i)[1] != '{') {
3128 e = strv_env_get(env, *i+1);
3131 if (!(m = strv_split_quoted(e))) {
3142 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3151 memcpy(r + k, m, q * sizeof(char*));
3159 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3160 if (!(r[k++] = replace_env(*i, env))) {
3170 int fd_columns(int fd) {
3174 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3183 unsigned columns(void) {
3187 if (_likely_(cached_columns > 0))
3188 return cached_columns;
3191 e = getenv("COLUMNS");
3196 c = fd_columns(STDOUT_FILENO);
3205 int fd_lines(int fd) {
3209 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3218 unsigned lines(void) {
3222 if (_likely_(cached_lines > 0))
3223 return cached_lines;
3226 e = getenv("LINES");
3231 l = fd_lines(STDOUT_FILENO);
3237 return cached_lines;
3240 /* intended to be used as a SIGWINCH sighandler */
3241 void columns_lines_cache_reset(int signum) {
3247 static int cached_on_tty = -1;
3249 if (_unlikely_(cached_on_tty < 0))
3250 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3252 return cached_on_tty;
3255 int running_in_chroot(void) {
3261 /* Only works as root */
3263 if (stat("/proc/1/root", &a) < 0)
3266 if (stat("/", &b) < 0)
3270 a.st_dev != b.st_dev ||
3271 a.st_ino != b.st_ino;
3274 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3279 assert(percent <= 100);
3280 assert(new_length >= 3);
3282 if (old_length <= 3 || old_length <= new_length)
3283 return strndup(s, old_length);
3285 r = new0(char, new_length+1);
3289 x = (new_length * percent) / 100;
3291 if (x > new_length - 3)
3299 s + old_length - (new_length - x - 3),
3300 new_length - x - 3);
3305 char *ellipsize(const char *s, size_t length, unsigned percent) {
3306 return ellipsize_mem(s, strlen(s), length, percent);
3309 int touch(const char *path) {
3314 /* This just opens the file for writing, ensuring it
3315 * exists. It doesn't call utimensat() the way /usr/bin/touch
3318 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3322 close_nointr_nofail(fd);
3326 char *unquote(const char *s, const char* quotes) {
3330 /* This is rather stupid, simply removes the heading and
3331 * trailing quotes if there is one. Doesn't care about
3332 * escaping or anything. We should make this smarter one
3339 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3340 return strndup(s+1, l-2);
3345 char *normalize_env_assignment(const char *s) {
3346 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3349 eq = strchr(s, '=');
3361 memmove(r, t, strlen(t) + 1);
3365 name = strndup(s, eq - s);
3373 value = unquote(strstrip(p), QUOTES);
3377 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3383 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3394 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3406 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3413 r = wait_for_terminate(pid, &status);
3415 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3419 if (status.si_code == CLD_EXITED) {
3420 if (status.si_status != 0) {
3421 log_warning("%s failed with error code %i.", name, status.si_status);
3422 return status.si_status;
3425 log_debug("%s succeeded.", name);
3428 } else if (status.si_code == CLD_KILLED ||
3429 status.si_code == CLD_DUMPED) {
3431 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3435 log_warning("%s failed due to unknown reason.", name);
3439 _noreturn_ void freeze(void) {
3441 /* Make sure nobody waits for us on a socket anymore */
3442 close_all_fds(NULL, 0);
3450 bool null_or_empty(struct stat *st) {
3453 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3456 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3462 int null_or_empty_path(const char *fn) {
3467 if (stat(fn, &st) < 0)
3470 return null_or_empty(&st);
3473 DIR *xopendirat(int fd, const char *name, int flags) {
3477 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3483 close_nointr_nofail(nfd);
3490 int signal_from_string_try_harder(const char *s) {
3494 signo = signal_from_string(s);
3496 if (startswith(s, "SIG"))
3497 return signal_from_string(s+3);
3502 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3506 /* FIXME: to follow udev's logic 100% we need to leave valid
3507 * UTF8 chars unescaped */
3509 u = unquote(tagvalue, "\"\'");
3513 t = xescape(u, "/ ");
3519 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3528 char *fstab_node_to_udev_node(const char *p) {
3531 if (startswith(p, "LABEL="))
3532 return tag_to_udev_node(p+6, "label");
3534 if (startswith(p, "UUID="))
3535 return tag_to_udev_node(p+5, "uuid");
3537 if (startswith(p, "PARTUUID="))
3538 return tag_to_udev_node(p+9, "partuuid");
3540 if (startswith(p, "PARTLABEL="))
3541 return tag_to_udev_node(p+10, "partlabel");
3546 bool tty_is_vc(const char *tty) {
3549 if (startswith(tty, "/dev/"))
3552 return vtnr_from_tty(tty) >= 0;
3555 bool tty_is_console(const char *tty) {
3558 if (startswith(tty, "/dev/"))
3561 return streq(tty, "console");
3564 int vtnr_from_tty(const char *tty) {
3569 if (startswith(tty, "/dev/"))
3572 if (!startswith(tty, "tty") )
3575 if (tty[3] < '0' || tty[3] > '9')
3578 r = safe_atoi(tty+3, &i);
3582 if (i < 0 || i > 63)
3588 char *resolve_dev_console(char **active) {
3591 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3592 * (i.e. not read-only-mounted which is a sign for container setups) */
3594 if (path_is_read_only_fs("/sys") > 0)
3597 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3600 /* If multiple log outputs are configured the last one is what
3601 * /dev/console points to */
3602 tty = strrchr(*active, ' ');
3611 bool tty_is_vc_resolve(const char *tty) {
3612 char *active = NULL;
3617 if (startswith(tty, "/dev/"))
3620 if (streq(tty, "console")) {
3621 tty = resolve_dev_console(&active);
3632 const char *default_term_for_tty(const char *tty) {
3635 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3638 bool dirent_is_file(const struct dirent *de) {
3641 if (ignore_file(de->d_name))
3644 if (de->d_type != DT_REG &&
3645 de->d_type != DT_LNK &&
3646 de->d_type != DT_UNKNOWN)
3652 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3655 if (de->d_type != DT_REG &&
3656 de->d_type != DT_LNK &&
3657 de->d_type != DT_UNKNOWN)
3660 if (ignore_file_allow_backup(de->d_name))
3663 return endswith(de->d_name, suffix);
3666 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3669 Hashmap *pids = NULL;
3673 /* Executes all binaries in a directory in parallel and
3674 * waits for them to finish. */
3677 if (!(_d = opendir(directory))) {
3679 if (errno == ENOENT)
3682 log_error("Failed to enumerate directory %s: %m", directory);
3689 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3690 log_error("Failed to allocate set.");
3694 while ((de = readdir(d))) {
3699 if (!dirent_is_file(de))
3702 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3707 if ((pid = fork()) < 0) {
3708 log_error("Failed to fork: %m");
3726 log_error("Failed to execute %s: %m", path);
3727 _exit(EXIT_FAILURE);
3730 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3732 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3733 log_error("Failed to add PID to set: %s", strerror(-k));
3738 while (!hashmap_isempty(pids)) {
3739 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3744 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3749 log_error("waitid() failed: %m");
3753 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3754 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3755 if (si.si_code == CLD_EXITED)
3756 log_error("%s exited with exit status %i.", path, si.si_status);
3758 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3760 log_debug("%s exited successfully.", path);
3771 hashmap_free_free(pids);
3774 int kill_and_sigcont(pid_t pid, int sig) {
3777 r = kill(pid, sig) < 0 ? -errno : 0;
3785 bool nulstr_contains(const char*nulstr, const char *needle) {
3791 NULSTR_FOREACH(i, nulstr)
3792 if (streq(i, needle))
3798 bool plymouth_running(void) {
3799 return access("/run/plymouth/pid", F_OK) >= 0;
3802 char* strshorten(char *s, size_t l) {
3811 static bool hostname_valid_char(char c) {
3813 (c >= 'a' && c <= 'z') ||
3814 (c >= 'A' && c <= 'Z') ||
3815 (c >= '0' && c <= '9') ||
3821 bool hostname_is_valid(const char *s) {
3828 for (p = s, dot = true; *p; p++) {
3835 if (!hostname_valid_char(*p))
3845 if (p-s > HOST_NAME_MAX)
3851 char* hostname_cleanup(char *s) {
3854 for (p = s, d = s; *p; p++)
3855 if ((*p >= 'a' && *p <= 'z') ||
3856 (*p >= 'A' && *p <= 'Z') ||
3857 (*p >= '0' && *p <= '9') ||
3865 strshorten(s, HOST_NAME_MAX);
3869 int pipe_eof(int fd) {
3870 struct pollfd pollfd;
3875 pollfd.events = POLLIN|POLLHUP;
3877 r = poll(&pollfd, 1, 0);
3884 return pollfd.revents & POLLHUP;
3887 int fd_wait_for_event(int fd, int event, usec_t t) {
3888 struct pollfd pollfd;
3893 pollfd.events = event;
3895 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3902 return pollfd.revents;
3905 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3916 t = new(char, strlen(path) + 1 + 6 + 1);
3920 fn = path_get_file_name(path);
3924 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3926 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3932 f = fdopen(fd, "we");
3945 int terminal_vhangup_fd(int fd) {
3948 if (ioctl(fd, TIOCVHANGUP) < 0)
3954 int terminal_vhangup(const char *name) {
3957 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3961 r = terminal_vhangup_fd(fd);
3962 close_nointr_nofail(fd);
3967 int vt_disallocate(const char *name) {
3971 /* Deallocate the VT if possible. If not possible
3972 * (i.e. because it is the active one), at least clear it
3973 * entirely (including the scrollback buffer) */
3975 if (!startswith(name, "/dev/"))
3978 if (!tty_is_vc(name)) {
3979 /* So this is not a VT. I guess we cannot deallocate
3980 * it then. But let's at least clear the screen */
3982 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3987 "\033[r" /* clear scrolling region */
3988 "\033[H" /* move home */
3989 "\033[2J", /* clear screen */
3991 close_nointr_nofail(fd);
3996 if (!startswith(name, "/dev/tty"))
3999 r = safe_atou(name+8, &u);
4006 /* Try to deallocate */
4007 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4011 r = ioctl(fd, VT_DISALLOCATE, u);
4012 close_nointr_nofail(fd);
4020 /* Couldn't deallocate, so let's clear it fully with
4022 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4027 "\033[r" /* clear scrolling region */
4028 "\033[H" /* move home */
4029 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4031 close_nointr_nofail(fd);
4036 int copy_file(const char *from, const char *to) {
4042 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4046 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4048 close_nointr_nofail(fdf);
4056 n = read(fdf, buf, sizeof(buf));
4060 close_nointr_nofail(fdf);
4071 k = loop_write(fdt, buf, n, false);
4073 r = k < 0 ? k : (errno ? -errno : -EIO);
4075 close_nointr_nofail(fdf);
4083 close_nointr_nofail(fdf);
4084 r = close_nointr(fdt);
4094 int symlink_atomic(const char *from, const char *to) {
4096 _cleanup_free_ char *t;
4099 unsigned long long ull;
4106 t = new(char, strlen(to) + 1 + 16 + 1);
4110 fn = path_get_file_name(to);
4114 x = stpcpy(t+k+1, fn);
4117 for (i = 0; i < 16; i++) {
4118 *(x++) = hexchar(ull & 0xF);
4124 if (symlink(from, t) < 0)
4127 if (rename(t, to) < 0) {
4136 bool display_is_local(const char *display) {
4140 display[0] == ':' &&
4141 display[1] >= '0' &&
4145 int socket_from_display(const char *display, char **path) {
4152 if (!display_is_local(display))
4155 k = strspn(display+1, "0123456789");
4157 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4161 c = stpcpy(f, "/tmp/.X11-unix/X");
4162 memcpy(c, display+1, k);
4171 const char **username,
4172 uid_t *uid, gid_t *gid,
4174 const char **shell) {
4182 /* We enforce some special rules for uid=0: in order to avoid
4183 * NSS lookups for root we hardcode its data. */
4185 if (streq(*username, "root") || streq(*username, "0")) {
4203 if (parse_uid(*username, &u) >= 0) {
4207 /* If there are multiple users with the same id, make
4208 * sure to leave $USER to the configured value instead
4209 * of the first occurrence in the database. However if
4210 * the uid was configured by a numeric uid, then let's
4211 * pick the real username from /etc/passwd. */
4213 *username = p->pw_name;
4216 p = getpwnam(*username);
4220 return errno > 0 ? -errno : -ESRCH;
4232 *shell = p->pw_shell;
4237 char* uid_to_name(uid_t uid) {
4242 return strdup("root");
4246 return strdup(p->pw_name);
4248 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4254 char* gid_to_name(gid_t gid) {
4259 return strdup("root");
4263 return strdup(p->gr_name);
4265 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4271 int get_group_creds(const char **groupname, gid_t *gid) {
4277 /* We enforce some special rules for gid=0: in order to avoid
4278 * NSS lookups for root we hardcode its data. */
4280 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4281 *groupname = "root";
4289 if (parse_gid(*groupname, &id) >= 0) {
4294 *groupname = g->gr_name;
4297 g = getgrnam(*groupname);
4301 return errno > 0 ? -errno : -ESRCH;
4309 int in_gid(gid_t gid) {
4311 int ngroups_max, r, i;
4313 if (getgid() == gid)
4316 if (getegid() == gid)
4319 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4320 assert(ngroups_max > 0);
4322 gids = alloca(sizeof(gid_t) * ngroups_max);
4324 r = getgroups(ngroups_max, gids);
4328 for (i = 0; i < r; i++)
4335 int in_group(const char *name) {
4339 r = get_group_creds(&name, &gid);
4346 int glob_exists(const char *path) {
4354 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4356 if (k == GLOB_NOMATCH)
4358 else if (k == GLOB_NOSPACE)
4361 r = !strv_isempty(g.gl_pathv);
4363 r = errno ? -errno : -EIO;
4370 int dirent_ensure_type(DIR *d, struct dirent *de) {
4376 if (de->d_type != DT_UNKNOWN)
4379 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4383 S_ISREG(st.st_mode) ? DT_REG :
4384 S_ISDIR(st.st_mode) ? DT_DIR :
4385 S_ISLNK(st.st_mode) ? DT_LNK :
4386 S_ISFIFO(st.st_mode) ? DT_FIFO :
4387 S_ISSOCK(st.st_mode) ? DT_SOCK :
4388 S_ISCHR(st.st_mode) ? DT_CHR :
4389 S_ISBLK(st.st_mode) ? DT_BLK :
4395 int in_search_path(const char *path, char **search) {
4399 r = path_get_parent(path, &parent);
4405 STRV_FOREACH(i, search) {
4406 if (path_equal(parent, *i)) {
4417 int get_files_in_directory(const char *path, char ***list) {
4425 /* Returns all files in a directory in *list, and the number
4426 * of files as return value. If list is NULL returns only the
4435 union dirent_storage buf;
4438 k = readdir_r(d, &buf.de, &de);
4447 dirent_ensure_type(d, de);
4449 if (!dirent_is_file(de))
4453 if ((unsigned) r >= n) {
4457 t = realloc(l, sizeof(char*) * n);
4466 assert((unsigned) r < n);
4468 l[r] = strdup(de->d_name);
4492 char *strjoin(const char *x, ...) {
4506 t = va_arg(ap, const char *);
4511 if (n > ((size_t) -1) - l) {
4535 t = va_arg(ap, const char *);
4549 bool is_main_thread(void) {
4550 static __thread int cached = 0;
4552 if (_unlikely_(cached == 0))
4553 cached = getpid() == gettid() ? 1 : -1;
4558 int block_get_whole_disk(dev_t d, dev_t *ret) {
4565 /* If it has a queue this is good enough for us */
4566 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4569 r = access(p, F_OK);
4577 /* If it is a partition find the originating device */
4578 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4581 r = access(p, F_OK);
4587 /* Get parent dev_t */
4588 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4591 r = read_one_line_file(p, &s);
4597 r = sscanf(s, "%u:%u", &m, &n);
4603 /* Only return this if it is really good enough for us. */
4604 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4607 r = access(p, F_OK);
4611 *ret = makedev(m, n);
4618 int file_is_priv_sticky(const char *p) {
4623 if (lstat(p, &st) < 0)
4627 (st.st_uid == 0 || st.st_uid == getuid()) &&
4628 (st.st_mode & S_ISVTX);
4631 static const char *const ioprio_class_table[] = {
4632 [IOPRIO_CLASS_NONE] = "none",
4633 [IOPRIO_CLASS_RT] = "realtime",
4634 [IOPRIO_CLASS_BE] = "best-effort",
4635 [IOPRIO_CLASS_IDLE] = "idle"
4638 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4640 static const char *const sigchld_code_table[] = {
4641 [CLD_EXITED] = "exited",
4642 [CLD_KILLED] = "killed",
4643 [CLD_DUMPED] = "dumped",
4644 [CLD_TRAPPED] = "trapped",
4645 [CLD_STOPPED] = "stopped",
4646 [CLD_CONTINUED] = "continued",
4649 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4651 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4652 [LOG_FAC(LOG_KERN)] = "kern",
4653 [LOG_FAC(LOG_USER)] = "user",
4654 [LOG_FAC(LOG_MAIL)] = "mail",
4655 [LOG_FAC(LOG_DAEMON)] = "daemon",
4656 [LOG_FAC(LOG_AUTH)] = "auth",
4657 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4658 [LOG_FAC(LOG_LPR)] = "lpr",
4659 [LOG_FAC(LOG_NEWS)] = "news",
4660 [LOG_FAC(LOG_UUCP)] = "uucp",
4661 [LOG_FAC(LOG_CRON)] = "cron",
4662 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4663 [LOG_FAC(LOG_FTP)] = "ftp",
4664 [LOG_FAC(LOG_LOCAL0)] = "local0",
4665 [LOG_FAC(LOG_LOCAL1)] = "local1",
4666 [LOG_FAC(LOG_LOCAL2)] = "local2",
4667 [LOG_FAC(LOG_LOCAL3)] = "local3",
4668 [LOG_FAC(LOG_LOCAL4)] = "local4",
4669 [LOG_FAC(LOG_LOCAL5)] = "local5",
4670 [LOG_FAC(LOG_LOCAL6)] = "local6",
4671 [LOG_FAC(LOG_LOCAL7)] = "local7"
4674 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4676 static const char *const log_level_table[] = {
4677 [LOG_EMERG] = "emerg",
4678 [LOG_ALERT] = "alert",
4679 [LOG_CRIT] = "crit",
4681 [LOG_WARNING] = "warning",
4682 [LOG_NOTICE] = "notice",
4683 [LOG_INFO] = "info",
4684 [LOG_DEBUG] = "debug"
4687 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4689 static const char* const sched_policy_table[] = {
4690 [SCHED_OTHER] = "other",
4691 [SCHED_BATCH] = "batch",
4692 [SCHED_IDLE] = "idle",
4693 [SCHED_FIFO] = "fifo",
4697 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4699 static const char* const rlimit_table[] = {
4700 [RLIMIT_CPU] = "LimitCPU",
4701 [RLIMIT_FSIZE] = "LimitFSIZE",
4702 [RLIMIT_DATA] = "LimitDATA",
4703 [RLIMIT_STACK] = "LimitSTACK",
4704 [RLIMIT_CORE] = "LimitCORE",
4705 [RLIMIT_RSS] = "LimitRSS",
4706 [RLIMIT_NOFILE] = "LimitNOFILE",
4707 [RLIMIT_AS] = "LimitAS",
4708 [RLIMIT_NPROC] = "LimitNPROC",
4709 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4710 [RLIMIT_LOCKS] = "LimitLOCKS",
4711 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4712 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4713 [RLIMIT_NICE] = "LimitNICE",
4714 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4715 [RLIMIT_RTTIME] = "LimitRTTIME"
4718 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4720 static const char* const ip_tos_table[] = {
4721 [IPTOS_LOWDELAY] = "low-delay",
4722 [IPTOS_THROUGHPUT] = "throughput",
4723 [IPTOS_RELIABILITY] = "reliability",
4724 [IPTOS_LOWCOST] = "low-cost",
4727 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4729 static const char *const __signal_table[] = {
4746 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4757 [SIGVTALRM] = "VTALRM",
4759 [SIGWINCH] = "WINCH",
4765 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4767 const char *signal_to_string(int signo) {
4768 static __thread char buf[12];
4771 name = __signal_to_string(signo);
4775 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4776 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4778 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4783 int signal_from_string(const char *s) {
4788 signo = __signal_from_string(s);
4792 if (startswith(s, "RTMIN+")) {
4796 if (safe_atou(s, &u) >= 0) {
4797 signo = (int) u + offset;
4798 if (signo > 0 && signo < _NSIG)
4804 bool kexec_loaded(void) {
4805 bool loaded = false;
4808 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4816 int strdup_or_null(const char *a, char **b) {
4834 int prot_from_flags(int flags) {
4836 switch (flags & O_ACCMODE) {
4845 return PROT_READ|PROT_WRITE;
4852 char *format_bytes(char *buf, size_t l, off_t t) {
4855 static const struct {
4859 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4860 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4861 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4862 { "G", 1024ULL*1024ULL*1024ULL },
4863 { "M", 1024ULL*1024ULL },
4867 for (i = 0; i < ELEMENTSOF(table); i++) {
4869 if (t >= table[i].factor) {
4872 (unsigned long long) (t / table[i].factor),
4873 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4880 snprintf(buf, l, "%lluB", (unsigned long long) t);
4888 void* memdup(const void *p, size_t l) {
4901 int fd_inc_sndbuf(int fd, size_t n) {
4903 socklen_t l = sizeof(value);
4905 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4907 l == sizeof(value) &&
4908 (size_t) value >= n*2)
4912 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4919 int fd_inc_rcvbuf(int fd, size_t n) {
4921 socklen_t l = sizeof(value);
4923 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4925 l == sizeof(value) &&
4926 (size_t) value >= n*2)
4930 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4937 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4938 pid_t parent_pid, agent_pid;
4940 bool stdout_is_tty, stderr_is_tty;
4948 parent_pid = getpid();
4950 /* Spawns a temporary TTY agent, making sure it goes away when
4957 if (agent_pid != 0) {
4964 * Make sure the agent goes away when the parent dies */
4965 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4966 _exit(EXIT_FAILURE);
4968 /* Check whether our parent died before we were able
4969 * to set the death signal */
4970 if (getppid() != parent_pid)
4971 _exit(EXIT_SUCCESS);
4973 /* Don't leak fds to the agent */
4974 close_all_fds(except, n_except);
4976 stdout_is_tty = isatty(STDOUT_FILENO);
4977 stderr_is_tty = isatty(STDERR_FILENO);
4979 if (!stdout_is_tty || !stderr_is_tty) {
4980 /* Detach from stdout/stderr. and reopen
4981 * /dev/tty for them. This is important to
4982 * ensure that when systemctl is started via
4983 * popen() or a similar call that expects to
4984 * read EOF we actually do generate EOF and
4985 * not delay this indefinitely by because we
4986 * keep an unused copy of stdin around. */
4987 fd = open("/dev/tty", O_WRONLY);
4989 log_error("Failed to open /dev/tty: %m");
4990 _exit(EXIT_FAILURE);
4994 dup2(fd, STDOUT_FILENO);
4997 dup2(fd, STDERR_FILENO);
5003 /* Count arguments */
5005 for (n = 0; va_arg(ap, char*); n++)
5010 l = alloca(sizeof(char *) * (n + 1));
5012 /* Fill in arguments */
5014 for (i = 0; i <= n; i++)
5015 l[i] = va_arg(ap, char*);
5019 _exit(EXIT_FAILURE);
5022 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5023 struct rlimit highest, fixed;
5027 if (setrlimit(resource, rlim) >= 0)
5033 /* So we failed to set the desired setrlimit, then let's try
5034 * to get as close as we can */
5035 assert_se(getrlimit(resource, &highest) == 0);
5037 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5038 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5040 if (setrlimit(resource, &fixed) < 0)
5046 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5047 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5059 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5062 f = fopen(path, "re");
5070 char line[LINE_MAX];
5073 for (i = 0; i < sizeof(line)-1; i++) {
5077 if (_unlikely_(c == EOF)) {
5087 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5088 value = strdup(line + l + 1);
5108 int can_sleep(const char *type) {
5112 _cleanup_free_ char *p = NULL;
5116 /* If /sys is read-only we cannot sleep */
5117 if (access("/sys/power/state", W_OK) < 0)
5120 r = read_one_line_file("/sys/power/state", &p);
5125 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5126 if (l == k && memcmp(w, type, l) == 0)
5132 int can_sleep_disk(const char *type) {
5136 _cleanup_free_ char *p = NULL;
5140 /* If /sys is read-only we cannot sleep */
5141 if (access("/sys/power/state", W_OK) < 0 ||
5142 access("/sys/power/disk", W_OK) < 0)
5145 r = read_one_line_file("/sys/power/disk", &p);
5150 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5151 if (l == k && memcmp(w, type, l) == 0)
5154 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5161 bool is_valid_documentation_url(const char *url) {
5164 if (startswith(url, "http://") && url[7])
5167 if (startswith(url, "https://") && url[8])
5170 if (startswith(url, "file:") && url[5])
5173 if (startswith(url, "info:") && url[5])
5176 if (startswith(url, "man:") && url[4])
5182 bool in_initrd(void) {
5183 static __thread int saved = -1;
5189 /* We make two checks here:
5191 * 1. the flag file /etc/initrd-release must exist
5192 * 2. the root file system must be a memory file system
5194 * The second check is extra paranoia, since misdetecting an
5195 * initrd can have bad bad consequences due the initrd
5196 * emptying when transititioning to the main systemd.
5199 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5200 statfs("/", &s) >= 0 &&
5201 is_temporary_fs(&s);
5206 void warn_melody(void) {
5207 _cleanup_close_ int fd = -1;
5209 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5213 /* Yeah, this is synchronous. Kinda sucks. But well... */
5215 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5216 usleep(125*USEC_PER_MSEC);
5218 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5219 usleep(125*USEC_PER_MSEC);
5221 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5222 usleep(125*USEC_PER_MSEC);
5224 ioctl(fd, KIOCSOUND, 0);
5227 int make_console_stdio(void) {
5230 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5232 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5234 log_error("Failed to acquire terminal: %s", strerror(-fd));
5240 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5247 int get_home_dir(char **_h) {
5255 /* Take the user specified one */
5266 /* Hardcode home directory for root to avoid NSS */
5269 h = strdup("/root");
5277 /* Check the database... */
5281 return errno ? -errno : -ESRCH;
5283 if (!path_is_absolute(p->pw_dir))
5286 h = strdup(p->pw_dir);
5294 void fclosep(FILE **f) {
5299 void pclosep(FILE **f) {
5304 void closep(int *fd) {
5306 close_nointr_nofail(*fd);
5309 void closedirp(DIR **d) {
5314 bool filename_is_safe(const char *p) {
5328 if (strlen(p) > FILENAME_MAX)
5334 bool string_is_safe(const char *p) {
5339 for (t = p; *t; t++) {
5340 if (*t > 0 && *t < ' ')
5343 if (strchr("\\\"\'", *t))
5350 bool string_has_cc(const char *p) {
5355 for (t = p; *t; t++)
5356 if (*t > 0 && *t < ' ')
5362 bool path_is_safe(const char *p) {
5367 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5370 if (strlen(p) > PATH_MAX)
5373 /* The following two checks are not really dangerous, but hey, they still are confusing */
5374 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5377 if (strstr(p, "//"))
5383 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5384 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5385 int (*compar) (const void *, const void *, void *), void *arg) {
5394 p = (void *)(((const char *) base) + (idx * size));
5395 comparison = compar(key, p, arg);
5398 else if (comparison > 0)
5406 bool is_locale_utf8(void) {
5408 static int cached_answer = -1;
5410 if (cached_answer >= 0)
5413 if (!setlocale(LC_ALL, "")) {
5414 cached_answer = true;
5418 set = nl_langinfo(CODESET);
5420 cached_answer = true;
5424 cached_answer = streq(set, "UTF-8");
5426 return (bool)cached_answer;
5429 const char *draw_special_char(DrawSpecialChar ch) {
5430 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5432 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5433 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5434 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5435 [DRAW_TREE_SPACE] = " ", /* */
5436 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5438 /* ASCII fallback */ {
5439 [DRAW_TREE_VERT] = "| ",
5440 [DRAW_TREE_BRANCH] = "|-",
5441 [DRAW_TREE_RIGHT] = "`-",
5442 [DRAW_TREE_SPACE] = " ",
5443 [DRAW_TRIANGULAR_BULLET] = "> ",
5447 return draw_table[!is_locale_utf8()][ch];
5450 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5453 size_t l, old_len, new_len;
5459 old_len = strlen(old_string);
5460 new_len = strlen(new_string);
5473 if (!startswith(f, old_string)) {
5479 nl = l - old_len + new_len;
5480 a = realloc(r, nl + 1);
5488 t = stpcpy(t, new_string);
5500 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5501 const char *i, *begin = NULL;
5506 } state = STATE_OTHER;
5508 size_t osz = 0, isz;
5514 /* Strips ANSI color and replaces TABs by 8 spaces */
5516 isz = _isz ? *_isz : strlen(*ibuf);
5518 f = open_memstream(&obuf, &osz);
5522 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5527 if (i >= *ibuf + isz) /* EOT */
5529 else if (*i == '\x1B')
5530 state = STATE_ESCAPE;
5531 else if (*i == '\t')
5538 if (i >= *ibuf + isz) { /* EOT */
5541 } else if (*i == '[') {
5542 state = STATE_BRACKET;
5547 state = STATE_OTHER;
5554 if (i >= *ibuf + isz || /* EOT */
5555 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5558 state = STATE_OTHER;
5560 } else if (*i == 'm')
5561 state = STATE_OTHER;
5583 int on_ac_power(void) {
5584 bool found_offline = false, found_online = false;
5585 _cleanup_closedir_ DIR *d = NULL;
5587 d = opendir("/sys/class/power_supply");
5593 union dirent_storage buf;
5594 _cleanup_close_ int fd = -1, device = -1;
5599 k = readdir_r(d, &buf.de, &de);
5606 if (ignore_file(de->d_name))
5609 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5611 if (errno == ENOENT || errno == ENOTDIR)
5617 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5619 if (errno == ENOENT)
5625 n = read(fd, contents, sizeof(contents));
5629 if (n != 6 || memcmp(contents, "Mains\n", 6))
5632 close_nointr_nofail(fd);
5633 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5635 if (errno == ENOENT)
5641 n = read(fd, contents, sizeof(contents));
5645 if (n != 2 || contents[1] != '\n')
5648 if (contents[0] == '1') {
5649 found_online = true;
5651 } else if (contents[0] == '0')
5652 found_offline = true;
5657 return found_online || !found_offline;
5660 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5667 if (!path_strv_canonicalize_uniq(search))
5670 STRV_FOREACH(i, search) {
5671 _cleanup_free_ char *p = NULL;
5674 p = strjoin(*i, "/", path, NULL);
5684 if (errno != ENOENT)
5691 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5692 _cleanup_strv_free_ char **copy = NULL;
5698 if (path_is_absolute(path)) {
5701 f = fopen(path, mode);
5710 copy = strv_copy((char**) search);
5714 return search_and_fopen_internal(path, mode, copy, _f);
5717 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5718 _cleanup_strv_free_ char **s = NULL;
5720 if (path_is_absolute(path)) {
5723 f = fopen(path, mode);
5732 s = strv_split_nulstr(search);
5736 return search_and_fopen_internal(path, mode, s, _f);
5739 int create_tmp_dir(char template[], char** dir_name) {
5742 mode_t _cleanup_umask_ u;
5747 d = mkdtemp(template);
5749 log_error("Can't create directory %s: %m", template);
5753 dt = strjoin(d, "/tmp", NULL);
5760 r = mkdir(dt, 0777);
5762 log_error("Can't create directory %s: %m", dt);
5766 log_debug("Created temporary directory %s", dt);
5768 r = chmod(dt, 0777 | S_ISVTX);
5770 log_error("Failed to chmod %s: %m", dt);
5774 log_debug("Set sticky bit on %s", dt);
5788 char *strextend(char **x, ...) {
5795 l = f = *x ? strlen(*x) : 0;
5802 t = va_arg(ap, const char *);
5807 if (n > ((size_t) -1) - l) {
5816 r = realloc(*x, l+1);
5826 t = va_arg(ap, const char *);
5840 char *strrep(const char *s, unsigned n) {
5848 p = r = malloc(l * n + 1);
5852 for (i = 0; i < n; i++)
5859 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5863 if (*allocated >= need)
5866 a = MAX(64, need * 2);