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 int _cleanup_close_ 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) {
2782 return (unsigned __SWORD_TYPE) s->f_type == TMPFS_MAGIC ||
2783 (unsigned __SWORD_TYPE) s->f_type == RAMFS_MAGIC;
2786 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2791 if (fstatfs(fd, &s) < 0) {
2792 close_nointr_nofail(fd);
2796 /* We refuse to clean disk file systems with this call. This
2797 * is extra paranoia just to be sure we never ever remove
2799 if (!is_temporary_fs(&s)) {
2800 log_error("Attempted to remove disk file system, and we can't allow that.");
2801 close_nointr_nofail(fd);
2805 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2808 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2814 /* We refuse to clean the root file system with this
2815 * call. This is extra paranoia to never cause a really
2816 * seriously broken system. */
2817 if (path_equal(path, "/")) {
2818 log_error("Attempted to remove entire root file system, and we can't allow that.");
2822 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2825 if (errno != ENOTDIR)
2829 if (statfs(path, &s) < 0)
2832 if (!is_temporary_fs(&s)) {
2833 log_error("Attempted to remove disk file system, and we can't allow that.");
2838 if (delete_root && !only_dirs)
2839 if (unlink(path) < 0 && errno != ENOENT)
2846 if (fstatfs(fd, &s) < 0) {
2847 close_nointr_nofail(fd);
2851 if (!is_temporary_fs(&s)) {
2852 log_error("Attempted to remove disk file system, and we can't allow that.");
2853 close_nointr_nofail(fd);
2858 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2861 if (honour_sticky && file_is_priv_sticky(path) > 0)
2864 if (rmdir(path) < 0 && errno != ENOENT) {
2873 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2874 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2877 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2878 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2881 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2884 /* Under the assumption that we are running privileged we
2885 * first change the access mode and only then hand out
2886 * ownership to avoid a window where access is too open. */
2888 if (mode != (mode_t) -1)
2889 if (chmod(path, mode) < 0)
2892 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2893 if (chown(path, uid, gid) < 0)
2899 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2902 /* Under the assumption that we are running privileged we
2903 * first change the access mode and only then hand out
2904 * ownership to avoid a window where access is too open. */
2906 if (fchmod(fd, mode) < 0)
2909 if (fchown(fd, uid, gid) < 0)
2915 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2919 /* Allocates the cpuset in the right size */
2922 if (!(r = CPU_ALLOC(n)))
2925 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2926 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2936 if (errno != EINVAL)
2943 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2944 static const char status_indent[] = " "; /* "[" STATUS "] " */
2945 _cleanup_free_ char *s = NULL;
2946 _cleanup_close_ int fd = -1;
2947 struct iovec iovec[6] = {};
2949 static bool prev_ephemeral;
2953 /* This is independent of logging, as status messages are
2954 * optional and go exclusively to the console. */
2956 if (vasprintf(&s, format, ap) < 0)
2959 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2972 sl = status ? sizeof(status_indent)-1 : 0;
2978 e = ellipsize(s, emax, 75);
2986 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2987 prev_ephemeral = ephemeral;
2990 if (!isempty(status)) {
2991 IOVEC_SET_STRING(iovec[n++], "[");
2992 IOVEC_SET_STRING(iovec[n++], status);
2993 IOVEC_SET_STRING(iovec[n++], "] ");
2995 IOVEC_SET_STRING(iovec[n++], status_indent);
2998 IOVEC_SET_STRING(iovec[n++], s);
3000 IOVEC_SET_STRING(iovec[n++], "\n");
3002 if (writev(fd, iovec, n) < 0)
3008 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3014 va_start(ap, format);
3015 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3021 int status_welcome(void) {
3023 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3025 r = parse_env_file("/etc/os-release", NEWLINE,
3026 "PRETTY_NAME", &pretty_name,
3027 "ANSI_COLOR", &ansi_color,
3029 if (r < 0 && r != -ENOENT)
3030 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3032 return status_printf(NULL, false, false,
3033 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3034 isempty(ansi_color) ? "1" : ansi_color,
3035 isempty(pretty_name) ? "Linux" : pretty_name);
3038 char *replace_env(const char *format, char **env) {
3045 const char *e, *word = format;
3050 for (e = format; *e; e ++) {
3061 if (!(k = strnappend(r, word, e-word-1)))
3070 } else if (*e == '$') {
3071 if (!(k = strnappend(r, word, e-word)))
3087 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3089 k = strappend(r, t);
3103 if (!(k = strnappend(r, word, e-word)))
3114 char **replace_env_argv(char **argv, char **env) {
3116 unsigned k = 0, l = 0;
3118 l = strv_length(argv);
3120 if (!(r = new(char*, l+1)))
3123 STRV_FOREACH(i, argv) {
3125 /* If $FOO appears as single word, replace it by the split up variable */
3126 if ((*i)[0] == '$' && (*i)[1] != '{') {
3131 e = strv_env_get(env, *i+1);
3134 if (!(m = strv_split_quoted(e))) {
3145 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3154 memcpy(r + k, m, q * sizeof(char*));
3162 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3163 if (!(r[k++] = replace_env(*i, env))) {
3173 int fd_columns(int fd) {
3174 struct winsize ws = {};
3176 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3185 unsigned columns(void) {
3189 if (_likely_(cached_columns > 0))
3190 return cached_columns;
3193 e = getenv("COLUMNS");
3198 c = fd_columns(STDOUT_FILENO);
3207 int fd_lines(int fd) {
3208 struct winsize ws = {};
3210 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3219 unsigned lines(void) {
3223 if (_likely_(cached_lines > 0))
3224 return cached_lines;
3227 e = getenv("LINES");
3232 l = fd_lines(STDOUT_FILENO);
3238 return cached_lines;
3241 /* intended to be used as a SIGWINCH sighandler */
3242 void columns_lines_cache_reset(int signum) {
3248 static int cached_on_tty = -1;
3250 if (_unlikely_(cached_on_tty < 0))
3251 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3253 return cached_on_tty;
3256 int running_in_chroot(void) {
3257 struct stat a = {}, b = {};
3259 /* Only works as root */
3260 if (stat("/proc/1/root", &a) < 0)
3263 if (stat("/", &b) < 0)
3267 a.st_dev != b.st_dev ||
3268 a.st_ino != b.st_ino;
3271 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3276 assert(percent <= 100);
3277 assert(new_length >= 3);
3279 if (old_length <= 3 || old_length <= new_length)
3280 return strndup(s, old_length);
3282 r = new0(char, new_length+1);
3286 x = (new_length * percent) / 100;
3288 if (x > new_length - 3)
3296 s + old_length - (new_length - x - 3),
3297 new_length - x - 3);
3302 char *ellipsize(const char *s, size_t length, unsigned percent) {
3303 return ellipsize_mem(s, strlen(s), length, percent);
3306 int touch(const char *path) {
3311 /* This just opens the file for writing, ensuring it
3312 * exists. It doesn't call utimensat() the way /usr/bin/touch
3315 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3319 close_nointr_nofail(fd);
3323 char *unquote(const char *s, const char* quotes) {
3327 /* This is rather stupid, simply removes the heading and
3328 * trailing quotes if there is one. Doesn't care about
3329 * escaping or anything. We should make this smarter one
3336 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3337 return strndup(s+1, l-2);
3342 char *normalize_env_assignment(const char *s) {
3343 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3346 eq = strchr(s, '=');
3358 memmove(r, t, strlen(t) + 1);
3362 name = strndup(s, eq - s);
3370 value = unquote(strstrip(p), QUOTES);
3374 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3380 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3391 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3403 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3410 r = wait_for_terminate(pid, &status);
3412 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3416 if (status.si_code == CLD_EXITED) {
3417 if (status.si_status != 0) {
3418 log_warning("%s failed with error code %i.", name, status.si_status);
3419 return status.si_status;
3422 log_debug("%s succeeded.", name);
3425 } else if (status.si_code == CLD_KILLED ||
3426 status.si_code == CLD_DUMPED) {
3428 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3432 log_warning("%s failed due to unknown reason.", name);
3436 _noreturn_ void freeze(void) {
3438 /* Make sure nobody waits for us on a socket anymore */
3439 close_all_fds(NULL, 0);
3447 bool null_or_empty(struct stat *st) {
3450 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3453 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3459 int null_or_empty_path(const char *fn) {
3464 if (stat(fn, &st) < 0)
3467 return null_or_empty(&st);
3470 DIR *xopendirat(int fd, const char *name, int flags) {
3474 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3480 close_nointr_nofail(nfd);
3487 int signal_from_string_try_harder(const char *s) {
3491 signo = signal_from_string(s);
3493 if (startswith(s, "SIG"))
3494 return signal_from_string(s+3);
3499 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3503 /* FIXME: to follow udev's logic 100% we need to leave valid
3504 * UTF8 chars unescaped */
3506 u = unquote(tagvalue, "\"\'");
3510 t = xescape(u, "/ ");
3516 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3525 char *fstab_node_to_udev_node(const char *p) {
3528 if (startswith(p, "LABEL="))
3529 return tag_to_udev_node(p+6, "label");
3531 if (startswith(p, "UUID="))
3532 return tag_to_udev_node(p+5, "uuid");
3534 if (startswith(p, "PARTUUID="))
3535 return tag_to_udev_node(p+9, "partuuid");
3537 if (startswith(p, "PARTLABEL="))
3538 return tag_to_udev_node(p+10, "partlabel");
3543 bool tty_is_vc(const char *tty) {
3546 if (startswith(tty, "/dev/"))
3549 return vtnr_from_tty(tty) >= 0;
3552 bool tty_is_console(const char *tty) {
3555 if (startswith(tty, "/dev/"))
3558 return streq(tty, "console");
3561 int vtnr_from_tty(const char *tty) {
3566 if (startswith(tty, "/dev/"))
3569 if (!startswith(tty, "tty") )
3572 if (tty[3] < '0' || tty[3] > '9')
3575 r = safe_atoi(tty+3, &i);
3579 if (i < 0 || i > 63)
3585 char *resolve_dev_console(char **active) {
3588 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3589 * (i.e. not read-only-mounted which is a sign for container setups) */
3591 if (path_is_read_only_fs("/sys") > 0)
3594 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3597 /* If multiple log outputs are configured the last one is what
3598 * /dev/console points to */
3599 tty = strrchr(*active, ' ');
3608 bool tty_is_vc_resolve(const char *tty) {
3609 char *active = NULL;
3614 if (startswith(tty, "/dev/"))
3617 if (streq(tty, "console")) {
3618 tty = resolve_dev_console(&active);
3629 const char *default_term_for_tty(const char *tty) {
3632 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3635 bool dirent_is_file(const struct dirent *de) {
3638 if (ignore_file(de->d_name))
3641 if (de->d_type != DT_REG &&
3642 de->d_type != DT_LNK &&
3643 de->d_type != DT_UNKNOWN)
3649 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3652 if (de->d_type != DT_REG &&
3653 de->d_type != DT_LNK &&
3654 de->d_type != DT_UNKNOWN)
3657 if (ignore_file_allow_backup(de->d_name))
3660 return endswith(de->d_name, suffix);
3663 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3666 Hashmap *pids = NULL;
3670 /* Executes all binaries in a directory in parallel and
3671 * waits for them to finish. */
3674 if (!(_d = opendir(directory))) {
3676 if (errno == ENOENT)
3679 log_error("Failed to enumerate directory %s: %m", directory);
3686 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3687 log_error("Failed to allocate set.");
3691 while ((de = readdir(d))) {
3696 if (!dirent_is_file(de))
3699 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3704 if ((pid = fork()) < 0) {
3705 log_error("Failed to fork: %m");
3723 log_error("Failed to execute %s: %m", path);
3724 _exit(EXIT_FAILURE);
3727 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3729 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3730 log_error("Failed to add PID to set: %s", strerror(-k));
3735 while (!hashmap_isempty(pids)) {
3736 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3740 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3745 log_error("waitid() failed: %m");
3749 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3750 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3751 if (si.si_code == CLD_EXITED)
3752 log_error("%s exited with exit status %i.", path, si.si_status);
3754 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3756 log_debug("%s exited successfully.", path);
3767 hashmap_free_free(pids);
3770 int kill_and_sigcont(pid_t pid, int sig) {
3773 r = kill(pid, sig) < 0 ? -errno : 0;
3781 bool nulstr_contains(const char*nulstr, const char *needle) {
3787 NULSTR_FOREACH(i, nulstr)
3788 if (streq(i, needle))
3794 bool plymouth_running(void) {
3795 return access("/run/plymouth/pid", F_OK) >= 0;
3798 char* strshorten(char *s, size_t l) {
3807 static bool hostname_valid_char(char c) {
3809 (c >= 'a' && c <= 'z') ||
3810 (c >= 'A' && c <= 'Z') ||
3811 (c >= '0' && c <= '9') ||
3817 bool hostname_is_valid(const char *s) {
3824 for (p = s, dot = true; *p; p++) {
3831 if (!hostname_valid_char(*p))
3841 if (p-s > HOST_NAME_MAX)
3847 char* hostname_cleanup(char *s) {
3851 for (p = s, d = s, dot = true; *p; p++) {
3853 if (dot || p[1] == 0)
3860 if (hostname_valid_char(*p))
3865 strshorten(s, HOST_NAME_MAX);
3870 int pipe_eof(int fd) {
3872 struct pollfd pollfd = {
3874 .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) {
3889 struct pollfd pollfd = {
3894 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3901 return pollfd.revents;
3904 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3915 t = new(char, strlen(path) + 1 + 6 + 1);
3919 fn = path_get_file_name(path);
3923 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3925 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3931 f = fdopen(fd, "we");
3944 int terminal_vhangup_fd(int fd) {
3947 if (ioctl(fd, TIOCVHANGUP) < 0)
3953 int terminal_vhangup(const char *name) {
3956 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3960 r = terminal_vhangup_fd(fd);
3961 close_nointr_nofail(fd);
3966 int vt_disallocate(const char *name) {
3970 /* Deallocate the VT if possible. If not possible
3971 * (i.e. because it is the active one), at least clear it
3972 * entirely (including the scrollback buffer) */
3974 if (!startswith(name, "/dev/"))
3977 if (!tty_is_vc(name)) {
3978 /* So this is not a VT. I guess we cannot deallocate
3979 * it then. But let's at least clear the screen */
3981 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3986 "\033[r" /* clear scrolling region */
3987 "\033[H" /* move home */
3988 "\033[2J", /* clear screen */
3990 close_nointr_nofail(fd);
3995 if (!startswith(name, "/dev/tty"))
3998 r = safe_atou(name+8, &u);
4005 /* Try to deallocate */
4006 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4010 r = ioctl(fd, VT_DISALLOCATE, u);
4011 close_nointr_nofail(fd);
4019 /* Couldn't deallocate, so let's clear it fully with
4021 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4026 "\033[r" /* clear scrolling region */
4027 "\033[H" /* move home */
4028 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4030 close_nointr_nofail(fd);
4035 int copy_file(const char *from, const char *to) {
4041 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4045 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4047 close_nointr_nofail(fdf);
4055 n = read(fdf, buf, sizeof(buf));
4059 close_nointr_nofail(fdf);
4070 k = loop_write(fdt, buf, n, false);
4072 r = k < 0 ? k : (errno ? -errno : -EIO);
4074 close_nointr_nofail(fdf);
4082 close_nointr_nofail(fdf);
4083 r = close_nointr(fdt);
4093 int symlink_atomic(const char *from, const char *to) {
4095 _cleanup_free_ char *t;
4098 unsigned long long ull;
4105 t = new(char, strlen(to) + 1 + 16 + 1);
4109 fn = path_get_file_name(to);
4113 x = stpcpy(t+k+1, fn);
4116 for (i = 0; i < 16; i++) {
4117 *(x++) = hexchar(ull & 0xF);
4123 if (symlink(from, t) < 0)
4126 if (rename(t, to) < 0) {
4135 bool display_is_local(const char *display) {
4139 display[0] == ':' &&
4140 display[1] >= '0' &&
4144 int socket_from_display(const char *display, char **path) {
4151 if (!display_is_local(display))
4154 k = strspn(display+1, "0123456789");
4156 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4160 c = stpcpy(f, "/tmp/.X11-unix/X");
4161 memcpy(c, display+1, k);
4170 const char **username,
4171 uid_t *uid, gid_t *gid,
4173 const char **shell) {
4181 /* We enforce some special rules for uid=0: in order to avoid
4182 * NSS lookups for root we hardcode its data. */
4184 if (streq(*username, "root") || streq(*username, "0")) {
4202 if (parse_uid(*username, &u) >= 0) {
4206 /* If there are multiple users with the same id, make
4207 * sure to leave $USER to the configured value instead
4208 * of the first occurrence in the database. However if
4209 * the uid was configured by a numeric uid, then let's
4210 * pick the real username from /etc/passwd. */
4212 *username = p->pw_name;
4215 p = getpwnam(*username);
4219 return errno > 0 ? -errno : -ESRCH;
4231 *shell = p->pw_shell;
4236 char* uid_to_name(uid_t uid) {
4241 return strdup("root");
4245 return strdup(p->pw_name);
4247 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4253 char* gid_to_name(gid_t gid) {
4258 return strdup("root");
4262 return strdup(p->gr_name);
4264 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4270 int get_group_creds(const char **groupname, gid_t *gid) {
4276 /* We enforce some special rules for gid=0: in order to avoid
4277 * NSS lookups for root we hardcode its data. */
4279 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4280 *groupname = "root";
4288 if (parse_gid(*groupname, &id) >= 0) {
4293 *groupname = g->gr_name;
4296 g = getgrnam(*groupname);
4300 return errno > 0 ? -errno : -ESRCH;
4308 int in_gid(gid_t gid) {
4310 int ngroups_max, r, i;
4312 if (getgid() == gid)
4315 if (getegid() == gid)
4318 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4319 assert(ngroups_max > 0);
4321 gids = alloca(sizeof(gid_t) * ngroups_max);
4323 r = getgroups(ngroups_max, gids);
4327 for (i = 0; i < r; i++)
4334 int in_group(const char *name) {
4338 r = get_group_creds(&name, &gid);
4345 int glob_exists(const char *path) {
4346 glob_t _cleanup_globfree_ g = {};
4352 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4354 if (k == GLOB_NOMATCH)
4356 else if (k == GLOB_NOSPACE)
4359 r = !strv_isempty(g.gl_pathv);
4361 r = errno ? -errno : -EIO;
4366 int dirent_ensure_type(DIR *d, struct dirent *de) {
4372 if (de->d_type != DT_UNKNOWN)
4375 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4379 S_ISREG(st.st_mode) ? DT_REG :
4380 S_ISDIR(st.st_mode) ? DT_DIR :
4381 S_ISLNK(st.st_mode) ? DT_LNK :
4382 S_ISFIFO(st.st_mode) ? DT_FIFO :
4383 S_ISSOCK(st.st_mode) ? DT_SOCK :
4384 S_ISCHR(st.st_mode) ? DT_CHR :
4385 S_ISBLK(st.st_mode) ? DT_BLK :
4391 int in_search_path(const char *path, char **search) {
4395 r = path_get_parent(path, &parent);
4401 STRV_FOREACH(i, search) {
4402 if (path_equal(parent, *i)) {
4413 int get_files_in_directory(const char *path, char ***list) {
4421 /* Returns all files in a directory in *list, and the number
4422 * of files as return value. If list is NULL returns only the
4431 union dirent_storage buf;
4434 k = readdir_r(d, &buf.de, &de);
4443 dirent_ensure_type(d, de);
4445 if (!dirent_is_file(de))
4449 if ((unsigned) r >= n) {
4453 t = realloc(l, sizeof(char*) * n);
4462 assert((unsigned) r < n);
4464 l[r] = strdup(de->d_name);
4488 char *strjoin(const char *x, ...) {
4502 t = va_arg(ap, const char *);
4507 if (n > ((size_t) -1) - l) {
4531 t = va_arg(ap, const char *);
4545 bool is_main_thread(void) {
4546 static __thread int cached = 0;
4548 if (_unlikely_(cached == 0))
4549 cached = getpid() == gettid() ? 1 : -1;
4554 int block_get_whole_disk(dev_t d, dev_t *ret) {
4561 /* If it has a queue this is good enough for us */
4562 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4565 r = access(p, F_OK);
4573 /* If it is a partition find the originating device */
4574 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4577 r = access(p, F_OK);
4583 /* Get parent dev_t */
4584 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4587 r = read_one_line_file(p, &s);
4593 r = sscanf(s, "%u:%u", &m, &n);
4599 /* Only return this if it is really good enough for us. */
4600 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4603 r = access(p, F_OK);
4607 *ret = makedev(m, n);
4614 int file_is_priv_sticky(const char *p) {
4619 if (lstat(p, &st) < 0)
4623 (st.st_uid == 0 || st.st_uid == getuid()) &&
4624 (st.st_mode & S_ISVTX);
4627 static const char *const ioprio_class_table[] = {
4628 [IOPRIO_CLASS_NONE] = "none",
4629 [IOPRIO_CLASS_RT] = "realtime",
4630 [IOPRIO_CLASS_BE] = "best-effort",
4631 [IOPRIO_CLASS_IDLE] = "idle"
4634 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4636 static const char *const sigchld_code_table[] = {
4637 [CLD_EXITED] = "exited",
4638 [CLD_KILLED] = "killed",
4639 [CLD_DUMPED] = "dumped",
4640 [CLD_TRAPPED] = "trapped",
4641 [CLD_STOPPED] = "stopped",
4642 [CLD_CONTINUED] = "continued",
4645 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4647 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4648 [LOG_FAC(LOG_KERN)] = "kern",
4649 [LOG_FAC(LOG_USER)] = "user",
4650 [LOG_FAC(LOG_MAIL)] = "mail",
4651 [LOG_FAC(LOG_DAEMON)] = "daemon",
4652 [LOG_FAC(LOG_AUTH)] = "auth",
4653 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4654 [LOG_FAC(LOG_LPR)] = "lpr",
4655 [LOG_FAC(LOG_NEWS)] = "news",
4656 [LOG_FAC(LOG_UUCP)] = "uucp",
4657 [LOG_FAC(LOG_CRON)] = "cron",
4658 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4659 [LOG_FAC(LOG_FTP)] = "ftp",
4660 [LOG_FAC(LOG_LOCAL0)] = "local0",
4661 [LOG_FAC(LOG_LOCAL1)] = "local1",
4662 [LOG_FAC(LOG_LOCAL2)] = "local2",
4663 [LOG_FAC(LOG_LOCAL3)] = "local3",
4664 [LOG_FAC(LOG_LOCAL4)] = "local4",
4665 [LOG_FAC(LOG_LOCAL5)] = "local5",
4666 [LOG_FAC(LOG_LOCAL6)] = "local6",
4667 [LOG_FAC(LOG_LOCAL7)] = "local7"
4670 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4672 static const char *const log_level_table[] = {
4673 [LOG_EMERG] = "emerg",
4674 [LOG_ALERT] = "alert",
4675 [LOG_CRIT] = "crit",
4677 [LOG_WARNING] = "warning",
4678 [LOG_NOTICE] = "notice",
4679 [LOG_INFO] = "info",
4680 [LOG_DEBUG] = "debug"
4683 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4685 static const char* const sched_policy_table[] = {
4686 [SCHED_OTHER] = "other",
4687 [SCHED_BATCH] = "batch",
4688 [SCHED_IDLE] = "idle",
4689 [SCHED_FIFO] = "fifo",
4693 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4695 static const char* const rlimit_table[] = {
4696 [RLIMIT_CPU] = "LimitCPU",
4697 [RLIMIT_FSIZE] = "LimitFSIZE",
4698 [RLIMIT_DATA] = "LimitDATA",
4699 [RLIMIT_STACK] = "LimitSTACK",
4700 [RLIMIT_CORE] = "LimitCORE",
4701 [RLIMIT_RSS] = "LimitRSS",
4702 [RLIMIT_NOFILE] = "LimitNOFILE",
4703 [RLIMIT_AS] = "LimitAS",
4704 [RLIMIT_NPROC] = "LimitNPROC",
4705 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4706 [RLIMIT_LOCKS] = "LimitLOCKS",
4707 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4708 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4709 [RLIMIT_NICE] = "LimitNICE",
4710 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4711 [RLIMIT_RTTIME] = "LimitRTTIME"
4714 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4716 static const char* const ip_tos_table[] = {
4717 [IPTOS_LOWDELAY] = "low-delay",
4718 [IPTOS_THROUGHPUT] = "throughput",
4719 [IPTOS_RELIABILITY] = "reliability",
4720 [IPTOS_LOWCOST] = "low-cost",
4723 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4725 static const char *const __signal_table[] = {
4742 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4753 [SIGVTALRM] = "VTALRM",
4755 [SIGWINCH] = "WINCH",
4761 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4763 const char *signal_to_string(int signo) {
4764 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4767 name = __signal_to_string(signo);
4771 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4772 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4774 snprintf(buf, sizeof(buf), "%d", signo);
4779 int signal_from_string(const char *s) {
4784 signo = __signal_from_string(s);
4788 if (startswith(s, "RTMIN+")) {
4792 if (safe_atou(s, &u) >= 0) {
4793 signo = (int) u + offset;
4794 if (signo > 0 && signo < _NSIG)
4800 bool kexec_loaded(void) {
4801 bool loaded = false;
4804 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4812 int strdup_or_null(const char *a, char **b) {
4830 int prot_from_flags(int flags) {
4832 switch (flags & O_ACCMODE) {
4841 return PROT_READ|PROT_WRITE;
4848 char *format_bytes(char *buf, size_t l, off_t t) {
4851 static const struct {
4855 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4856 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4857 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4858 { "G", 1024ULL*1024ULL*1024ULL },
4859 { "M", 1024ULL*1024ULL },
4863 for (i = 0; i < ELEMENTSOF(table); i++) {
4865 if (t >= table[i].factor) {
4868 (unsigned long long) (t / table[i].factor),
4869 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4876 snprintf(buf, l, "%lluB", (unsigned long long) t);
4884 void* memdup(const void *p, size_t l) {
4897 int fd_inc_sndbuf(int fd, size_t n) {
4899 socklen_t l = sizeof(value);
4901 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4903 l == sizeof(value) &&
4904 (size_t) value >= n*2)
4908 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4915 int fd_inc_rcvbuf(int fd, size_t n) {
4917 socklen_t l = sizeof(value);
4919 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4921 l == sizeof(value) &&
4922 (size_t) value >= n*2)
4926 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4933 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4934 pid_t parent_pid, agent_pid;
4936 bool stdout_is_tty, stderr_is_tty;
4944 parent_pid = getpid();
4946 /* Spawns a temporary TTY agent, making sure it goes away when
4953 if (agent_pid != 0) {
4960 * Make sure the agent goes away when the parent dies */
4961 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4962 _exit(EXIT_FAILURE);
4964 /* Check whether our parent died before we were able
4965 * to set the death signal */
4966 if (getppid() != parent_pid)
4967 _exit(EXIT_SUCCESS);
4969 /* Don't leak fds to the agent */
4970 close_all_fds(except, n_except);
4972 stdout_is_tty = isatty(STDOUT_FILENO);
4973 stderr_is_tty = isatty(STDERR_FILENO);
4975 if (!stdout_is_tty || !stderr_is_tty) {
4976 /* Detach from stdout/stderr. and reopen
4977 * /dev/tty for them. This is important to
4978 * ensure that when systemctl is started via
4979 * popen() or a similar call that expects to
4980 * read EOF we actually do generate EOF and
4981 * not delay this indefinitely by because we
4982 * keep an unused copy of stdin around. */
4983 fd = open("/dev/tty", O_WRONLY);
4985 log_error("Failed to open /dev/tty: %m");
4986 _exit(EXIT_FAILURE);
4990 dup2(fd, STDOUT_FILENO);
4993 dup2(fd, STDERR_FILENO);
4999 /* Count arguments */
5001 for (n = 0; va_arg(ap, char*); n++)
5006 l = alloca(sizeof(char *) * (n + 1));
5008 /* Fill in arguments */
5010 for (i = 0; i <= n; i++)
5011 l[i] = va_arg(ap, char*);
5015 _exit(EXIT_FAILURE);
5018 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5019 struct rlimit highest, fixed;
5023 if (setrlimit(resource, rlim) >= 0)
5029 /* So we failed to set the desired setrlimit, then let's try
5030 * to get as close as we can */
5031 assert_se(getrlimit(resource, &highest) == 0);
5033 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5034 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5036 if (setrlimit(resource, &fixed) < 0)
5042 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5043 _cleanup_fclose_ FILE *f = NULL;
5055 path = "/proc/self/environ";
5057 path = procfs_file_alloca(pid, "environ");
5059 f = fopen(path, "re");
5067 char line[LINE_MAX];
5070 for (i = 0; i < sizeof(line)-1; i++) {
5074 if (_unlikely_(c == EOF)) {
5084 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5085 value = strdup(line + l + 1);
5099 int can_sleep(const char *type) {
5103 _cleanup_free_ char *p = NULL;
5107 /* If /sys is read-only we cannot sleep */
5108 if (access("/sys/power/state", W_OK) < 0)
5111 r = read_one_line_file("/sys/power/state", &p);
5116 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5117 if (l == k && memcmp(w, type, l) == 0)
5123 int can_sleep_disk(const char *type) {
5127 _cleanup_free_ char *p = NULL;
5131 /* If /sys is read-only we cannot sleep */
5132 if (access("/sys/power/state", W_OK) < 0 ||
5133 access("/sys/power/disk", W_OK) < 0)
5136 r = read_one_line_file("/sys/power/disk", &p);
5141 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5142 if (l == k && memcmp(w, type, l) == 0)
5145 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5152 bool is_valid_documentation_url(const char *url) {
5155 if (startswith(url, "http://") && url[7])
5158 if (startswith(url, "https://") && url[8])
5161 if (startswith(url, "file:") && url[5])
5164 if (startswith(url, "info:") && url[5])
5167 if (startswith(url, "man:") && url[4])
5173 bool in_initrd(void) {
5174 static __thread int saved = -1;
5180 /* We make two checks here:
5182 * 1. the flag file /etc/initrd-release must exist
5183 * 2. the root file system must be a memory file system
5185 * The second check is extra paranoia, since misdetecting an
5186 * initrd can have bad bad consequences due the initrd
5187 * emptying when transititioning to the main systemd.
5190 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5191 statfs("/", &s) >= 0 &&
5192 is_temporary_fs(&s);
5197 void warn_melody(void) {
5198 _cleanup_close_ int fd = -1;
5200 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5204 /* Yeah, this is synchronous. Kinda sucks. But well... */
5206 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5207 usleep(125*USEC_PER_MSEC);
5209 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5210 usleep(125*USEC_PER_MSEC);
5212 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5213 usleep(125*USEC_PER_MSEC);
5215 ioctl(fd, KIOCSOUND, 0);
5218 int make_console_stdio(void) {
5221 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5223 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5225 log_error("Failed to acquire terminal: %s", strerror(-fd));
5231 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5238 int get_home_dir(char **_h) {
5246 /* Take the user specified one */
5257 /* Hardcode home directory for root to avoid NSS */
5260 h = strdup("/root");
5268 /* Check the database... */
5272 return errno > 0 ? -errno : -ESRCH;
5274 if (!path_is_absolute(p->pw_dir))
5277 h = strdup(p->pw_dir);
5285 bool filename_is_safe(const char *p) {
5299 if (strlen(p) > FILENAME_MAX)
5305 bool string_is_safe(const char *p) {
5310 for (t = p; *t; t++) {
5311 if (*t > 0 && *t < ' ')
5314 if (strchr("\\\"\'", *t))
5321 bool string_has_cc(const char *p) {
5326 for (t = p; *t; t++)
5327 if (*t > 0 && *t < ' ')
5333 bool path_is_safe(const char *p) {
5338 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5341 if (strlen(p) > PATH_MAX)
5344 /* The following two checks are not really dangerous, but hey, they still are confusing */
5345 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5348 if (strstr(p, "//"))
5354 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5355 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5356 int (*compar) (const void *, const void *, void *), void *arg) {
5365 p = (void *)(((const char *) base) + (idx * size));
5366 comparison = compar(key, p, arg);
5369 else if (comparison > 0)
5377 bool is_locale_utf8(void) {
5379 static int cached_answer = -1;
5381 if (cached_answer >= 0)
5384 if (!setlocale(LC_ALL, "")) {
5385 cached_answer = true;
5389 set = nl_langinfo(CODESET);
5391 cached_answer = true;
5395 if(streq(set, "UTF-8")) {
5396 cached_answer = true;
5400 /* For LC_CTYPE=="C" return true,
5401 * because CTYPE is effectly unset and
5402 * everything defaults to UTF-8 nowadays. */
5404 set = setlocale(LC_CTYPE, NULL);
5406 cached_answer = true;
5410 cached_answer = streq(set, "C");
5413 return (bool)cached_answer;
5416 const char *draw_special_char(DrawSpecialChar ch) {
5417 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5419 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5420 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5421 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5422 [DRAW_TREE_SPACE] = " ", /* */
5423 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5425 /* ASCII fallback */ {
5426 [DRAW_TREE_VERT] = "| ",
5427 [DRAW_TREE_BRANCH] = "|-",
5428 [DRAW_TREE_RIGHT] = "`-",
5429 [DRAW_TREE_SPACE] = " ",
5430 [DRAW_TRIANGULAR_BULLET] = "> ",
5434 return draw_table[!is_locale_utf8()][ch];
5437 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5440 size_t l, old_len, new_len;
5446 old_len = strlen(old_string);
5447 new_len = strlen(new_string);
5460 if (!startswith(f, old_string)) {
5466 nl = l - old_len + new_len;
5467 a = realloc(r, nl + 1);
5475 t = stpcpy(t, new_string);
5487 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5488 const char *i, *begin = NULL;
5493 } state = STATE_OTHER;
5495 size_t osz = 0, isz;
5501 /* Strips ANSI color and replaces TABs by 8 spaces */
5503 isz = _isz ? *_isz : strlen(*ibuf);
5505 f = open_memstream(&obuf, &osz);
5509 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5514 if (i >= *ibuf + isz) /* EOT */
5516 else if (*i == '\x1B')
5517 state = STATE_ESCAPE;
5518 else if (*i == '\t')
5525 if (i >= *ibuf + isz) { /* EOT */
5528 } else if (*i == '[') {
5529 state = STATE_BRACKET;
5534 state = STATE_OTHER;
5541 if (i >= *ibuf + isz || /* EOT */
5542 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5545 state = STATE_OTHER;
5547 } else if (*i == 'm')
5548 state = STATE_OTHER;
5570 int on_ac_power(void) {
5571 bool found_offline = false, found_online = false;
5572 _cleanup_closedir_ DIR *d = NULL;
5574 d = opendir("/sys/class/power_supply");
5580 union dirent_storage buf;
5581 _cleanup_close_ int fd = -1, device = -1;
5586 k = readdir_r(d, &buf.de, &de);
5593 if (ignore_file(de->d_name))
5596 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5598 if (errno == ENOENT || errno == ENOTDIR)
5604 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5606 if (errno == ENOENT)
5612 n = read(fd, contents, sizeof(contents));
5616 if (n != 6 || memcmp(contents, "Mains\n", 6))
5619 close_nointr_nofail(fd);
5620 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5622 if (errno == ENOENT)
5628 n = read(fd, contents, sizeof(contents));
5632 if (n != 2 || contents[1] != '\n')
5635 if (contents[0] == '1') {
5636 found_online = true;
5638 } else if (contents[0] == '0')
5639 found_offline = true;
5644 return found_online || !found_offline;
5647 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5654 if (!path_strv_canonicalize_uniq(search))
5657 STRV_FOREACH(i, search) {
5658 _cleanup_free_ char *p = NULL;
5661 p = strjoin(*i, "/", path, NULL);
5671 if (errno != ENOENT)
5678 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5679 _cleanup_strv_free_ char **copy = NULL;
5685 if (path_is_absolute(path)) {
5688 f = fopen(path, mode);
5697 copy = strv_copy((char**) search);
5701 return search_and_fopen_internal(path, mode, copy, _f);
5704 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5705 _cleanup_strv_free_ char **s = NULL;
5707 if (path_is_absolute(path)) {
5710 f = fopen(path, mode);
5719 s = strv_split_nulstr(search);
5723 return search_and_fopen_internal(path, mode, s, _f);
5726 int create_tmp_dir(char template[], char** dir_name) {
5732 RUN_WITH_UMASK(0077) {
5733 d = mkdtemp(template);
5736 log_error("Can't create directory %s: %m", template);
5740 dt = strjoin(d, "/tmp", NULL);
5746 RUN_WITH_UMASK(0000) {
5747 r = mkdir(dt, 0777);
5750 log_error("Can't create directory %s: %m", dt);
5754 log_debug("Created temporary directory %s", dt);
5756 r = chmod(dt, 0777 | S_ISVTX);
5758 log_error("Failed to chmod %s: %m", dt);
5762 log_debug("Set sticky bit on %s", dt);
5776 char *strextend(char **x, ...) {
5783 l = f = *x ? strlen(*x) : 0;
5790 t = va_arg(ap, const char *);
5795 if (n > ((size_t) -1) - l) {
5804 r = realloc(*x, l+1);
5814 t = va_arg(ap, const char *);
5828 char *strrep(const char *s, unsigned n) {
5836 p = r = malloc(l * n + 1);
5840 for (i = 0; i < n; i++)
5847 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5851 if (*allocated >= need)
5854 a = MAX(64u, need * 2);