1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
71 #include "path-util.h"
72 #include "exit-status.h"
78 char **saved_argv = NULL;
80 static volatile unsigned cached_columns = 0;
81 static volatile unsigned cached_lines = 0;
83 #define procfs_file_alloca(pid, field) \
85 pid_t _pid_ = (pid); \
87 _r_ = alloca(sizeof("/proc/") -1 + DECIMAL_STR_MAX(pid_t) + 1 + sizeof(field)); \
88 sprintf(_r_, "/proc/%lu/" field, (unsigned long) _pid_); \
92 size_t page_size(void) {
93 static __thread size_t pgsz = 0;
96 if (_likely_(pgsz > 0))
99 r = sysconf(_SC_PAGESIZE);
106 bool streq_ptr(const char *a, const char *b) {
108 /* Like streq(), but tries to make sense of NULL pointers */
119 char* endswith(const char *s, const char *postfix) {
126 pl = strlen(postfix);
129 return (char*) s + sl;
134 if (memcmp(s + sl - pl, postfix, pl) != 0)
137 return (char*) s + sl - pl;
140 char* startswith(const char *s, const char *prefix) {
157 char* startswith_no_case(const char *s, const char *prefix) {
167 if (tolower(*a) != tolower(*b))
174 bool first_word(const char *s, const char *word) {
189 if (memcmp(s, word, wl) != 0)
193 strchr(WHITESPACE, s[wl]);
196 int close_nointr(int fd) {
202 /* Just ignore EINTR; a retry loop is the wrong
203 * thing to do on Linux.
205 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
206 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
207 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
208 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
210 if (_unlikely_(r < 0 && errno == EINTR))
218 void close_nointr_nofail(int fd) {
221 /* like close_nointr() but cannot fail, and guarantees errno
224 assert_se(close_nointr(fd) == 0);
227 void close_many(const int fds[], unsigned n_fd) {
230 assert(fds || n_fd <= 0);
232 for (i = 0; i < n_fd; i++)
233 close_nointr_nofail(fds[i]);
236 int unlink_noerrno(const char *path) {
247 int parse_boolean(const char *v) {
250 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
252 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
258 int parse_pid(const char *s, pid_t* ret_pid) {
259 unsigned long ul = 0;
266 r = safe_atolu(s, &ul);
272 if ((unsigned long) pid != ul)
282 int parse_uid(const char *s, uid_t* ret_uid) {
283 unsigned long ul = 0;
290 r = safe_atolu(s, &ul);
296 if ((unsigned long) uid != ul)
303 int safe_atou(const char *s, unsigned *ret_u) {
311 l = strtoul(s, &x, 0);
313 if (!x || x == s || *x || errno)
314 return errno > 0 ? -errno : -EINVAL;
316 if ((unsigned long) (unsigned) l != l)
319 *ret_u = (unsigned) l;
323 int safe_atoi(const char *s, int *ret_i) {
331 l = strtol(s, &x, 0);
333 if (!x || x == s || *x || errno)
334 return errno > 0 ? -errno : -EINVAL;
336 if ((long) (int) l != l)
343 int safe_atollu(const char *s, long long unsigned *ret_llu) {
345 unsigned long long l;
351 l = strtoull(s, &x, 0);
353 if (!x || x == s || *x || errno)
354 return errno ? -errno : -EINVAL;
360 int safe_atolli(const char *s, long long int *ret_lli) {
368 l = strtoll(s, &x, 0);
370 if (!x || x == s || *x || errno)
371 return errno ? -errno : -EINVAL;
377 int safe_atod(const char *s, double *ret_d) {
387 if (!x || x == s || *x || errno)
388 return errno ? -errno : -EINVAL;
394 /* Split a string into words. */
395 char *split(const char *c, size_t *l, const char *separator, char **state) {
398 current = *state ? *state : (char*) c;
400 if (!*current || *c == 0)
403 current += strspn(current, separator);
404 *l = strcspn(current, separator);
407 return (char*) current;
410 /* Split a string into words, but consider strings enclosed in '' and
411 * "" as words even if they include spaces. */
412 char *split_quoted(const char *c, size_t *l, char **state) {
414 bool escaped = false;
416 current = *state ? *state : (char*) c;
418 if (!*current || *c == 0)
421 current += strspn(current, WHITESPACE);
423 if (*current == '\'') {
426 for (e = current; *e; e++) {
436 *state = *e == 0 ? e : e+1;
437 } else if (*current == '\"') {
440 for (e = current; *e; e++) {
450 *state = *e == 0 ? e : e+1;
452 for (e = current; *e; e++) {
457 else if (strchr(WHITESPACE, *e))
464 return (char*) current;
467 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
469 _cleanup_fclose_ FILE *f = NULL;
482 p = procfs_file_alloca(pid, "stat");
487 if (!fgets(line, sizeof(line), f)) {
488 r = feof(f) ? -EIO : -errno;
492 /* Let's skip the pid and comm fields. The latter is enclosed
493 * in () but does not escape any () in its value, so let's
494 * skip over it manually */
496 p = strrchr(line, ')');
508 if ((long unsigned) (pid_t) ppid != ppid)
511 *_ppid = (pid_t) ppid;
516 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
517 _cleanup_fclose_ FILE *f = NULL;
525 p = "/proc/self/stat";
527 p = procfs_file_alloca(pid, "stat");
533 if (!fgets(line, sizeof(line), f)) {
540 /* Let's skip the pid and comm fields. The latter is enclosed
541 * in () but does not escape any () in its value, so let's
542 * skip over it manually */
544 p = strrchr(line, ')');
566 "%*d " /* priority */
568 "%*d " /* num_threads */
569 "%*d " /* itrealvalue */
570 "%llu " /* starttime */,
577 int fchmod_umask(int fd, mode_t m) {
582 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
588 char *truncate_nl(char *s) {
591 s[strcspn(s, NEWLINE)] = 0;
595 int get_process_comm(pid_t pid, char **name) {
602 p = "/proc/self/comm";
604 p = procfs_file_alloca(pid, "comm");
606 return read_one_line_file(p, name);
609 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
610 _cleanup_fclose_ FILE *f = NULL;
619 p = "/proc/self/cmdline";
621 p = procfs_file_alloca(pid, "cmdline");
627 if (max_length == 0) {
628 size_t len = 0, allocated = 0;
630 while ((c = getc(f)) != EOF) {
632 if (!GREEDY_REALLOC(r, allocated, len+2)) {
637 r[len++] = isprint(c) ? c : ' ';
647 r = new(char, max_length);
653 while ((c = getc(f)) != EOF) {
675 size_t n = MIN(left-1, 3U);
682 /* Kernel threads have no argv[] */
683 if (r == NULL || r[0] == 0) {
692 h = get_process_comm(pid, &t);
696 r = strjoin("[", t, "]", NULL);
707 int is_kernel_thread(pid_t pid) {
719 p = procfs_file_alloca(pid, "cmdline");
724 count = fread(&c, 1, 1, f);
728 /* Kernel threads have an empty cmdline */
731 return eof ? 1 : -errno;
737 int get_process_exe(pid_t pid, char **name) {
744 p = "/proc/self/exe";
746 p = procfs_file_alloca(pid, "exe");
748 return readlink_malloc(p, name);
751 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
752 _cleanup_fclose_ FILE *f = NULL;
762 p = procfs_file_alloca(pid, "status");
767 FOREACH_LINE(line, f, return -errno) {
772 if (startswith(l, field)) {
774 l += strspn(l, WHITESPACE);
776 l[strcspn(l, WHITESPACE)] = 0;
778 return parse_uid(l, uid);
785 int get_process_uid(pid_t pid, uid_t *uid) {
786 return get_process_id(pid, "Uid:", uid);
789 int get_process_gid(pid_t pid, gid_t *gid) {
790 assert_cc(sizeof(uid_t) == sizeof(gid_t));
791 return get_process_id(pid, "Gid:", gid);
794 char *strnappend(const char *s, const char *suffix, size_t b) {
802 return strndup(suffix, b);
811 if (b > ((size_t) -1) - a)
814 r = new(char, a+b+1);
819 memcpy(r+a, suffix, b);
825 char *strappend(const char *s, const char *suffix) {
826 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
829 int readlink_malloc(const char *p, char **r) {
839 if (!(c = new(char, l)))
842 if ((n = readlink(p, c, l-1)) < 0) {
848 if ((size_t) n < l-1) {
859 int readlink_and_make_absolute(const char *p, char **r) {
866 if ((j = readlink_malloc(p, &target)) < 0)
869 k = file_in_same_dir(p, target);
879 int readlink_and_canonicalize(const char *p, char **r) {
886 j = readlink_and_make_absolute(p, &t);
890 s = canonicalize_file_name(t);
897 path_kill_slashes(*r);
902 int reset_all_signal_handlers(void) {
905 for (sig = 1; sig < _NSIG; sig++) {
906 struct sigaction sa = {
907 .sa_handler = SIG_DFL,
908 .sa_flags = SA_RESTART,
911 if (sig == SIGKILL || sig == SIGSTOP)
914 /* On Linux the first two RT signals are reserved by
915 * glibc, and sigaction() will return EINVAL for them. */
916 if ((sigaction(sig, &sa, NULL) < 0))
924 char *strstrip(char *s) {
927 /* Drops trailing whitespace. Modifies the string in
928 * place. Returns pointer to first non-space character */
930 s += strspn(s, WHITESPACE);
932 for (e = strchr(s, 0); e > s; e --)
933 if (!strchr(WHITESPACE, e[-1]))
941 char *delete_chars(char *s, const char *bad) {
944 /* Drops all whitespace, regardless where in the string */
946 for (f = s, t = s; *f; f++) {
958 bool in_charset(const char *s, const char* charset) {
965 if (!strchr(charset, *i))
971 char *file_in_same_dir(const char *path, const char *filename) {
978 /* This removes the last component of path and appends
979 * filename, unless the latter is absolute anyway or the
982 if (path_is_absolute(filename))
983 return strdup(filename);
985 if (!(e = strrchr(path, '/')))
986 return strdup(filename);
988 k = strlen(filename);
989 if (!(r = new(char, e-path+1+k+1)))
992 memcpy(r, path, e-path+1);
993 memcpy(r+(e-path)+1, filename, k+1);
998 int rmdir_parents(const char *path, const char *stop) {
1007 /* Skip trailing slashes */
1008 while (l > 0 && path[l-1] == '/')
1014 /* Skip last component */
1015 while (l > 0 && path[l-1] != '/')
1018 /* Skip trailing slashes */
1019 while (l > 0 && path[l-1] == '/')
1025 if (!(t = strndup(path, l)))
1028 if (path_startswith(stop, t)) {
1037 if (errno != ENOENT)
1044 char hexchar(int x) {
1045 static const char table[16] = "0123456789abcdef";
1047 return table[x & 15];
1050 int unhexchar(char c) {
1052 if (c >= '0' && c <= '9')
1055 if (c >= 'a' && c <= 'f')
1056 return c - 'a' + 10;
1058 if (c >= 'A' && c <= 'F')
1059 return c - 'A' + 10;
1064 char *hexmem(const void *p, size_t l) {
1068 z = r = malloc(l * 2 + 1);
1072 for (x = p; x < (const uint8_t*) p + l; x++) {
1073 *(z++) = hexchar(*x >> 4);
1074 *(z++) = hexchar(*x & 15);
1081 void *unhexmem(const char *p, size_t l) {
1087 z = r = malloc((l + 1) / 2 + 1);
1091 for (x = p; x < p + l; x += 2) {
1094 a = unhexchar(x[0]);
1096 b = unhexchar(x[1]);
1100 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1107 char octchar(int x) {
1108 return '0' + (x & 7);
1111 int unoctchar(char c) {
1113 if (c >= '0' && c <= '7')
1119 char decchar(int x) {
1120 return '0' + (x % 10);
1123 int undecchar(char c) {
1125 if (c >= '0' && c <= '9')
1131 char *cescape(const char *s) {
1137 /* Does C style string escaping. */
1139 r = new(char, strlen(s)*4 + 1);
1143 for (f = s, t = r; *f; f++)
1189 /* For special chars we prefer octal over
1190 * hexadecimal encoding, simply because glib's
1191 * g_strescape() does the same */
1192 if ((*f < ' ') || (*f >= 127)) {
1194 *(t++) = octchar((unsigned char) *f >> 6);
1195 *(t++) = octchar((unsigned char) *f >> 3);
1196 *(t++) = octchar((unsigned char) *f);
1207 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1214 /* Undoes C style string escaping, and optionally prefixes it. */
1216 pl = prefix ? strlen(prefix) : 0;
1218 r = new(char, pl+length+1);
1223 memcpy(r, prefix, pl);
1225 for (f = s, t = r + pl; f < s + length; f++) {
1268 /* This is an extension of the XDG syntax files */
1273 /* hexadecimal encoding */
1276 a = unhexchar(f[1]);
1277 b = unhexchar(f[2]);
1279 if (a < 0 || b < 0) {
1280 /* Invalid escape code, let's take it literal then */
1284 *(t++) = (char) ((a << 4) | b);
1299 /* octal encoding */
1302 a = unoctchar(f[0]);
1303 b = unoctchar(f[1]);
1304 c = unoctchar(f[2]);
1306 if (a < 0 || b < 0 || c < 0) {
1307 /* Invalid escape code, let's take it literal then */
1311 *(t++) = (char) ((a << 6) | (b << 3) | c);
1319 /* premature end of string.*/
1324 /* Invalid escape code, let's take it literal then */
1336 char *cunescape_length(const char *s, size_t length) {
1337 return cunescape_length_with_prefix(s, length, NULL);
1340 char *cunescape(const char *s) {
1343 return cunescape_length(s, strlen(s));
1346 char *xescape(const char *s, const char *bad) {
1350 /* Escapes all chars in bad, in addition to \ and all special
1351 * chars, in \xFF style escaping. May be reversed with
1354 r = new(char, strlen(s) * 4 + 1);
1358 for (f = s, t = r; *f; f++) {
1360 if ((*f < ' ') || (*f >= 127) ||
1361 (*f == '\\') || strchr(bad, *f)) {
1364 *(t++) = hexchar(*f >> 4);
1365 *(t++) = hexchar(*f);
1375 char *bus_path_escape(const char *s) {
1381 /* Escapes all chars that D-Bus' object path cannot deal
1382 * with. Can be reverse with bus_path_unescape(). We special
1383 * case the empty string. */
1388 r = new(char, strlen(s)*3 + 1);
1392 for (f = s, t = r; *f; f++) {
1394 /* Escape everything that is not a-zA-Z0-9. We also
1395 * escape 0-9 if it's the first character */
1397 if (!(*f >= 'A' && *f <= 'Z') &&
1398 !(*f >= 'a' && *f <= 'z') &&
1399 !(f > s && *f >= '0' && *f <= '9')) {
1401 *(t++) = hexchar(*f >> 4);
1402 *(t++) = hexchar(*f);
1412 char *bus_path_unescape(const char *f) {
1417 /* Special case for the empty string */
1421 r = new(char, strlen(f) + 1);
1425 for (t = r; *f; f++) {
1430 if ((a = unhexchar(f[1])) < 0 ||
1431 (b = unhexchar(f[2])) < 0) {
1432 /* Invalid escape code, let's take it literal then */
1435 *(t++) = (char) ((a << 4) | b);
1447 char *ascii_strlower(char *t) {
1452 for (p = t; *p; p++)
1453 if (*p >= 'A' && *p <= 'Z')
1454 *p = *p - 'A' + 'a';
1459 static bool ignore_file_allow_backup(const char *filename) {
1463 filename[0] == '.' ||
1464 streq(filename, "lost+found") ||
1465 streq(filename, "aquota.user") ||
1466 streq(filename, "aquota.group") ||
1467 endswith(filename, ".rpmnew") ||
1468 endswith(filename, ".rpmsave") ||
1469 endswith(filename, ".rpmorig") ||
1470 endswith(filename, ".dpkg-old") ||
1471 endswith(filename, ".dpkg-new") ||
1472 endswith(filename, ".swp");
1475 bool ignore_file(const char *filename) {
1478 if (endswith(filename, "~"))
1481 return ignore_file_allow_backup(filename);
1484 int fd_nonblock(int fd, bool nonblock) {
1489 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1493 flags |= O_NONBLOCK;
1495 flags &= ~O_NONBLOCK;
1497 if (fcntl(fd, F_SETFL, flags) < 0)
1503 int fd_cloexec(int fd, bool cloexec) {
1508 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1512 flags |= FD_CLOEXEC;
1514 flags &= ~FD_CLOEXEC;
1516 if (fcntl(fd, F_SETFD, flags) < 0)
1522 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1525 assert(n_fdset == 0 || fdset);
1527 for (i = 0; i < n_fdset; i++)
1534 int close_all_fds(const int except[], unsigned n_except) {
1539 assert(n_except == 0 || except);
1541 d = opendir("/proc/self/fd");
1546 /* When /proc isn't available (for example in chroots)
1547 * the fallback is brute forcing through the fd
1550 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1551 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1553 if (fd_in_set(fd, except, n_except))
1556 if (close_nointr(fd) < 0)
1557 if (errno != EBADF && r == 0)
1564 while ((de = readdir(d))) {
1567 if (ignore_file(de->d_name))
1570 if (safe_atoi(de->d_name, &fd) < 0)
1571 /* Let's better ignore this, just in case */
1580 if (fd_in_set(fd, except, n_except))
1583 if (close_nointr(fd) < 0) {
1584 /* Valgrind has its own FD and doesn't want to have it closed */
1585 if (errno != EBADF && r == 0)
1594 bool chars_intersect(const char *a, const char *b) {
1597 /* Returns true if any of the chars in a are in b. */
1598 for (p = a; *p; p++)
1605 bool fstype_is_network(const char *fstype) {
1606 static const char table[] =
1615 return nulstr_contains(table, fstype);
1619 _cleanup_close_ int fd;
1621 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1627 TIOCL_GETKMSGREDIRECT,
1631 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1634 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1637 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1643 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1644 struct termios old_termios, new_termios;
1646 char line[LINE_MAX];
1651 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1652 new_termios = old_termios;
1654 new_termios.c_lflag &= ~ICANON;
1655 new_termios.c_cc[VMIN] = 1;
1656 new_termios.c_cc[VTIME] = 0;
1658 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1661 if (t != (usec_t) -1) {
1662 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1663 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1668 k = fread(&c, 1, 1, f);
1670 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1676 *need_nl = c != '\n';
1683 if (t != (usec_t) -1)
1684 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1687 if (!fgets(line, sizeof(line), f))
1692 if (strlen(line) != 1)
1702 int ask(char *ret, const char *replies, const char *text, ...) {
1712 bool need_nl = true;
1715 fputs(ANSI_HIGHLIGHT_ON, stdout);
1722 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1726 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1729 if (r == -EBADMSG) {
1730 puts("Bad input, please try again.");
1741 if (strchr(replies, c)) {
1746 puts("Read unexpected character, please try again.");
1750 int reset_terminal_fd(int fd, bool switch_to_text) {
1751 struct termios termios;
1754 /* Set terminal to some sane defaults */
1758 /* We leave locked terminal attributes untouched, so that
1759 * Plymouth may set whatever it wants to set, and we don't
1760 * interfere with that. */
1762 /* Disable exclusive mode, just in case */
1763 ioctl(fd, TIOCNXCL);
1765 /* Switch to text mode */
1767 ioctl(fd, KDSETMODE, KD_TEXT);
1769 /* Enable console unicode mode */
1770 ioctl(fd, KDSKBMODE, K_UNICODE);
1772 if (tcgetattr(fd, &termios) < 0) {
1777 /* We only reset the stuff that matters to the software. How
1778 * hardware is set up we don't touch assuming that somebody
1779 * else will do that for us */
1781 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1782 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1783 termios.c_oflag |= ONLCR;
1784 termios.c_cflag |= CREAD;
1785 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1787 termios.c_cc[VINTR] = 03; /* ^C */
1788 termios.c_cc[VQUIT] = 034; /* ^\ */
1789 termios.c_cc[VERASE] = 0177;
1790 termios.c_cc[VKILL] = 025; /* ^X */
1791 termios.c_cc[VEOF] = 04; /* ^D */
1792 termios.c_cc[VSTART] = 021; /* ^Q */
1793 termios.c_cc[VSTOP] = 023; /* ^S */
1794 termios.c_cc[VSUSP] = 032; /* ^Z */
1795 termios.c_cc[VLNEXT] = 026; /* ^V */
1796 termios.c_cc[VWERASE] = 027; /* ^W */
1797 termios.c_cc[VREPRINT] = 022; /* ^R */
1798 termios.c_cc[VEOL] = 0;
1799 termios.c_cc[VEOL2] = 0;
1801 termios.c_cc[VTIME] = 0;
1802 termios.c_cc[VMIN] = 1;
1804 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1808 /* Just in case, flush all crap out */
1809 tcflush(fd, TCIOFLUSH);
1814 int reset_terminal(const char *name) {
1817 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1821 r = reset_terminal_fd(fd, true);
1822 close_nointr_nofail(fd);
1827 int open_terminal(const char *name, int mode) {
1832 * If a TTY is in the process of being closed opening it might
1833 * cause EIO. This is horribly awful, but unlikely to be
1834 * changed in the kernel. Hence we work around this problem by
1835 * retrying a couple of times.
1837 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1841 fd = open(name, mode);
1848 /* Max 1s in total */
1852 usleep(50 * USEC_PER_MSEC);
1861 close_nointr_nofail(fd);
1866 close_nointr_nofail(fd);
1873 int flush_fd(int fd) {
1874 struct pollfd pollfd = {
1884 r = poll(&pollfd, 1, 0);
1894 l = read(fd, buf, sizeof(buf));
1900 if (errno == EAGAIN)
1909 int acquire_terminal(
1913 bool ignore_tiocstty_eperm,
1916 int fd = -1, notify = -1, r = 0, wd = -1;
1921 /* We use inotify to be notified when the tty is closed. We
1922 * create the watch before checking if we can actually acquire
1923 * it, so that we don't lose any event.
1925 * Note: strictly speaking this actually watches for the
1926 * device being closed, it does *not* really watch whether a
1927 * tty loses its controlling process. However, unless some
1928 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1929 * its tty otherwise this will not become a problem. As long
1930 * as the administrator makes sure not configure any service
1931 * on the same tty as an untrusted user this should not be a
1932 * problem. (Which he probably should not do anyway.) */
1934 if (timeout != (usec_t) -1)
1935 ts = now(CLOCK_MONOTONIC);
1937 if (!fail && !force) {
1938 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1944 wd = inotify_add_watch(notify, name, IN_CLOSE);
1952 struct sigaction sa_old, sa_new = {
1953 .sa_handler = SIG_IGN,
1954 .sa_flags = SA_RESTART,
1958 r = flush_fd(notify);
1963 /* We pass here O_NOCTTY only so that we can check the return
1964 * value TIOCSCTTY and have a reliable way to figure out if we
1965 * successfully became the controlling process of the tty */
1966 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1970 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1971 * if we already own the tty. */
1972 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1974 /* First, try to get the tty */
1975 if (ioctl(fd, TIOCSCTTY, force) < 0)
1978 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1980 /* Sometimes it makes sense to ignore TIOCSCTTY
1981 * returning EPERM, i.e. when very likely we already
1982 * are have this controlling terminal. */
1983 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1986 if (r < 0 && (force || fail || r != -EPERM)) {
1995 assert(notify >= 0);
1998 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2000 struct inotify_event *e;
2002 if (timeout != (usec_t) -1) {
2005 n = now(CLOCK_MONOTONIC);
2006 if (ts + timeout < n) {
2011 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2021 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2024 if (errno == EINTR || errno == EAGAIN)
2031 e = (struct inotify_event*) inotify_buffer;
2036 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2041 step = sizeof(struct inotify_event) + e->len;
2042 assert(step <= (size_t) l);
2044 e = (struct inotify_event*) ((uint8_t*) e + step);
2051 /* We close the tty fd here since if the old session
2052 * ended our handle will be dead. It's important that
2053 * we do this after sleeping, so that we don't enter
2054 * an endless loop. */
2055 close_nointr_nofail(fd);
2059 close_nointr_nofail(notify);
2061 r = reset_terminal_fd(fd, true);
2063 log_warning("Failed to reset terminal: %s", strerror(-r));
2069 close_nointr_nofail(fd);
2072 close_nointr_nofail(notify);
2077 int release_terminal(void) {
2079 struct sigaction sa_old, sa_new = {
2080 .sa_handler = SIG_IGN,
2081 .sa_flags = SA_RESTART,
2083 _cleanup_close_ int fd;
2085 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2089 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2090 * by our own TIOCNOTTY */
2091 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2093 if (ioctl(fd, TIOCNOTTY) < 0)
2096 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2101 int sigaction_many(const struct sigaction *sa, ...) {
2106 while ((sig = va_arg(ap, int)) > 0)
2107 if (sigaction(sig, sa, NULL) < 0)
2114 int ignore_signals(int sig, ...) {
2115 struct sigaction sa = {
2116 .sa_handler = SIG_IGN,
2117 .sa_flags = SA_RESTART,
2123 if (sigaction(sig, &sa, NULL) < 0)
2127 while ((sig = va_arg(ap, int)) > 0)
2128 if (sigaction(sig, &sa, NULL) < 0)
2135 int default_signals(int sig, ...) {
2136 struct sigaction sa = {
2137 .sa_handler = SIG_DFL,
2138 .sa_flags = SA_RESTART,
2143 if (sigaction(sig, &sa, NULL) < 0)
2147 while ((sig = va_arg(ap, int)) > 0)
2148 if (sigaction(sig, &sa, NULL) < 0)
2155 int close_pipe(int p[]) {
2161 a = close_nointr(p[0]);
2166 b = close_nointr(p[1]);
2170 return a < 0 ? a : b;
2173 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2182 while (nbytes > 0) {
2185 if ((k = read(fd, p, nbytes)) <= 0) {
2187 if (k < 0 && errno == EINTR)
2190 if (k < 0 && errno == EAGAIN && do_poll) {
2191 struct pollfd pollfd = {
2196 if (poll(&pollfd, 1, -1) < 0) {
2200 return n > 0 ? n : -errno;
2203 if (pollfd.revents != POLLIN)
2204 return n > 0 ? n : -EIO;
2209 return n > 0 ? n : (k < 0 ? -errno : 0);
2220 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2229 while (nbytes > 0) {
2232 k = write(fd, p, nbytes);
2235 if (k < 0 && errno == EINTR)
2238 if (k < 0 && errno == EAGAIN && do_poll) {
2239 struct pollfd pollfd = {
2244 if (poll(&pollfd, 1, -1) < 0) {
2248 return n > 0 ? n : -errno;
2251 if (pollfd.revents != POLLOUT)
2252 return n > 0 ? n : -EIO;
2257 return n > 0 ? n : (k < 0 ? -errno : 0);
2268 int parse_bytes(const char *t, off_t *bytes) {
2269 static const struct {
2275 { "M", 1024ULL*1024ULL },
2276 { "G", 1024ULL*1024ULL*1024ULL },
2277 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2278 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2279 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2296 l = strtoll(p, &e, 10);
2307 e += strspn(e, WHITESPACE);
2309 for (i = 0; i < ELEMENTSOF(table); i++)
2310 if (startswith(e, table[i].suffix)) {
2311 r += (off_t) l * table[i].factor;
2312 p = e + strlen(table[i].suffix);
2316 if (i >= ELEMENTSOF(table))
2326 int make_stdio(int fd) {
2331 r = dup3(fd, STDIN_FILENO, 0);
2332 s = dup3(fd, STDOUT_FILENO, 0);
2333 t = dup3(fd, STDERR_FILENO, 0);
2336 close_nointr_nofail(fd);
2338 if (r < 0 || s < 0 || t < 0)
2341 /* We rely here that the new fd has O_CLOEXEC not set */
2346 int make_null_stdio(void) {
2349 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2353 return make_stdio(null_fd);
2356 bool is_device_path(const char *path) {
2358 /* Returns true on paths that refer to a device, either in
2359 * sysfs or in /dev */
2362 path_startswith(path, "/dev/") ||
2363 path_startswith(path, "/sys/");
2366 int dir_is_empty(const char *path) {
2367 _cleanup_closedir_ DIR *d;
2376 union dirent_storage buf;
2378 r = readdir_r(d, &buf.de, &de);
2385 if (!ignore_file(de->d_name))
2390 char* dirname_malloc(const char *path) {
2391 char *d, *dir, *dir2;
2408 unsigned long long random_ull(void) {
2409 _cleanup_close_ int fd;
2413 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2417 r = loop_read(fd, &ull, sizeof(ull), true);
2418 if (r != sizeof(ull))
2424 return random() * RAND_MAX + random();
2427 void rename_process(const char name[8]) {
2430 /* This is a like a poor man's setproctitle(). It changes the
2431 * comm field, argv[0], and also the glibc's internally used
2432 * name of the process. For the first one a limit of 16 chars
2433 * applies, to the second one usually one of 10 (i.e. length
2434 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2435 * "systemd"). If you pass a longer string it will be
2438 prctl(PR_SET_NAME, name);
2440 if (program_invocation_name)
2441 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2443 if (saved_argc > 0) {
2447 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2449 for (i = 1; i < saved_argc; i++) {
2453 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2458 void sigset_add_many(sigset_t *ss, ...) {
2465 while ((sig = va_arg(ap, int)) > 0)
2466 assert_se(sigaddset(ss, sig) == 0);
2470 char* gethostname_malloc(void) {
2473 assert_se(uname(&u) >= 0);
2475 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2476 return strdup(u.nodename);
2478 return strdup(u.sysname);
2481 bool hostname_is_set(void) {
2484 assert_se(uname(&u) >= 0);
2486 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2489 static char *lookup_uid(uid_t uid) {
2492 _cleanup_free_ char *buf = NULL;
2493 struct passwd pwbuf, *pw = NULL;
2495 /* Shortcut things to avoid NSS lookups */
2497 return strdup("root");
2499 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2503 buf = malloc(bufsize);
2507 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2508 return strdup(pw->pw_name);
2510 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2516 char* getlogname_malloc(void) {
2520 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2525 return lookup_uid(uid);
2528 char *getusername_malloc(void) {
2535 return lookup_uid(getuid());
2538 int getttyname_malloc(int fd, char **r) {
2539 char path[PATH_MAX], *c;
2544 k = ttyname_r(fd, path, sizeof(path));
2550 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2558 int getttyname_harder(int fd, char **r) {
2562 k = getttyname_malloc(fd, &s);
2566 if (streq(s, "tty")) {
2568 return get_ctty(0, NULL, r);
2575 int get_ctty_devnr(pid_t pid, dev_t *d) {
2576 _cleanup_fclose_ FILE *f = NULL;
2577 char line[LINE_MAX], *p;
2578 unsigned long ttynr;
2586 fn = "/proc/self/stat";
2588 fn = procfs_file_alloca(pid, "stat");
2590 f = fopen(fn, "re");
2594 if (!fgets(line, sizeof(line), f)) {
2595 k = feof(f) ? -EIO : -errno;
2599 p = strrchr(line, ')');
2609 "%*d " /* session */
2614 if (major(ttynr) == 0 && minor(ttynr) == 0)
2621 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2623 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2628 k = get_ctty_devnr(pid, &devnr);
2632 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2634 k = readlink_malloc(fn, &s);
2640 /* This is an ugly hack */
2641 if (major(devnr) == 136) {
2642 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2652 /* Probably something like the ptys which have no
2653 * symlink in /dev/char. Let's return something
2654 * vaguely useful. */
2667 if (startswith(s, "/dev/"))
2669 else if (startswith(s, "../"))
2687 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2693 /* This returns the first error we run into, but nevertheless
2694 * tries to go on. This closes the passed fd. */
2698 close_nointr_nofail(fd);
2700 return errno == ENOENT ? 0 : -errno;
2705 union dirent_storage buf;
2706 bool is_dir, keep_around;
2710 r = readdir_r(d, &buf.de, &de);
2711 if (r != 0 && ret == 0) {
2719 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2722 if (de->d_type == DT_UNKNOWN ||
2724 (de->d_type == DT_DIR && root_dev)) {
2725 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2726 if (ret == 0 && errno != ENOENT)
2731 is_dir = S_ISDIR(st.st_mode);
2734 (st.st_uid == 0 || st.st_uid == getuid()) &&
2735 (st.st_mode & S_ISVTX);
2737 is_dir = de->d_type == DT_DIR;
2738 keep_around = false;
2744 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2745 if (root_dev && st.st_dev != root_dev->st_dev)
2748 subdir_fd = openat(fd, de->d_name,
2749 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2750 if (subdir_fd < 0) {
2751 if (ret == 0 && errno != ENOENT)
2756 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2757 if (r < 0 && ret == 0)
2761 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2762 if (ret == 0 && errno != ENOENT)
2766 } else if (!only_dirs && !keep_around) {
2768 if (unlinkat(fd, de->d_name, 0) < 0) {
2769 if (ret == 0 && errno != ENOENT)
2780 static int is_temporary_fs(struct statfs *s) {
2783 F_TYPE_CMP(s->f_type, TMPFS_MAGIC) ||
2784 F_TYPE_CMP(s->f_type, RAMFS_MAGIC);
2787 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2792 if (fstatfs(fd, &s) < 0) {
2793 close_nointr_nofail(fd);
2797 /* We refuse to clean disk file systems with this call. This
2798 * is extra paranoia just to be sure we never ever remove
2800 if (!is_temporary_fs(&s)) {
2801 log_error("Attempted to remove disk file system, and we can't allow that.");
2802 close_nointr_nofail(fd);
2806 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2809 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2815 /* We refuse to clean the root file system with this
2816 * call. This is extra paranoia to never cause a really
2817 * seriously broken system. */
2818 if (path_equal(path, "/")) {
2819 log_error("Attempted to remove entire root file system, and we can't allow that.");
2823 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2826 if (errno != ENOTDIR)
2830 if (statfs(path, &s) < 0)
2833 if (!is_temporary_fs(&s)) {
2834 log_error("Attempted to remove disk file system, and we can't allow that.");
2839 if (delete_root && !only_dirs)
2840 if (unlink(path) < 0 && errno != ENOENT)
2847 if (fstatfs(fd, &s) < 0) {
2848 close_nointr_nofail(fd);
2852 if (!is_temporary_fs(&s)) {
2853 log_error("Attempted to remove disk file system, and we can't allow that.");
2854 close_nointr_nofail(fd);
2859 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2862 if (honour_sticky && file_is_priv_sticky(path) > 0)
2865 if (rmdir(path) < 0 && errno != ENOENT) {
2874 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2875 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2878 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2879 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2882 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2885 /* Under the assumption that we are running privileged we
2886 * first change the access mode and only then hand out
2887 * ownership to avoid a window where access is too open. */
2889 if (mode != (mode_t) -1)
2890 if (chmod(path, mode) < 0)
2893 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2894 if (chown(path, uid, gid) < 0)
2900 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2903 /* Under the assumption that we are running privileged we
2904 * first change the access mode and only then hand out
2905 * ownership to avoid a window where access is too open. */
2907 if (fchmod(fd, mode) < 0)
2910 if (fchown(fd, uid, gid) < 0)
2916 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2920 /* Allocates the cpuset in the right size */
2923 if (!(r = CPU_ALLOC(n)))
2926 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2927 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2937 if (errno != EINVAL)
2944 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2945 static const char status_indent[] = " "; /* "[" STATUS "] " */
2946 _cleanup_free_ char *s = NULL;
2947 _cleanup_close_ int fd = -1;
2948 struct iovec iovec[6] = {};
2950 static bool prev_ephemeral;
2954 /* This is independent of logging, as status messages are
2955 * optional and go exclusively to the console. */
2957 if (vasprintf(&s, format, ap) < 0)
2960 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2973 sl = status ? sizeof(status_indent)-1 : 0;
2979 e = ellipsize(s, emax, 75);
2987 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2988 prev_ephemeral = ephemeral;
2991 if (!isempty(status)) {
2992 IOVEC_SET_STRING(iovec[n++], "[");
2993 IOVEC_SET_STRING(iovec[n++], status);
2994 IOVEC_SET_STRING(iovec[n++], "] ");
2996 IOVEC_SET_STRING(iovec[n++], status_indent);
2999 IOVEC_SET_STRING(iovec[n++], s);
3001 IOVEC_SET_STRING(iovec[n++], "\n");
3003 if (writev(fd, iovec, n) < 0)
3009 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3015 va_start(ap, format);
3016 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3022 int status_welcome(void) {
3024 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3026 r = parse_env_file("/etc/os-release", NEWLINE,
3027 "PRETTY_NAME", &pretty_name,
3028 "ANSI_COLOR", &ansi_color,
3030 if (r < 0 && r != -ENOENT)
3031 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3033 return status_printf(NULL, false, false,
3034 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3035 isempty(ansi_color) ? "1" : ansi_color,
3036 isempty(pretty_name) ? "Linux" : pretty_name);
3039 char *replace_env(const char *format, char **env) {
3046 const char *e, *word = format;
3051 for (e = format; *e; e ++) {
3062 if (!(k = strnappend(r, word, e-word-1)))
3071 } else if (*e == '$') {
3072 if (!(k = strnappend(r, word, e-word)))
3088 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3090 k = strappend(r, t);
3104 if (!(k = strnappend(r, word, e-word)))
3115 char **replace_env_argv(char **argv, char **env) {
3117 unsigned k = 0, l = 0;
3119 l = strv_length(argv);
3121 if (!(r = new(char*, l+1)))
3124 STRV_FOREACH(i, argv) {
3126 /* If $FOO appears as single word, replace it by the split up variable */
3127 if ((*i)[0] == '$' && (*i)[1] != '{') {
3132 e = strv_env_get(env, *i+1);
3135 if (!(m = strv_split_quoted(e))) {
3146 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3155 memcpy(r + k, m, q * sizeof(char*));
3163 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3164 if (!(r[k++] = replace_env(*i, env))) {
3174 int fd_columns(int fd) {
3175 struct winsize ws = {};
3177 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3186 unsigned columns(void) {
3190 if (_likely_(cached_columns > 0))
3191 return cached_columns;
3194 e = getenv("COLUMNS");
3199 c = fd_columns(STDOUT_FILENO);
3208 int fd_lines(int fd) {
3209 struct winsize ws = {};
3211 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3220 unsigned lines(void) {
3224 if (_likely_(cached_lines > 0))
3225 return cached_lines;
3228 e = getenv("LINES");
3233 l = fd_lines(STDOUT_FILENO);
3239 return cached_lines;
3242 /* intended to be used as a SIGWINCH sighandler */
3243 void columns_lines_cache_reset(int signum) {
3249 static int cached_on_tty = -1;
3251 if (_unlikely_(cached_on_tty < 0))
3252 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3254 return cached_on_tty;
3257 int running_in_chroot(void) {
3258 struct stat a = {}, b = {};
3260 /* Only works as root */
3261 if (stat("/proc/1/root", &a) < 0)
3264 if (stat("/", &b) < 0)
3268 a.st_dev != b.st_dev ||
3269 a.st_ino != b.st_ino;
3272 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3277 assert(percent <= 100);
3278 assert(new_length >= 3);
3280 if (old_length <= 3 || old_length <= new_length)
3281 return strndup(s, old_length);
3283 r = new0(char, new_length+1);
3287 x = (new_length * percent) / 100;
3289 if (x > new_length - 3)
3297 s + old_length - (new_length - x - 3),
3298 new_length - x - 3);
3303 char *ellipsize(const char *s, size_t length, unsigned percent) {
3304 return ellipsize_mem(s, strlen(s), length, percent);
3307 int touch(const char *path) {
3312 /* This just opens the file for writing, ensuring it
3313 * exists. It doesn't call utimensat() the way /usr/bin/touch
3316 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3320 close_nointr_nofail(fd);
3324 char *unquote(const char *s, const char* quotes) {
3328 /* This is rather stupid, simply removes the heading and
3329 * trailing quotes if there is one. Doesn't care about
3330 * escaping or anything. We should make this smarter one
3337 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3338 return strndup(s+1, l-2);
3343 char *normalize_env_assignment(const char *s) {
3344 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3347 eq = strchr(s, '=');
3359 memmove(r, t, strlen(t) + 1);
3363 name = strndup(s, eq - s);
3371 value = unquote(strstrip(p), QUOTES);
3375 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3381 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3392 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3404 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3411 r = wait_for_terminate(pid, &status);
3413 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3417 if (status.si_code == CLD_EXITED) {
3418 if (status.si_status != 0) {
3419 log_warning("%s failed with error code %i.", name, status.si_status);
3420 return status.si_status;
3423 log_debug("%s succeeded.", name);
3426 } else if (status.si_code == CLD_KILLED ||
3427 status.si_code == CLD_DUMPED) {
3429 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3433 log_warning("%s failed due to unknown reason.", name);
3437 _noreturn_ void freeze(void) {
3439 /* Make sure nobody waits for us on a socket anymore */
3440 close_all_fds(NULL, 0);
3448 bool null_or_empty(struct stat *st) {
3451 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3454 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3460 int null_or_empty_path(const char *fn) {
3465 if (stat(fn, &st) < 0)
3468 return null_or_empty(&st);
3471 DIR *xopendirat(int fd, const char *name, int flags) {
3475 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3481 close_nointr_nofail(nfd);
3488 int signal_from_string_try_harder(const char *s) {
3492 signo = signal_from_string(s);
3494 if (startswith(s, "SIG"))
3495 return signal_from_string(s+3);
3500 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3504 /* FIXME: to follow udev's logic 100% we need to leave valid
3505 * UTF8 chars unescaped */
3507 u = unquote(tagvalue, "\"\'");
3511 t = xescape(u, "/ ");
3517 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3526 char *fstab_node_to_udev_node(const char *p) {
3529 if (startswith(p, "LABEL="))
3530 return tag_to_udev_node(p+6, "label");
3532 if (startswith(p, "UUID="))
3533 return tag_to_udev_node(p+5, "uuid");
3535 if (startswith(p, "PARTUUID="))
3536 return tag_to_udev_node(p+9, "partuuid");
3538 if (startswith(p, "PARTLABEL="))
3539 return tag_to_udev_node(p+10, "partlabel");
3544 bool tty_is_vc(const char *tty) {
3547 if (startswith(tty, "/dev/"))
3550 return vtnr_from_tty(tty) >= 0;
3553 bool tty_is_console(const char *tty) {
3556 if (startswith(tty, "/dev/"))
3559 return streq(tty, "console");
3562 int vtnr_from_tty(const char *tty) {
3567 if (startswith(tty, "/dev/"))
3570 if (!startswith(tty, "tty") )
3573 if (tty[3] < '0' || tty[3] > '9')
3576 r = safe_atoi(tty+3, &i);
3580 if (i < 0 || i > 63)
3586 char *resolve_dev_console(char **active) {
3589 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3590 * (i.e. not read-only-mounted which is a sign for container setups) */
3592 if (path_is_read_only_fs("/sys") > 0)
3595 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3598 /* If multiple log outputs are configured the last one is what
3599 * /dev/console points to */
3600 tty = strrchr(*active, ' ');
3609 bool tty_is_vc_resolve(const char *tty) {
3610 char *active = NULL;
3615 if (startswith(tty, "/dev/"))
3618 if (streq(tty, "console")) {
3619 tty = resolve_dev_console(&active);
3630 const char *default_term_for_tty(const char *tty) {
3633 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3636 bool dirent_is_file(const struct dirent *de) {
3639 if (ignore_file(de->d_name))
3642 if (de->d_type != DT_REG &&
3643 de->d_type != DT_LNK &&
3644 de->d_type != DT_UNKNOWN)
3650 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3653 if (de->d_type != DT_REG &&
3654 de->d_type != DT_LNK &&
3655 de->d_type != DT_UNKNOWN)
3658 if (ignore_file_allow_backup(de->d_name))
3661 return endswith(de->d_name, suffix);
3664 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3667 Hashmap *pids = NULL;
3671 /* Executes all binaries in a directory in parallel and
3672 * waits for them to finish. */
3675 if (!(_d = opendir(directory))) {
3677 if (errno == ENOENT)
3680 log_error("Failed to enumerate directory %s: %m", directory);
3687 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3688 log_error("Failed to allocate set.");
3692 while ((de = readdir(d))) {
3697 if (!dirent_is_file(de))
3700 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3705 if ((pid = fork()) < 0) {
3706 log_error("Failed to fork: %m");
3724 log_error("Failed to execute %s: %m", path);
3725 _exit(EXIT_FAILURE);
3728 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3730 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3731 log_error("Failed to add PID to set: %s", strerror(-k));
3736 while (!hashmap_isempty(pids)) {
3737 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3741 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3746 log_error("waitid() failed: %m");
3750 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3751 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3752 if (si.si_code == CLD_EXITED)
3753 log_error("%s exited with exit status %i.", path, si.si_status);
3755 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3757 log_debug("%s exited successfully.", path);
3768 hashmap_free_free(pids);
3771 int kill_and_sigcont(pid_t pid, int sig) {
3774 r = kill(pid, sig) < 0 ? -errno : 0;
3782 bool nulstr_contains(const char*nulstr, const char *needle) {
3788 NULSTR_FOREACH(i, nulstr)
3789 if (streq(i, needle))
3795 bool plymouth_running(void) {
3796 return access("/run/plymouth/pid", F_OK) >= 0;
3799 char* strshorten(char *s, size_t l) {
3808 static bool hostname_valid_char(char c) {
3810 (c >= 'a' && c <= 'z') ||
3811 (c >= 'A' && c <= 'Z') ||
3812 (c >= '0' && c <= '9') ||
3818 bool hostname_is_valid(const char *s) {
3825 for (p = s, dot = true; *p; p++) {
3832 if (!hostname_valid_char(*p))
3842 if (p-s > HOST_NAME_MAX)
3848 char* hostname_cleanup(char *s) {
3852 for (p = s, d = s, dot = true; *p; p++) {
3854 if (dot || p[1] == 0)
3861 if (hostname_valid_char(*p))
3866 strshorten(s, HOST_NAME_MAX);
3871 int pipe_eof(int fd) {
3873 struct pollfd pollfd = {
3875 .events = POLLIN|POLLHUP,
3878 r = poll(&pollfd, 1, 0);
3885 return pollfd.revents & POLLHUP;
3888 int fd_wait_for_event(int fd, int event, usec_t t) {
3890 struct pollfd pollfd = {
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) {
4347 _cleanup_globfree_ glob_t g = {};
4353 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4355 if (k == GLOB_NOMATCH)
4357 else if (k == GLOB_NOSPACE)
4360 r = !strv_isempty(g.gl_pathv);
4362 r = errno ? -errno : -EIO;
4367 int dirent_ensure_type(DIR *d, struct dirent *de) {
4373 if (de->d_type != DT_UNKNOWN)
4376 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4380 S_ISREG(st.st_mode) ? DT_REG :
4381 S_ISDIR(st.st_mode) ? DT_DIR :
4382 S_ISLNK(st.st_mode) ? DT_LNK :
4383 S_ISFIFO(st.st_mode) ? DT_FIFO :
4384 S_ISSOCK(st.st_mode) ? DT_SOCK :
4385 S_ISCHR(st.st_mode) ? DT_CHR :
4386 S_ISBLK(st.st_mode) ? DT_BLK :
4392 int in_search_path(const char *path, char **search) {
4396 r = path_get_parent(path, &parent);
4402 STRV_FOREACH(i, search) {
4403 if (path_equal(parent, *i)) {
4414 int get_files_in_directory(const char *path, char ***list) {
4422 /* Returns all files in a directory in *list, and the number
4423 * of files as return value. If list is NULL returns only the
4432 union dirent_storage buf;
4435 k = readdir_r(d, &buf.de, &de);
4444 dirent_ensure_type(d, de);
4446 if (!dirent_is_file(de))
4450 if ((unsigned) r >= n) {
4454 t = realloc(l, sizeof(char*) * n);
4463 assert((unsigned) r < n);
4465 l[r] = strdup(de->d_name);
4489 char *strjoin(const char *x, ...) {
4503 t = va_arg(ap, const char *);
4508 if (n > ((size_t) -1) - l) {
4532 t = va_arg(ap, const char *);
4546 bool is_main_thread(void) {
4547 static __thread int cached = 0;
4549 if (_unlikely_(cached == 0))
4550 cached = getpid() == gettid() ? 1 : -1;
4555 int block_get_whole_disk(dev_t d, dev_t *ret) {
4562 /* If it has a queue this is good enough for us */
4563 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4566 r = access(p, F_OK);
4574 /* If it is a partition find the originating device */
4575 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4578 r = access(p, F_OK);
4584 /* Get parent dev_t */
4585 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4588 r = read_one_line_file(p, &s);
4594 r = sscanf(s, "%u:%u", &m, &n);
4600 /* Only return this if it is really good enough for us. */
4601 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4604 r = access(p, F_OK);
4608 *ret = makedev(m, n);
4615 int file_is_priv_sticky(const char *p) {
4620 if (lstat(p, &st) < 0)
4624 (st.st_uid == 0 || st.st_uid == getuid()) &&
4625 (st.st_mode & S_ISVTX);
4628 static const char *const ioprio_class_table[] = {
4629 [IOPRIO_CLASS_NONE] = "none",
4630 [IOPRIO_CLASS_RT] = "realtime",
4631 [IOPRIO_CLASS_BE] = "best-effort",
4632 [IOPRIO_CLASS_IDLE] = "idle"
4635 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4637 static const char *const sigchld_code_table[] = {
4638 [CLD_EXITED] = "exited",
4639 [CLD_KILLED] = "killed",
4640 [CLD_DUMPED] = "dumped",
4641 [CLD_TRAPPED] = "trapped",
4642 [CLD_STOPPED] = "stopped",
4643 [CLD_CONTINUED] = "continued",
4646 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4648 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4649 [LOG_FAC(LOG_KERN)] = "kern",
4650 [LOG_FAC(LOG_USER)] = "user",
4651 [LOG_FAC(LOG_MAIL)] = "mail",
4652 [LOG_FAC(LOG_DAEMON)] = "daemon",
4653 [LOG_FAC(LOG_AUTH)] = "auth",
4654 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4655 [LOG_FAC(LOG_LPR)] = "lpr",
4656 [LOG_FAC(LOG_NEWS)] = "news",
4657 [LOG_FAC(LOG_UUCP)] = "uucp",
4658 [LOG_FAC(LOG_CRON)] = "cron",
4659 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4660 [LOG_FAC(LOG_FTP)] = "ftp",
4661 [LOG_FAC(LOG_LOCAL0)] = "local0",
4662 [LOG_FAC(LOG_LOCAL1)] = "local1",
4663 [LOG_FAC(LOG_LOCAL2)] = "local2",
4664 [LOG_FAC(LOG_LOCAL3)] = "local3",
4665 [LOG_FAC(LOG_LOCAL4)] = "local4",
4666 [LOG_FAC(LOG_LOCAL5)] = "local5",
4667 [LOG_FAC(LOG_LOCAL6)] = "local6",
4668 [LOG_FAC(LOG_LOCAL7)] = "local7"
4671 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4673 static const char *const log_level_table[] = {
4674 [LOG_EMERG] = "emerg",
4675 [LOG_ALERT] = "alert",
4676 [LOG_CRIT] = "crit",
4678 [LOG_WARNING] = "warning",
4679 [LOG_NOTICE] = "notice",
4680 [LOG_INFO] = "info",
4681 [LOG_DEBUG] = "debug"
4684 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4686 static const char* const sched_policy_table[] = {
4687 [SCHED_OTHER] = "other",
4688 [SCHED_BATCH] = "batch",
4689 [SCHED_IDLE] = "idle",
4690 [SCHED_FIFO] = "fifo",
4694 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4696 static const char* const rlimit_table[] = {
4697 [RLIMIT_CPU] = "LimitCPU",
4698 [RLIMIT_FSIZE] = "LimitFSIZE",
4699 [RLIMIT_DATA] = "LimitDATA",
4700 [RLIMIT_STACK] = "LimitSTACK",
4701 [RLIMIT_CORE] = "LimitCORE",
4702 [RLIMIT_RSS] = "LimitRSS",
4703 [RLIMIT_NOFILE] = "LimitNOFILE",
4704 [RLIMIT_AS] = "LimitAS",
4705 [RLIMIT_NPROC] = "LimitNPROC",
4706 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4707 [RLIMIT_LOCKS] = "LimitLOCKS",
4708 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4709 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4710 [RLIMIT_NICE] = "LimitNICE",
4711 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4712 [RLIMIT_RTTIME] = "LimitRTTIME"
4715 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4717 static const char* const ip_tos_table[] = {
4718 [IPTOS_LOWDELAY] = "low-delay",
4719 [IPTOS_THROUGHPUT] = "throughput",
4720 [IPTOS_RELIABILITY] = "reliability",
4721 [IPTOS_LOWCOST] = "low-cost",
4724 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4726 static const char *const __signal_table[] = {
4743 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4754 [SIGVTALRM] = "VTALRM",
4756 [SIGWINCH] = "WINCH",
4762 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4764 const char *signal_to_string(int signo) {
4765 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4768 name = __signal_to_string(signo);
4772 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4773 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4775 snprintf(buf, sizeof(buf), "%d", signo);
4780 int signal_from_string(const char *s) {
4785 signo = __signal_from_string(s);
4789 if (startswith(s, "RTMIN+")) {
4793 if (safe_atou(s, &u) >= 0) {
4794 signo = (int) u + offset;
4795 if (signo > 0 && signo < _NSIG)
4801 bool kexec_loaded(void) {
4802 bool loaded = false;
4805 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4813 int strdup_or_null(const char *a, char **b) {
4831 int prot_from_flags(int flags) {
4833 switch (flags & O_ACCMODE) {
4842 return PROT_READ|PROT_WRITE;
4849 char *format_bytes(char *buf, size_t l, off_t t) {
4852 static const struct {
4856 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4857 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4858 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4859 { "G", 1024ULL*1024ULL*1024ULL },
4860 { "M", 1024ULL*1024ULL },
4864 for (i = 0; i < ELEMENTSOF(table); i++) {
4866 if (t >= table[i].factor) {
4869 (unsigned long long) (t / table[i].factor),
4870 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4877 snprintf(buf, l, "%lluB", (unsigned long long) t);
4885 void* memdup(const void *p, size_t l) {
4898 int fd_inc_sndbuf(int fd, size_t n) {
4900 socklen_t l = sizeof(value);
4902 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4904 l == sizeof(value) &&
4905 (size_t) value >= n*2)
4909 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4916 int fd_inc_rcvbuf(int fd, size_t n) {
4918 socklen_t l = sizeof(value);
4920 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4922 l == sizeof(value) &&
4923 (size_t) value >= n*2)
4927 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4934 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4935 pid_t parent_pid, agent_pid;
4937 bool stdout_is_tty, stderr_is_tty;
4945 parent_pid = getpid();
4947 /* Spawns a temporary TTY agent, making sure it goes away when
4954 if (agent_pid != 0) {
4961 * Make sure the agent goes away when the parent dies */
4962 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4963 _exit(EXIT_FAILURE);
4965 /* Check whether our parent died before we were able
4966 * to set the death signal */
4967 if (getppid() != parent_pid)
4968 _exit(EXIT_SUCCESS);
4970 /* Don't leak fds to the agent */
4971 close_all_fds(except, n_except);
4973 stdout_is_tty = isatty(STDOUT_FILENO);
4974 stderr_is_tty = isatty(STDERR_FILENO);
4976 if (!stdout_is_tty || !stderr_is_tty) {
4977 /* Detach from stdout/stderr. and reopen
4978 * /dev/tty for them. This is important to
4979 * ensure that when systemctl is started via
4980 * popen() or a similar call that expects to
4981 * read EOF we actually do generate EOF and
4982 * not delay this indefinitely by because we
4983 * keep an unused copy of stdin around. */
4984 fd = open("/dev/tty", O_WRONLY);
4986 log_error("Failed to open /dev/tty: %m");
4987 _exit(EXIT_FAILURE);
4991 dup2(fd, STDOUT_FILENO);
4994 dup2(fd, STDERR_FILENO);
5000 /* Count arguments */
5002 for (n = 0; va_arg(ap, char*); n++)
5007 l = alloca(sizeof(char *) * (n + 1));
5009 /* Fill in arguments */
5011 for (i = 0; i <= n; i++)
5012 l[i] = va_arg(ap, char*);
5016 _exit(EXIT_FAILURE);
5019 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5020 struct rlimit highest, fixed;
5024 if (setrlimit(resource, rlim) >= 0)
5030 /* So we failed to set the desired setrlimit, then let's try
5031 * to get as close as we can */
5032 assert_se(getrlimit(resource, &highest) == 0);
5034 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5035 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5037 if (setrlimit(resource, &fixed) < 0)
5043 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5044 _cleanup_fclose_ FILE *f = NULL;
5056 path = "/proc/self/environ";
5058 path = procfs_file_alloca(pid, "environ");
5060 f = fopen(path, "re");
5068 char line[LINE_MAX];
5071 for (i = 0; i < sizeof(line)-1; i++) {
5075 if (_unlikely_(c == EOF)) {
5085 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5086 value = strdup(line + l + 1);
5100 int can_sleep(const char *type) {
5104 _cleanup_free_ char *p = NULL;
5108 /* If /sys is read-only we cannot sleep */
5109 if (access("/sys/power/state", W_OK) < 0)
5112 r = read_one_line_file("/sys/power/state", &p);
5117 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5118 if (l == k && memcmp(w, type, l) == 0)
5124 int can_sleep_disk(const char *type) {
5128 _cleanup_free_ char *p = NULL;
5132 /* If /sys is read-only we cannot sleep */
5133 if (access("/sys/power/state", W_OK) < 0 ||
5134 access("/sys/power/disk", W_OK) < 0)
5137 r = read_one_line_file("/sys/power/disk", &p);
5142 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5143 if (l == k && memcmp(w, type, l) == 0)
5146 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5153 bool is_valid_documentation_url(const char *url) {
5156 if (startswith(url, "http://") && url[7])
5159 if (startswith(url, "https://") && url[8])
5162 if (startswith(url, "file:") && url[5])
5165 if (startswith(url, "info:") && url[5])
5168 if (startswith(url, "man:") && url[4])
5174 bool in_initrd(void) {
5175 static __thread int saved = -1;
5181 /* We make two checks here:
5183 * 1. the flag file /etc/initrd-release must exist
5184 * 2. the root file system must be a memory file system
5186 * The second check is extra paranoia, since misdetecting an
5187 * initrd can have bad bad consequences due the initrd
5188 * emptying when transititioning to the main systemd.
5191 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5192 statfs("/", &s) >= 0 &&
5193 is_temporary_fs(&s);
5198 void warn_melody(void) {
5199 _cleanup_close_ int fd = -1;
5201 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5205 /* Yeah, this is synchronous. Kinda sucks. But well... */
5207 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5208 usleep(125*USEC_PER_MSEC);
5210 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5211 usleep(125*USEC_PER_MSEC);
5213 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5214 usleep(125*USEC_PER_MSEC);
5216 ioctl(fd, KIOCSOUND, 0);
5219 int make_console_stdio(void) {
5222 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5224 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5226 log_error("Failed to acquire terminal: %s", strerror(-fd));
5232 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5239 int get_home_dir(char **_h) {
5247 /* Take the user specified one */
5258 /* Hardcode home directory for root to avoid NSS */
5261 h = strdup("/root");
5269 /* Check the database... */
5273 return errno > 0 ? -errno : -ESRCH;
5275 if (!path_is_absolute(p->pw_dir))
5278 h = strdup(p->pw_dir);
5286 bool filename_is_safe(const char *p) {
5300 if (strlen(p) > FILENAME_MAX)
5306 bool string_is_safe(const char *p) {
5311 for (t = p; *t; t++) {
5312 if (*t > 0 && *t < ' ')
5315 if (strchr("\\\"\'", *t))
5322 bool string_has_cc(const char *p) {
5327 for (t = p; *t; t++)
5328 if (*t > 0 && *t < ' ')
5334 bool path_is_safe(const char *p) {
5339 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5342 if (strlen(p) > PATH_MAX)
5345 /* The following two checks are not really dangerous, but hey, they still are confusing */
5346 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5349 if (strstr(p, "//"))
5355 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5356 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5357 int (*compar) (const void *, const void *, void *), void *arg) {
5366 p = (void *)(((const char *) base) + (idx * size));
5367 comparison = compar(key, p, arg);
5370 else if (comparison > 0)
5378 bool is_locale_utf8(void) {
5380 static int cached_answer = -1;
5382 if (cached_answer >= 0)
5385 if (!setlocale(LC_ALL, "")) {
5386 cached_answer = true;
5390 set = nl_langinfo(CODESET);
5392 cached_answer = true;
5396 if(streq(set, "UTF-8")) {
5397 cached_answer = true;
5401 /* For LC_CTYPE=="C" return true,
5402 * because CTYPE is effectly unset and
5403 * everything defaults to UTF-8 nowadays. */
5405 set = setlocale(LC_CTYPE, NULL);
5407 cached_answer = true;
5411 cached_answer = streq(set, "C");
5414 return (bool)cached_answer;
5417 const char *draw_special_char(DrawSpecialChar ch) {
5418 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5420 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5421 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5422 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5423 [DRAW_TREE_SPACE] = " ", /* */
5424 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5426 /* ASCII fallback */ {
5427 [DRAW_TREE_VERT] = "| ",
5428 [DRAW_TREE_BRANCH] = "|-",
5429 [DRAW_TREE_RIGHT] = "`-",
5430 [DRAW_TREE_SPACE] = " ",
5431 [DRAW_TRIANGULAR_BULLET] = "> ",
5435 return draw_table[!is_locale_utf8()][ch];
5438 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5441 size_t l, old_len, new_len;
5447 old_len = strlen(old_string);
5448 new_len = strlen(new_string);
5461 if (!startswith(f, old_string)) {
5467 nl = l - old_len + new_len;
5468 a = realloc(r, nl + 1);
5476 t = stpcpy(t, new_string);
5488 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5489 const char *i, *begin = NULL;
5494 } state = STATE_OTHER;
5496 size_t osz = 0, isz;
5502 /* Strips ANSI color and replaces TABs by 8 spaces */
5504 isz = _isz ? *_isz : strlen(*ibuf);
5506 f = open_memstream(&obuf, &osz);
5510 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5515 if (i >= *ibuf + isz) /* EOT */
5517 else if (*i == '\x1B')
5518 state = STATE_ESCAPE;
5519 else if (*i == '\t')
5526 if (i >= *ibuf + isz) { /* EOT */
5529 } else if (*i == '[') {
5530 state = STATE_BRACKET;
5535 state = STATE_OTHER;
5542 if (i >= *ibuf + isz || /* EOT */
5543 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5546 state = STATE_OTHER;
5548 } else if (*i == 'm')
5549 state = STATE_OTHER;
5571 int on_ac_power(void) {
5572 bool found_offline = false, found_online = false;
5573 _cleanup_closedir_ DIR *d = NULL;
5575 d = opendir("/sys/class/power_supply");
5581 union dirent_storage buf;
5582 _cleanup_close_ int fd = -1, device = -1;
5587 k = readdir_r(d, &buf.de, &de);
5594 if (ignore_file(de->d_name))
5597 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5599 if (errno == ENOENT || errno == ENOTDIR)
5605 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5607 if (errno == ENOENT)
5613 n = read(fd, contents, sizeof(contents));
5617 if (n != 6 || memcmp(contents, "Mains\n", 6))
5620 close_nointr_nofail(fd);
5621 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5623 if (errno == ENOENT)
5629 n = read(fd, contents, sizeof(contents));
5633 if (n != 2 || contents[1] != '\n')
5636 if (contents[0] == '1') {
5637 found_online = true;
5639 } else if (contents[0] == '0')
5640 found_offline = true;
5645 return found_online || !found_offline;
5648 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5655 if (!path_strv_canonicalize_uniq(search))
5658 STRV_FOREACH(i, search) {
5659 _cleanup_free_ char *p = NULL;
5662 p = strjoin(*i, "/", path, NULL);
5672 if (errno != ENOENT)
5679 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5680 _cleanup_strv_free_ char **copy = NULL;
5686 if (path_is_absolute(path)) {
5689 f = fopen(path, mode);
5698 copy = strv_copy((char**) search);
5702 return search_and_fopen_internal(path, mode, copy, _f);
5705 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5706 _cleanup_strv_free_ char **s = NULL;
5708 if (path_is_absolute(path)) {
5711 f = fopen(path, mode);
5720 s = strv_split_nulstr(search);
5724 return search_and_fopen_internal(path, mode, s, _f);
5727 int create_tmp_dir(char template[], char** dir_name) {
5733 RUN_WITH_UMASK(0077) {
5734 d = mkdtemp(template);
5737 log_error("Can't create directory %s: %m", template);
5741 dt = strjoin(d, "/tmp", NULL);
5747 RUN_WITH_UMASK(0000) {
5748 r = mkdir(dt, 0777);
5751 log_error("Can't create directory %s: %m", dt);
5755 log_debug("Created temporary directory %s", dt);
5757 r = chmod(dt, 0777 | S_ISVTX);
5759 log_error("Failed to chmod %s: %m", dt);
5763 log_debug("Set sticky bit on %s", dt);
5777 char *strextend(char **x, ...) {
5784 l = f = *x ? strlen(*x) : 0;
5791 t = va_arg(ap, const char *);
5796 if (n > ((size_t) -1) - l) {
5805 r = realloc(*x, l+1);
5815 t = va_arg(ap, const char *);
5829 char *strrep(const char *s, unsigned n) {
5837 p = r = malloc(l * n + 1);
5841 for (i = 0; i < n; i++)
5848 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5852 if (*allocated >= need)
5855 a = MAX(64u, need * 2);