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 assert(fds || n_fd <= 0);
224 for (i = 0; i < n_fd; i++)
225 close_nointr_nofail(fds[i]);
228 int parse_boolean(const char *v) {
231 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
233 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
239 int parse_pid(const char *s, pid_t* ret_pid) {
240 unsigned long ul = 0;
247 r = safe_atolu(s, &ul);
253 if ((unsigned long) pid != ul)
263 int parse_uid(const char *s, uid_t* ret_uid) {
264 unsigned long ul = 0;
271 r = safe_atolu(s, &ul);
277 if ((unsigned long) uid != ul)
284 int safe_atou(const char *s, unsigned *ret_u) {
292 l = strtoul(s, &x, 0);
294 if (!x || x == s || *x || errno)
295 return errno > 0 ? -errno : -EINVAL;
297 if ((unsigned long) (unsigned) l != l)
300 *ret_u = (unsigned) l;
304 int safe_atoi(const char *s, int *ret_i) {
312 l = strtol(s, &x, 0);
314 if (!x || x == s || *x || errno)
315 return errno > 0 ? -errno : -EINVAL;
317 if ((long) (int) l != l)
324 int safe_atollu(const char *s, long long unsigned *ret_llu) {
326 unsigned long long l;
332 l = strtoull(s, &x, 0);
334 if (!x || x == s || *x || errno)
335 return errno ? -errno : -EINVAL;
341 int safe_atolli(const char *s, long long int *ret_lli) {
349 l = strtoll(s, &x, 0);
351 if (!x || x == s || *x || errno)
352 return errno ? -errno : -EINVAL;
358 int safe_atod(const char *s, double *ret_d) {
368 if (!x || x == s || *x || errno)
369 return errno ? -errno : -EINVAL;
375 /* Split a string into words. */
376 char *split(const char *c, size_t *l, const char *separator, char **state) {
379 current = *state ? *state : (char*) c;
381 if (!*current || *c == 0)
384 current += strspn(current, separator);
385 *l = strcspn(current, separator);
388 return (char*) current;
391 /* Split a string into words, but consider strings enclosed in '' and
392 * "" as words even if they include spaces. */
393 char *split_quoted(const char *c, size_t *l, char **state) {
395 bool escaped = false;
397 current = *state ? *state : (char*) c;
399 if (!*current || *c == 0)
402 current += strspn(current, WHITESPACE);
404 if (*current == '\'') {
407 for (e = current; *e; e++) {
417 *state = *e == 0 ? e : e+1;
418 } else if (*current == '\"') {
421 for (e = current; *e; e++) {
431 *state = *e == 0 ? e : e+1;
433 for (e = current; *e; e++) {
438 else if (strchr(WHITESPACE, *e))
445 return (char*) current;
448 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
450 _cleanup_fclose_ FILE *f = NULL;
451 char fn[PATH_MAX], line[LINE_MAX], *p;
457 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
464 if (!fgets(line, sizeof(line), f)) {
465 r = feof(f) ? -EIO : -errno;
469 /* Let's skip the pid and comm fields. The latter is enclosed
470 * in () but does not escape any () in its value, so let's
471 * skip over it manually */
473 p = strrchr(line, ')');
485 if ((long unsigned) (pid_t) ppid != ppid)
488 *_ppid = (pid_t) ppid;
493 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
494 _cleanup_fclose_ FILE *f = NULL;
495 char fn[PATH_MAX], line[LINE_MAX], *p;
500 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
507 if (!fgets(line, sizeof(line), f)) {
514 /* Let's skip the pid and comm fields. The latter is enclosed
515 * in () but does not escape any () in its value, so let's
516 * skip over it manually */
518 p = strrchr(line, ')');
540 "%*d " /* priority */
542 "%*d " /* num_threads */
543 "%*d " /* itrealvalue */
544 "%llu " /* starttime */,
551 int fchmod_umask(int fd, mode_t m) {
556 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
562 char *truncate_nl(char *s) {
565 s[strcspn(s, NEWLINE)] = 0;
569 int get_process_comm(pid_t pid, char **name) {
575 r = read_one_line_file("/proc/self/comm", name);
578 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
581 r = read_one_line_file(p, name);
588 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
596 f = fopen("/proc/self/cmdline", "re");
599 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
608 if (max_length == 0) {
610 while ((c = getc(f)) != EOF) {
611 k = realloc(r, len+1);
618 r[len-1] = isprint(c) ? c : ' ';
625 r = new(char, max_length);
633 while ((c = getc(f)) != EOF) {
655 size_t n = MIN(left-1, 3U);
664 /* Kernel threads have no argv[] */
665 if (r == NULL || r[0] == 0) {
674 h = get_process_comm(pid, &t);
678 r = strjoin("[", t, "]", NULL);
689 int is_kernel_thread(pid_t pid) {
699 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
708 count = fread(&c, 1, 1, f);
712 /* Kernel threads have an empty cmdline */
715 return eof ? 1 : -errno;
720 int get_process_exe(pid_t pid, char **name) {
726 r = readlink_malloc("/proc/self/exe", name);
729 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
732 r = readlink_malloc(p, name);
739 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
740 _cleanup_fclose_ FILE *f = NULL;
741 _cleanup_free_ char *p = NULL;
750 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
757 FOREACH_LINE(line, f, return -errno) {
762 if (startswith(l, field)) {
764 l += strspn(l, WHITESPACE);
766 l[strcspn(l, WHITESPACE)] = 0;
768 return parse_uid(l, uid);
775 int get_process_uid(pid_t pid, uid_t *uid) {
776 return get_process_id(pid, "Uid:", uid);
779 int get_process_gid(pid_t pid, gid_t *gid) {
780 return get_process_id(pid, "Gid:", gid);
783 char *strnappend(const char *s, const char *suffix, size_t b) {
791 return strndup(suffix, b);
800 if (b > ((size_t) -1) - a)
803 r = new(char, a+b+1);
808 memcpy(r+a, suffix, b);
814 char *strappend(const char *s, const char *suffix) {
815 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
818 int readlink_malloc(const char *p, char **r) {
828 if (!(c = new(char, l)))
831 if ((n = readlink(p, c, l-1)) < 0) {
837 if ((size_t) n < l-1) {
848 int readlink_and_make_absolute(const char *p, char **r) {
855 if ((j = readlink_malloc(p, &target)) < 0)
858 k = file_in_same_dir(p, target);
868 int readlink_and_canonicalize(const char *p, char **r) {
875 j = readlink_and_make_absolute(p, &t);
879 s = canonicalize_file_name(t);
886 path_kill_slashes(*r);
891 int reset_all_signal_handlers(void) {
894 for (sig = 1; sig < _NSIG; sig++) {
897 if (sig == SIGKILL || sig == SIGSTOP)
901 sa.sa_handler = SIG_DFL;
902 sa.sa_flags = SA_RESTART;
904 /* On Linux the first two RT signals are reserved by
905 * glibc, and sigaction() will return EINVAL for them. */
906 if ((sigaction(sig, &sa, NULL) < 0))
914 char *strstrip(char *s) {
917 /* Drops trailing whitespace. Modifies the string in
918 * place. Returns pointer to first non-space character */
920 s += strspn(s, WHITESPACE);
922 for (e = strchr(s, 0); e > s; e --)
923 if (!strchr(WHITESPACE, e[-1]))
931 char *delete_chars(char *s, const char *bad) {
934 /* Drops all whitespace, regardless where in the string */
936 for (f = s, t = s; *f; f++) {
948 bool in_charset(const char *s, const char* charset) {
955 if (!strchr(charset, *i))
961 char *file_in_same_dir(const char *path, const char *filename) {
968 /* This removes the last component of path and appends
969 * filename, unless the latter is absolute anyway or the
972 if (path_is_absolute(filename))
973 return strdup(filename);
975 if (!(e = strrchr(path, '/')))
976 return strdup(filename);
978 k = strlen(filename);
979 if (!(r = new(char, e-path+1+k+1)))
982 memcpy(r, path, e-path+1);
983 memcpy(r+(e-path)+1, filename, k+1);
988 int rmdir_parents(const char *path, const char *stop) {
997 /* Skip trailing slashes */
998 while (l > 0 && path[l-1] == '/')
1004 /* Skip last component */
1005 while (l > 0 && path[l-1] != '/')
1008 /* Skip trailing slashes */
1009 while (l > 0 && path[l-1] == '/')
1015 if (!(t = strndup(path, l)))
1018 if (path_startswith(stop, t)) {
1027 if (errno != ENOENT)
1034 char hexchar(int x) {
1035 static const char table[16] = "0123456789abcdef";
1037 return table[x & 15];
1040 int unhexchar(char c) {
1042 if (c >= '0' && c <= '9')
1045 if (c >= 'a' && c <= 'f')
1046 return c - 'a' + 10;
1048 if (c >= 'A' && c <= 'F')
1049 return c - 'A' + 10;
1054 char *hexmem(const void *p, size_t l) {
1058 z = r = malloc(l * 2 + 1);
1062 for (x = p; x < (const uint8_t*) p + l; x++) {
1063 *(z++) = hexchar(*x >> 4);
1064 *(z++) = hexchar(*x & 15);
1071 char octchar(int x) {
1072 return '0' + (x & 7);
1075 int unoctchar(char c) {
1077 if (c >= '0' && c <= '7')
1083 char decchar(int x) {
1084 return '0' + (x % 10);
1087 int undecchar(char c) {
1089 if (c >= '0' && c <= '9')
1095 char *cescape(const char *s) {
1101 /* Does C style string escaping. */
1103 r = new(char, strlen(s)*4 + 1);
1107 for (f = s, t = r; *f; f++)
1153 /* For special chars we prefer octal over
1154 * hexadecimal encoding, simply because glib's
1155 * g_strescape() does the same */
1156 if ((*f < ' ') || (*f >= 127)) {
1158 *(t++) = octchar((unsigned char) *f >> 6);
1159 *(t++) = octchar((unsigned char) *f >> 3);
1160 *(t++) = octchar((unsigned char) *f);
1171 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1178 /* Undoes C style string escaping, and optionally prefixes it. */
1180 pl = prefix ? strlen(prefix) : 0;
1182 r = new(char, pl+length+1);
1187 memcpy(r, prefix, pl);
1189 for (f = s, t = r + pl; f < s + length; f++) {
1232 /* This is an extension of the XDG syntax files */
1237 /* hexadecimal encoding */
1240 a = unhexchar(f[1]);
1241 b = unhexchar(f[2]);
1243 if (a < 0 || b < 0) {
1244 /* Invalid escape code, let's take it literal then */
1248 *(t++) = (char) ((a << 4) | b);
1263 /* octal encoding */
1266 a = unoctchar(f[0]);
1267 b = unoctchar(f[1]);
1268 c = unoctchar(f[2]);
1270 if (a < 0 || b < 0 || c < 0) {
1271 /* Invalid escape code, let's take it literal then */
1275 *(t++) = (char) ((a << 6) | (b << 3) | c);
1283 /* premature end of string.*/
1288 /* Invalid escape code, let's take it literal then */
1300 char *cunescape_length(const char *s, size_t length) {
1301 return cunescape_length_with_prefix(s, length, NULL);
1304 char *cunescape(const char *s) {
1307 return cunescape_length(s, strlen(s));
1310 char *xescape(const char *s, const char *bad) {
1314 /* Escapes all chars in bad, in addition to \ and all special
1315 * chars, in \xFF style escaping. May be reversed with
1318 r = new(char, strlen(s) * 4 + 1);
1322 for (f = s, t = r; *f; f++) {
1324 if ((*f < ' ') || (*f >= 127) ||
1325 (*f == '\\') || strchr(bad, *f)) {
1328 *(t++) = hexchar(*f >> 4);
1329 *(t++) = hexchar(*f);
1339 char *bus_path_escape(const char *s) {
1345 /* Escapes all chars that D-Bus' object path cannot deal
1346 * with. Can be reverse with bus_path_unescape(). We special
1347 * case the empty string. */
1352 r = new(char, strlen(s)*3 + 1);
1356 for (f = s, t = r; *f; f++) {
1358 /* Escape everything that is not a-zA-Z0-9. We also
1359 * escape 0-9 if it's the first character */
1361 if (!(*f >= 'A' && *f <= 'Z') &&
1362 !(*f >= 'a' && *f <= 'z') &&
1363 !(f > s && *f >= '0' && *f <= '9')) {
1365 *(t++) = hexchar(*f >> 4);
1366 *(t++) = hexchar(*f);
1376 char *bus_path_unescape(const char *f) {
1381 /* Special case for the empty string */
1385 r = new(char, strlen(f) + 1);
1389 for (t = r; *f; f++) {
1394 if ((a = unhexchar(f[1])) < 0 ||
1395 (b = unhexchar(f[2])) < 0) {
1396 /* Invalid escape code, let's take it literal then */
1399 *(t++) = (char) ((a << 4) | b);
1411 char *ascii_strlower(char *t) {
1416 for (p = t; *p; p++)
1417 if (*p >= 'A' && *p <= 'Z')
1418 *p = *p - 'A' + 'a';
1423 static bool ignore_file_allow_backup(const char *filename) {
1427 filename[0] == '.' ||
1428 streq(filename, "lost+found") ||
1429 streq(filename, "aquota.user") ||
1430 streq(filename, "aquota.group") ||
1431 endswith(filename, ".rpmnew") ||
1432 endswith(filename, ".rpmsave") ||
1433 endswith(filename, ".rpmorig") ||
1434 endswith(filename, ".dpkg-old") ||
1435 endswith(filename, ".dpkg-new") ||
1436 endswith(filename, ".swp");
1439 bool ignore_file(const char *filename) {
1442 if (endswith(filename, "~"))
1445 return ignore_file_allow_backup(filename);
1448 int fd_nonblock(int fd, bool nonblock) {
1453 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1457 flags |= O_NONBLOCK;
1459 flags &= ~O_NONBLOCK;
1461 if (fcntl(fd, F_SETFL, flags) < 0)
1467 int fd_cloexec(int fd, bool cloexec) {
1472 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1476 flags |= FD_CLOEXEC;
1478 flags &= ~FD_CLOEXEC;
1480 if (fcntl(fd, F_SETFD, flags) < 0)
1486 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1489 assert(n_fdset == 0 || fdset);
1491 for (i = 0; i < n_fdset; i++)
1498 int close_all_fds(const int except[], unsigned n_except) {
1503 assert(n_except == 0 || except);
1505 d = opendir("/proc/self/fd");
1510 /* When /proc isn't available (for example in chroots)
1511 * the fallback is brute forcing through the fd
1514 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1515 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1517 if (fd_in_set(fd, except, n_except))
1520 if (close_nointr(fd) < 0)
1521 if (errno != EBADF && r == 0)
1528 while ((de = readdir(d))) {
1531 if (ignore_file(de->d_name))
1534 if (safe_atoi(de->d_name, &fd) < 0)
1535 /* Let's better ignore this, just in case */
1544 if (fd_in_set(fd, except, n_except))
1547 if (close_nointr(fd) < 0) {
1548 /* Valgrind has its own FD and doesn't want to have it closed */
1549 if (errno != EBADF && r == 0)
1558 bool chars_intersect(const char *a, const char *b) {
1561 /* Returns true if any of the chars in a are in b. */
1562 for (p = a; *p; p++)
1569 bool fstype_is_network(const char *fstype) {
1570 static const char table[] =
1579 return nulstr_contains(table, fstype);
1583 _cleanup_close_ int fd;
1585 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1591 TIOCL_GETKMSGREDIRECT,
1595 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1598 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1601 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1607 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1608 struct termios old_termios, new_termios;
1610 char line[LINE_MAX];
1615 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1616 new_termios = old_termios;
1618 new_termios.c_lflag &= ~ICANON;
1619 new_termios.c_cc[VMIN] = 1;
1620 new_termios.c_cc[VTIME] = 0;
1622 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1625 if (t != (usec_t) -1) {
1626 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1627 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1632 k = fread(&c, 1, 1, f);
1634 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1640 *need_nl = c != '\n';
1647 if (t != (usec_t) -1)
1648 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1651 if (!fgets(line, sizeof(line), f))
1656 if (strlen(line) != 1)
1666 int ask(char *ret, const char *replies, const char *text, ...) {
1676 bool need_nl = true;
1679 fputs(ANSI_HIGHLIGHT_ON, stdout);
1686 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1690 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1693 if (r == -EBADMSG) {
1694 puts("Bad input, please try again.");
1705 if (strchr(replies, c)) {
1710 puts("Read unexpected character, please try again.");
1714 int reset_terminal_fd(int fd, bool switch_to_text) {
1715 struct termios termios;
1718 /* Set terminal to some sane defaults */
1722 /* We leave locked terminal attributes untouched, so that
1723 * Plymouth may set whatever it wants to set, and we don't
1724 * interfere with that. */
1726 /* Disable exclusive mode, just in case */
1727 ioctl(fd, TIOCNXCL);
1729 /* Switch to text mode */
1731 ioctl(fd, KDSETMODE, KD_TEXT);
1733 /* Enable console unicode mode */
1734 ioctl(fd, KDSKBMODE, K_UNICODE);
1736 if (tcgetattr(fd, &termios) < 0) {
1741 /* We only reset the stuff that matters to the software. How
1742 * hardware is set up we don't touch assuming that somebody
1743 * else will do that for us */
1745 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1746 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1747 termios.c_oflag |= ONLCR;
1748 termios.c_cflag |= CREAD;
1749 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1751 termios.c_cc[VINTR] = 03; /* ^C */
1752 termios.c_cc[VQUIT] = 034; /* ^\ */
1753 termios.c_cc[VERASE] = 0177;
1754 termios.c_cc[VKILL] = 025; /* ^X */
1755 termios.c_cc[VEOF] = 04; /* ^D */
1756 termios.c_cc[VSTART] = 021; /* ^Q */
1757 termios.c_cc[VSTOP] = 023; /* ^S */
1758 termios.c_cc[VSUSP] = 032; /* ^Z */
1759 termios.c_cc[VLNEXT] = 026; /* ^V */
1760 termios.c_cc[VWERASE] = 027; /* ^W */
1761 termios.c_cc[VREPRINT] = 022; /* ^R */
1762 termios.c_cc[VEOL] = 0;
1763 termios.c_cc[VEOL2] = 0;
1765 termios.c_cc[VTIME] = 0;
1766 termios.c_cc[VMIN] = 1;
1768 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1772 /* Just in case, flush all crap out */
1773 tcflush(fd, TCIOFLUSH);
1778 int reset_terminal(const char *name) {
1781 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1785 r = reset_terminal_fd(fd, true);
1786 close_nointr_nofail(fd);
1791 int open_terminal(const char *name, int mode) {
1796 * If a TTY is in the process of being closed opening it might
1797 * cause EIO. This is horribly awful, but unlikely to be
1798 * changed in the kernel. Hence we work around this problem by
1799 * retrying a couple of times.
1801 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1805 fd = open(name, mode);
1812 /* Max 1s in total */
1816 usleep(50 * USEC_PER_MSEC);
1825 close_nointr_nofail(fd);
1830 close_nointr_nofail(fd);
1837 int flush_fd(int fd) {
1838 struct pollfd pollfd;
1842 pollfd.events = POLLIN;
1849 if ((r = poll(&pollfd, 1, 0)) < 0) {
1860 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1865 if (errno == EAGAIN)
1876 int acquire_terminal(
1880 bool ignore_tiocstty_eperm,
1883 int fd = -1, notify = -1, r = 0, wd = -1;
1885 struct sigaction sa_old, sa_new;
1889 /* We use inotify to be notified when the tty is closed. We
1890 * create the watch before checking if we can actually acquire
1891 * it, so that we don't lose any event.
1893 * Note: strictly speaking this actually watches for the
1894 * device being closed, it does *not* really watch whether a
1895 * tty loses its controlling process. However, unless some
1896 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1897 * its tty otherwise this will not become a problem. As long
1898 * as the administrator makes sure not configure any service
1899 * on the same tty as an untrusted user this should not be a
1900 * problem. (Which he probably should not do anyway.) */
1902 if (timeout != (usec_t) -1)
1903 ts = now(CLOCK_MONOTONIC);
1905 if (!fail && !force) {
1906 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1912 wd = inotify_add_watch(notify, name, IN_CLOSE);
1921 r = flush_fd(notify);
1926 /* We pass here O_NOCTTY only so that we can check the return
1927 * value TIOCSCTTY and have a reliable way to figure out if we
1928 * successfully became the controlling process of the tty */
1929 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1933 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1934 * if we already own the tty. */
1936 sa_new.sa_handler = SIG_IGN;
1937 sa_new.sa_flags = SA_RESTART;
1938 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1940 /* First, try to get the tty */
1941 if (ioctl(fd, TIOCSCTTY, force) < 0)
1944 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1946 /* Sometimes it makes sense to ignore TIOCSCTTY
1947 * returning EPERM, i.e. when very likely we already
1948 * are have this controlling terminal. */
1949 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1952 if (r < 0 && (force || fail || r != -EPERM)) {
1961 assert(notify >= 0);
1964 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1966 struct inotify_event *e;
1968 if (timeout != (usec_t) -1) {
1971 n = now(CLOCK_MONOTONIC);
1972 if (ts + timeout < n) {
1977 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1987 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1990 if (errno == EINTR || errno == EAGAIN)
1997 e = (struct inotify_event*) inotify_buffer;
2002 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2007 step = sizeof(struct inotify_event) + e->len;
2008 assert(step <= (size_t) l);
2010 e = (struct inotify_event*) ((uint8_t*) e + step);
2017 /* We close the tty fd here since if the old session
2018 * ended our handle will be dead. It's important that
2019 * we do this after sleeping, so that we don't enter
2020 * an endless loop. */
2021 close_nointr_nofail(fd);
2025 close_nointr_nofail(notify);
2027 r = reset_terminal_fd(fd, true);
2029 log_warning("Failed to reset terminal: %s", strerror(-r));
2035 close_nointr_nofail(fd);
2038 close_nointr_nofail(notify);
2043 int release_terminal(void) {
2045 struct sigaction sa_old, sa_new;
2047 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2050 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2051 * by our own TIOCNOTTY */
2054 sa_new.sa_handler = SIG_IGN;
2055 sa_new.sa_flags = SA_RESTART;
2056 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2058 if (ioctl(fd, TIOCNOTTY) < 0)
2061 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2063 close_nointr_nofail(fd);
2067 int sigaction_many(const struct sigaction *sa, ...) {
2072 while ((sig = va_arg(ap, int)) > 0)
2073 if (sigaction(sig, sa, NULL) < 0)
2080 int ignore_signals(int sig, ...) {
2081 struct sigaction sa;
2086 sa.sa_handler = SIG_IGN;
2087 sa.sa_flags = SA_RESTART;
2089 if (sigaction(sig, &sa, NULL) < 0)
2093 while ((sig = va_arg(ap, int)) > 0)
2094 if (sigaction(sig, &sa, NULL) < 0)
2101 int default_signals(int sig, ...) {
2102 struct sigaction sa;
2107 sa.sa_handler = SIG_DFL;
2108 sa.sa_flags = SA_RESTART;
2110 if (sigaction(sig, &sa, NULL) < 0)
2114 while ((sig = va_arg(ap, int)) > 0)
2115 if (sigaction(sig, &sa, NULL) < 0)
2122 int close_pipe(int p[]) {
2128 a = close_nointr(p[0]);
2133 b = close_nointr(p[1]);
2137 return a < 0 ? a : b;
2140 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2149 while (nbytes > 0) {
2152 if ((k = read(fd, p, nbytes)) <= 0) {
2154 if (k < 0 && errno == EINTR)
2157 if (k < 0 && errno == EAGAIN && do_poll) {
2158 struct pollfd pollfd;
2162 pollfd.events = POLLIN;
2164 if (poll(&pollfd, 1, -1) < 0) {
2168 return n > 0 ? n : -errno;
2171 if (pollfd.revents != POLLIN)
2172 return n > 0 ? n : -EIO;
2177 return n > 0 ? n : (k < 0 ? -errno : 0);
2188 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2197 while (nbytes > 0) {
2200 k = write(fd, p, nbytes);
2203 if (k < 0 && errno == EINTR)
2206 if (k < 0 && errno == EAGAIN && do_poll) {
2207 struct pollfd pollfd;
2211 pollfd.events = POLLOUT;
2213 if (poll(&pollfd, 1, -1) < 0) {
2217 return n > 0 ? n : -errno;
2220 if (pollfd.revents != POLLOUT)
2221 return n > 0 ? n : -EIO;
2226 return n > 0 ? n : (k < 0 ? -errno : 0);
2237 int parse_bytes(const char *t, off_t *bytes) {
2238 static const struct {
2244 { "M", 1024ULL*1024ULL },
2245 { "G", 1024ULL*1024ULL*1024ULL },
2246 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2247 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2248 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2265 l = strtoll(p, &e, 10);
2276 e += strspn(e, WHITESPACE);
2278 for (i = 0; i < ELEMENTSOF(table); i++)
2279 if (startswith(e, table[i].suffix)) {
2280 r += (off_t) l * table[i].factor;
2281 p = e + strlen(table[i].suffix);
2285 if (i >= ELEMENTSOF(table))
2295 int make_stdio(int fd) {
2300 r = dup3(fd, STDIN_FILENO, 0);
2301 s = dup3(fd, STDOUT_FILENO, 0);
2302 t = dup3(fd, STDERR_FILENO, 0);
2305 close_nointr_nofail(fd);
2307 if (r < 0 || s < 0 || t < 0)
2310 /* We rely here that the new fd has O_CLOEXEC not set */
2315 int make_null_stdio(void) {
2318 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2322 return make_stdio(null_fd);
2325 bool is_device_path(const char *path) {
2327 /* Returns true on paths that refer to a device, either in
2328 * sysfs or in /dev */
2331 path_startswith(path, "/dev/") ||
2332 path_startswith(path, "/sys/");
2335 int dir_is_empty(const char *path) {
2336 _cleanup_closedir_ DIR *d;
2345 union dirent_storage buf;
2347 r = readdir_r(d, &buf.de, &de);
2354 if (!ignore_file(de->d_name))
2359 unsigned long long random_ull(void) {
2360 _cleanup_close_ int fd;
2364 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2368 r = loop_read(fd, &ull, sizeof(ull), true);
2369 if (r != sizeof(ull))
2375 return random() * RAND_MAX + random();
2378 void rename_process(const char name[8]) {
2381 /* This is a like a poor man's setproctitle(). It changes the
2382 * comm field, argv[0], and also the glibc's internally used
2383 * name of the process. For the first one a limit of 16 chars
2384 * applies, to the second one usually one of 10 (i.e. length
2385 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2386 * "systemd"). If you pass a longer string it will be
2389 prctl(PR_SET_NAME, name);
2391 if (program_invocation_name)
2392 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2394 if (saved_argc > 0) {
2398 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2400 for (i = 1; i < saved_argc; i++) {
2404 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2409 void sigset_add_many(sigset_t *ss, ...) {
2416 while ((sig = va_arg(ap, int)) > 0)
2417 assert_se(sigaddset(ss, sig) == 0);
2421 char* gethostname_malloc(void) {
2424 assert_se(uname(&u) >= 0);
2426 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2427 return strdup(u.nodename);
2429 return strdup(u.sysname);
2432 bool hostname_is_set(void) {
2435 assert_se(uname(&u) >= 0);
2437 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2440 static char *lookup_uid(uid_t uid) {
2443 _cleanup_free_ char *buf = NULL;
2444 struct passwd pwbuf, *pw = NULL;
2446 /* Shortcut things to avoid NSS lookups */
2448 return strdup("root");
2450 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2454 buf = malloc(bufsize);
2458 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2459 return strdup(pw->pw_name);
2461 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2467 char* getlogname_malloc(void) {
2471 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2476 return lookup_uid(uid);
2479 char *getusername_malloc(void) {
2486 return lookup_uid(getuid());
2489 int getttyname_malloc(int fd, char **r) {
2490 char path[PATH_MAX], *c;
2495 k = ttyname_r(fd, path, sizeof(path));
2501 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2509 int getttyname_harder(int fd, char **r) {
2513 k = getttyname_malloc(fd, &s);
2517 if (streq(s, "tty")) {
2519 return get_ctty(0, NULL, r);
2526 int get_ctty_devnr(pid_t pid, dev_t *d) {
2528 char line[LINE_MAX], *p, *fn;
2529 unsigned long ttynr;
2532 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2535 f = fopen(fn, "re");
2540 if (!fgets(line, sizeof(line), f)) {
2541 k = feof(f) ? -EIO : -errno;
2548 p = strrchr(line, ')');
2558 "%*d " /* session */
2563 if (major(ttynr) == 0 && minor(ttynr) == 0)
2570 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2572 char fn[PATH_MAX], *s, *b, *p;
2577 k = get_ctty_devnr(pid, &devnr);
2581 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2584 k = readlink_malloc(fn, &s);
2590 /* This is an ugly hack */
2591 if (major(devnr) == 136) {
2592 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2602 /* Probably something like the ptys which have no
2603 * symlink in /dev/char. Let's return something
2604 * vaguely useful. */
2617 if (startswith(s, "/dev/"))
2619 else if (startswith(s, "../"))
2637 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2643 /* This returns the first error we run into, but nevertheless
2644 * tries to go on. This closes the passed fd. */
2648 close_nointr_nofail(fd);
2650 return errno == ENOENT ? 0 : -errno;
2655 union dirent_storage buf;
2656 bool is_dir, keep_around;
2660 r = readdir_r(d, &buf.de, &de);
2661 if (r != 0 && ret == 0) {
2669 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2672 if (de->d_type == DT_UNKNOWN ||
2674 (de->d_type == DT_DIR && root_dev)) {
2675 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2676 if (ret == 0 && errno != ENOENT)
2681 is_dir = S_ISDIR(st.st_mode);
2684 (st.st_uid == 0 || st.st_uid == getuid()) &&
2685 (st.st_mode & S_ISVTX);
2687 is_dir = de->d_type == DT_DIR;
2688 keep_around = false;
2694 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2695 if (root_dev && st.st_dev != root_dev->st_dev)
2698 subdir_fd = openat(fd, de->d_name,
2699 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2700 if (subdir_fd < 0) {
2701 if (ret == 0 && errno != ENOENT)
2706 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2707 if (r < 0 && ret == 0)
2711 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2712 if (ret == 0 && errno != ENOENT)
2716 } else if (!only_dirs && !keep_around) {
2718 if (unlinkat(fd, de->d_name, 0) < 0) {
2719 if (ret == 0 && errno != ENOENT)
2730 static int is_temporary_fs(struct statfs *s) {
2732 return s->f_type == TMPFS_MAGIC ||
2733 (long)s->f_type == (long)RAMFS_MAGIC;
2736 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2741 if (fstatfs(fd, &s) < 0) {
2742 close_nointr_nofail(fd);
2746 /* We refuse to clean disk file systems with this call. This
2747 * is extra paranoia just to be sure we never ever remove
2749 if (!is_temporary_fs(&s)) {
2750 log_error("Attempted to remove disk file system, and we can't allow that.");
2751 close_nointr_nofail(fd);
2755 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2758 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2764 /* We refuse to clean the root file system with this
2765 * call. This is extra paranoia to never cause a really
2766 * seriously broken system. */
2767 if (path_equal(path, "/")) {
2768 log_error("Attempted to remove entire root file system, and we can't allow that.");
2772 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2775 if (errno != ENOTDIR)
2779 if (statfs(path, &s) < 0)
2782 if (!is_temporary_fs(&s)) {
2783 log_error("Attempted to remove disk file system, and we can't allow that.");
2788 if (delete_root && !only_dirs)
2789 if (unlink(path) < 0 && errno != ENOENT)
2796 if (fstatfs(fd, &s) < 0) {
2797 close_nointr_nofail(fd);
2801 if (!is_temporary_fs(&s)) {
2802 log_error("Attempted to remove disk file system, and we can't allow that.");
2803 close_nointr_nofail(fd);
2808 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2811 if (honour_sticky && file_is_priv_sticky(path) > 0)
2814 if (rmdir(path) < 0 && errno != ENOENT) {
2823 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2824 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2827 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2828 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2831 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2834 /* Under the assumption that we are running privileged we
2835 * first change the access mode and only then hand out
2836 * ownership to avoid a window where access is too open. */
2838 if (mode != (mode_t) -1)
2839 if (chmod(path, mode) < 0)
2842 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2843 if (chown(path, uid, gid) < 0)
2849 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2852 /* Under the assumption that we are running privileged we
2853 * first change the access mode and only then hand out
2854 * ownership to avoid a window where access is too open. */
2856 if (fchmod(fd, mode) < 0)
2859 if (fchown(fd, uid, gid) < 0)
2865 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2869 /* Allocates the cpuset in the right size */
2872 if (!(r = CPU_ALLOC(n)))
2875 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2876 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2886 if (errno != EINVAL)
2893 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2894 static const char status_indent[] = " "; /* "[" STATUS "] " */
2895 _cleanup_free_ char *s = NULL;
2896 _cleanup_close_ int fd = -1;
2897 struct iovec iovec[6];
2899 static bool prev_ephemeral;
2903 /* This is independent of logging, as status messages are
2904 * optional and go exclusively to the console. */
2906 if (vasprintf(&s, format, ap) < 0)
2909 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2922 sl = status ? sizeof(status_indent)-1 : 0;
2928 e = ellipsize(s, emax, 75);
2938 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2939 prev_ephemeral = ephemeral;
2942 if (!isempty(status)) {
2943 IOVEC_SET_STRING(iovec[n++], "[");
2944 IOVEC_SET_STRING(iovec[n++], status);
2945 IOVEC_SET_STRING(iovec[n++], "] ");
2947 IOVEC_SET_STRING(iovec[n++], status_indent);
2950 IOVEC_SET_STRING(iovec[n++], s);
2952 IOVEC_SET_STRING(iovec[n++], "\n");
2954 if (writev(fd, iovec, n) < 0)
2960 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2966 va_start(ap, format);
2967 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2973 int status_welcome(void) {
2975 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2977 r = parse_env_file("/etc/os-release", NEWLINE,
2978 "PRETTY_NAME", &pretty_name,
2979 "ANSI_COLOR", &ansi_color,
2981 if (r < 0 && r != -ENOENT)
2982 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2984 return status_printf(NULL, false, false,
2985 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2986 isempty(ansi_color) ? "1" : ansi_color,
2987 isempty(pretty_name) ? "Linux" : pretty_name);
2990 char *replace_env(const char *format, char **env) {
2997 const char *e, *word = format;
3002 for (e = format; *e; e ++) {
3013 if (!(k = strnappend(r, word, e-word-1)))
3022 } else if (*e == '$') {
3023 if (!(k = strnappend(r, word, e-word)))
3039 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3041 k = strappend(r, t);
3055 if (!(k = strnappend(r, word, e-word)))
3066 char **replace_env_argv(char **argv, char **env) {
3068 unsigned k = 0, l = 0;
3070 l = strv_length(argv);
3072 if (!(r = new(char*, l+1)))
3075 STRV_FOREACH(i, argv) {
3077 /* If $FOO appears as single word, replace it by the split up variable */
3078 if ((*i)[0] == '$' && (*i)[1] != '{') {
3083 e = strv_env_get(env, *i+1);
3086 if (!(m = strv_split_quoted(e))) {
3097 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3106 memcpy(r + k, m, q * sizeof(char*));
3114 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3115 if (!(r[k++] = replace_env(*i, env))) {
3125 int fd_columns(int fd) {
3129 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3138 unsigned columns(void) {
3142 if (_likely_(cached_columns > 0))
3143 return cached_columns;
3146 e = getenv("COLUMNS");
3151 c = fd_columns(STDOUT_FILENO);
3160 int fd_lines(int fd) {
3164 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3173 unsigned lines(void) {
3177 if (_likely_(cached_lines > 0))
3178 return cached_lines;
3181 e = getenv("LINES");
3186 l = fd_lines(STDOUT_FILENO);
3192 return cached_lines;
3195 /* intended to be used as a SIGWINCH sighandler */
3196 void columns_lines_cache_reset(int signum) {
3202 static int cached_on_tty = -1;
3204 if (_unlikely_(cached_on_tty < 0))
3205 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3207 return cached_on_tty;
3210 int running_in_chroot(void) {
3216 /* Only works as root */
3218 if (stat("/proc/1/root", &a) < 0)
3221 if (stat("/", &b) < 0)
3225 a.st_dev != b.st_dev ||
3226 a.st_ino != b.st_ino;
3229 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3234 assert(percent <= 100);
3235 assert(new_length >= 3);
3237 if (old_length <= 3 || old_length <= new_length)
3238 return strndup(s, old_length);
3240 r = new0(char, new_length+1);
3244 x = (new_length * percent) / 100;
3246 if (x > new_length - 3)
3254 s + old_length - (new_length - x - 3),
3255 new_length - x - 3);
3260 char *ellipsize(const char *s, size_t length, unsigned percent) {
3261 return ellipsize_mem(s, strlen(s), length, percent);
3264 int touch(const char *path) {
3269 /* This just opens the file for writing, ensuring it
3270 * exists. It doesn't call utimensat() the way /usr/bin/touch
3273 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3277 close_nointr_nofail(fd);
3281 char *unquote(const char *s, const char* quotes) {
3285 /* This is rather stupid, simply removes the heading and
3286 * trailing quotes if there is one. Doesn't care about
3287 * escaping or anything. We should make this smarter one
3294 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3295 return strndup(s+1, l-2);
3300 char *normalize_env_assignment(const char *s) {
3301 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3304 eq = strchr(s, '=');
3316 memmove(r, t, strlen(t) + 1);
3320 name = strndup(s, eq - s);
3328 value = unquote(strstrip(p), QUOTES);
3332 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3338 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3349 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3361 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3368 r = wait_for_terminate(pid, &status);
3370 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3374 if (status.si_code == CLD_EXITED) {
3375 if (status.si_status != 0) {
3376 log_warning("%s failed with error code %i.", name, status.si_status);
3377 return status.si_status;
3380 log_debug("%s succeeded.", name);
3383 } else if (status.si_code == CLD_KILLED ||
3384 status.si_code == CLD_DUMPED) {
3386 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3390 log_warning("%s failed due to unknown reason.", name);
3394 _noreturn_ void freeze(void) {
3396 /* Make sure nobody waits for us on a socket anymore */
3397 close_all_fds(NULL, 0);
3405 bool null_or_empty(struct stat *st) {
3408 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3411 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3417 int null_or_empty_path(const char *fn) {
3422 if (stat(fn, &st) < 0)
3425 return null_or_empty(&st);
3428 DIR *xopendirat(int fd, const char *name, int flags) {
3432 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3438 close_nointr_nofail(nfd);
3445 int signal_from_string_try_harder(const char *s) {
3449 signo = signal_from_string(s);
3451 if (startswith(s, "SIG"))
3452 return signal_from_string(s+3);
3457 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3461 /* FIXME: to follow udev's logic 100% we need to leave valid
3462 * UTF8 chars unescaped */
3464 u = unquote(tagvalue, "\"\'");
3468 t = xescape(u, "/ ");
3474 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3483 char *fstab_node_to_udev_node(const char *p) {
3486 if (startswith(p, "LABEL="))
3487 return tag_to_udev_node(p+6, "label");
3489 if (startswith(p, "UUID="))
3490 return tag_to_udev_node(p+5, "uuid");
3492 if (startswith(p, "PARTUUID="))
3493 return tag_to_udev_node(p+9, "partuuid");
3495 if (startswith(p, "PARTLABEL="))
3496 return tag_to_udev_node(p+10, "partlabel");
3501 bool tty_is_vc(const char *tty) {
3504 if (startswith(tty, "/dev/"))
3507 return vtnr_from_tty(tty) >= 0;
3510 bool tty_is_console(const char *tty) {
3513 if (startswith(tty, "/dev/"))
3516 return streq(tty, "console");
3519 int vtnr_from_tty(const char *tty) {
3524 if (startswith(tty, "/dev/"))
3527 if (!startswith(tty, "tty") )
3530 if (tty[3] < '0' || tty[3] > '9')
3533 r = safe_atoi(tty+3, &i);
3537 if (i < 0 || i > 63)
3543 char *resolve_dev_console(char **active) {
3546 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3547 * (i.e. not read-only-mounted which is a sign for container setups) */
3549 if (path_is_read_only_fs("/sys") > 0)
3552 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3555 /* If multiple log outputs are configured the last one is what
3556 * /dev/console points to */
3557 tty = strrchr(*active, ' ');
3566 bool tty_is_vc_resolve(const char *tty) {
3567 char *active = NULL;
3572 if (startswith(tty, "/dev/"))
3575 if (streq(tty, "console")) {
3576 tty = resolve_dev_console(&active);
3587 const char *default_term_for_tty(const char *tty) {
3590 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3593 bool dirent_is_file(const struct dirent *de) {
3596 if (ignore_file(de->d_name))
3599 if (de->d_type != DT_REG &&
3600 de->d_type != DT_LNK &&
3601 de->d_type != DT_UNKNOWN)
3607 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3610 if (de->d_type != DT_REG &&
3611 de->d_type != DT_LNK &&
3612 de->d_type != DT_UNKNOWN)
3615 if (ignore_file_allow_backup(de->d_name))
3618 return endswith(de->d_name, suffix);
3621 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3624 Hashmap *pids = NULL;
3628 /* Executes all binaries in a directory in parallel and
3629 * waits for them to finish. */
3632 if (!(_d = opendir(directory))) {
3634 if (errno == ENOENT)
3637 log_error("Failed to enumerate directory %s: %m", directory);
3644 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3645 log_error("Failed to allocate set.");
3649 while ((de = readdir(d))) {
3654 if (!dirent_is_file(de))
3657 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3662 if ((pid = fork()) < 0) {
3663 log_error("Failed to fork: %m");
3681 log_error("Failed to execute %s: %m", path);
3682 _exit(EXIT_FAILURE);
3685 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3687 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3688 log_error("Failed to add PID to set: %s", strerror(-k));
3693 while (!hashmap_isempty(pids)) {
3694 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3699 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3704 log_error("waitid() failed: %m");
3708 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3709 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3710 if (si.si_code == CLD_EXITED)
3711 log_error("%s exited with exit status %i.", path, si.si_status);
3713 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3715 log_debug("%s exited successfully.", path);
3726 hashmap_free_free(pids);
3729 int kill_and_sigcont(pid_t pid, int sig) {
3732 r = kill(pid, sig) < 0 ? -errno : 0;
3740 bool nulstr_contains(const char*nulstr, const char *needle) {
3746 NULSTR_FOREACH(i, nulstr)
3747 if (streq(i, needle))
3753 bool plymouth_running(void) {
3754 return access("/run/plymouth/pid", F_OK) >= 0;
3757 char* strshorten(char *s, size_t l) {
3766 static bool hostname_valid_char(char c) {
3768 (c >= 'a' && c <= 'z') ||
3769 (c >= 'A' && c <= 'Z') ||
3770 (c >= '0' && c <= '9') ||
3776 bool hostname_is_valid(const char *s) {
3783 for (p = s, dot = true; *p; p++) {
3790 if (!hostname_valid_char(*p))
3800 if (p-s > HOST_NAME_MAX)
3806 char* hostname_cleanup(char *s) {
3809 for (p = s, d = s; *p; p++)
3810 if ((*p >= 'a' && *p <= 'z') ||
3811 (*p >= 'A' && *p <= 'Z') ||
3812 (*p >= '0' && *p <= '9') ||
3820 strshorten(s, HOST_NAME_MAX);
3824 int pipe_eof(int fd) {
3825 struct pollfd pollfd;
3830 pollfd.events = POLLIN|POLLHUP;
3832 r = poll(&pollfd, 1, 0);
3839 return pollfd.revents & POLLHUP;
3842 int fd_wait_for_event(int fd, int event, usec_t t) {
3843 struct pollfd pollfd;
3848 pollfd.events = event;
3850 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3857 return pollfd.revents;
3860 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3871 t = new(char, strlen(path) + 1 + 6 + 1);
3875 fn = path_get_file_name(path);
3879 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3881 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3887 f = fdopen(fd, "we");
3900 int terminal_vhangup_fd(int fd) {
3903 if (ioctl(fd, TIOCVHANGUP) < 0)
3909 int terminal_vhangup(const char *name) {
3912 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3916 r = terminal_vhangup_fd(fd);
3917 close_nointr_nofail(fd);
3922 int vt_disallocate(const char *name) {
3926 /* Deallocate the VT if possible. If not possible
3927 * (i.e. because it is the active one), at least clear it
3928 * entirely (including the scrollback buffer) */
3930 if (!startswith(name, "/dev/"))
3933 if (!tty_is_vc(name)) {
3934 /* So this is not a VT. I guess we cannot deallocate
3935 * it then. But let's at least clear the screen */
3937 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3942 "\033[r" /* clear scrolling region */
3943 "\033[H" /* move home */
3944 "\033[2J", /* clear screen */
3946 close_nointr_nofail(fd);
3951 if (!startswith(name, "/dev/tty"))
3954 r = safe_atou(name+8, &u);
3961 /* Try to deallocate */
3962 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3966 r = ioctl(fd, VT_DISALLOCATE, u);
3967 close_nointr_nofail(fd);
3975 /* Couldn't deallocate, so let's clear it fully with
3977 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3982 "\033[r" /* clear scrolling region */
3983 "\033[H" /* move home */
3984 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3986 close_nointr_nofail(fd);
3991 int copy_file(const char *from, const char *to) {
3997 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4001 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4003 close_nointr_nofail(fdf);
4011 n = read(fdf, buf, sizeof(buf));
4015 close_nointr_nofail(fdf);
4026 k = loop_write(fdt, buf, n, false);
4028 r = k < 0 ? k : (errno ? -errno : -EIO);
4030 close_nointr_nofail(fdf);
4038 close_nointr_nofail(fdf);
4039 r = close_nointr(fdt);
4049 int symlink_atomic(const char *from, const char *to) {
4051 _cleanup_free_ char *t;
4054 unsigned long long ull;
4061 t = new(char, strlen(to) + 1 + 16 + 1);
4065 fn = path_get_file_name(to);
4069 x = stpcpy(t+k+1, fn);
4072 for (i = 0; i < 16; i++) {
4073 *(x++) = hexchar(ull & 0xF);
4079 if (symlink(from, t) < 0)
4082 if (rename(t, to) < 0) {
4091 bool display_is_local(const char *display) {
4095 display[0] == ':' &&
4096 display[1] >= '0' &&
4100 int socket_from_display(const char *display, char **path) {
4107 if (!display_is_local(display))
4110 k = strspn(display+1, "0123456789");
4112 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4116 c = stpcpy(f, "/tmp/.X11-unix/X");
4117 memcpy(c, display+1, k);
4126 const char **username,
4127 uid_t *uid, gid_t *gid,
4129 const char **shell) {
4137 /* We enforce some special rules for uid=0: in order to avoid
4138 * NSS lookups for root we hardcode its data. */
4140 if (streq(*username, "root") || streq(*username, "0")) {
4158 if (parse_uid(*username, &u) >= 0) {
4162 /* If there are multiple users with the same id, make
4163 * sure to leave $USER to the configured value instead
4164 * of the first occurrence in the database. However if
4165 * the uid was configured by a numeric uid, then let's
4166 * pick the real username from /etc/passwd. */
4168 *username = p->pw_name;
4171 p = getpwnam(*username);
4175 return errno != 0 ? -errno : -ESRCH;
4187 *shell = p->pw_shell;
4192 char* uid_to_name(uid_t uid) {
4197 return strdup("root");
4201 return strdup(p->pw_name);
4203 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4209 char* gid_to_name(gid_t gid) {
4214 return strdup("root");
4218 return strdup(p->gr_name);
4220 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4226 int get_group_creds(const char **groupname, gid_t *gid) {
4232 /* We enforce some special rules for gid=0: in order to avoid
4233 * NSS lookups for root we hardcode its data. */
4235 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4236 *groupname = "root";
4244 if (parse_gid(*groupname, &id) >= 0) {
4249 *groupname = g->gr_name;
4252 g = getgrnam(*groupname);
4256 return errno != 0 ? -errno : -ESRCH;
4264 int in_gid(gid_t gid) {
4266 int ngroups_max, r, i;
4268 if (getgid() == gid)
4271 if (getegid() == gid)
4274 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4275 assert(ngroups_max > 0);
4277 gids = alloca(sizeof(gid_t) * ngroups_max);
4279 r = getgroups(ngroups_max, gids);
4283 for (i = 0; i < r; i++)
4290 int in_group(const char *name) {
4294 r = get_group_creds(&name, &gid);
4301 int glob_exists(const char *path) {
4309 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4311 if (k == GLOB_NOMATCH)
4313 else if (k == GLOB_NOSPACE)
4316 r = !strv_isempty(g.gl_pathv);
4318 r = errno ? -errno : -EIO;
4325 int dirent_ensure_type(DIR *d, struct dirent *de) {
4331 if (de->d_type != DT_UNKNOWN)
4334 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4338 S_ISREG(st.st_mode) ? DT_REG :
4339 S_ISDIR(st.st_mode) ? DT_DIR :
4340 S_ISLNK(st.st_mode) ? DT_LNK :
4341 S_ISFIFO(st.st_mode) ? DT_FIFO :
4342 S_ISSOCK(st.st_mode) ? DT_SOCK :
4343 S_ISCHR(st.st_mode) ? DT_CHR :
4344 S_ISBLK(st.st_mode) ? DT_BLK :
4350 int in_search_path(const char *path, char **search) {
4354 r = path_get_parent(path, &parent);
4360 STRV_FOREACH(i, search) {
4361 if (path_equal(parent, *i)) {
4372 int get_files_in_directory(const char *path, char ***list) {
4380 /* Returns all files in a directory in *list, and the number
4381 * of files as return value. If list is NULL returns only the
4390 union dirent_storage buf;
4393 k = readdir_r(d, &buf.de, &de);
4402 dirent_ensure_type(d, de);
4404 if (!dirent_is_file(de))
4408 if ((unsigned) r >= n) {
4412 t = realloc(l, sizeof(char*) * n);
4421 assert((unsigned) r < n);
4423 l[r] = strdup(de->d_name);
4447 char *strjoin(const char *x, ...) {
4461 t = va_arg(ap, const char *);
4466 if (n > ((size_t) -1) - l) {
4490 t = va_arg(ap, const char *);
4504 bool is_main_thread(void) {
4505 static __thread int cached = 0;
4507 if (_unlikely_(cached == 0))
4508 cached = getpid() == gettid() ? 1 : -1;
4513 int block_get_whole_disk(dev_t d, dev_t *ret) {
4520 /* If it has a queue this is good enough for us */
4521 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4524 r = access(p, F_OK);
4532 /* If it is a partition find the originating device */
4533 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4536 r = access(p, F_OK);
4542 /* Get parent dev_t */
4543 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4546 r = read_one_line_file(p, &s);
4552 r = sscanf(s, "%u:%u", &m, &n);
4558 /* Only return this if it is really good enough for us. */
4559 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4562 r = access(p, F_OK);
4566 *ret = makedev(m, n);
4573 int file_is_priv_sticky(const char *p) {
4578 if (lstat(p, &st) < 0)
4582 (st.st_uid == 0 || st.st_uid == getuid()) &&
4583 (st.st_mode & S_ISVTX);
4586 static const char *const ioprio_class_table[] = {
4587 [IOPRIO_CLASS_NONE] = "none",
4588 [IOPRIO_CLASS_RT] = "realtime",
4589 [IOPRIO_CLASS_BE] = "best-effort",
4590 [IOPRIO_CLASS_IDLE] = "idle"
4593 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4595 static const char *const sigchld_code_table[] = {
4596 [CLD_EXITED] = "exited",
4597 [CLD_KILLED] = "killed",
4598 [CLD_DUMPED] = "dumped",
4599 [CLD_TRAPPED] = "trapped",
4600 [CLD_STOPPED] = "stopped",
4601 [CLD_CONTINUED] = "continued",
4604 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4606 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4607 [LOG_FAC(LOG_KERN)] = "kern",
4608 [LOG_FAC(LOG_USER)] = "user",
4609 [LOG_FAC(LOG_MAIL)] = "mail",
4610 [LOG_FAC(LOG_DAEMON)] = "daemon",
4611 [LOG_FAC(LOG_AUTH)] = "auth",
4612 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4613 [LOG_FAC(LOG_LPR)] = "lpr",
4614 [LOG_FAC(LOG_NEWS)] = "news",
4615 [LOG_FAC(LOG_UUCP)] = "uucp",
4616 [LOG_FAC(LOG_CRON)] = "cron",
4617 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4618 [LOG_FAC(LOG_FTP)] = "ftp",
4619 [LOG_FAC(LOG_LOCAL0)] = "local0",
4620 [LOG_FAC(LOG_LOCAL1)] = "local1",
4621 [LOG_FAC(LOG_LOCAL2)] = "local2",
4622 [LOG_FAC(LOG_LOCAL3)] = "local3",
4623 [LOG_FAC(LOG_LOCAL4)] = "local4",
4624 [LOG_FAC(LOG_LOCAL5)] = "local5",
4625 [LOG_FAC(LOG_LOCAL6)] = "local6",
4626 [LOG_FAC(LOG_LOCAL7)] = "local7"
4629 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4631 static const char *const log_level_table[] = {
4632 [LOG_EMERG] = "emerg",
4633 [LOG_ALERT] = "alert",
4634 [LOG_CRIT] = "crit",
4636 [LOG_WARNING] = "warning",
4637 [LOG_NOTICE] = "notice",
4638 [LOG_INFO] = "info",
4639 [LOG_DEBUG] = "debug"
4642 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4644 static const char* const sched_policy_table[] = {
4645 [SCHED_OTHER] = "other",
4646 [SCHED_BATCH] = "batch",
4647 [SCHED_IDLE] = "idle",
4648 [SCHED_FIFO] = "fifo",
4652 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4654 static const char* const rlimit_table[] = {
4655 [RLIMIT_CPU] = "LimitCPU",
4656 [RLIMIT_FSIZE] = "LimitFSIZE",
4657 [RLIMIT_DATA] = "LimitDATA",
4658 [RLIMIT_STACK] = "LimitSTACK",
4659 [RLIMIT_CORE] = "LimitCORE",
4660 [RLIMIT_RSS] = "LimitRSS",
4661 [RLIMIT_NOFILE] = "LimitNOFILE",
4662 [RLIMIT_AS] = "LimitAS",
4663 [RLIMIT_NPROC] = "LimitNPROC",
4664 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4665 [RLIMIT_LOCKS] = "LimitLOCKS",
4666 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4667 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4668 [RLIMIT_NICE] = "LimitNICE",
4669 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4670 [RLIMIT_RTTIME] = "LimitRTTIME"
4673 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4675 static const char* const ip_tos_table[] = {
4676 [IPTOS_LOWDELAY] = "low-delay",
4677 [IPTOS_THROUGHPUT] = "throughput",
4678 [IPTOS_RELIABILITY] = "reliability",
4679 [IPTOS_LOWCOST] = "low-cost",
4682 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4684 static const char *const __signal_table[] = {
4701 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4712 [SIGVTALRM] = "VTALRM",
4714 [SIGWINCH] = "WINCH",
4720 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4722 const char *signal_to_string(int signo) {
4723 static __thread char buf[12];
4726 name = __signal_to_string(signo);
4730 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4731 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4733 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4738 int signal_from_string(const char *s) {
4743 signo = __signal_from_string(s);
4747 if (startswith(s, "RTMIN+")) {
4751 if (safe_atou(s, &u) >= 0) {
4752 signo = (int) u + offset;
4753 if (signo > 0 && signo < _NSIG)
4759 bool kexec_loaded(void) {
4760 bool loaded = false;
4763 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4771 int strdup_or_null(const char *a, char **b) {
4789 int prot_from_flags(int flags) {
4791 switch (flags & O_ACCMODE) {
4800 return PROT_READ|PROT_WRITE;
4807 char *format_bytes(char *buf, size_t l, off_t t) {
4810 static const struct {
4814 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4815 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4816 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4817 { "G", 1024ULL*1024ULL*1024ULL },
4818 { "M", 1024ULL*1024ULL },
4822 for (i = 0; i < ELEMENTSOF(table); i++) {
4824 if (t >= table[i].factor) {
4827 (unsigned long long) (t / table[i].factor),
4828 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4835 snprintf(buf, l, "%lluB", (unsigned long long) t);
4843 void* memdup(const void *p, size_t l) {
4856 int fd_inc_sndbuf(int fd, size_t n) {
4858 socklen_t l = sizeof(value);
4860 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4862 l == sizeof(value) &&
4863 (size_t) value >= n*2)
4867 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4874 int fd_inc_rcvbuf(int fd, size_t n) {
4876 socklen_t l = sizeof(value);
4878 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4880 l == sizeof(value) &&
4881 (size_t) value >= n*2)
4885 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4892 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4893 pid_t parent_pid, agent_pid;
4895 bool stdout_is_tty, stderr_is_tty;
4903 parent_pid = getpid();
4905 /* Spawns a temporary TTY agent, making sure it goes away when
4912 if (agent_pid != 0) {
4919 * Make sure the agent goes away when the parent dies */
4920 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4921 _exit(EXIT_FAILURE);
4923 /* Check whether our parent died before we were able
4924 * to set the death signal */
4925 if (getppid() != parent_pid)
4926 _exit(EXIT_SUCCESS);
4928 /* Don't leak fds to the agent */
4929 close_all_fds(except, n_except);
4931 stdout_is_tty = isatty(STDOUT_FILENO);
4932 stderr_is_tty = isatty(STDERR_FILENO);
4934 if (!stdout_is_tty || !stderr_is_tty) {
4935 /* Detach from stdout/stderr. and reopen
4936 * /dev/tty for them. This is important to
4937 * ensure that when systemctl is started via
4938 * popen() or a similar call that expects to
4939 * read EOF we actually do generate EOF and
4940 * not delay this indefinitely by because we
4941 * keep an unused copy of stdin around. */
4942 fd = open("/dev/tty", O_WRONLY);
4944 log_error("Failed to open /dev/tty: %m");
4945 _exit(EXIT_FAILURE);
4949 dup2(fd, STDOUT_FILENO);
4952 dup2(fd, STDERR_FILENO);
4958 /* Count arguments */
4960 for (n = 0; va_arg(ap, char*); n++)
4965 l = alloca(sizeof(char *) * (n + 1));
4967 /* Fill in arguments */
4969 for (i = 0; i <= n; i++)
4970 l[i] = va_arg(ap, char*);
4974 _exit(EXIT_FAILURE);
4977 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4978 struct rlimit highest, fixed;
4982 if (setrlimit(resource, rlim) >= 0)
4988 /* So we failed to set the desired setrlimit, then let's try
4989 * to get as close as we can */
4990 assert_se(getrlimit(resource, &highest) == 0);
4992 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4993 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4995 if (setrlimit(resource, &fixed) < 0)
5001 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5002 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5014 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5017 f = fopen(path, "re");
5025 char line[LINE_MAX];
5028 for (i = 0; i < sizeof(line)-1; i++) {
5032 if (_unlikely_(c == EOF)) {
5042 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5043 value = strdup(line + l + 1);
5063 int can_sleep(const char *type) {
5067 _cleanup_free_ char *p = NULL;
5071 /* If /sys is read-only we cannot sleep */
5072 if (access("/sys/power/state", W_OK) < 0)
5075 r = read_one_line_file("/sys/power/state", &p);
5080 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5081 if (l == k && memcmp(w, type, l) == 0)
5087 int can_sleep_disk(const char *type) {
5091 _cleanup_free_ char *p = NULL;
5095 /* If /sys is read-only we cannot sleep */
5096 if (access("/sys/power/state", W_OK) < 0 ||
5097 access("/sys/power/disk", W_OK) < 0)
5100 r = read_one_line_file("/sys/power/disk", &p);
5105 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5106 if (l == k && memcmp(w, type, l) == 0)
5109 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5116 bool is_valid_documentation_url(const char *url) {
5119 if (startswith(url, "http://") && url[7])
5122 if (startswith(url, "https://") && url[8])
5125 if (startswith(url, "file:") && url[5])
5128 if (startswith(url, "info:") && url[5])
5131 if (startswith(url, "man:") && url[4])
5137 bool in_initrd(void) {
5138 static __thread int saved = -1;
5144 /* We make two checks here:
5146 * 1. the flag file /etc/initrd-release must exist
5147 * 2. the root file system must be a memory file system
5149 * The second check is extra paranoia, since misdetecting an
5150 * initrd can have bad bad consequences due the initrd
5151 * emptying when transititioning to the main systemd.
5154 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5155 statfs("/", &s) >= 0 &&
5156 is_temporary_fs(&s);
5161 void warn_melody(void) {
5162 _cleanup_close_ int fd = -1;
5164 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5168 /* Yeah, this is synchronous. Kinda sucks. But well... */
5170 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5171 usleep(125*USEC_PER_MSEC);
5173 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5174 usleep(125*USEC_PER_MSEC);
5176 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5177 usleep(125*USEC_PER_MSEC);
5179 ioctl(fd, KIOCSOUND, 0);
5182 int make_console_stdio(void) {
5185 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5187 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5189 log_error("Failed to acquire terminal: %s", strerror(-fd));
5195 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5202 int get_home_dir(char **_h) {
5210 /* Take the user specified one */
5221 /* Hardcode home directory for root to avoid NSS */
5224 h = strdup("/root");
5232 /* Check the database... */
5236 return errno ? -errno : -ESRCH;
5238 if (!path_is_absolute(p->pw_dir))
5241 h = strdup(p->pw_dir);
5249 void fclosep(FILE **f) {
5254 void pclosep(FILE **f) {
5259 void closep(int *fd) {
5261 close_nointr_nofail(*fd);
5264 void closedirp(DIR **d) {
5269 bool filename_is_safe(const char *p) {
5283 if (strlen(p) > FILENAME_MAX)
5289 bool string_is_safe(const char *p) {
5294 for (t = p; *t; t++) {
5295 if (*t > 0 && *t < ' ')
5298 if (strchr("\\\"\'", *t))
5305 bool string_has_cc(const char *p) {
5310 for (t = p; *t; t++)
5311 if (*t > 0 && *t < ' ')
5317 bool path_is_safe(const char *p) {
5322 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5325 if (strlen(p) > PATH_MAX)
5328 /* The following two checks are not really dangerous, but hey, they still are confusing */
5329 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5332 if (strstr(p, "//"))
5338 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5339 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5340 int (*compar) (const void *, const void *, void *), void *arg) {
5349 p = (void *)(((const char *) base) + (idx * size));
5350 comparison = compar(key, p, arg);
5353 else if (comparison > 0)
5361 bool is_locale_utf8(void) {
5363 static int cached_answer = -1;
5365 if (cached_answer >= 0)
5368 if (!setlocale(LC_ALL, "")) {
5369 cached_answer = true;
5373 set = nl_langinfo(CODESET);
5375 cached_answer = true;
5379 cached_answer = streq(set, "UTF-8");
5381 return (bool)cached_answer;
5384 const char *draw_special_char(DrawSpecialChar ch) {
5385 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5387 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5388 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5389 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5390 [DRAW_TREE_SPACE] = " ", /* */
5391 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5393 /* ASCII fallback */ {
5394 [DRAW_TREE_VERT] = "| ",
5395 [DRAW_TREE_BRANCH] = "|-",
5396 [DRAW_TREE_RIGHT] = "`-",
5397 [DRAW_TREE_SPACE] = " ",
5398 [DRAW_TRIANGULAR_BULLET] = "> ",
5402 return draw_table[!is_locale_utf8()][ch];
5405 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5408 size_t l, old_len, new_len;
5414 old_len = strlen(old_string);
5415 new_len = strlen(new_string);
5428 if (!startswith(f, old_string)) {
5434 nl = l - old_len + new_len;
5435 a = realloc(r, nl + 1);
5443 t = stpcpy(t, new_string);
5455 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5456 const char *i, *begin = NULL;
5461 } state = STATE_OTHER;
5463 size_t osz = 0, isz;
5469 /* Strips ANSI color and replaces TABs by 8 spaces */
5471 isz = _isz ? *_isz : strlen(*ibuf);
5473 f = open_memstream(&obuf, &osz);
5477 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5482 if (i >= *ibuf + isz) /* EOT */
5484 else if (*i == '\x1B')
5485 state = STATE_ESCAPE;
5486 else if (*i == '\t')
5493 if (i >= *ibuf + isz) { /* EOT */
5496 } else if (*i == '[') {
5497 state = STATE_BRACKET;
5502 state = STATE_OTHER;
5509 if (i >= *ibuf + isz || /* EOT */
5510 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5513 state = STATE_OTHER;
5515 } else if (*i == 'm')
5516 state = STATE_OTHER;
5538 int on_ac_power(void) {
5539 bool found_offline = false, found_online = false;
5540 _cleanup_closedir_ DIR *d = NULL;
5542 d = opendir("/sys/class/power_supply");
5548 union dirent_storage buf;
5549 _cleanup_close_ int fd = -1, device = -1;
5554 k = readdir_r(d, &buf.de, &de);
5561 if (ignore_file(de->d_name))
5564 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5566 if (errno == ENOENT || errno == ENOTDIR)
5572 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5574 if (errno == ENOENT)
5580 n = read(fd, contents, sizeof(contents));
5584 if (n != 6 || memcmp(contents, "Mains\n", 6))
5587 close_nointr_nofail(fd);
5588 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5590 if (errno == ENOENT)
5596 n = read(fd, contents, sizeof(contents));
5600 if (n != 2 || contents[1] != '\n')
5603 if (contents[0] == '1') {
5604 found_online = true;
5606 } else if (contents[0] == '0')
5607 found_offline = true;
5612 return found_online || !found_offline;
5615 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5622 if (!path_strv_canonicalize_uniq(search))
5625 STRV_FOREACH(i, search) {
5626 _cleanup_free_ char *p = NULL;
5629 p = strjoin(*i, "/", path, NULL);
5639 if (errno != ENOENT)
5646 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5647 _cleanup_strv_free_ char **copy = NULL;
5653 if (path_is_absolute(path)) {
5656 f = fopen(path, mode);
5665 copy = strv_copy((char**) search);
5669 return search_and_fopen_internal(path, mode, copy, _f);
5672 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5673 _cleanup_strv_free_ char **s = NULL;
5675 if (path_is_absolute(path)) {
5678 f = fopen(path, mode);
5687 s = strv_split_nulstr(search);
5691 return search_and_fopen_internal(path, mode, s, _f);
5694 int create_tmp_dir(char template[], char** dir_name) {
5697 mode_t _cleanup_umask_ u;
5702 d = mkdtemp(template);
5704 log_error("Can't create directory %s: %m", template);
5708 dt = strjoin(d, "/tmp", NULL);
5715 r = mkdir(dt, 0777);
5717 log_error("Can't create directory %s: %m", dt);
5721 log_debug("Created temporary directory %s", dt);
5723 r = chmod(dt, 0777 | S_ISVTX);
5725 log_error("Failed to chmod %s: %m", dt);
5729 log_debug("Set sticky bit on %s", dt);
5741 char *strextend(char **x, ...) {
5748 l = f = *x ? strlen(*x) : 0;
5755 t = va_arg(ap, const char *);
5760 if (n > ((size_t) -1) - l) {
5769 r = realloc(*x, l+1);
5779 t = va_arg(ap, const char *);
5793 char *strrep(const char *s, unsigned n) {
5801 p = r = malloc(l * n + 1);
5805 for (i = 0; i < n; i++)