1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
71 #include "path-util.h"
72 #include "exit-status.h"
78 char **saved_argv = NULL;
80 static volatile unsigned cached_columns = 0;
81 static volatile unsigned cached_lines = 0;
83 size_t page_size(void) {
84 static __thread size_t pgsz = 0;
87 if (_likely_(pgsz > 0))
90 r = sysconf(_SC_PAGESIZE);
97 bool streq_ptr(const char *a, const char *b) {
99 /* Like streq(), but tries to make sense of NULL pointers */
110 char* endswith(const char *s, const char *postfix) {
117 pl = strlen(postfix);
120 return (char*) s + sl;
125 if (memcmp(s + sl - pl, postfix, pl) != 0)
128 return (char*) s + sl - pl;
131 char* startswith(const char *s, const char *prefix) {
148 char* startswith_no_case(const char *s, const char *prefix) {
158 if (tolower(*a) != tolower(*b))
165 bool first_word(const char *s, const char *word) {
180 if (memcmp(s, word, wl) != 0)
184 strchr(WHITESPACE, s[wl]);
187 int close_nointr(int fd) {
193 /* Just ignore EINTR; a retry loop is the wrong
194 * thing to do on Linux.
196 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
197 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
198 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
199 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
201 if (_unlikely_(r < 0 && errno == EINTR))
209 void close_nointr_nofail(int fd) {
212 /* like close_nointr() but cannot fail, and guarantees errno
215 assert_se(close_nointr(fd) == 0);
218 void close_many(const int fds[], unsigned n_fd) {
221 assert(fds || n_fd <= 0);
223 for (i = 0; i < n_fd; i++)
224 close_nointr_nofail(fds[i]);
227 int parse_boolean(const char *v) {
230 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
232 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
238 int parse_pid(const char *s, pid_t* ret_pid) {
239 unsigned long ul = 0;
246 r = safe_atolu(s, &ul);
252 if ((unsigned long) pid != ul)
262 int parse_uid(const char *s, uid_t* ret_uid) {
263 unsigned long ul = 0;
270 r = safe_atolu(s, &ul);
276 if ((unsigned long) uid != ul)
283 int safe_atou(const char *s, unsigned *ret_u) {
291 l = strtoul(s, &x, 0);
293 if (!x || x == s || *x || errno)
294 return errno > 0 ? -errno : -EINVAL;
296 if ((unsigned long) (unsigned) l != l)
299 *ret_u = (unsigned) l;
303 int safe_atoi(const char *s, int *ret_i) {
311 l = strtol(s, &x, 0);
313 if (!x || x == s || *x || errno)
314 return errno > 0 ? -errno : -EINVAL;
316 if ((long) (int) l != l)
323 int safe_atollu(const char *s, long long unsigned *ret_llu) {
325 unsigned long long l;
331 l = strtoull(s, &x, 0);
333 if (!x || x == s || *x || errno)
334 return errno ? -errno : -EINVAL;
340 int safe_atolli(const char *s, long long int *ret_lli) {
348 l = strtoll(s, &x, 0);
350 if (!x || x == s || *x || errno)
351 return errno ? -errno : -EINVAL;
357 int safe_atod(const char *s, double *ret_d) {
367 if (!x || x == s || *x || errno)
368 return errno ? -errno : -EINVAL;
374 /* Split a string into words. */
375 char *split(const char *c, size_t *l, const char *separator, char **state) {
378 current = *state ? *state : (char*) c;
380 if (!*current || *c == 0)
383 current += strspn(current, separator);
384 *l = strcspn(current, separator);
387 return (char*) current;
390 /* Split a string into words, but consider strings enclosed in '' and
391 * "" as words even if they include spaces. */
392 char *split_quoted(const char *c, size_t *l, char **state) {
394 bool escaped = false;
396 current = *state ? *state : (char*) c;
398 if (!*current || *c == 0)
401 current += strspn(current, WHITESPACE);
403 if (*current == '\'') {
406 for (e = current; *e; e++) {
416 *state = *e == 0 ? e : e+1;
417 } else if (*current == '\"') {
420 for (e = current; *e; e++) {
430 *state = *e == 0 ? e : e+1;
432 for (e = current; *e; e++) {
437 else if (strchr(WHITESPACE, *e))
444 return (char*) current;
447 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
449 _cleanup_fclose_ FILE *f = NULL;
450 char fn[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/stat")], line[LINE_MAX], *p;
456 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
462 if (!fgets(line, sizeof(line), f)) {
463 r = feof(f) ? -EIO : -errno;
467 /* Let's skip the pid and comm fields. The latter is enclosed
468 * in () but does not escape any () in its value, so let's
469 * skip over it manually */
471 p = strrchr(line, ')');
483 if ((long unsigned) (pid_t) ppid != ppid)
486 *_ppid = (pid_t) ppid;
491 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
492 _cleanup_fclose_ FILE *f = NULL;
493 char fn[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/stat")], line[LINE_MAX], *p;
498 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
504 if (!fgets(line, sizeof(line), f)) {
511 /* Let's skip the pid and comm fields. The latter is enclosed
512 * in () but does not escape any () in its value, so let's
513 * skip over it manually */
515 p = strrchr(line, ')');
537 "%*d " /* priority */
539 "%*d " /* num_threads */
540 "%*d " /* itrealvalue */
541 "%llu " /* starttime */,
548 int fchmod_umask(int fd, mode_t m) {
553 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
559 char *truncate_nl(char *s) {
562 s[strcspn(s, NEWLINE)] = 0;
566 int get_process_comm(pid_t pid, char **name) {
572 r = read_one_line_file("/proc/self/comm", name);
575 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
578 r = read_one_line_file(p, name);
585 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
593 f = fopen("/proc/self/cmdline", "re");
596 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
605 if (max_length == 0) {
607 while ((c = getc(f)) != EOF) {
608 k = realloc(r, len+1);
615 r[len-1] = isprint(c) ? c : ' ';
622 r = new(char, max_length);
630 while ((c = getc(f)) != EOF) {
652 size_t n = MIN(left-1, 3U);
661 /* Kernel threads have no argv[] */
662 if (r == NULL || r[0] == 0) {
671 h = get_process_comm(pid, &t);
675 r = strjoin("[", t, "]", NULL);
686 int is_kernel_thread(pid_t pid) {
696 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
705 count = fread(&c, 1, 1, f);
709 /* Kernel threads have an empty cmdline */
712 return eof ? 1 : -errno;
717 int get_process_exe(pid_t pid, char **name) {
723 r = readlink_malloc("/proc/self/exe", name);
726 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
729 r = readlink_malloc(p, name);
736 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
737 _cleanup_fclose_ FILE *f = NULL;
738 _cleanup_free_ char *p = NULL;
747 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
754 FOREACH_LINE(line, f, return -errno) {
759 if (startswith(l, field)) {
761 l += strspn(l, WHITESPACE);
763 l[strcspn(l, WHITESPACE)] = 0;
765 return parse_uid(l, uid);
772 int get_process_uid(pid_t pid, uid_t *uid) {
773 return get_process_id(pid, "Uid:", uid);
776 int get_process_gid(pid_t pid, gid_t *gid) {
777 return get_process_id(pid, "Gid:", gid);
780 char *strnappend(const char *s, const char *suffix, size_t b) {
788 return strndup(suffix, b);
797 if (b > ((size_t) -1) - a)
800 r = new(char, a+b+1);
805 memcpy(r+a, suffix, b);
811 char *strappend(const char *s, const char *suffix) {
812 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
815 int readlink_malloc(const char *p, char **r) {
825 if (!(c = new(char, l)))
828 if ((n = readlink(p, c, l-1)) < 0) {
834 if ((size_t) n < l-1) {
845 int readlink_and_make_absolute(const char *p, char **r) {
852 if ((j = readlink_malloc(p, &target)) < 0)
855 k = file_in_same_dir(p, target);
865 int readlink_and_canonicalize(const char *p, char **r) {
872 j = readlink_and_make_absolute(p, &t);
876 s = canonicalize_file_name(t);
883 path_kill_slashes(*r);
888 int reset_all_signal_handlers(void) {
891 for (sig = 1; sig < _NSIG; sig++) {
894 if (sig == SIGKILL || sig == SIGSTOP)
898 sa.sa_handler = SIG_DFL;
899 sa.sa_flags = SA_RESTART;
901 /* On Linux the first two RT signals are reserved by
902 * glibc, and sigaction() will return EINVAL for them. */
903 if ((sigaction(sig, &sa, NULL) < 0))
911 char *strstrip(char *s) {
914 /* Drops trailing whitespace. Modifies the string in
915 * place. Returns pointer to first non-space character */
917 s += strspn(s, WHITESPACE);
919 for (e = strchr(s, 0); e > s; e --)
920 if (!strchr(WHITESPACE, e[-1]))
928 char *delete_chars(char *s, const char *bad) {
931 /* Drops all whitespace, regardless where in the string */
933 for (f = s, t = s; *f; f++) {
945 bool in_charset(const char *s, const char* charset) {
952 if (!strchr(charset, *i))
958 char *file_in_same_dir(const char *path, const char *filename) {
965 /* This removes the last component of path and appends
966 * filename, unless the latter is absolute anyway or the
969 if (path_is_absolute(filename))
970 return strdup(filename);
972 if (!(e = strrchr(path, '/')))
973 return strdup(filename);
975 k = strlen(filename);
976 if (!(r = new(char, e-path+1+k+1)))
979 memcpy(r, path, e-path+1);
980 memcpy(r+(e-path)+1, filename, k+1);
985 int rmdir_parents(const char *path, const char *stop) {
994 /* Skip trailing slashes */
995 while (l > 0 && path[l-1] == '/')
1001 /* Skip last component */
1002 while (l > 0 && path[l-1] != '/')
1005 /* Skip trailing slashes */
1006 while (l > 0 && path[l-1] == '/')
1012 if (!(t = strndup(path, l)))
1015 if (path_startswith(stop, t)) {
1024 if (errno != ENOENT)
1031 char hexchar(int x) {
1032 static const char table[16] = "0123456789abcdef";
1034 return table[x & 15];
1037 int unhexchar(char c) {
1039 if (c >= '0' && c <= '9')
1042 if (c >= 'a' && c <= 'f')
1043 return c - 'a' + 10;
1045 if (c >= 'A' && c <= 'F')
1046 return c - 'A' + 10;
1051 char *hexmem(const void *p, size_t l) {
1055 z = r = malloc(l * 2 + 1);
1059 for (x = p; x < (const uint8_t*) p + l; x++) {
1060 *(z++) = hexchar(*x >> 4);
1061 *(z++) = hexchar(*x & 15);
1068 void *unhexmem(const char *p, size_t l) {
1074 z = r = malloc((l + 1) / 2 + 1);
1078 for (x = p; x < p + l; x += 2) {
1081 a = unhexchar(x[0]);
1083 b = unhexchar(x[1]);
1087 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1094 char octchar(int x) {
1095 return '0' + (x & 7);
1098 int unoctchar(char c) {
1100 if (c >= '0' && c <= '7')
1106 char decchar(int x) {
1107 return '0' + (x % 10);
1110 int undecchar(char c) {
1112 if (c >= '0' && c <= '9')
1118 char *cescape(const char *s) {
1124 /* Does C style string escaping. */
1126 r = new(char, strlen(s)*4 + 1);
1130 for (f = s, t = r; *f; f++)
1176 /* For special chars we prefer octal over
1177 * hexadecimal encoding, simply because glib's
1178 * g_strescape() does the same */
1179 if ((*f < ' ') || (*f >= 127)) {
1181 *(t++) = octchar((unsigned char) *f >> 6);
1182 *(t++) = octchar((unsigned char) *f >> 3);
1183 *(t++) = octchar((unsigned char) *f);
1194 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1201 /* Undoes C style string escaping, and optionally prefixes it. */
1203 pl = prefix ? strlen(prefix) : 0;
1205 r = new(char, pl+length+1);
1210 memcpy(r, prefix, pl);
1212 for (f = s, t = r + pl; f < s + length; f++) {
1255 /* This is an extension of the XDG syntax files */
1260 /* hexadecimal encoding */
1263 a = unhexchar(f[1]);
1264 b = unhexchar(f[2]);
1266 if (a < 0 || b < 0) {
1267 /* Invalid escape code, let's take it literal then */
1271 *(t++) = (char) ((a << 4) | b);
1286 /* octal encoding */
1289 a = unoctchar(f[0]);
1290 b = unoctchar(f[1]);
1291 c = unoctchar(f[2]);
1293 if (a < 0 || b < 0 || c < 0) {
1294 /* Invalid escape code, let's take it literal then */
1298 *(t++) = (char) ((a << 6) | (b << 3) | c);
1306 /* premature end of string.*/
1311 /* Invalid escape code, let's take it literal then */
1323 char *cunescape_length(const char *s, size_t length) {
1324 return cunescape_length_with_prefix(s, length, NULL);
1327 char *cunescape(const char *s) {
1330 return cunescape_length(s, strlen(s));
1333 char *xescape(const char *s, const char *bad) {
1337 /* Escapes all chars in bad, in addition to \ and all special
1338 * chars, in \xFF style escaping. May be reversed with
1341 r = new(char, strlen(s) * 4 + 1);
1345 for (f = s, t = r; *f; f++) {
1347 if ((*f < ' ') || (*f >= 127) ||
1348 (*f == '\\') || strchr(bad, *f)) {
1351 *(t++) = hexchar(*f >> 4);
1352 *(t++) = hexchar(*f);
1362 char *bus_path_escape(const char *s) {
1368 /* Escapes all chars that D-Bus' object path cannot deal
1369 * with. Can be reverse with bus_path_unescape(). We special
1370 * case the empty string. */
1375 r = new(char, strlen(s)*3 + 1);
1379 for (f = s, t = r; *f; f++) {
1381 /* Escape everything that is not a-zA-Z0-9. We also
1382 * escape 0-9 if it's the first character */
1384 if (!(*f >= 'A' && *f <= 'Z') &&
1385 !(*f >= 'a' && *f <= 'z') &&
1386 !(f > s && *f >= '0' && *f <= '9')) {
1388 *(t++) = hexchar(*f >> 4);
1389 *(t++) = hexchar(*f);
1399 char *bus_path_unescape(const char *f) {
1404 /* Special case for the empty string */
1408 r = new(char, strlen(f) + 1);
1412 for (t = r; *f; f++) {
1417 if ((a = unhexchar(f[1])) < 0 ||
1418 (b = unhexchar(f[2])) < 0) {
1419 /* Invalid escape code, let's take it literal then */
1422 *(t++) = (char) ((a << 4) | b);
1434 char *ascii_strlower(char *t) {
1439 for (p = t; *p; p++)
1440 if (*p >= 'A' && *p <= 'Z')
1441 *p = *p - 'A' + 'a';
1446 static bool ignore_file_allow_backup(const char *filename) {
1450 filename[0] == '.' ||
1451 streq(filename, "lost+found") ||
1452 streq(filename, "aquota.user") ||
1453 streq(filename, "aquota.group") ||
1454 endswith(filename, ".rpmnew") ||
1455 endswith(filename, ".rpmsave") ||
1456 endswith(filename, ".rpmorig") ||
1457 endswith(filename, ".dpkg-old") ||
1458 endswith(filename, ".dpkg-new") ||
1459 endswith(filename, ".swp");
1462 bool ignore_file(const char *filename) {
1465 if (endswith(filename, "~"))
1468 return ignore_file_allow_backup(filename);
1471 int fd_nonblock(int fd, bool nonblock) {
1476 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1480 flags |= O_NONBLOCK;
1482 flags &= ~O_NONBLOCK;
1484 if (fcntl(fd, F_SETFL, flags) < 0)
1490 int fd_cloexec(int fd, bool cloexec) {
1495 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1499 flags |= FD_CLOEXEC;
1501 flags &= ~FD_CLOEXEC;
1503 if (fcntl(fd, F_SETFD, flags) < 0)
1509 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1512 assert(n_fdset == 0 || fdset);
1514 for (i = 0; i < n_fdset; i++)
1521 int close_all_fds(const int except[], unsigned n_except) {
1526 assert(n_except == 0 || except);
1528 d = opendir("/proc/self/fd");
1533 /* When /proc isn't available (for example in chroots)
1534 * the fallback is brute forcing through the fd
1537 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1538 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1540 if (fd_in_set(fd, except, n_except))
1543 if (close_nointr(fd) < 0)
1544 if (errno != EBADF && r == 0)
1551 while ((de = readdir(d))) {
1554 if (ignore_file(de->d_name))
1557 if (safe_atoi(de->d_name, &fd) < 0)
1558 /* Let's better ignore this, just in case */
1567 if (fd_in_set(fd, except, n_except))
1570 if (close_nointr(fd) < 0) {
1571 /* Valgrind has its own FD and doesn't want to have it closed */
1572 if (errno != EBADF && r == 0)
1581 bool chars_intersect(const char *a, const char *b) {
1584 /* Returns true if any of the chars in a are in b. */
1585 for (p = a; *p; p++)
1592 bool fstype_is_network(const char *fstype) {
1593 static const char table[] =
1602 return nulstr_contains(table, fstype);
1606 _cleanup_close_ int fd;
1608 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1614 TIOCL_GETKMSGREDIRECT,
1618 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1621 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1624 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1630 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1631 struct termios old_termios, new_termios;
1633 char line[LINE_MAX];
1638 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1639 new_termios = old_termios;
1641 new_termios.c_lflag &= ~ICANON;
1642 new_termios.c_cc[VMIN] = 1;
1643 new_termios.c_cc[VTIME] = 0;
1645 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1648 if (t != (usec_t) -1) {
1649 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1650 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1655 k = fread(&c, 1, 1, f);
1657 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1663 *need_nl = c != '\n';
1670 if (t != (usec_t) -1)
1671 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1674 if (!fgets(line, sizeof(line), f))
1679 if (strlen(line) != 1)
1689 int ask(char *ret, const char *replies, const char *text, ...) {
1699 bool need_nl = true;
1702 fputs(ANSI_HIGHLIGHT_ON, stdout);
1709 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1713 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1716 if (r == -EBADMSG) {
1717 puts("Bad input, please try again.");
1728 if (strchr(replies, c)) {
1733 puts("Read unexpected character, please try again.");
1737 int reset_terminal_fd(int fd, bool switch_to_text) {
1738 struct termios termios;
1741 /* Set terminal to some sane defaults */
1745 /* We leave locked terminal attributes untouched, so that
1746 * Plymouth may set whatever it wants to set, and we don't
1747 * interfere with that. */
1749 /* Disable exclusive mode, just in case */
1750 ioctl(fd, TIOCNXCL);
1752 /* Switch to text mode */
1754 ioctl(fd, KDSETMODE, KD_TEXT);
1756 /* Enable console unicode mode */
1757 ioctl(fd, KDSKBMODE, K_UNICODE);
1759 if (tcgetattr(fd, &termios) < 0) {
1764 /* We only reset the stuff that matters to the software. How
1765 * hardware is set up we don't touch assuming that somebody
1766 * else will do that for us */
1768 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1769 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1770 termios.c_oflag |= ONLCR;
1771 termios.c_cflag |= CREAD;
1772 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1774 termios.c_cc[VINTR] = 03; /* ^C */
1775 termios.c_cc[VQUIT] = 034; /* ^\ */
1776 termios.c_cc[VERASE] = 0177;
1777 termios.c_cc[VKILL] = 025; /* ^X */
1778 termios.c_cc[VEOF] = 04; /* ^D */
1779 termios.c_cc[VSTART] = 021; /* ^Q */
1780 termios.c_cc[VSTOP] = 023; /* ^S */
1781 termios.c_cc[VSUSP] = 032; /* ^Z */
1782 termios.c_cc[VLNEXT] = 026; /* ^V */
1783 termios.c_cc[VWERASE] = 027; /* ^W */
1784 termios.c_cc[VREPRINT] = 022; /* ^R */
1785 termios.c_cc[VEOL] = 0;
1786 termios.c_cc[VEOL2] = 0;
1788 termios.c_cc[VTIME] = 0;
1789 termios.c_cc[VMIN] = 1;
1791 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1795 /* Just in case, flush all crap out */
1796 tcflush(fd, TCIOFLUSH);
1801 int reset_terminal(const char *name) {
1804 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1808 r = reset_terminal_fd(fd, true);
1809 close_nointr_nofail(fd);
1814 int open_terminal(const char *name, int mode) {
1819 * If a TTY is in the process of being closed opening it might
1820 * cause EIO. This is horribly awful, but unlikely to be
1821 * changed in the kernel. Hence we work around this problem by
1822 * retrying a couple of times.
1824 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1828 fd = open(name, mode);
1835 /* Max 1s in total */
1839 usleep(50 * USEC_PER_MSEC);
1848 close_nointr_nofail(fd);
1853 close_nointr_nofail(fd);
1860 int flush_fd(int fd) {
1861 struct pollfd pollfd;
1865 pollfd.events = POLLIN;
1872 r = poll(&pollfd, 1, 0);
1882 l = read(fd, buf, sizeof(buf));
1888 if (errno == EAGAIN)
1897 int acquire_terminal(
1901 bool ignore_tiocstty_eperm,
1904 int fd = -1, notify = -1, r = 0, wd = -1;
1906 struct sigaction sa_old, sa_new;
1910 /* We use inotify to be notified when the tty is closed. We
1911 * create the watch before checking if we can actually acquire
1912 * it, so that we don't lose any event.
1914 * Note: strictly speaking this actually watches for the
1915 * device being closed, it does *not* really watch whether a
1916 * tty loses its controlling process. However, unless some
1917 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1918 * its tty otherwise this will not become a problem. As long
1919 * as the administrator makes sure not configure any service
1920 * on the same tty as an untrusted user this should not be a
1921 * problem. (Which he probably should not do anyway.) */
1923 if (timeout != (usec_t) -1)
1924 ts = now(CLOCK_MONOTONIC);
1926 if (!fail && !force) {
1927 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1933 wd = inotify_add_watch(notify, name, IN_CLOSE);
1942 r = flush_fd(notify);
1947 /* We pass here O_NOCTTY only so that we can check the return
1948 * value TIOCSCTTY and have a reliable way to figure out if we
1949 * successfully became the controlling process of the tty */
1950 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1954 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1955 * if we already own the tty. */
1957 sa_new.sa_handler = SIG_IGN;
1958 sa_new.sa_flags = SA_RESTART;
1959 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1961 /* First, try to get the tty */
1962 if (ioctl(fd, TIOCSCTTY, force) < 0)
1965 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1967 /* Sometimes it makes sense to ignore TIOCSCTTY
1968 * returning EPERM, i.e. when very likely we already
1969 * are have this controlling terminal. */
1970 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1973 if (r < 0 && (force || fail || r != -EPERM)) {
1982 assert(notify >= 0);
1985 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1987 struct inotify_event *e;
1989 if (timeout != (usec_t) -1) {
1992 n = now(CLOCK_MONOTONIC);
1993 if (ts + timeout < n) {
1998 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2008 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2011 if (errno == EINTR || errno == EAGAIN)
2018 e = (struct inotify_event*) inotify_buffer;
2023 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2028 step = sizeof(struct inotify_event) + e->len;
2029 assert(step <= (size_t) l);
2031 e = (struct inotify_event*) ((uint8_t*) e + step);
2038 /* We close the tty fd here since if the old session
2039 * ended our handle will be dead. It's important that
2040 * we do this after sleeping, so that we don't enter
2041 * an endless loop. */
2042 close_nointr_nofail(fd);
2046 close_nointr_nofail(notify);
2048 r = reset_terminal_fd(fd, true);
2050 log_warning("Failed to reset terminal: %s", strerror(-r));
2056 close_nointr_nofail(fd);
2059 close_nointr_nofail(notify);
2064 int release_terminal(void) {
2066 struct sigaction sa_old, sa_new;
2067 int _cleanup_close_ fd;
2069 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2073 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2074 * by our own TIOCNOTTY */
2077 sa_new.sa_handler = SIG_IGN;
2078 sa_new.sa_flags = SA_RESTART;
2079 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2081 if (ioctl(fd, TIOCNOTTY) < 0)
2084 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2089 int sigaction_many(const struct sigaction *sa, ...) {
2094 while ((sig = va_arg(ap, int)) > 0)
2095 if (sigaction(sig, sa, NULL) < 0)
2102 int ignore_signals(int sig, ...) {
2103 struct sigaction sa;
2108 sa.sa_handler = SIG_IGN;
2109 sa.sa_flags = SA_RESTART;
2111 if (sigaction(sig, &sa, NULL) < 0)
2115 while ((sig = va_arg(ap, int)) > 0)
2116 if (sigaction(sig, &sa, NULL) < 0)
2123 int default_signals(int sig, ...) {
2124 struct sigaction sa;
2129 sa.sa_handler = SIG_DFL;
2130 sa.sa_flags = SA_RESTART;
2132 if (sigaction(sig, &sa, NULL) < 0)
2136 while ((sig = va_arg(ap, int)) > 0)
2137 if (sigaction(sig, &sa, NULL) < 0)
2144 int close_pipe(int p[]) {
2150 a = close_nointr(p[0]);
2155 b = close_nointr(p[1]);
2159 return a < 0 ? a : b;
2162 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2171 while (nbytes > 0) {
2174 if ((k = read(fd, p, nbytes)) <= 0) {
2176 if (k < 0 && errno == EINTR)
2179 if (k < 0 && errno == EAGAIN && do_poll) {
2180 struct pollfd pollfd;
2184 pollfd.events = POLLIN;
2186 if (poll(&pollfd, 1, -1) < 0) {
2190 return n > 0 ? n : -errno;
2193 if (pollfd.revents != POLLIN)
2194 return n > 0 ? n : -EIO;
2199 return n > 0 ? n : (k < 0 ? -errno : 0);
2210 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2219 while (nbytes > 0) {
2222 k = write(fd, p, nbytes);
2225 if (k < 0 && errno == EINTR)
2228 if (k < 0 && errno == EAGAIN && do_poll) {
2229 struct pollfd pollfd;
2233 pollfd.events = POLLOUT;
2235 if (poll(&pollfd, 1, -1) < 0) {
2239 return n > 0 ? n : -errno;
2242 if (pollfd.revents != POLLOUT)
2243 return n > 0 ? n : -EIO;
2248 return n > 0 ? n : (k < 0 ? -errno : 0);
2259 int parse_bytes(const char *t, off_t *bytes) {
2260 static const struct {
2266 { "M", 1024ULL*1024ULL },
2267 { "G", 1024ULL*1024ULL*1024ULL },
2268 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2269 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2270 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2287 l = strtoll(p, &e, 10);
2298 e += strspn(e, WHITESPACE);
2300 for (i = 0; i < ELEMENTSOF(table); i++)
2301 if (startswith(e, table[i].suffix)) {
2302 r += (off_t) l * table[i].factor;
2303 p = e + strlen(table[i].suffix);
2307 if (i >= ELEMENTSOF(table))
2317 int make_stdio(int fd) {
2322 r = dup3(fd, STDIN_FILENO, 0);
2323 s = dup3(fd, STDOUT_FILENO, 0);
2324 t = dup3(fd, STDERR_FILENO, 0);
2327 close_nointr_nofail(fd);
2329 if (r < 0 || s < 0 || t < 0)
2332 /* We rely here that the new fd has O_CLOEXEC not set */
2337 int make_null_stdio(void) {
2340 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2344 return make_stdio(null_fd);
2347 bool is_device_path(const char *path) {
2349 /* Returns true on paths that refer to a device, either in
2350 * sysfs or in /dev */
2353 path_startswith(path, "/dev/") ||
2354 path_startswith(path, "/sys/");
2357 int dir_is_empty(const char *path) {
2358 _cleanup_closedir_ DIR *d;
2367 union dirent_storage buf;
2369 r = readdir_r(d, &buf.de, &de);
2376 if (!ignore_file(de->d_name))
2381 char* dirname_malloc(const char *path) {
2382 char *d, *dir, *dir2;
2399 unsigned long long random_ull(void) {
2400 _cleanup_close_ int fd;
2404 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2408 r = loop_read(fd, &ull, sizeof(ull), true);
2409 if (r != sizeof(ull))
2415 return random() * RAND_MAX + random();
2418 void rename_process(const char name[8]) {
2421 /* This is a like a poor man's setproctitle(). It changes the
2422 * comm field, argv[0], and also the glibc's internally used
2423 * name of the process. For the first one a limit of 16 chars
2424 * applies, to the second one usually one of 10 (i.e. length
2425 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2426 * "systemd"). If you pass a longer string it will be
2429 prctl(PR_SET_NAME, name);
2431 if (program_invocation_name)
2432 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2434 if (saved_argc > 0) {
2438 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2440 for (i = 1; i < saved_argc; i++) {
2444 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2449 void sigset_add_many(sigset_t *ss, ...) {
2456 while ((sig = va_arg(ap, int)) > 0)
2457 assert_se(sigaddset(ss, sig) == 0);
2461 char* gethostname_malloc(void) {
2464 assert_se(uname(&u) >= 0);
2466 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2467 return strdup(u.nodename);
2469 return strdup(u.sysname);
2472 bool hostname_is_set(void) {
2475 assert_se(uname(&u) >= 0);
2477 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2480 static char *lookup_uid(uid_t uid) {
2483 _cleanup_free_ char *buf = NULL;
2484 struct passwd pwbuf, *pw = NULL;
2486 /* Shortcut things to avoid NSS lookups */
2488 return strdup("root");
2490 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2494 buf = malloc(bufsize);
2498 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2499 return strdup(pw->pw_name);
2501 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2507 char* getlogname_malloc(void) {
2511 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2516 return lookup_uid(uid);
2519 char *getusername_malloc(void) {
2526 return lookup_uid(getuid());
2529 int getttyname_malloc(int fd, char **r) {
2530 char path[PATH_MAX], *c;
2535 k = ttyname_r(fd, path, sizeof(path));
2541 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2549 int getttyname_harder(int fd, char **r) {
2553 k = getttyname_malloc(fd, &s);
2557 if (streq(s, "tty")) {
2559 return get_ctty(0, NULL, r);
2566 int get_ctty_devnr(pid_t pid, dev_t *d) {
2568 char line[LINE_MAX], *p, *fn;
2569 unsigned long ttynr;
2572 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2575 f = fopen(fn, "re");
2580 if (!fgets(line, sizeof(line), f)) {
2581 k = feof(f) ? -EIO : -errno;
2588 p = strrchr(line, ')');
2598 "%*d " /* session */
2603 if (major(ttynr) == 0 && minor(ttynr) == 0)
2610 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2612 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2617 k = get_ctty_devnr(pid, &devnr);
2621 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2623 k = readlink_malloc(fn, &s);
2629 /* This is an ugly hack */
2630 if (major(devnr) == 136) {
2631 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2641 /* Probably something like the ptys which have no
2642 * symlink in /dev/char. Let's return something
2643 * vaguely useful. */
2656 if (startswith(s, "/dev/"))
2658 else if (startswith(s, "../"))
2676 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2682 /* This returns the first error we run into, but nevertheless
2683 * tries to go on. This closes the passed fd. */
2687 close_nointr_nofail(fd);
2689 return errno == ENOENT ? 0 : -errno;
2694 union dirent_storage buf;
2695 bool is_dir, keep_around;
2699 r = readdir_r(d, &buf.de, &de);
2700 if (r != 0 && ret == 0) {
2708 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2711 if (de->d_type == DT_UNKNOWN ||
2713 (de->d_type == DT_DIR && root_dev)) {
2714 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2715 if (ret == 0 && errno != ENOENT)
2720 is_dir = S_ISDIR(st.st_mode);
2723 (st.st_uid == 0 || st.st_uid == getuid()) &&
2724 (st.st_mode & S_ISVTX);
2726 is_dir = de->d_type == DT_DIR;
2727 keep_around = false;
2733 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2734 if (root_dev && st.st_dev != root_dev->st_dev)
2737 subdir_fd = openat(fd, de->d_name,
2738 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2739 if (subdir_fd < 0) {
2740 if (ret == 0 && errno != ENOENT)
2745 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2746 if (r < 0 && ret == 0)
2750 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2751 if (ret == 0 && errno != ENOENT)
2755 } else if (!only_dirs && !keep_around) {
2757 if (unlinkat(fd, de->d_name, 0) < 0) {
2758 if (ret == 0 && errno != ENOENT)
2769 static int is_temporary_fs(struct statfs *s) {
2771 return s->f_type == TMPFS_MAGIC ||
2772 (long)s->f_type == (long)RAMFS_MAGIC;
2775 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2780 if (fstatfs(fd, &s) < 0) {
2781 close_nointr_nofail(fd);
2785 /* We refuse to clean disk file systems with this call. This
2786 * is extra paranoia just to be sure we never ever remove
2788 if (!is_temporary_fs(&s)) {
2789 log_error("Attempted to remove disk file system, and we can't allow that.");
2790 close_nointr_nofail(fd);
2794 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2797 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2803 /* We refuse to clean the root file system with this
2804 * call. This is extra paranoia to never cause a really
2805 * seriously broken system. */
2806 if (path_equal(path, "/")) {
2807 log_error("Attempted to remove entire root file system, and we can't allow that.");
2811 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2814 if (errno != ENOTDIR)
2818 if (statfs(path, &s) < 0)
2821 if (!is_temporary_fs(&s)) {
2822 log_error("Attempted to remove disk file system, and we can't allow that.");
2827 if (delete_root && !only_dirs)
2828 if (unlink(path) < 0 && errno != ENOENT)
2835 if (fstatfs(fd, &s) < 0) {
2836 close_nointr_nofail(fd);
2840 if (!is_temporary_fs(&s)) {
2841 log_error("Attempted to remove disk file system, and we can't allow that.");
2842 close_nointr_nofail(fd);
2847 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2850 if (honour_sticky && file_is_priv_sticky(path) > 0)
2853 if (rmdir(path) < 0 && errno != ENOENT) {
2862 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2863 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2866 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2867 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2870 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2873 /* Under the assumption that we are running privileged we
2874 * first change the access mode and only then hand out
2875 * ownership to avoid a window where access is too open. */
2877 if (mode != (mode_t) -1)
2878 if (chmod(path, mode) < 0)
2881 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2882 if (chown(path, uid, gid) < 0)
2888 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2891 /* Under the assumption that we are running privileged we
2892 * first change the access mode and only then hand out
2893 * ownership to avoid a window where access is too open. */
2895 if (fchmod(fd, mode) < 0)
2898 if (fchown(fd, uid, gid) < 0)
2904 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2908 /* Allocates the cpuset in the right size */
2911 if (!(r = CPU_ALLOC(n)))
2914 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2915 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2925 if (errno != EINVAL)
2932 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2933 static const char status_indent[] = " "; /* "[" STATUS "] " */
2934 _cleanup_free_ char *s = NULL;
2935 _cleanup_close_ int fd = -1;
2936 struct iovec iovec[6];
2938 static bool prev_ephemeral;
2942 /* This is independent of logging, as status messages are
2943 * optional and go exclusively to the console. */
2945 if (vasprintf(&s, format, ap) < 0)
2948 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2961 sl = status ? sizeof(status_indent)-1 : 0;
2967 e = ellipsize(s, emax, 75);
2977 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2978 prev_ephemeral = ephemeral;
2981 if (!isempty(status)) {
2982 IOVEC_SET_STRING(iovec[n++], "[");
2983 IOVEC_SET_STRING(iovec[n++], status);
2984 IOVEC_SET_STRING(iovec[n++], "] ");
2986 IOVEC_SET_STRING(iovec[n++], status_indent);
2989 IOVEC_SET_STRING(iovec[n++], s);
2991 IOVEC_SET_STRING(iovec[n++], "\n");
2993 if (writev(fd, iovec, n) < 0)
2999 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3005 va_start(ap, format);
3006 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3012 int status_welcome(void) {
3014 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3016 r = parse_env_file("/etc/os-release", NEWLINE,
3017 "PRETTY_NAME", &pretty_name,
3018 "ANSI_COLOR", &ansi_color,
3020 if (r < 0 && r != -ENOENT)
3021 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3023 return status_printf(NULL, false, false,
3024 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3025 isempty(ansi_color) ? "1" : ansi_color,
3026 isempty(pretty_name) ? "Linux" : pretty_name);
3029 char *replace_env(const char *format, char **env) {
3036 const char *e, *word = format;
3041 for (e = format; *e; e ++) {
3052 if (!(k = strnappend(r, word, e-word-1)))
3061 } else if (*e == '$') {
3062 if (!(k = strnappend(r, word, e-word)))
3078 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3080 k = strappend(r, t);
3094 if (!(k = strnappend(r, word, e-word)))
3105 char **replace_env_argv(char **argv, char **env) {
3107 unsigned k = 0, l = 0;
3109 l = strv_length(argv);
3111 if (!(r = new(char*, l+1)))
3114 STRV_FOREACH(i, argv) {
3116 /* If $FOO appears as single word, replace it by the split up variable */
3117 if ((*i)[0] == '$' && (*i)[1] != '{') {
3122 e = strv_env_get(env, *i+1);
3125 if (!(m = strv_split_quoted(e))) {
3136 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3145 memcpy(r + k, m, q * sizeof(char*));
3153 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3154 if (!(r[k++] = replace_env(*i, env))) {
3164 int fd_columns(int fd) {
3168 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3177 unsigned columns(void) {
3181 if (_likely_(cached_columns > 0))
3182 return cached_columns;
3185 e = getenv("COLUMNS");
3190 c = fd_columns(STDOUT_FILENO);
3199 int fd_lines(int fd) {
3203 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3212 unsigned lines(void) {
3216 if (_likely_(cached_lines > 0))
3217 return cached_lines;
3220 e = getenv("LINES");
3225 l = fd_lines(STDOUT_FILENO);
3231 return cached_lines;
3234 /* intended to be used as a SIGWINCH sighandler */
3235 void columns_lines_cache_reset(int signum) {
3241 static int cached_on_tty = -1;
3243 if (_unlikely_(cached_on_tty < 0))
3244 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3246 return cached_on_tty;
3249 int running_in_chroot(void) {
3255 /* Only works as root */
3257 if (stat("/proc/1/root", &a) < 0)
3260 if (stat("/", &b) < 0)
3264 a.st_dev != b.st_dev ||
3265 a.st_ino != b.st_ino;
3268 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3273 assert(percent <= 100);
3274 assert(new_length >= 3);
3276 if (old_length <= 3 || old_length <= new_length)
3277 return strndup(s, old_length);
3279 r = new0(char, new_length+1);
3283 x = (new_length * percent) / 100;
3285 if (x > new_length - 3)
3293 s + old_length - (new_length - x - 3),
3294 new_length - x - 3);
3299 char *ellipsize(const char *s, size_t length, unsigned percent) {
3300 return ellipsize_mem(s, strlen(s), length, percent);
3303 int touch(const char *path) {
3308 /* This just opens the file for writing, ensuring it
3309 * exists. It doesn't call utimensat() the way /usr/bin/touch
3312 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3316 close_nointr_nofail(fd);
3320 char *unquote(const char *s, const char* quotes) {
3324 /* This is rather stupid, simply removes the heading and
3325 * trailing quotes if there is one. Doesn't care about
3326 * escaping or anything. We should make this smarter one
3333 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3334 return strndup(s+1, l-2);
3339 char *normalize_env_assignment(const char *s) {
3340 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3343 eq = strchr(s, '=');
3355 memmove(r, t, strlen(t) + 1);
3359 name = strndup(s, eq - s);
3367 value = unquote(strstrip(p), QUOTES);
3371 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3377 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3388 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3400 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3407 r = wait_for_terminate(pid, &status);
3409 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3413 if (status.si_code == CLD_EXITED) {
3414 if (status.si_status != 0) {
3415 log_warning("%s failed with error code %i.", name, status.si_status);
3416 return status.si_status;
3419 log_debug("%s succeeded.", name);
3422 } else if (status.si_code == CLD_KILLED ||
3423 status.si_code == CLD_DUMPED) {
3425 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3429 log_warning("%s failed due to unknown reason.", name);
3433 _noreturn_ void freeze(void) {
3435 /* Make sure nobody waits for us on a socket anymore */
3436 close_all_fds(NULL, 0);
3444 bool null_or_empty(struct stat *st) {
3447 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3450 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3456 int null_or_empty_path(const char *fn) {
3461 if (stat(fn, &st) < 0)
3464 return null_or_empty(&st);
3467 DIR *xopendirat(int fd, const char *name, int flags) {
3471 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3477 close_nointr_nofail(nfd);
3484 int signal_from_string_try_harder(const char *s) {
3488 signo = signal_from_string(s);
3490 if (startswith(s, "SIG"))
3491 return signal_from_string(s+3);
3496 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3500 /* FIXME: to follow udev's logic 100% we need to leave valid
3501 * UTF8 chars unescaped */
3503 u = unquote(tagvalue, "\"\'");
3507 t = xescape(u, "/ ");
3513 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3522 char *fstab_node_to_udev_node(const char *p) {
3525 if (startswith(p, "LABEL="))
3526 return tag_to_udev_node(p+6, "label");
3528 if (startswith(p, "UUID="))
3529 return tag_to_udev_node(p+5, "uuid");
3531 if (startswith(p, "PARTUUID="))
3532 return tag_to_udev_node(p+9, "partuuid");
3534 if (startswith(p, "PARTLABEL="))
3535 return tag_to_udev_node(p+10, "partlabel");
3540 bool tty_is_vc(const char *tty) {
3543 if (startswith(tty, "/dev/"))
3546 return vtnr_from_tty(tty) >= 0;
3549 bool tty_is_console(const char *tty) {
3552 if (startswith(tty, "/dev/"))
3555 return streq(tty, "console");
3558 int vtnr_from_tty(const char *tty) {
3563 if (startswith(tty, "/dev/"))
3566 if (!startswith(tty, "tty") )
3569 if (tty[3] < '0' || tty[3] > '9')
3572 r = safe_atoi(tty+3, &i);
3576 if (i < 0 || i > 63)
3582 char *resolve_dev_console(char **active) {
3585 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3586 * (i.e. not read-only-mounted which is a sign for container setups) */
3588 if (path_is_read_only_fs("/sys") > 0)
3591 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3594 /* If multiple log outputs are configured the last one is what
3595 * /dev/console points to */
3596 tty = strrchr(*active, ' ');
3605 bool tty_is_vc_resolve(const char *tty) {
3606 char *active = NULL;
3611 if (startswith(tty, "/dev/"))
3614 if (streq(tty, "console")) {
3615 tty = resolve_dev_console(&active);
3626 const char *default_term_for_tty(const char *tty) {
3629 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3632 bool dirent_is_file(const struct dirent *de) {
3635 if (ignore_file(de->d_name))
3638 if (de->d_type != DT_REG &&
3639 de->d_type != DT_LNK &&
3640 de->d_type != DT_UNKNOWN)
3646 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3649 if (de->d_type != DT_REG &&
3650 de->d_type != DT_LNK &&
3651 de->d_type != DT_UNKNOWN)
3654 if (ignore_file_allow_backup(de->d_name))
3657 return endswith(de->d_name, suffix);
3660 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3663 Hashmap *pids = NULL;
3667 /* Executes all binaries in a directory in parallel and
3668 * waits for them to finish. */
3671 if (!(_d = opendir(directory))) {
3673 if (errno == ENOENT)
3676 log_error("Failed to enumerate directory %s: %m", directory);
3683 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3684 log_error("Failed to allocate set.");
3688 while ((de = readdir(d))) {
3693 if (!dirent_is_file(de))
3696 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3701 if ((pid = fork()) < 0) {
3702 log_error("Failed to fork: %m");
3720 log_error("Failed to execute %s: %m", path);
3721 _exit(EXIT_FAILURE);
3724 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3726 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3727 log_error("Failed to add PID to set: %s", strerror(-k));
3732 while (!hashmap_isempty(pids)) {
3733 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3738 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3743 log_error("waitid() failed: %m");
3747 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3748 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3749 if (si.si_code == CLD_EXITED)
3750 log_error("%s exited with exit status %i.", path, si.si_status);
3752 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3754 log_debug("%s exited successfully.", path);
3765 hashmap_free_free(pids);
3768 int kill_and_sigcont(pid_t pid, int sig) {
3771 r = kill(pid, sig) < 0 ? -errno : 0;
3779 bool nulstr_contains(const char*nulstr, const char *needle) {
3785 NULSTR_FOREACH(i, nulstr)
3786 if (streq(i, needle))
3792 bool plymouth_running(void) {
3793 return access("/run/plymouth/pid", F_OK) >= 0;
3796 char* strshorten(char *s, size_t l) {
3805 static bool hostname_valid_char(char c) {
3807 (c >= 'a' && c <= 'z') ||
3808 (c >= 'A' && c <= 'Z') ||
3809 (c >= '0' && c <= '9') ||
3815 bool hostname_is_valid(const char *s) {
3822 for (p = s, dot = true; *p; p++) {
3829 if (!hostname_valid_char(*p))
3839 if (p-s > HOST_NAME_MAX)
3845 char* hostname_cleanup(char *s) {
3848 for (p = s, d = s; *p; p++)
3849 if ((*p >= 'a' && *p <= 'z') ||
3850 (*p >= 'A' && *p <= 'Z') ||
3851 (*p >= '0' && *p <= '9') ||
3859 strshorten(s, HOST_NAME_MAX);
3863 int pipe_eof(int fd) {
3864 struct pollfd pollfd;
3869 pollfd.events = POLLIN|POLLHUP;
3871 r = poll(&pollfd, 1, 0);
3878 return pollfd.revents & POLLHUP;
3881 int fd_wait_for_event(int fd, int event, usec_t t) {
3882 struct pollfd pollfd;
3887 pollfd.events = event;
3889 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3896 return pollfd.revents;
3899 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3910 t = new(char, strlen(path) + 1 + 6 + 1);
3914 fn = path_get_file_name(path);
3918 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3920 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3926 f = fdopen(fd, "we");
3939 int terminal_vhangup_fd(int fd) {
3942 if (ioctl(fd, TIOCVHANGUP) < 0)
3948 int terminal_vhangup(const char *name) {
3951 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3955 r = terminal_vhangup_fd(fd);
3956 close_nointr_nofail(fd);
3961 int vt_disallocate(const char *name) {
3965 /* Deallocate the VT if possible. If not possible
3966 * (i.e. because it is the active one), at least clear it
3967 * entirely (including the scrollback buffer) */
3969 if (!startswith(name, "/dev/"))
3972 if (!tty_is_vc(name)) {
3973 /* So this is not a VT. I guess we cannot deallocate
3974 * it then. But let's at least clear the screen */
3976 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3981 "\033[r" /* clear scrolling region */
3982 "\033[H" /* move home */
3983 "\033[2J", /* clear screen */
3985 close_nointr_nofail(fd);
3990 if (!startswith(name, "/dev/tty"))
3993 r = safe_atou(name+8, &u);
4000 /* Try to deallocate */
4001 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4005 r = ioctl(fd, VT_DISALLOCATE, u);
4006 close_nointr_nofail(fd);
4014 /* Couldn't deallocate, so let's clear it fully with
4016 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4021 "\033[r" /* clear scrolling region */
4022 "\033[H" /* move home */
4023 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4025 close_nointr_nofail(fd);
4030 int copy_file(const char *from, const char *to) {
4036 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4040 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4042 close_nointr_nofail(fdf);
4050 n = read(fdf, buf, sizeof(buf));
4054 close_nointr_nofail(fdf);
4065 k = loop_write(fdt, buf, n, false);
4067 r = k < 0 ? k : (errno ? -errno : -EIO);
4069 close_nointr_nofail(fdf);
4077 close_nointr_nofail(fdf);
4078 r = close_nointr(fdt);
4088 int symlink_atomic(const char *from, const char *to) {
4090 _cleanup_free_ char *t;
4093 unsigned long long ull;
4100 t = new(char, strlen(to) + 1 + 16 + 1);
4104 fn = path_get_file_name(to);
4108 x = stpcpy(t+k+1, fn);
4111 for (i = 0; i < 16; i++) {
4112 *(x++) = hexchar(ull & 0xF);
4118 if (symlink(from, t) < 0)
4121 if (rename(t, to) < 0) {
4130 bool display_is_local(const char *display) {
4134 display[0] == ':' &&
4135 display[1] >= '0' &&
4139 int socket_from_display(const char *display, char **path) {
4146 if (!display_is_local(display))
4149 k = strspn(display+1, "0123456789");
4151 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4155 c = stpcpy(f, "/tmp/.X11-unix/X");
4156 memcpy(c, display+1, k);
4165 const char **username,
4166 uid_t *uid, gid_t *gid,
4168 const char **shell) {
4176 /* We enforce some special rules for uid=0: in order to avoid
4177 * NSS lookups for root we hardcode its data. */
4179 if (streq(*username, "root") || streq(*username, "0")) {
4197 if (parse_uid(*username, &u) >= 0) {
4201 /* If there are multiple users with the same id, make
4202 * sure to leave $USER to the configured value instead
4203 * of the first occurrence in the database. However if
4204 * the uid was configured by a numeric uid, then let's
4205 * pick the real username from /etc/passwd. */
4207 *username = p->pw_name;
4210 p = getpwnam(*username);
4214 return errno > 0 ? -errno : -ESRCH;
4226 *shell = p->pw_shell;
4231 char* uid_to_name(uid_t uid) {
4236 return strdup("root");
4240 return strdup(p->pw_name);
4242 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4248 char* gid_to_name(gid_t gid) {
4253 return strdup("root");
4257 return strdup(p->gr_name);
4259 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4265 int get_group_creds(const char **groupname, gid_t *gid) {
4271 /* We enforce some special rules for gid=0: in order to avoid
4272 * NSS lookups for root we hardcode its data. */
4274 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4275 *groupname = "root";
4283 if (parse_gid(*groupname, &id) >= 0) {
4288 *groupname = g->gr_name;
4291 g = getgrnam(*groupname);
4295 return errno > 0 ? -errno : -ESRCH;
4303 int in_gid(gid_t gid) {
4305 int ngroups_max, r, i;
4307 if (getgid() == gid)
4310 if (getegid() == gid)
4313 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4314 assert(ngroups_max > 0);
4316 gids = alloca(sizeof(gid_t) * ngroups_max);
4318 r = getgroups(ngroups_max, gids);
4322 for (i = 0; i < r; i++)
4329 int in_group(const char *name) {
4333 r = get_group_creds(&name, &gid);
4340 int glob_exists(const char *path) {
4348 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4350 if (k == GLOB_NOMATCH)
4352 else if (k == GLOB_NOSPACE)
4355 r = !strv_isempty(g.gl_pathv);
4357 r = errno ? -errno : -EIO;
4364 int dirent_ensure_type(DIR *d, struct dirent *de) {
4370 if (de->d_type != DT_UNKNOWN)
4373 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4377 S_ISREG(st.st_mode) ? DT_REG :
4378 S_ISDIR(st.st_mode) ? DT_DIR :
4379 S_ISLNK(st.st_mode) ? DT_LNK :
4380 S_ISFIFO(st.st_mode) ? DT_FIFO :
4381 S_ISSOCK(st.st_mode) ? DT_SOCK :
4382 S_ISCHR(st.st_mode) ? DT_CHR :
4383 S_ISBLK(st.st_mode) ? DT_BLK :
4389 int in_search_path(const char *path, char **search) {
4393 r = path_get_parent(path, &parent);
4399 STRV_FOREACH(i, search) {
4400 if (path_equal(parent, *i)) {
4411 int get_files_in_directory(const char *path, char ***list) {
4419 /* Returns all files in a directory in *list, and the number
4420 * of files as return value. If list is NULL returns only the
4429 union dirent_storage buf;
4432 k = readdir_r(d, &buf.de, &de);
4441 dirent_ensure_type(d, de);
4443 if (!dirent_is_file(de))
4447 if ((unsigned) r >= n) {
4451 t = realloc(l, sizeof(char*) * n);
4460 assert((unsigned) r < n);
4462 l[r] = strdup(de->d_name);
4486 char *strjoin(const char *x, ...) {
4500 t = va_arg(ap, const char *);
4505 if (n > ((size_t) -1) - l) {
4529 t = va_arg(ap, const char *);
4543 bool is_main_thread(void) {
4544 static __thread int cached = 0;
4546 if (_unlikely_(cached == 0))
4547 cached = getpid() == gettid() ? 1 : -1;
4552 int block_get_whole_disk(dev_t d, dev_t *ret) {
4559 /* If it has a queue this is good enough for us */
4560 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4563 r = access(p, F_OK);
4571 /* If it is a partition find the originating device */
4572 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4575 r = access(p, F_OK);
4581 /* Get parent dev_t */
4582 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4585 r = read_one_line_file(p, &s);
4591 r = sscanf(s, "%u:%u", &m, &n);
4597 /* Only return this if it is really good enough for us. */
4598 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4601 r = access(p, F_OK);
4605 *ret = makedev(m, n);
4612 int file_is_priv_sticky(const char *p) {
4617 if (lstat(p, &st) < 0)
4621 (st.st_uid == 0 || st.st_uid == getuid()) &&
4622 (st.st_mode & S_ISVTX);
4625 static const char *const ioprio_class_table[] = {
4626 [IOPRIO_CLASS_NONE] = "none",
4627 [IOPRIO_CLASS_RT] = "realtime",
4628 [IOPRIO_CLASS_BE] = "best-effort",
4629 [IOPRIO_CLASS_IDLE] = "idle"
4632 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4634 static const char *const sigchld_code_table[] = {
4635 [CLD_EXITED] = "exited",
4636 [CLD_KILLED] = "killed",
4637 [CLD_DUMPED] = "dumped",
4638 [CLD_TRAPPED] = "trapped",
4639 [CLD_STOPPED] = "stopped",
4640 [CLD_CONTINUED] = "continued",
4643 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4645 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4646 [LOG_FAC(LOG_KERN)] = "kern",
4647 [LOG_FAC(LOG_USER)] = "user",
4648 [LOG_FAC(LOG_MAIL)] = "mail",
4649 [LOG_FAC(LOG_DAEMON)] = "daemon",
4650 [LOG_FAC(LOG_AUTH)] = "auth",
4651 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4652 [LOG_FAC(LOG_LPR)] = "lpr",
4653 [LOG_FAC(LOG_NEWS)] = "news",
4654 [LOG_FAC(LOG_UUCP)] = "uucp",
4655 [LOG_FAC(LOG_CRON)] = "cron",
4656 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4657 [LOG_FAC(LOG_FTP)] = "ftp",
4658 [LOG_FAC(LOG_LOCAL0)] = "local0",
4659 [LOG_FAC(LOG_LOCAL1)] = "local1",
4660 [LOG_FAC(LOG_LOCAL2)] = "local2",
4661 [LOG_FAC(LOG_LOCAL3)] = "local3",
4662 [LOG_FAC(LOG_LOCAL4)] = "local4",
4663 [LOG_FAC(LOG_LOCAL5)] = "local5",
4664 [LOG_FAC(LOG_LOCAL6)] = "local6",
4665 [LOG_FAC(LOG_LOCAL7)] = "local7"
4668 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4670 static const char *const log_level_table[] = {
4671 [LOG_EMERG] = "emerg",
4672 [LOG_ALERT] = "alert",
4673 [LOG_CRIT] = "crit",
4675 [LOG_WARNING] = "warning",
4676 [LOG_NOTICE] = "notice",
4677 [LOG_INFO] = "info",
4678 [LOG_DEBUG] = "debug"
4681 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4683 static const char* const sched_policy_table[] = {
4684 [SCHED_OTHER] = "other",
4685 [SCHED_BATCH] = "batch",
4686 [SCHED_IDLE] = "idle",
4687 [SCHED_FIFO] = "fifo",
4691 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4693 static const char* const rlimit_table[] = {
4694 [RLIMIT_CPU] = "LimitCPU",
4695 [RLIMIT_FSIZE] = "LimitFSIZE",
4696 [RLIMIT_DATA] = "LimitDATA",
4697 [RLIMIT_STACK] = "LimitSTACK",
4698 [RLIMIT_CORE] = "LimitCORE",
4699 [RLIMIT_RSS] = "LimitRSS",
4700 [RLIMIT_NOFILE] = "LimitNOFILE",
4701 [RLIMIT_AS] = "LimitAS",
4702 [RLIMIT_NPROC] = "LimitNPROC",
4703 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4704 [RLIMIT_LOCKS] = "LimitLOCKS",
4705 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4706 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4707 [RLIMIT_NICE] = "LimitNICE",
4708 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4709 [RLIMIT_RTTIME] = "LimitRTTIME"
4712 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4714 static const char* const ip_tos_table[] = {
4715 [IPTOS_LOWDELAY] = "low-delay",
4716 [IPTOS_THROUGHPUT] = "throughput",
4717 [IPTOS_RELIABILITY] = "reliability",
4718 [IPTOS_LOWCOST] = "low-cost",
4721 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4723 static const char *const __signal_table[] = {
4740 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4751 [SIGVTALRM] = "VTALRM",
4753 [SIGWINCH] = "WINCH",
4759 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4761 const char *signal_to_string(int signo) {
4762 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4765 name = __signal_to_string(signo);
4769 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4770 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4772 snprintf(buf, sizeof(buf), "%d", signo);
4777 int signal_from_string(const char *s) {
4782 signo = __signal_from_string(s);
4786 if (startswith(s, "RTMIN+")) {
4790 if (safe_atou(s, &u) >= 0) {
4791 signo = (int) u + offset;
4792 if (signo > 0 && signo < _NSIG)
4798 bool kexec_loaded(void) {
4799 bool loaded = false;
4802 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4810 int strdup_or_null(const char *a, char **b) {
4828 int prot_from_flags(int flags) {
4830 switch (flags & O_ACCMODE) {
4839 return PROT_READ|PROT_WRITE;
4846 char *format_bytes(char *buf, size_t l, off_t t) {
4849 static const struct {
4853 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4854 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4855 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4856 { "G", 1024ULL*1024ULL*1024ULL },
4857 { "M", 1024ULL*1024ULL },
4861 for (i = 0; i < ELEMENTSOF(table); i++) {
4863 if (t >= table[i].factor) {
4866 (unsigned long long) (t / table[i].factor),
4867 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4874 snprintf(buf, l, "%lluB", (unsigned long long) t);
4882 void* memdup(const void *p, size_t l) {
4895 int fd_inc_sndbuf(int fd, size_t n) {
4897 socklen_t l = sizeof(value);
4899 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4901 l == sizeof(value) &&
4902 (size_t) value >= n*2)
4906 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4913 int fd_inc_rcvbuf(int fd, size_t n) {
4915 socklen_t l = sizeof(value);
4917 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4919 l == sizeof(value) &&
4920 (size_t) value >= n*2)
4924 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4931 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4932 pid_t parent_pid, agent_pid;
4934 bool stdout_is_tty, stderr_is_tty;
4942 parent_pid = getpid();
4944 /* Spawns a temporary TTY agent, making sure it goes away when
4951 if (agent_pid != 0) {
4958 * Make sure the agent goes away when the parent dies */
4959 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4960 _exit(EXIT_FAILURE);
4962 /* Check whether our parent died before we were able
4963 * to set the death signal */
4964 if (getppid() != parent_pid)
4965 _exit(EXIT_SUCCESS);
4967 /* Don't leak fds to the agent */
4968 close_all_fds(except, n_except);
4970 stdout_is_tty = isatty(STDOUT_FILENO);
4971 stderr_is_tty = isatty(STDERR_FILENO);
4973 if (!stdout_is_tty || !stderr_is_tty) {
4974 /* Detach from stdout/stderr. and reopen
4975 * /dev/tty for them. This is important to
4976 * ensure that when systemctl is started via
4977 * popen() or a similar call that expects to
4978 * read EOF we actually do generate EOF and
4979 * not delay this indefinitely by because we
4980 * keep an unused copy of stdin around. */
4981 fd = open("/dev/tty", O_WRONLY);
4983 log_error("Failed to open /dev/tty: %m");
4984 _exit(EXIT_FAILURE);
4988 dup2(fd, STDOUT_FILENO);
4991 dup2(fd, STDERR_FILENO);
4997 /* Count arguments */
4999 for (n = 0; va_arg(ap, char*); n++)
5004 l = alloca(sizeof(char *) * (n + 1));
5006 /* Fill in arguments */
5008 for (i = 0; i <= n; i++)
5009 l[i] = va_arg(ap, char*);
5013 _exit(EXIT_FAILURE);
5016 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5017 struct rlimit highest, fixed;
5021 if (setrlimit(resource, rlim) >= 0)
5027 /* So we failed to set the desired setrlimit, then let's try
5028 * to get as close as we can */
5029 assert_se(getrlimit(resource, &highest) == 0);
5031 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5032 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5034 if (setrlimit(resource, &fixed) < 0)
5040 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5041 char path[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/environ")], *value = NULL;
5053 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5055 f = fopen(path, "re");
5063 char line[LINE_MAX];
5066 for (i = 0; i < sizeof(line)-1; i++) {
5070 if (_unlikely_(c == EOF)) {
5080 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5081 value = strdup(line + l + 1);
5101 int can_sleep(const char *type) {
5105 _cleanup_free_ char *p = NULL;
5109 /* If /sys is read-only we cannot sleep */
5110 if (access("/sys/power/state", W_OK) < 0)
5113 r = read_one_line_file("/sys/power/state", &p);
5118 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5119 if (l == k && memcmp(w, type, l) == 0)
5125 int can_sleep_disk(const char *type) {
5129 _cleanup_free_ char *p = NULL;
5133 /* If /sys is read-only we cannot sleep */
5134 if (access("/sys/power/state", W_OK) < 0 ||
5135 access("/sys/power/disk", W_OK) < 0)
5138 r = read_one_line_file("/sys/power/disk", &p);
5143 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5144 if (l == k && memcmp(w, type, l) == 0)
5147 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5154 bool is_valid_documentation_url(const char *url) {
5157 if (startswith(url, "http://") && url[7])
5160 if (startswith(url, "https://") && url[8])
5163 if (startswith(url, "file:") && url[5])
5166 if (startswith(url, "info:") && url[5])
5169 if (startswith(url, "man:") && url[4])
5175 bool in_initrd(void) {
5176 static __thread int saved = -1;
5182 /* We make two checks here:
5184 * 1. the flag file /etc/initrd-release must exist
5185 * 2. the root file system must be a memory file system
5187 * The second check is extra paranoia, since misdetecting an
5188 * initrd can have bad bad consequences due the initrd
5189 * emptying when transititioning to the main systemd.
5192 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5193 statfs("/", &s) >= 0 &&
5194 is_temporary_fs(&s);
5199 void warn_melody(void) {
5200 _cleanup_close_ int fd = -1;
5202 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5206 /* Yeah, this is synchronous. Kinda sucks. But well... */
5208 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5209 usleep(125*USEC_PER_MSEC);
5211 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5212 usleep(125*USEC_PER_MSEC);
5214 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5215 usleep(125*USEC_PER_MSEC);
5217 ioctl(fd, KIOCSOUND, 0);
5220 int make_console_stdio(void) {
5223 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5225 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5227 log_error("Failed to acquire terminal: %s", strerror(-fd));
5233 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5240 int get_home_dir(char **_h) {
5248 /* Take the user specified one */
5259 /* Hardcode home directory for root to avoid NSS */
5262 h = strdup("/root");
5270 /* Check the database... */
5274 return errno ? -errno : -ESRCH;
5276 if (!path_is_absolute(p->pw_dir))
5279 h = strdup(p->pw_dir);
5287 void fclosep(FILE **f) {
5292 void pclosep(FILE **f) {
5297 void closep(int *fd) {
5299 close_nointr_nofail(*fd);
5302 void closedirp(DIR **d) {
5307 bool filename_is_safe(const char *p) {
5321 if (strlen(p) > FILENAME_MAX)
5327 bool string_is_safe(const char *p) {
5332 for (t = p; *t; t++) {
5333 if (*t > 0 && *t < ' ')
5336 if (strchr("\\\"\'", *t))
5343 bool string_has_cc(const char *p) {
5348 for (t = p; *t; t++)
5349 if (*t > 0 && *t < ' ')
5355 bool path_is_safe(const char *p) {
5360 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5363 if (strlen(p) > PATH_MAX)
5366 /* The following two checks are not really dangerous, but hey, they still are confusing */
5367 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5370 if (strstr(p, "//"))
5376 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5377 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5378 int (*compar) (const void *, const void *, void *), void *arg) {
5387 p = (void *)(((const char *) base) + (idx * size));
5388 comparison = compar(key, p, arg);
5391 else if (comparison > 0)
5399 bool is_locale_utf8(void) {
5401 static int cached_answer = -1;
5403 if (cached_answer >= 0)
5406 if (!setlocale(LC_ALL, "")) {
5407 cached_answer = true;
5411 set = nl_langinfo(CODESET);
5413 cached_answer = true;
5417 cached_answer = streq(set, "UTF-8");
5419 return (bool)cached_answer;
5422 const char *draw_special_char(DrawSpecialChar ch) {
5423 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5425 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5426 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5427 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5428 [DRAW_TREE_SPACE] = " ", /* */
5429 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5431 /* ASCII fallback */ {
5432 [DRAW_TREE_VERT] = "| ",
5433 [DRAW_TREE_BRANCH] = "|-",
5434 [DRAW_TREE_RIGHT] = "`-",
5435 [DRAW_TREE_SPACE] = " ",
5436 [DRAW_TRIANGULAR_BULLET] = "> ",
5440 return draw_table[!is_locale_utf8()][ch];
5443 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5446 size_t l, old_len, new_len;
5452 old_len = strlen(old_string);
5453 new_len = strlen(new_string);
5466 if (!startswith(f, old_string)) {
5472 nl = l - old_len + new_len;
5473 a = realloc(r, nl + 1);
5481 t = stpcpy(t, new_string);
5493 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5494 const char *i, *begin = NULL;
5499 } state = STATE_OTHER;
5501 size_t osz = 0, isz;
5507 /* Strips ANSI color and replaces TABs by 8 spaces */
5509 isz = _isz ? *_isz : strlen(*ibuf);
5511 f = open_memstream(&obuf, &osz);
5515 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5520 if (i >= *ibuf + isz) /* EOT */
5522 else if (*i == '\x1B')
5523 state = STATE_ESCAPE;
5524 else if (*i == '\t')
5531 if (i >= *ibuf + isz) { /* EOT */
5534 } else if (*i == '[') {
5535 state = STATE_BRACKET;
5540 state = STATE_OTHER;
5547 if (i >= *ibuf + isz || /* EOT */
5548 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5551 state = STATE_OTHER;
5553 } else if (*i == 'm')
5554 state = STATE_OTHER;
5576 int on_ac_power(void) {
5577 bool found_offline = false, found_online = false;
5578 _cleanup_closedir_ DIR *d = NULL;
5580 d = opendir("/sys/class/power_supply");
5586 union dirent_storage buf;
5587 _cleanup_close_ int fd = -1, device = -1;
5592 k = readdir_r(d, &buf.de, &de);
5599 if (ignore_file(de->d_name))
5602 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5604 if (errno == ENOENT || errno == ENOTDIR)
5610 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5612 if (errno == ENOENT)
5618 n = read(fd, contents, sizeof(contents));
5622 if (n != 6 || memcmp(contents, "Mains\n", 6))
5625 close_nointr_nofail(fd);
5626 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5628 if (errno == ENOENT)
5634 n = read(fd, contents, sizeof(contents));
5638 if (n != 2 || contents[1] != '\n')
5641 if (contents[0] == '1') {
5642 found_online = true;
5644 } else if (contents[0] == '0')
5645 found_offline = true;
5650 return found_online || !found_offline;
5653 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5660 if (!path_strv_canonicalize_uniq(search))
5663 STRV_FOREACH(i, search) {
5664 _cleanup_free_ char *p = NULL;
5667 p = strjoin(*i, "/", path, NULL);
5677 if (errno != ENOENT)
5684 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5685 _cleanup_strv_free_ char **copy = NULL;
5691 if (path_is_absolute(path)) {
5694 f = fopen(path, mode);
5703 copy = strv_copy((char**) search);
5707 return search_and_fopen_internal(path, mode, copy, _f);
5710 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5711 _cleanup_strv_free_ char **s = NULL;
5713 if (path_is_absolute(path)) {
5716 f = fopen(path, mode);
5725 s = strv_split_nulstr(search);
5729 return search_and_fopen_internal(path, mode, s, _f);
5732 int create_tmp_dir(char template[], char** dir_name) {
5735 mode_t _cleanup_umask_ u;
5740 d = mkdtemp(template);
5742 log_error("Can't create directory %s: %m", template);
5746 dt = strjoin(d, "/tmp", NULL);
5753 r = mkdir(dt, 0777);
5755 log_error("Can't create directory %s: %m", dt);
5759 log_debug("Created temporary directory %s", dt);
5761 r = chmod(dt, 0777 | S_ISVTX);
5763 log_error("Failed to chmod %s: %m", dt);
5767 log_debug("Set sticky bit on %s", dt);
5781 char *strextend(char **x, ...) {
5788 l = f = *x ? strlen(*x) : 0;
5795 t = va_arg(ap, const char *);
5800 if (n > ((size_t) -1) - l) {
5809 r = realloc(*x, l+1);
5819 t = va_arg(ap, const char *);
5833 char *strrep(const char *s, unsigned n) {
5841 p = r = malloc(l * n + 1);
5845 for (i = 0; i < n; i++)
5852 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5856 if (*allocated >= need)
5859 a = MAX(64u, need * 2);