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>
70 #include "path-util.h"
71 #include "exit-status.h"
77 char **saved_argv = NULL;
79 static volatile unsigned cached_columns = 0;
80 static volatile unsigned cached_lines = 0;
82 size_t page_size(void) {
83 static __thread size_t pgsz = 0;
86 if (_likely_(pgsz > 0))
89 r = sysconf(_SC_PAGESIZE);
96 bool streq_ptr(const char *a, const char *b) {
98 /* Like streq(), but tries to make sense of NULL pointers */
109 char* endswith(const char *s, const char *postfix) {
116 pl = strlen(postfix);
119 return (char*) s + sl;
124 if (memcmp(s + sl - pl, postfix, pl) != 0)
127 return (char*) s + sl - pl;
130 char* startswith(const char *s, const char *prefix) {
147 char* startswith_no_case(const char *s, const char *prefix) {
157 if (tolower(*a) != tolower(*b))
164 bool first_word(const char *s, const char *word) {
179 if (memcmp(s, word, wl) != 0)
183 strchr(WHITESPACE, s[wl]);
186 int close_nointr(int fd) {
192 /* Just ignore EINTR; a retry loop is the wrong
193 * thing to do on Linux.
195 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
196 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
197 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
198 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
200 if (_unlikely_(r < 0 && errno == EINTR))
208 void close_nointr_nofail(int fd) {
209 int saved_errno = errno;
211 /* like close_nointr() but cannot fail, and guarantees errno
214 assert_se(close_nointr(fd) == 0);
219 void close_many(const int fds[], unsigned n_fd) {
222 for (i = 0; i < n_fd; i++)
223 close_nointr_nofail(fds[i]);
226 int parse_boolean(const char *v) {
229 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
231 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
237 int parse_pid(const char *s, pid_t* ret_pid) {
238 unsigned long ul = 0;
245 r = safe_atolu(s, &ul);
251 if ((unsigned long) pid != ul)
261 int parse_uid(const char *s, uid_t* ret_uid) {
262 unsigned long ul = 0;
269 r = safe_atolu(s, &ul);
275 if ((unsigned long) uid != ul)
282 int safe_atou(const char *s, unsigned *ret_u) {
290 l = strtoul(s, &x, 0);
292 if (!x || x == s || *x || errno)
293 return errno ? -errno : -EINVAL;
295 if ((unsigned long) (unsigned) l != l)
298 *ret_u = (unsigned) l;
302 int safe_atoi(const char *s, int *ret_i) {
310 l = strtol(s, &x, 0);
312 if (!x || x == s || *x || errno)
313 return errno ? -errno : -EINVAL;
315 if ((long) (int) l != l)
322 int safe_atollu(const char *s, long long unsigned *ret_llu) {
324 unsigned long long l;
330 l = strtoull(s, &x, 0);
332 if (!x || x == s || *x || errno)
333 return errno ? -errno : -EINVAL;
339 int safe_atolli(const char *s, long long int *ret_lli) {
347 l = strtoll(s, &x, 0);
349 if (!x || x == s || *x || errno)
350 return errno ? -errno : -EINVAL;
356 /* Split a string into words. */
357 char *split(const char *c, size_t *l, const char *separator, char **state) {
360 current = *state ? *state : (char*) c;
362 if (!*current || *c == 0)
365 current += strspn(current, separator);
366 *l = strcspn(current, separator);
369 return (char*) current;
372 /* Split a string into words, but consider strings enclosed in '' and
373 * "" as words even if they include spaces. */
374 char *split_quoted(const char *c, size_t *l, char **state) {
376 bool escaped = false;
378 current = *state ? *state : (char*) c;
380 if (!*current || *c == 0)
383 current += strspn(current, WHITESPACE);
385 if (*current == '\'') {
388 for (e = current; *e; e++) {
398 *state = *e == 0 ? e : e+1;
399 } else if (*current == '\"') {
402 for (e = current; *e; e++) {
412 *state = *e == 0 ? e : e+1;
414 for (e = current; *e; e++) {
419 else if (strchr(WHITESPACE, *e))
426 return (char*) current;
429 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
431 _cleanup_fclose_ FILE *f = NULL;
432 char fn[PATH_MAX], line[LINE_MAX], *p;
438 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
445 if (!fgets(line, sizeof(line), f)) {
446 r = feof(f) ? -EIO : -errno;
450 /* Let's skip the pid and comm fields. The latter is enclosed
451 * in () but does not escape any () in its value, so let's
452 * skip over it manually */
454 p = strrchr(line, ')');
466 if ((long unsigned) (pid_t) ppid != ppid)
469 *_ppid = (pid_t) ppid;
474 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
475 _cleanup_fclose_ FILE *f = NULL;
476 char fn[PATH_MAX], line[LINE_MAX], *p;
481 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
488 if (!fgets(line, sizeof(line), f)) {
495 /* Let's skip the pid and comm fields. The latter is enclosed
496 * in () but does not escape any () in its value, so let's
497 * skip over it manually */
499 p = strrchr(line, ')');
521 "%*d " /* priority */
523 "%*d " /* num_threads */
524 "%*d " /* itrealvalue */
525 "%llu " /* starttime */,
532 int fchmod_umask(int fd, mode_t m) {
537 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
543 char *truncate_nl(char *s) {
546 s[strcspn(s, NEWLINE)] = 0;
550 int get_process_comm(pid_t pid, char **name) {
556 r = read_one_line_file("/proc/self/comm", name);
559 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
562 r = read_one_line_file(p, name);
569 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
577 f = fopen("/proc/self/cmdline", "re");
580 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
589 if (max_length == 0) {
591 while ((c = getc(f)) != EOF) {
592 k = realloc(r, len+1);
599 r[len-1] = isprint(c) ? c : ' ';
606 r = new(char, max_length);
614 while ((c = getc(f)) != EOF) {
636 size_t n = MIN(left-1, 3U);
645 /* Kernel threads have no argv[] */
646 if (r == NULL || r[0] == 0) {
655 h = get_process_comm(pid, &t);
659 r = strjoin("[", t, "]", NULL);
670 int is_kernel_thread(pid_t pid) {
680 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
689 count = fread(&c, 1, 1, f);
693 /* Kernel threads have an empty cmdline */
696 return eof ? 1 : -errno;
701 int get_process_exe(pid_t pid, char **name) {
707 r = readlink_malloc("/proc/self/exe", name);
710 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
713 r = readlink_malloc(p, name);
720 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
721 _cleanup_fclose_ FILE *f = NULL;
722 _cleanup_free_ char *p = NULL;
731 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
738 FOREACH_LINE(line, f, return -errno) {
743 if (startswith(l, field)) {
745 l += strspn(l, WHITESPACE);
747 l[strcspn(l, WHITESPACE)] = 0;
749 return parse_uid(l, uid);
756 int get_process_uid(pid_t pid, uid_t *uid) {
757 return get_process_id(pid, "Uid:", uid);
760 int get_process_gid(pid_t pid, gid_t *gid) {
761 return get_process_id(pid, "Gid:", gid);
764 char *strnappend(const char *s, const char *suffix, size_t b) {
772 return strndup(suffix, b);
781 if (b > ((size_t) -1) - a)
784 r = new(char, a+b+1);
789 memcpy(r+a, suffix, b);
795 char *strappend(const char *s, const char *suffix) {
796 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
799 int readlink_malloc(const char *p, char **r) {
809 if (!(c = new(char, l)))
812 if ((n = readlink(p, c, l-1)) < 0) {
818 if ((size_t) n < l-1) {
829 int readlink_and_make_absolute(const char *p, char **r) {
836 if ((j = readlink_malloc(p, &target)) < 0)
839 k = file_in_same_dir(p, target);
849 int readlink_and_canonicalize(const char *p, char **r) {
856 j = readlink_and_make_absolute(p, &t);
860 s = canonicalize_file_name(t);
867 path_kill_slashes(*r);
872 int reset_all_signal_handlers(void) {
875 for (sig = 1; sig < _NSIG; sig++) {
878 if (sig == SIGKILL || sig == SIGSTOP)
882 sa.sa_handler = SIG_DFL;
883 sa.sa_flags = SA_RESTART;
885 /* On Linux the first two RT signals are reserved by
886 * glibc, and sigaction() will return EINVAL for them. */
887 if ((sigaction(sig, &sa, NULL) < 0))
895 char *strstrip(char *s) {
898 /* Drops trailing whitespace. Modifies the string in
899 * place. Returns pointer to first non-space character */
901 s += strspn(s, WHITESPACE);
903 for (e = strchr(s, 0); e > s; e --)
904 if (!strchr(WHITESPACE, e[-1]))
912 char *delete_chars(char *s, const char *bad) {
915 /* Drops all whitespace, regardless where in the string */
917 for (f = s, t = s; *f; f++) {
929 bool in_charset(const char *s, const char* charset) {
936 if (!strchr(charset, *i))
942 char *file_in_same_dir(const char *path, const char *filename) {
949 /* This removes the last component of path and appends
950 * filename, unless the latter is absolute anyway or the
953 if (path_is_absolute(filename))
954 return strdup(filename);
956 if (!(e = strrchr(path, '/')))
957 return strdup(filename);
959 k = strlen(filename);
960 if (!(r = new(char, e-path+1+k+1)))
963 memcpy(r, path, e-path+1);
964 memcpy(r+(e-path)+1, filename, k+1);
969 int rmdir_parents(const char *path, const char *stop) {
978 /* Skip trailing slashes */
979 while (l > 0 && path[l-1] == '/')
985 /* Skip last component */
986 while (l > 0 && path[l-1] != '/')
989 /* Skip trailing slashes */
990 while (l > 0 && path[l-1] == '/')
996 if (!(t = strndup(path, l)))
999 if (path_startswith(stop, t)) {
1008 if (errno != ENOENT)
1016 char hexchar(int x) {
1017 static const char table[16] = "0123456789abcdef";
1019 return table[x & 15];
1022 int unhexchar(char c) {
1024 if (c >= '0' && c <= '9')
1027 if (c >= 'a' && c <= 'f')
1028 return c - 'a' + 10;
1030 if (c >= 'A' && c <= 'F')
1031 return c - 'A' + 10;
1036 char octchar(int x) {
1037 return '0' + (x & 7);
1040 int unoctchar(char c) {
1042 if (c >= '0' && c <= '7')
1048 char decchar(int x) {
1049 return '0' + (x % 10);
1052 int undecchar(char c) {
1054 if (c >= '0' && c <= '9')
1060 char *cescape(const char *s) {
1066 /* Does C style string escaping. */
1068 r = new(char, strlen(s)*4 + 1);
1072 for (f = s, t = r; *f; f++)
1118 /* For special chars we prefer octal over
1119 * hexadecimal encoding, simply because glib's
1120 * g_strescape() does the same */
1121 if ((*f < ' ') || (*f >= 127)) {
1123 *(t++) = octchar((unsigned char) *f >> 6);
1124 *(t++) = octchar((unsigned char) *f >> 3);
1125 *(t++) = octchar((unsigned char) *f);
1136 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1143 /* Undoes C style string escaping, and optionally prefixes it. */
1145 pl = prefix ? strlen(prefix) : 0;
1147 r = new(char, pl+length+1);
1152 memcpy(r, prefix, pl);
1154 for (f = s, t = r + pl; f < s + length; f++) {
1197 /* This is an extension of the XDG syntax files */
1202 /* hexadecimal encoding */
1205 a = unhexchar(f[1]);
1206 b = unhexchar(f[2]);
1208 if (a < 0 || b < 0) {
1209 /* Invalid escape code, let's take it literal then */
1213 *(t++) = (char) ((a << 4) | b);
1228 /* octal encoding */
1231 a = unoctchar(f[0]);
1232 b = unoctchar(f[1]);
1233 c = unoctchar(f[2]);
1235 if (a < 0 || b < 0 || c < 0) {
1236 /* Invalid escape code, let's take it literal then */
1240 *(t++) = (char) ((a << 6) | (b << 3) | c);
1248 /* premature end of string.*/
1253 /* Invalid escape code, let's take it literal then */
1265 char *cunescape_length(const char *s, size_t length) {
1266 return cunescape_length_with_prefix(s, length, NULL);
1269 char *cunescape(const char *s) {
1272 return cunescape_length(s, strlen(s));
1275 char *xescape(const char *s, const char *bad) {
1279 /* Escapes all chars in bad, in addition to \ and all special
1280 * chars, in \xFF style escaping. May be reversed with
1283 r = new(char, strlen(s) * 4 + 1);
1287 for (f = s, t = r; *f; f++) {
1289 if ((*f < ' ') || (*f >= 127) ||
1290 (*f == '\\') || strchr(bad, *f)) {
1293 *(t++) = hexchar(*f >> 4);
1294 *(t++) = hexchar(*f);
1304 char *bus_path_escape(const char *s) {
1310 /* Escapes all chars that D-Bus' object path cannot deal
1311 * with. Can be reverse with bus_path_unescape() */
1313 if (!(r = new(char, strlen(s)*3+1)))
1316 for (f = s, t = r; *f; f++) {
1318 if (!(*f >= 'A' && *f <= 'Z') &&
1319 !(*f >= 'a' && *f <= 'z') &&
1320 !(*f >= '0' && *f <= '9')) {
1322 *(t++) = hexchar(*f >> 4);
1323 *(t++) = hexchar(*f);
1333 char *bus_path_unescape(const char *f) {
1338 if (!(r = strdup(f)))
1341 for (t = r; *f; f++) {
1346 if ((a = unhexchar(f[1])) < 0 ||
1347 (b = unhexchar(f[2])) < 0) {
1348 /* Invalid escape code, let's take it literal then */
1351 *(t++) = (char) ((a << 4) | b);
1363 char *ascii_strlower(char *t) {
1368 for (p = t; *p; p++)
1369 if (*p >= 'A' && *p <= 'Z')
1370 *p = *p - 'A' + 'a';
1375 static bool ignore_file_allow_backup(const char *filename) {
1379 filename[0] == '.' ||
1380 streq(filename, "lost+found") ||
1381 streq(filename, "aquota.user") ||
1382 streq(filename, "aquota.group") ||
1383 endswith(filename, ".rpmnew") ||
1384 endswith(filename, ".rpmsave") ||
1385 endswith(filename, ".rpmorig") ||
1386 endswith(filename, ".dpkg-old") ||
1387 endswith(filename, ".dpkg-new") ||
1388 endswith(filename, ".swp");
1391 bool ignore_file(const char *filename) {
1394 if (endswith(filename, "~"))
1397 return ignore_file_allow_backup(filename);
1400 int fd_nonblock(int fd, bool nonblock) {
1405 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1409 flags |= O_NONBLOCK;
1411 flags &= ~O_NONBLOCK;
1413 if (fcntl(fd, F_SETFL, flags) < 0)
1419 int fd_cloexec(int fd, bool cloexec) {
1424 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1428 flags |= FD_CLOEXEC;
1430 flags &= ~FD_CLOEXEC;
1432 if (fcntl(fd, F_SETFD, flags) < 0)
1438 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1441 assert(n_fdset == 0 || fdset);
1443 for (i = 0; i < n_fdset; i++)
1450 int close_all_fds(const int except[], unsigned n_except) {
1455 assert(n_except == 0 || except);
1457 d = opendir("/proc/self/fd");
1462 /* When /proc isn't available (for example in chroots)
1463 * the fallback is brute forcing through the fd
1466 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1467 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1469 if (fd_in_set(fd, except, n_except))
1472 if (close_nointr(fd) < 0)
1473 if (errno != EBADF && r == 0)
1480 while ((de = readdir(d))) {
1483 if (ignore_file(de->d_name))
1486 if (safe_atoi(de->d_name, &fd) < 0)
1487 /* Let's better ignore this, just in case */
1496 if (fd_in_set(fd, except, n_except))
1499 if (close_nointr(fd) < 0) {
1500 /* Valgrind has its own FD and doesn't want to have it closed */
1501 if (errno != EBADF && r == 0)
1510 bool chars_intersect(const char *a, const char *b) {
1513 /* Returns true if any of the chars in a are in b. */
1514 for (p = a; *p; p++)
1521 bool fstype_is_network(const char *fstype) {
1522 static const char table[] =
1531 return nulstr_contains(table, fstype);
1535 _cleanup_close_ int fd;
1537 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1543 TIOCL_GETKMSGREDIRECT,
1547 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1550 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1553 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1559 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1560 struct termios old_termios, new_termios;
1562 char line[LINE_MAX];
1567 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1568 new_termios = old_termios;
1570 new_termios.c_lflag &= ~ICANON;
1571 new_termios.c_cc[VMIN] = 1;
1572 new_termios.c_cc[VTIME] = 0;
1574 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1577 if (t != (usec_t) -1) {
1578 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1579 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1584 k = fread(&c, 1, 1, f);
1586 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1592 *need_nl = c != '\n';
1599 if (t != (usec_t) -1)
1600 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1603 if (!fgets(line, sizeof(line), f))
1608 if (strlen(line) != 1)
1618 int ask(char *ret, const char *replies, const char *text, ...) {
1628 bool need_nl = true;
1631 fputs(ANSI_HIGHLIGHT_ON, stdout);
1638 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1642 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1645 if (r == -EBADMSG) {
1646 puts("Bad input, please try again.");
1657 if (strchr(replies, c)) {
1662 puts("Read unexpected character, please try again.");
1666 int reset_terminal_fd(int fd, bool switch_to_text) {
1667 struct termios termios;
1670 /* Set terminal to some sane defaults */
1674 /* We leave locked terminal attributes untouched, so that
1675 * Plymouth may set whatever it wants to set, and we don't
1676 * interfere with that. */
1678 /* Disable exclusive mode, just in case */
1679 ioctl(fd, TIOCNXCL);
1681 /* Switch to text mode */
1683 ioctl(fd, KDSETMODE, KD_TEXT);
1685 /* Enable console unicode mode */
1686 ioctl(fd, KDSKBMODE, K_UNICODE);
1688 if (tcgetattr(fd, &termios) < 0) {
1693 /* We only reset the stuff that matters to the software. How
1694 * hardware is set up we don't touch assuming that somebody
1695 * else will do that for us */
1697 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1698 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1699 termios.c_oflag |= ONLCR;
1700 termios.c_cflag |= CREAD;
1701 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1703 termios.c_cc[VINTR] = 03; /* ^C */
1704 termios.c_cc[VQUIT] = 034; /* ^\ */
1705 termios.c_cc[VERASE] = 0177;
1706 termios.c_cc[VKILL] = 025; /* ^X */
1707 termios.c_cc[VEOF] = 04; /* ^D */
1708 termios.c_cc[VSTART] = 021; /* ^Q */
1709 termios.c_cc[VSTOP] = 023; /* ^S */
1710 termios.c_cc[VSUSP] = 032; /* ^Z */
1711 termios.c_cc[VLNEXT] = 026; /* ^V */
1712 termios.c_cc[VWERASE] = 027; /* ^W */
1713 termios.c_cc[VREPRINT] = 022; /* ^R */
1714 termios.c_cc[VEOL] = 0;
1715 termios.c_cc[VEOL2] = 0;
1717 termios.c_cc[VTIME] = 0;
1718 termios.c_cc[VMIN] = 1;
1720 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1724 /* Just in case, flush all crap out */
1725 tcflush(fd, TCIOFLUSH);
1730 int reset_terminal(const char *name) {
1733 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1737 r = reset_terminal_fd(fd, true);
1738 close_nointr_nofail(fd);
1743 int open_terminal(const char *name, int mode) {
1748 * If a TTY is in the process of being closed opening it might
1749 * cause EIO. This is horribly awful, but unlikely to be
1750 * changed in the kernel. Hence we work around this problem by
1751 * retrying a couple of times.
1753 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1757 fd = open(name, mode);
1764 /* Max 1s in total */
1768 usleep(50 * USEC_PER_MSEC);
1777 close_nointr_nofail(fd);
1782 close_nointr_nofail(fd);
1789 int flush_fd(int fd) {
1790 struct pollfd pollfd;
1794 pollfd.events = POLLIN;
1801 if ((r = poll(&pollfd, 1, 0)) < 0) {
1812 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1817 if (errno == EAGAIN)
1828 int acquire_terminal(
1832 bool ignore_tiocstty_eperm,
1835 int fd = -1, notify = -1, r = 0, wd = -1;
1837 struct sigaction sa_old, sa_new;
1841 /* We use inotify to be notified when the tty is closed. We
1842 * create the watch before checking if we can actually acquire
1843 * it, so that we don't lose any event.
1845 * Note: strictly speaking this actually watches for the
1846 * device being closed, it does *not* really watch whether a
1847 * tty loses its controlling process. However, unless some
1848 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1849 * its tty otherwise this will not become a problem. As long
1850 * as the administrator makes sure not configure any service
1851 * on the same tty as an untrusted user this should not be a
1852 * problem. (Which he probably should not do anyway.) */
1854 if (timeout != (usec_t) -1)
1855 ts = now(CLOCK_MONOTONIC);
1857 if (!fail && !force) {
1858 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1864 wd = inotify_add_watch(notify, name, IN_CLOSE);
1873 r = flush_fd(notify);
1878 /* We pass here O_NOCTTY only so that we can check the return
1879 * value TIOCSCTTY and have a reliable way to figure out if we
1880 * successfully became the controlling process of the tty */
1881 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1885 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1886 * if we already own the tty. */
1888 sa_new.sa_handler = SIG_IGN;
1889 sa_new.sa_flags = SA_RESTART;
1890 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1892 /* First, try to get the tty */
1893 if (ioctl(fd, TIOCSCTTY, force) < 0)
1896 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1898 /* Sometimes it makes sense to ignore TIOCSCTTY
1899 * returning EPERM, i.e. when very likely we already
1900 * are have this controlling terminal. */
1901 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1904 if (r < 0 && (force || fail || r != -EPERM)) {
1913 assert(notify >= 0);
1916 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1918 struct inotify_event *e;
1920 if (timeout != (usec_t) -1) {
1923 n = now(CLOCK_MONOTONIC);
1924 if (ts + timeout < n) {
1929 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1939 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1942 if (errno == EINTR || errno == EAGAIN)
1949 e = (struct inotify_event*) inotify_buffer;
1954 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1959 step = sizeof(struct inotify_event) + e->len;
1960 assert(step <= (size_t) l);
1962 e = (struct inotify_event*) ((uint8_t*) e + step);
1969 /* We close the tty fd here since if the old session
1970 * ended our handle will be dead. It's important that
1971 * we do this after sleeping, so that we don't enter
1972 * an endless loop. */
1973 close_nointr_nofail(fd);
1977 close_nointr_nofail(notify);
1979 r = reset_terminal_fd(fd, true);
1981 log_warning("Failed to reset terminal: %s", strerror(-r));
1987 close_nointr_nofail(fd);
1990 close_nointr_nofail(notify);
1995 int release_terminal(void) {
1997 struct sigaction sa_old, sa_new;
1999 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2002 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2003 * by our own TIOCNOTTY */
2006 sa_new.sa_handler = SIG_IGN;
2007 sa_new.sa_flags = SA_RESTART;
2008 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2010 if (ioctl(fd, TIOCNOTTY) < 0)
2013 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2015 close_nointr_nofail(fd);
2019 int sigaction_many(const struct sigaction *sa, ...) {
2024 while ((sig = va_arg(ap, int)) > 0)
2025 if (sigaction(sig, sa, NULL) < 0)
2032 int ignore_signals(int sig, ...) {
2033 struct sigaction sa;
2038 sa.sa_handler = SIG_IGN;
2039 sa.sa_flags = SA_RESTART;
2041 if (sigaction(sig, &sa, NULL) < 0)
2045 while ((sig = va_arg(ap, int)) > 0)
2046 if (sigaction(sig, &sa, NULL) < 0)
2053 int default_signals(int sig, ...) {
2054 struct sigaction sa;
2059 sa.sa_handler = SIG_DFL;
2060 sa.sa_flags = SA_RESTART;
2062 if (sigaction(sig, &sa, NULL) < 0)
2066 while ((sig = va_arg(ap, int)) > 0)
2067 if (sigaction(sig, &sa, NULL) < 0)
2074 int close_pipe(int p[]) {
2080 a = close_nointr(p[0]);
2085 b = close_nointr(p[1]);
2089 return a < 0 ? a : b;
2092 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2101 while (nbytes > 0) {
2104 if ((k = read(fd, p, nbytes)) <= 0) {
2106 if (k < 0 && errno == EINTR)
2109 if (k < 0 && errno == EAGAIN && do_poll) {
2110 struct pollfd pollfd;
2114 pollfd.events = POLLIN;
2116 if (poll(&pollfd, 1, -1) < 0) {
2120 return n > 0 ? n : -errno;
2123 if (pollfd.revents != POLLIN)
2124 return n > 0 ? n : -EIO;
2129 return n > 0 ? n : (k < 0 ? -errno : 0);
2140 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2149 while (nbytes > 0) {
2152 k = write(fd, p, nbytes);
2155 if (k < 0 && errno == EINTR)
2158 if (k < 0 && errno == EAGAIN && do_poll) {
2159 struct pollfd pollfd;
2163 pollfd.events = POLLOUT;
2165 if (poll(&pollfd, 1, -1) < 0) {
2169 return n > 0 ? n : -errno;
2172 if (pollfd.revents != POLLOUT)
2173 return n > 0 ? n : -EIO;
2178 return n > 0 ? n : (k < 0 ? -errno : 0);
2189 int parse_bytes(const char *t, off_t *bytes) {
2190 static const struct {
2196 { "M", 1024ULL*1024ULL },
2197 { "G", 1024ULL*1024ULL*1024ULL },
2198 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2199 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2200 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2217 l = strtoll(p, &e, 10);
2228 e += strspn(e, WHITESPACE);
2230 for (i = 0; i < ELEMENTSOF(table); i++)
2231 if (startswith(e, table[i].suffix)) {
2232 r += (off_t) l * table[i].factor;
2233 p = e + strlen(table[i].suffix);
2237 if (i >= ELEMENTSOF(table))
2247 int make_stdio(int fd) {
2252 r = dup3(fd, STDIN_FILENO, 0);
2253 s = dup3(fd, STDOUT_FILENO, 0);
2254 t = dup3(fd, STDERR_FILENO, 0);
2257 close_nointr_nofail(fd);
2259 if (r < 0 || s < 0 || t < 0)
2262 /* We rely here that the new fd has O_CLOEXEC not set */
2267 int make_null_stdio(void) {
2270 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2274 return make_stdio(null_fd);
2277 bool is_device_path(const char *path) {
2279 /* Returns true on paths that refer to a device, either in
2280 * sysfs or in /dev */
2283 path_startswith(path, "/dev/") ||
2284 path_startswith(path, "/sys/");
2287 int dir_is_empty(const char *path) {
2288 _cleanup_closedir_ DIR *d;
2297 union dirent_storage buf;
2299 r = readdir_r(d, &buf.de, &de);
2306 if (!ignore_file(de->d_name))
2311 unsigned long long random_ull(void) {
2312 _cleanup_close_ int fd;
2316 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2320 r = loop_read(fd, &ull, sizeof(ull), true);
2321 if (r != sizeof(ull))
2327 return random() * RAND_MAX + random();
2330 void rename_process(const char name[8]) {
2333 /* This is a like a poor man's setproctitle(). It changes the
2334 * comm field, argv[0], and also the glibc's internally used
2335 * name of the process. For the first one a limit of 16 chars
2336 * applies, to the second one usually one of 10 (i.e. length
2337 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2338 * "systemd"). If you pass a longer string it will be
2341 prctl(PR_SET_NAME, name);
2343 if (program_invocation_name)
2344 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2346 if (saved_argc > 0) {
2350 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2352 for (i = 1; i < saved_argc; i++) {
2356 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2361 void sigset_add_many(sigset_t *ss, ...) {
2368 while ((sig = va_arg(ap, int)) > 0)
2369 assert_se(sigaddset(ss, sig) == 0);
2373 char* gethostname_malloc(void) {
2376 assert_se(uname(&u) >= 0);
2378 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2379 return strdup(u.nodename);
2381 return strdup(u.sysname);
2384 bool hostname_is_set(void) {
2387 assert_se(uname(&u) >= 0);
2389 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2392 static char *lookup_uid(uid_t uid) {
2395 _cleanup_free_ char *buf = NULL;
2396 struct passwd pwbuf, *pw = NULL;
2398 /* Shortcut things to avoid NSS lookups */
2400 return strdup("root");
2402 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2406 buf = malloc(bufsize);
2410 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2411 return strdup(pw->pw_name);
2413 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2419 char* getlogname_malloc(void) {
2423 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2428 return lookup_uid(uid);
2431 char *getusername_malloc(void) {
2438 return lookup_uid(getuid());
2441 int getttyname_malloc(int fd, char **r) {
2442 char path[PATH_MAX], *c;
2447 k = ttyname_r(fd, path, sizeof(path));
2453 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2461 int getttyname_harder(int fd, char **r) {
2465 k = getttyname_malloc(fd, &s);
2469 if (streq(s, "tty")) {
2471 return get_ctty(0, NULL, r);
2478 int get_ctty_devnr(pid_t pid, dev_t *d) {
2480 char line[LINE_MAX], *p, *fn;
2481 unsigned long ttynr;
2484 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2487 f = fopen(fn, "re");
2492 if (!fgets(line, sizeof(line), f)) {
2493 k = feof(f) ? -EIO : -errno;
2500 p = strrchr(line, ')');
2510 "%*d " /* session */
2515 if (major(ttynr) == 0 && minor(ttynr) == 0)
2522 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2524 char fn[PATH_MAX], *s, *b, *p;
2529 k = get_ctty_devnr(pid, &devnr);
2533 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2536 k = readlink_malloc(fn, &s);
2542 /* This is an ugly hack */
2543 if (major(devnr) == 136) {
2544 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2554 /* Probably something like the ptys which have no
2555 * symlink in /dev/char. Let's return something
2556 * vaguely useful. */
2569 if (startswith(s, "/dev/"))
2571 else if (startswith(s, "../"))
2589 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2595 /* This returns the first error we run into, but nevertheless
2596 * tries to go on. This closes the passed fd. */
2600 close_nointr_nofail(fd);
2602 return errno == ENOENT ? 0 : -errno;
2607 union dirent_storage buf;
2608 bool is_dir, keep_around;
2612 r = readdir_r(d, &buf.de, &de);
2613 if (r != 0 && ret == 0) {
2621 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2624 if (de->d_type == DT_UNKNOWN ||
2626 (de->d_type == DT_DIR && root_dev)) {
2627 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2628 if (ret == 0 && errno != ENOENT)
2633 is_dir = S_ISDIR(st.st_mode);
2636 (st.st_uid == 0 || st.st_uid == getuid()) &&
2637 (st.st_mode & S_ISVTX);
2639 is_dir = de->d_type == DT_DIR;
2640 keep_around = false;
2646 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2647 if (root_dev && st.st_dev != root_dev->st_dev)
2650 subdir_fd = openat(fd, de->d_name,
2651 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2652 if (subdir_fd < 0) {
2653 if (ret == 0 && errno != ENOENT)
2658 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2659 if (r < 0 && ret == 0)
2663 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2664 if (ret == 0 && errno != ENOENT)
2668 } else if (!only_dirs && !keep_around) {
2670 if (unlinkat(fd, de->d_name, 0) < 0) {
2671 if (ret == 0 && errno != ENOENT)
2682 static int is_temporary_fs(struct statfs *s) {
2684 return s->f_type == TMPFS_MAGIC ||
2685 (long)s->f_type == (long)RAMFS_MAGIC;
2688 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2693 if (fstatfs(fd, &s) < 0) {
2694 close_nointr_nofail(fd);
2698 /* We refuse to clean disk file systems with this call. This
2699 * is extra paranoia just to be sure we never ever remove
2701 if (!is_temporary_fs(&s)) {
2702 log_error("Attempted to remove disk file system, and we can't allow that.");
2703 close_nointr_nofail(fd);
2707 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2710 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2716 /* We refuse to clean the root file system with this
2717 * call. This is extra paranoia to never cause a really
2718 * seriously broken system. */
2719 if (path_equal(path, "/")) {
2720 log_error("Attempted to remove entire root file system, and we can't allow that.");
2724 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2727 if (errno != ENOTDIR)
2731 if (statfs(path, &s) < 0)
2734 if (!is_temporary_fs(&s)) {
2735 log_error("Attempted to remove disk file system, and we can't allow that.");
2740 if (delete_root && !only_dirs)
2741 if (unlink(path) < 0 && errno != ENOENT)
2748 if (fstatfs(fd, &s) < 0) {
2749 close_nointr_nofail(fd);
2753 if (!is_temporary_fs(&s)) {
2754 log_error("Attempted to remove disk file system, and we can't allow that.");
2755 close_nointr_nofail(fd);
2760 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2763 if (honour_sticky && file_is_priv_sticky(path) > 0)
2766 if (rmdir(path) < 0 && errno != ENOENT) {
2775 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2776 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2779 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2780 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2783 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2786 /* Under the assumption that we are running privileged we
2787 * first change the access mode and only then hand out
2788 * ownership to avoid a window where access is too open. */
2790 if (mode != (mode_t) -1)
2791 if (chmod(path, mode) < 0)
2794 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2795 if (chown(path, uid, gid) < 0)
2801 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2804 /* Under the assumption that we are running privileged we
2805 * first change the access mode and only then hand out
2806 * ownership to avoid a window where access is too open. */
2808 if (fchmod(fd, mode) < 0)
2811 if (fchown(fd, uid, gid) < 0)
2817 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2821 /* Allocates the cpuset in the right size */
2824 if (!(r = CPU_ALLOC(n)))
2827 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2828 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2838 if (errno != EINVAL)
2845 int status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
2846 static const char status_indent[] = " "; /* "[" STATUS "] " */
2847 _cleanup_free_ char *s = NULL;
2848 _cleanup_close_ int fd = -1;
2849 struct iovec iovec[5];
2854 /* This is independent of logging, as status messages are
2855 * optional and go exclusively to the console. */
2857 if (vasprintf(&s, format, ap) < 0)
2860 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2873 sl = status ? sizeof(status_indent)-1 : 0;
2879 e = ellipsize(s, emax, 75);
2889 if (!isempty(status)) {
2890 IOVEC_SET_STRING(iovec[n++], "[");
2891 IOVEC_SET_STRING(iovec[n++], status);
2892 IOVEC_SET_STRING(iovec[n++], "] ");
2894 IOVEC_SET_STRING(iovec[n++], status_indent);
2897 IOVEC_SET_STRING(iovec[n++], s);
2898 IOVEC_SET_STRING(iovec[n++], "\n");
2900 if (writev(fd, iovec, n) < 0)
2906 int status_printf(const char *status, bool ellipse, const char *format, ...) {
2912 va_start(ap, format);
2913 r = status_vprintf(status, ellipse, format, ap);
2919 int status_welcome(void) {
2921 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2923 r = parse_env_file("/etc/os-release", NEWLINE,
2924 "PRETTY_NAME", &pretty_name,
2925 "ANSI_COLOR", &ansi_color,
2927 if (r < 0 && r != -ENOENT)
2928 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2930 return status_printf(NULL, false,
2931 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2932 isempty(ansi_color) ? "1" : ansi_color,
2933 isempty(pretty_name) ? "Linux" : pretty_name);
2936 char *replace_env(const char *format, char **env) {
2943 const char *e, *word = format;
2948 for (e = format; *e; e ++) {
2959 if (!(k = strnappend(r, word, e-word-1)))
2968 } else if (*e == '$') {
2969 if (!(k = strnappend(r, word, e-word)))
2985 t = strempty(strv_env_get_n(env, word+2, e-word-2));
2987 k = strappend(r, t);
3001 if (!(k = strnappend(r, word, e-word)))
3012 char **replace_env_argv(char **argv, char **env) {
3014 unsigned k = 0, l = 0;
3016 l = strv_length(argv);
3018 if (!(r = new(char*, l+1)))
3021 STRV_FOREACH(i, argv) {
3023 /* If $FOO appears as single word, replace it by the split up variable */
3024 if ((*i)[0] == '$' && (*i)[1] != '{') {
3029 e = strv_env_get(env, *i+1);
3032 if (!(m = strv_split_quoted(e))) {
3043 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3052 memcpy(r + k, m, q * sizeof(char*));
3060 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3061 if (!(r[k++] = replace_env(*i, env))) {
3071 int fd_columns(int fd) {
3075 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3084 unsigned columns(void) {
3088 if (_likely_(cached_columns > 0))
3089 return cached_columns;
3092 e = getenv("COLUMNS");
3097 c = fd_columns(STDOUT_FILENO);
3106 int fd_lines(int fd) {
3110 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3119 unsigned lines(void) {
3123 if (_likely_(cached_lines > 0))
3124 return cached_lines;
3127 e = getenv("LINES");
3132 l = fd_lines(STDOUT_FILENO);
3138 return cached_lines;
3141 /* intended to be used as a SIGWINCH sighandler */
3142 void columns_lines_cache_reset(int signum) {
3148 static int cached_on_tty = -1;
3150 if (_unlikely_(cached_on_tty < 0))
3151 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3153 return cached_on_tty;
3156 int running_in_chroot(void) {
3162 /* Only works as root */
3164 if (stat("/proc/1/root", &a) < 0)
3167 if (stat("/", &b) < 0)
3171 a.st_dev != b.st_dev ||
3172 a.st_ino != b.st_ino;
3175 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3180 assert(percent <= 100);
3181 assert(new_length >= 3);
3183 if (old_length <= 3 || old_length <= new_length)
3184 return strndup(s, old_length);
3186 r = new0(char, new_length+1);
3190 x = (new_length * percent) / 100;
3192 if (x > new_length - 3)
3200 s + old_length - (new_length - x - 3),
3201 new_length - x - 3);
3206 char *ellipsize(const char *s, size_t length, unsigned percent) {
3207 return ellipsize_mem(s, strlen(s), length, percent);
3210 int touch(const char *path) {
3215 /* This just opens the file for writing, ensuring it
3216 * exists. It doesn't call utimensat() the way /usr/bin/touch
3219 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3223 close_nointr_nofail(fd);
3227 char *unquote(const char *s, const char* quotes) {
3231 /* This is rather stupid, simply removes the heading and
3232 * trailing quotes if there is one. Doesn't care about
3233 * escaping or anything. We should make this smarter one
3240 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3241 return strndup(s+1, l-2);
3246 char *normalize_env_assignment(const char *s) {
3247 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3250 eq = strchr(s, '=');
3262 memmove(r, t, strlen(t) + 1);
3266 name = strndup(s, eq - s);
3274 value = unquote(strstrip(p), QUOTES);
3278 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3284 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3295 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3307 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3314 r = wait_for_terminate(pid, &status);
3316 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3320 if (status.si_code == CLD_EXITED) {
3321 if (status.si_status != 0) {
3322 log_warning("%s failed with error code %i.", name, status.si_status);
3323 return status.si_status;
3326 log_debug("%s succeeded.", name);
3329 } else if (status.si_code == CLD_KILLED ||
3330 status.si_code == CLD_DUMPED) {
3332 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3336 log_warning("%s failed due to unknown reason.", name);
3340 _noreturn_ void freeze(void) {
3342 /* Make sure nobody waits for us on a socket anymore */
3343 close_all_fds(NULL, 0);
3351 bool null_or_empty(struct stat *st) {
3354 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3357 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3363 int null_or_empty_path(const char *fn) {
3368 if (stat(fn, &st) < 0)
3371 return null_or_empty(&st);
3374 DIR *xopendirat(int fd, const char *name, int flags) {
3378 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3384 close_nointr_nofail(nfd);
3391 int signal_from_string_try_harder(const char *s) {
3395 signo = signal_from_string(s);
3397 if (startswith(s, "SIG"))
3398 return signal_from_string(s+3);
3403 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3407 /* FIXME: to follow udev's logic 100% we need to leave valid
3408 * UTF8 chars unescaped */
3410 u = unquote(tagvalue, "\"\'");
3414 t = xescape(u, "/ ");
3420 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3429 char *fstab_node_to_udev_node(const char *p) {
3432 if (startswith(p, "LABEL="))
3433 return tag_to_udev_node(p+6, "label");
3435 if (startswith(p, "UUID="))
3436 return tag_to_udev_node(p+5, "uuid");
3438 if (startswith(p, "PARTUUID="))
3439 return tag_to_udev_node(p+9, "partuuid");
3441 if (startswith(p, "PARTLABEL="))
3442 return tag_to_udev_node(p+10, "partlabel");
3447 bool tty_is_vc(const char *tty) {
3450 if (startswith(tty, "/dev/"))
3453 return vtnr_from_tty(tty) >= 0;
3456 bool tty_is_console(const char *tty) {
3459 if (startswith(tty, "/dev/"))
3462 return streq(tty, "console");
3465 int vtnr_from_tty(const char *tty) {
3470 if (startswith(tty, "/dev/"))
3473 if (!startswith(tty, "tty") )
3476 if (tty[3] < '0' || tty[3] > '9')
3479 r = safe_atoi(tty+3, &i);
3483 if (i < 0 || i > 63)
3489 bool tty_is_vc_resolve(const char *tty) {
3490 char *active = NULL;
3495 if (startswith(tty, "/dev/"))
3498 /* Resolve where /dev/console is pointing to, if /sys is
3499 * actually ours (i.e. not read-only-mounted which is a sign
3500 * for container setups) */
3501 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3502 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3503 /* If multiple log outputs are configured the
3504 * last one is what /dev/console points to */
3505 tty = strrchr(active, ' ');
3518 const char *default_term_for_tty(const char *tty) {
3521 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3524 bool dirent_is_file(const struct dirent *de) {
3527 if (ignore_file(de->d_name))
3530 if (de->d_type != DT_REG &&
3531 de->d_type != DT_LNK &&
3532 de->d_type != DT_UNKNOWN)
3538 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3541 if (de->d_type != DT_REG &&
3542 de->d_type != DT_LNK &&
3543 de->d_type != DT_UNKNOWN)
3546 if (ignore_file_allow_backup(de->d_name))
3549 return endswith(de->d_name, suffix);
3552 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3555 Hashmap *pids = NULL;
3559 /* Executes all binaries in a directory in parallel and waits
3560 * until all they all finished. */
3563 if (!(_d = opendir(directory))) {
3565 if (errno == ENOENT)
3568 log_error("Failed to enumerate directory %s: %m", directory);
3575 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3576 log_error("Failed to allocate set.");
3580 while ((de = readdir(d))) {
3585 if (!dirent_is_file(de))
3588 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3593 if ((pid = fork()) < 0) {
3594 log_error("Failed to fork: %m");
3612 log_error("Failed to execute %s: %m", path);
3613 _exit(EXIT_FAILURE);
3616 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3618 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3619 log_error("Failed to add PID to set: %s", strerror(-k));
3624 while (!hashmap_isempty(pids)) {
3625 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3630 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3635 log_error("waitid() failed: %m");
3639 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3640 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3641 if (si.si_code == CLD_EXITED)
3642 log_error("%s exited with exit status %i.", path, si.si_status);
3644 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3646 log_debug("%s exited successfully.", path);
3657 hashmap_free_free(pids);
3660 int kill_and_sigcont(pid_t pid, int sig) {
3663 r = kill(pid, sig) < 0 ? -errno : 0;
3671 bool nulstr_contains(const char*nulstr, const char *needle) {
3677 NULSTR_FOREACH(i, nulstr)
3678 if (streq(i, needle))
3684 bool plymouth_running(void) {
3685 return access("/run/plymouth/pid", F_OK) >= 0;
3688 char* strshorten(char *s, size_t l) {
3697 static bool hostname_valid_char(char c) {
3699 (c >= 'a' && c <= 'z') ||
3700 (c >= 'A' && c <= 'Z') ||
3701 (c >= '0' && c <= '9') ||
3707 bool hostname_is_valid(const char *s) {
3713 for (p = s; *p; p++)
3714 if (!hostname_valid_char(*p))
3717 if (p-s > HOST_NAME_MAX)
3723 char* hostname_cleanup(char *s) {
3726 for (p = s, d = s; *p; p++)
3727 if ((*p >= 'a' && *p <= 'z') ||
3728 (*p >= 'A' && *p <= 'Z') ||
3729 (*p >= '0' && *p <= '9') ||
3737 strshorten(s, HOST_NAME_MAX);
3741 int pipe_eof(int fd) {
3742 struct pollfd pollfd;
3747 pollfd.events = POLLIN|POLLHUP;
3749 r = poll(&pollfd, 1, 0);
3756 return pollfd.revents & POLLHUP;
3759 int fd_wait_for_event(int fd, int event, usec_t t) {
3760 struct pollfd pollfd;
3765 pollfd.events = event;
3767 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3774 return pollfd.revents;
3777 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3788 t = new(char, strlen(path) + 1 + 6 + 1);
3792 fn = path_get_file_name(path);
3796 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3798 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3804 f = fdopen(fd, "we");
3817 int terminal_vhangup_fd(int fd) {
3820 if (ioctl(fd, TIOCVHANGUP) < 0)
3826 int terminal_vhangup(const char *name) {
3829 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3833 r = terminal_vhangup_fd(fd);
3834 close_nointr_nofail(fd);
3839 int vt_disallocate(const char *name) {
3843 /* Deallocate the VT if possible. If not possible
3844 * (i.e. because it is the active one), at least clear it
3845 * entirely (including the scrollback buffer) */
3847 if (!startswith(name, "/dev/"))
3850 if (!tty_is_vc(name)) {
3851 /* So this is not a VT. I guess we cannot deallocate
3852 * it then. But let's at least clear the screen */
3854 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3859 "\033[r" /* clear scrolling region */
3860 "\033[H" /* move home */
3861 "\033[2J", /* clear screen */
3863 close_nointr_nofail(fd);
3868 if (!startswith(name, "/dev/tty"))
3871 r = safe_atou(name+8, &u);
3878 /* Try to deallocate */
3879 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3883 r = ioctl(fd, VT_DISALLOCATE, u);
3884 close_nointr_nofail(fd);
3892 /* Couldn't deallocate, so let's clear it fully with
3894 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3899 "\033[r" /* clear scrolling region */
3900 "\033[H" /* move home */
3901 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3903 close_nointr_nofail(fd);
3908 int copy_file(const char *from, const char *to) {
3914 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3918 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
3920 close_nointr_nofail(fdf);
3928 n = read(fdf, buf, sizeof(buf));
3932 close_nointr_nofail(fdf);
3943 k = loop_write(fdt, buf, n, false);
3945 r = k < 0 ? k : (errno ? -errno : -EIO);
3947 close_nointr_nofail(fdf);
3955 close_nointr_nofail(fdf);
3956 r = close_nointr(fdt);
3966 int symlink_atomic(const char *from, const char *to) {
3968 _cleanup_free_ char *t;
3971 unsigned long long ull;
3978 t = new(char, strlen(to) + 1 + 16 + 1);
3982 fn = path_get_file_name(to);
3986 x = stpcpy(t+k+1, fn);
3989 for (i = 0; i < 16; i++) {
3990 *(x++) = hexchar(ull & 0xF);
3996 if (symlink(from, t) < 0)
3999 if (rename(t, to) < 0) {
4008 bool display_is_local(const char *display) {
4012 display[0] == ':' &&
4013 display[1] >= '0' &&
4017 int socket_from_display(const char *display, char **path) {
4024 if (!display_is_local(display))
4027 k = strspn(display+1, "0123456789");
4029 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4033 c = stpcpy(f, "/tmp/.X11-unix/X");
4034 memcpy(c, display+1, k);
4043 const char **username,
4044 uid_t *uid, gid_t *gid,
4046 const char **shell) {
4054 /* We enforce some special rules for uid=0: in order to avoid
4055 * NSS lookups for root we hardcode its data. */
4057 if (streq(*username, "root") || streq(*username, "0")) {
4075 if (parse_uid(*username, &u) >= 0) {
4079 /* If there are multiple users with the same id, make
4080 * sure to leave $USER to the configured value instead
4081 * of the first occurrence in the database. However if
4082 * the uid was configured by a numeric uid, then let's
4083 * pick the real username from /etc/passwd. */
4085 *username = p->pw_name;
4088 p = getpwnam(*username);
4092 return errno != 0 ? -errno : -ESRCH;
4104 *shell = p->pw_shell;
4109 char* uid_to_name(uid_t uid) {
4114 return strdup("root");
4118 return strdup(p->pw_name);
4120 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4126 int get_group_creds(const char **groupname, gid_t *gid) {
4132 /* We enforce some special rules for gid=0: in order to avoid
4133 * NSS lookups for root we hardcode its data. */
4135 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4136 *groupname = "root";
4144 if (parse_gid(*groupname, &id) >= 0) {
4149 *groupname = g->gr_name;
4152 g = getgrnam(*groupname);
4156 return errno != 0 ? -errno : -ESRCH;
4164 int in_group(const char *name) {
4166 int ngroups_max, r, i;
4168 r = get_group_creds(&name, &gid);
4172 if (getgid() == gid)
4175 if (getegid() == gid)
4178 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4179 assert(ngroups_max > 0);
4181 gids = alloca(sizeof(gid_t) * ngroups_max);
4183 r = getgroups(ngroups_max, gids);
4187 for (i = 0; i < r; i++)
4194 int glob_exists(const char *path) {
4202 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4204 if (k == GLOB_NOMATCH)
4206 else if (k == GLOB_NOSPACE)
4209 r = !strv_isempty(g.gl_pathv);
4211 r = errno ? -errno : -EIO;
4218 int dirent_ensure_type(DIR *d, struct dirent *de) {
4224 if (de->d_type != DT_UNKNOWN)
4227 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4231 S_ISREG(st.st_mode) ? DT_REG :
4232 S_ISDIR(st.st_mode) ? DT_DIR :
4233 S_ISLNK(st.st_mode) ? DT_LNK :
4234 S_ISFIFO(st.st_mode) ? DT_FIFO :
4235 S_ISSOCK(st.st_mode) ? DT_SOCK :
4236 S_ISCHR(st.st_mode) ? DT_CHR :
4237 S_ISBLK(st.st_mode) ? DT_BLK :
4243 int in_search_path(const char *path, char **search) {
4247 r = path_get_parent(path, &parent);
4253 STRV_FOREACH(i, search) {
4254 if (path_equal(parent, *i)) {
4265 int get_files_in_directory(const char *path, char ***list) {
4273 /* Returns all files in a directory in *list, and the number
4274 * of files as return value. If list is NULL returns only the
4283 union dirent_storage buf;
4286 k = readdir_r(d, &buf.de, &de);
4295 dirent_ensure_type(d, de);
4297 if (!dirent_is_file(de))
4301 if ((unsigned) r >= n) {
4305 t = realloc(l, sizeof(char*) * n);
4314 assert((unsigned) r < n);
4316 l[r] = strdup(de->d_name);
4340 char *strjoin(const char *x, ...) {
4354 t = va_arg(ap, const char *);
4359 if (n > ((size_t) -1) - l) {
4383 t = va_arg(ap, const char *);
4397 bool is_main_thread(void) {
4398 static __thread int cached = 0;
4400 if (_unlikely_(cached == 0))
4401 cached = getpid() == gettid() ? 1 : -1;
4406 int block_get_whole_disk(dev_t d, dev_t *ret) {
4413 /* If it has a queue this is good enough for us */
4414 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4417 r = access(p, F_OK);
4425 /* If it is a partition find the originating device */
4426 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4429 r = access(p, F_OK);
4435 /* Get parent dev_t */
4436 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4439 r = read_one_line_file(p, &s);
4445 r = sscanf(s, "%u:%u", &m, &n);
4451 /* Only return this if it is really good enough for us. */
4452 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4455 r = access(p, F_OK);
4459 *ret = makedev(m, n);
4466 int file_is_priv_sticky(const char *p) {
4471 if (lstat(p, &st) < 0)
4475 (st.st_uid == 0 || st.st_uid == getuid()) &&
4476 (st.st_mode & S_ISVTX);
4479 static const char *const ioprio_class_table[] = {
4480 [IOPRIO_CLASS_NONE] = "none",
4481 [IOPRIO_CLASS_RT] = "realtime",
4482 [IOPRIO_CLASS_BE] = "best-effort",
4483 [IOPRIO_CLASS_IDLE] = "idle"
4486 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4488 static const char *const sigchld_code_table[] = {
4489 [CLD_EXITED] = "exited",
4490 [CLD_KILLED] = "killed",
4491 [CLD_DUMPED] = "dumped",
4492 [CLD_TRAPPED] = "trapped",
4493 [CLD_STOPPED] = "stopped",
4494 [CLD_CONTINUED] = "continued",
4497 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4499 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4500 [LOG_FAC(LOG_KERN)] = "kern",
4501 [LOG_FAC(LOG_USER)] = "user",
4502 [LOG_FAC(LOG_MAIL)] = "mail",
4503 [LOG_FAC(LOG_DAEMON)] = "daemon",
4504 [LOG_FAC(LOG_AUTH)] = "auth",
4505 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4506 [LOG_FAC(LOG_LPR)] = "lpr",
4507 [LOG_FAC(LOG_NEWS)] = "news",
4508 [LOG_FAC(LOG_UUCP)] = "uucp",
4509 [LOG_FAC(LOG_CRON)] = "cron",
4510 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4511 [LOG_FAC(LOG_FTP)] = "ftp",
4512 [LOG_FAC(LOG_LOCAL0)] = "local0",
4513 [LOG_FAC(LOG_LOCAL1)] = "local1",
4514 [LOG_FAC(LOG_LOCAL2)] = "local2",
4515 [LOG_FAC(LOG_LOCAL3)] = "local3",
4516 [LOG_FAC(LOG_LOCAL4)] = "local4",
4517 [LOG_FAC(LOG_LOCAL5)] = "local5",
4518 [LOG_FAC(LOG_LOCAL6)] = "local6",
4519 [LOG_FAC(LOG_LOCAL7)] = "local7"
4522 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4524 static const char *const log_level_table[] = {
4525 [LOG_EMERG] = "emerg",
4526 [LOG_ALERT] = "alert",
4527 [LOG_CRIT] = "crit",
4529 [LOG_WARNING] = "warning",
4530 [LOG_NOTICE] = "notice",
4531 [LOG_INFO] = "info",
4532 [LOG_DEBUG] = "debug"
4535 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4537 static const char* const sched_policy_table[] = {
4538 [SCHED_OTHER] = "other",
4539 [SCHED_BATCH] = "batch",
4540 [SCHED_IDLE] = "idle",
4541 [SCHED_FIFO] = "fifo",
4545 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4547 static const char* const rlimit_table[] = {
4548 [RLIMIT_CPU] = "LimitCPU",
4549 [RLIMIT_FSIZE] = "LimitFSIZE",
4550 [RLIMIT_DATA] = "LimitDATA",
4551 [RLIMIT_STACK] = "LimitSTACK",
4552 [RLIMIT_CORE] = "LimitCORE",
4553 [RLIMIT_RSS] = "LimitRSS",
4554 [RLIMIT_NOFILE] = "LimitNOFILE",
4555 [RLIMIT_AS] = "LimitAS",
4556 [RLIMIT_NPROC] = "LimitNPROC",
4557 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4558 [RLIMIT_LOCKS] = "LimitLOCKS",
4559 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4560 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4561 [RLIMIT_NICE] = "LimitNICE",
4562 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4563 [RLIMIT_RTTIME] = "LimitRTTIME"
4566 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4568 static const char* const ip_tos_table[] = {
4569 [IPTOS_LOWDELAY] = "low-delay",
4570 [IPTOS_THROUGHPUT] = "throughput",
4571 [IPTOS_RELIABILITY] = "reliability",
4572 [IPTOS_LOWCOST] = "low-cost",
4575 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4577 static const char *const __signal_table[] = {
4594 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4605 [SIGVTALRM] = "VTALRM",
4607 [SIGWINCH] = "WINCH",
4613 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4615 const char *signal_to_string(int signo) {
4616 static __thread char buf[12];
4619 name = __signal_to_string(signo);
4623 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4624 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4626 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4631 int signal_from_string(const char *s) {
4636 signo = __signal_from_string(s);
4640 if (startswith(s, "RTMIN+")) {
4644 if (safe_atou(s, &u) >= 0) {
4645 signo = (int) u + offset;
4646 if (signo > 0 && signo < _NSIG)
4652 bool kexec_loaded(void) {
4653 bool loaded = false;
4656 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4664 int strdup_or_null(const char *a, char **b) {
4682 int prot_from_flags(int flags) {
4684 switch (flags & O_ACCMODE) {
4693 return PROT_READ|PROT_WRITE;
4700 char *format_bytes(char *buf, size_t l, off_t t) {
4703 static const struct {
4707 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4708 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4709 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4710 { "G", 1024ULL*1024ULL*1024ULL },
4711 { "M", 1024ULL*1024ULL },
4715 for (i = 0; i < ELEMENTSOF(table); i++) {
4717 if (t >= table[i].factor) {
4720 (unsigned long long) (t / table[i].factor),
4721 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4728 snprintf(buf, l, "%lluB", (unsigned long long) t);
4736 void* memdup(const void *p, size_t l) {
4749 int fd_inc_sndbuf(int fd, size_t n) {
4751 socklen_t l = sizeof(value);
4753 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4755 l == sizeof(value) &&
4756 (size_t) value >= n*2)
4760 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4767 int fd_inc_rcvbuf(int fd, size_t n) {
4769 socklen_t l = sizeof(value);
4771 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4773 l == sizeof(value) &&
4774 (size_t) value >= n*2)
4778 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4785 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4786 pid_t parent_pid, agent_pid;
4788 bool stdout_is_tty, stderr_is_tty;
4796 parent_pid = getpid();
4798 /* Spawns a temporary TTY agent, making sure it goes away when
4805 if (agent_pid != 0) {
4812 * Make sure the agent goes away when the parent dies */
4813 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4814 _exit(EXIT_FAILURE);
4816 /* Check whether our parent died before we were able
4817 * to set the death signal */
4818 if (getppid() != parent_pid)
4819 _exit(EXIT_SUCCESS);
4821 /* Don't leak fds to the agent */
4822 close_all_fds(except, n_except);
4824 stdout_is_tty = isatty(STDOUT_FILENO);
4825 stderr_is_tty = isatty(STDERR_FILENO);
4827 if (!stdout_is_tty || !stderr_is_tty) {
4828 /* Detach from stdout/stderr. and reopen
4829 * /dev/tty for them. This is important to
4830 * ensure that when systemctl is started via
4831 * popen() or a similar call that expects to
4832 * read EOF we actually do generate EOF and
4833 * not delay this indefinitely by because we
4834 * keep an unused copy of stdin around. */
4835 fd = open("/dev/tty", O_WRONLY);
4837 log_error("Failed to open /dev/tty: %m");
4838 _exit(EXIT_FAILURE);
4842 dup2(fd, STDOUT_FILENO);
4845 dup2(fd, STDERR_FILENO);
4851 /* Count arguments */
4853 for (n = 0; va_arg(ap, char*); n++)
4858 l = alloca(sizeof(char *) * (n + 1));
4860 /* Fill in arguments */
4862 for (i = 0; i <= n; i++)
4863 l[i] = va_arg(ap, char*);
4867 _exit(EXIT_FAILURE);
4870 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4871 struct rlimit highest, fixed;
4875 if (setrlimit(resource, rlim) >= 0)
4881 /* So we failed to set the desired setrlimit, then let's try
4882 * to get as close as we can */
4883 assert_se(getrlimit(resource, &highest) == 0);
4885 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4886 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4888 if (setrlimit(resource, &fixed) < 0)
4894 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
4895 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
4907 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
4910 f = fopen(path, "re");
4918 char line[LINE_MAX];
4921 for (i = 0; i < sizeof(line)-1; i++) {
4925 if (_unlikely_(c == EOF)) {
4935 if (memcmp(line, field, l) == 0 && line[l] == '=') {
4936 value = strdup(line + l + 1);
4956 int can_sleep(const char *type) {
4960 _cleanup_free_ char *p = NULL;
4964 /* If /sys is read-only we cannot sleep */
4965 if (access("/sys/power/state", W_OK) < 0)
4968 r = read_one_line_file("/sys/power/state", &p);
4973 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
4974 if (l == k && memcmp(w, type, l) == 0)
4980 int can_sleep_disk(const char *type) {
4984 _cleanup_free_ char *p = NULL;
4988 /* If /sys is read-only we cannot sleep */
4989 if (access("/sys/power/state", W_OK) < 0 ||
4990 access("/sys/power/disk", W_OK) < 0)
4993 r = read_one_line_file("/sys/power/disk", &p);
4998 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
4999 if (l == k && memcmp(w, type, l) == 0)
5002 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5009 bool is_valid_documentation_url(const char *url) {
5012 if (startswith(url, "http://") && url[7])
5015 if (startswith(url, "https://") && url[8])
5018 if (startswith(url, "file:") && url[5])
5021 if (startswith(url, "info:") && url[5])
5024 if (startswith(url, "man:") && url[4])
5030 bool in_initrd(void) {
5031 static __thread int saved = -1;
5037 /* We make two checks here:
5039 * 1. the flag file /etc/initrd-release must exist
5040 * 2. the root file system must be a memory file system
5042 * The second check is extra paranoia, since misdetecting an
5043 * initrd can have bad bad consequences due the initrd
5044 * emptying when transititioning to the main systemd.
5047 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5048 statfs("/", &s) >= 0 &&
5049 is_temporary_fs(&s);
5054 void warn_melody(void) {
5055 _cleanup_close_ int fd = -1;
5057 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5061 /* Yeah, this is synchronous. Kinda sucks. But well... */
5063 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5064 usleep(125*USEC_PER_MSEC);
5066 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5067 usleep(125*USEC_PER_MSEC);
5069 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5070 usleep(125*USEC_PER_MSEC);
5072 ioctl(fd, KIOCSOUND, 0);
5075 int make_console_stdio(void) {
5078 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5080 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5082 log_error("Failed to acquire terminal: %s", strerror(-fd));
5088 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5095 int get_home_dir(char **_h) {
5103 /* Take the user specified one */
5114 /* Hardcode home directory for root to avoid NSS */
5117 h = strdup("/root");
5125 /* Check the database... */
5129 return errno ? -errno : -ESRCH;
5131 if (!path_is_absolute(p->pw_dir))
5134 h = strdup(p->pw_dir);
5142 int get_shell(char **_sh) {
5150 /* Take the user specified one */
5151 e = getenv("SHELL");
5161 /* Hardcode home directory for root to avoid NSS */
5164 sh = strdup("/bin/sh");
5172 /* Check the database... */
5176 return errno ? -errno : -ESRCH;
5178 if (!path_is_absolute(p->pw_shell))
5181 sh = strdup(p->pw_shell);
5189 void freep(void *p) {
5193 void fclosep(FILE **f) {
5198 void pclosep(FILE **f) {
5203 void closep(int *fd) {
5205 close_nointr_nofail(*fd);
5208 void closedirp(DIR **d) {
5213 void umaskp(mode_t *u) {
5217 bool filename_is_safe(const char *p) {
5231 if (strlen(p) > FILENAME_MAX)
5237 bool string_is_safe(const char *p) {
5242 for (t = p; *t; t++) {
5243 if (*t > 0 && *t < ' ')
5246 if (strchr("\\\"\'", *t))
5253 bool string_has_cc(const char *p) {
5258 for (t = p; *t; t++)
5259 if (*t > 0 && *t < ' ')
5265 bool path_is_safe(const char *p) {
5270 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5273 if (strlen(p) > PATH_MAX)
5276 /* The following two checks are not really dangerous, but hey, they still are confusing */
5277 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5280 if (strstr(p, "//"))
5286 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5287 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5288 int (*compar) (const void *, const void *, void *), void *arg) {
5297 p = (void *)(((const char *) base) + (idx * size));
5298 comparison = compar(key, p, arg);
5301 else if (comparison > 0)
5309 bool is_locale_utf8(void) {
5311 static int cached_answer = -1;
5313 if (cached_answer >= 0)
5316 if (!setlocale(LC_ALL, "")) {
5317 cached_answer = true;
5321 set = nl_langinfo(CODESET);
5323 cached_answer = true;
5327 cached_answer = streq(set, "UTF-8");
5329 return (bool)cached_answer;
5332 const char *draw_special_char(DrawSpecialChar ch) {
5333 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5335 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5336 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5337 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5338 [DRAW_TREE_SPACE] = " ", /* */
5339 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5341 /* ASCII fallback */ {
5342 [DRAW_TREE_VERT] = "| ",
5343 [DRAW_TREE_BRANCH] = "|-",
5344 [DRAW_TREE_RIGHT] = "`-",
5345 [DRAW_TREE_SPACE] = " ",
5346 [DRAW_TRIANGULAR_BULLET] = "> ",
5350 return draw_table[!is_locale_utf8()][ch];
5353 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5356 size_t l, old_len, new_len;
5362 old_len = strlen(old_string);
5363 new_len = strlen(new_string);
5376 if (!startswith(f, old_string)) {
5382 nl = l - old_len + new_len;
5383 a = realloc(r, nl + 1);
5391 t = stpcpy(t, new_string);
5403 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5404 const char *i, *begin = NULL;
5409 } state = STATE_OTHER;
5411 size_t osz = 0, isz;
5417 /* Strips ANSI color and replaces TABs by 8 spaces */
5419 isz = _isz ? *_isz : strlen(*ibuf);
5421 f = open_memstream(&obuf, &osz);
5425 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5430 if (i >= *ibuf + isz) /* EOT */
5432 else if (*i == '\x1B')
5433 state = STATE_ESCAPE;
5434 else if (*i == '\t')
5441 if (i >= *ibuf + isz) { /* EOT */
5444 } else if (*i == '[') {
5445 state = STATE_BRACKET;
5450 state = STATE_OTHER;
5457 if (i >= *ibuf + isz || /* EOT */
5458 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5461 state = STATE_OTHER;
5463 } else if (*i == 'm')
5464 state = STATE_OTHER;
5486 int on_ac_power(void) {
5487 bool found_offline = false, found_online = false;
5488 _cleanup_closedir_ DIR *d = NULL;
5490 d = opendir("/sys/class/power_supply");
5496 union dirent_storage buf;
5497 _cleanup_free_ char *p = NULL;
5498 _cleanup_close_ int fd = -1, device = -1;
5503 k = readdir_r(d, &buf.de, &de);
5510 if (ignore_file(de->d_name))
5513 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5515 if (errno == ENOENT || errno == ENOTDIR)
5521 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5523 if (errno == ENOENT)
5529 n = read(fd, contents, sizeof(contents));
5533 if (n != 6 || memcmp(contents, "Mains\n", 6))
5536 close_nointr_nofail(fd);
5537 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5539 if (errno == ENOENT)
5545 n = read(fd, contents, sizeof(contents));
5549 if (n != 2 || contents[1] != '\n')
5552 if (contents[0] == '1') {
5553 found_online = true;
5555 } else if (contents[0] == '0')
5556 found_offline = true;
5561 return found_online || !found_offline;
5564 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5571 if (!path_strv_canonicalize_uniq(search))
5574 STRV_FOREACH(i, search) {
5575 _cleanup_free_ char *p = NULL;
5578 p = strjoin(*i, "/", path, NULL);
5588 if (errno != ENOENT)
5595 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5596 _cleanup_strv_free_ char **copy = NULL;
5602 if (path_is_absolute(path)) {
5605 f = fopen(path, mode);
5614 copy = strv_copy((char**) search);
5618 return search_and_fopen_internal(path, mode, copy, _f);
5621 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5622 _cleanup_strv_free_ char **s = NULL;
5624 if (path_is_absolute(path)) {
5627 f = fopen(path, mode);
5636 s = strv_split_nulstr(search);
5640 return search_and_fopen_internal(path, mode, s, _f);