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++) {
892 struct sigaction sa = {
893 .sa_handler = SIG_DFL,
894 .sa_flags = SA_RESTART,
897 if (sig == SIGKILL || sig == SIGSTOP)
900 /* On Linux the first two RT signals are reserved by
901 * glibc, and sigaction() will return EINVAL for them. */
902 if ((sigaction(sig, &sa, NULL) < 0))
910 char *strstrip(char *s) {
913 /* Drops trailing whitespace. Modifies the string in
914 * place. Returns pointer to first non-space character */
916 s += strspn(s, WHITESPACE);
918 for (e = strchr(s, 0); e > s; e --)
919 if (!strchr(WHITESPACE, e[-1]))
927 char *delete_chars(char *s, const char *bad) {
930 /* Drops all whitespace, regardless where in the string */
932 for (f = s, t = s; *f; f++) {
944 bool in_charset(const char *s, const char* charset) {
951 if (!strchr(charset, *i))
957 char *file_in_same_dir(const char *path, const char *filename) {
964 /* This removes the last component of path and appends
965 * filename, unless the latter is absolute anyway or the
968 if (path_is_absolute(filename))
969 return strdup(filename);
971 if (!(e = strrchr(path, '/')))
972 return strdup(filename);
974 k = strlen(filename);
975 if (!(r = new(char, e-path+1+k+1)))
978 memcpy(r, path, e-path+1);
979 memcpy(r+(e-path)+1, filename, k+1);
984 int rmdir_parents(const char *path, const char *stop) {
993 /* Skip trailing slashes */
994 while (l > 0 && path[l-1] == '/')
1000 /* Skip last component */
1001 while (l > 0 && path[l-1] != '/')
1004 /* Skip trailing slashes */
1005 while (l > 0 && path[l-1] == '/')
1011 if (!(t = strndup(path, l)))
1014 if (path_startswith(stop, t)) {
1023 if (errno != ENOENT)
1030 char hexchar(int x) {
1031 static const char table[16] = "0123456789abcdef";
1033 return table[x & 15];
1036 int unhexchar(char c) {
1038 if (c >= '0' && c <= '9')
1041 if (c >= 'a' && c <= 'f')
1042 return c - 'a' + 10;
1044 if (c >= 'A' && c <= 'F')
1045 return c - 'A' + 10;
1050 char *hexmem(const void *p, size_t l) {
1054 z = r = malloc(l * 2 + 1);
1058 for (x = p; x < (const uint8_t*) p + l; x++) {
1059 *(z++) = hexchar(*x >> 4);
1060 *(z++) = hexchar(*x & 15);
1067 void *unhexmem(const char *p, size_t l) {
1073 z = r = malloc((l + 1) / 2 + 1);
1077 for (x = p; x < p + l; x += 2) {
1080 a = unhexchar(x[0]);
1082 b = unhexchar(x[1]);
1086 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1093 char octchar(int x) {
1094 return '0' + (x & 7);
1097 int unoctchar(char c) {
1099 if (c >= '0' && c <= '7')
1105 char decchar(int x) {
1106 return '0' + (x % 10);
1109 int undecchar(char c) {
1111 if (c >= '0' && c <= '9')
1117 char *cescape(const char *s) {
1123 /* Does C style string escaping. */
1125 r = new(char, strlen(s)*4 + 1);
1129 for (f = s, t = r; *f; f++)
1175 /* For special chars we prefer octal over
1176 * hexadecimal encoding, simply because glib's
1177 * g_strescape() does the same */
1178 if ((*f < ' ') || (*f >= 127)) {
1180 *(t++) = octchar((unsigned char) *f >> 6);
1181 *(t++) = octchar((unsigned char) *f >> 3);
1182 *(t++) = octchar((unsigned char) *f);
1193 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1200 /* Undoes C style string escaping, and optionally prefixes it. */
1202 pl = prefix ? strlen(prefix) : 0;
1204 r = new(char, pl+length+1);
1209 memcpy(r, prefix, pl);
1211 for (f = s, t = r + pl; f < s + length; f++) {
1254 /* This is an extension of the XDG syntax files */
1259 /* hexadecimal encoding */
1262 a = unhexchar(f[1]);
1263 b = unhexchar(f[2]);
1265 if (a < 0 || b < 0) {
1266 /* Invalid escape code, let's take it literal then */
1270 *(t++) = (char) ((a << 4) | b);
1285 /* octal encoding */
1288 a = unoctchar(f[0]);
1289 b = unoctchar(f[1]);
1290 c = unoctchar(f[2]);
1292 if (a < 0 || b < 0 || c < 0) {
1293 /* Invalid escape code, let's take it literal then */
1297 *(t++) = (char) ((a << 6) | (b << 3) | c);
1305 /* premature end of string.*/
1310 /* Invalid escape code, let's take it literal then */
1322 char *cunescape_length(const char *s, size_t length) {
1323 return cunescape_length_with_prefix(s, length, NULL);
1326 char *cunescape(const char *s) {
1329 return cunescape_length(s, strlen(s));
1332 char *xescape(const char *s, const char *bad) {
1336 /* Escapes all chars in bad, in addition to \ and all special
1337 * chars, in \xFF style escaping. May be reversed with
1340 r = new(char, strlen(s) * 4 + 1);
1344 for (f = s, t = r; *f; f++) {
1346 if ((*f < ' ') || (*f >= 127) ||
1347 (*f == '\\') || strchr(bad, *f)) {
1350 *(t++) = hexchar(*f >> 4);
1351 *(t++) = hexchar(*f);
1361 char *bus_path_escape(const char *s) {
1367 /* Escapes all chars that D-Bus' object path cannot deal
1368 * with. Can be reverse with bus_path_unescape(). We special
1369 * case the empty string. */
1374 r = new(char, strlen(s)*3 + 1);
1378 for (f = s, t = r; *f; f++) {
1380 /* Escape everything that is not a-zA-Z0-9. We also
1381 * escape 0-9 if it's the first character */
1383 if (!(*f >= 'A' && *f <= 'Z') &&
1384 !(*f >= 'a' && *f <= 'z') &&
1385 !(f > s && *f >= '0' && *f <= '9')) {
1387 *(t++) = hexchar(*f >> 4);
1388 *(t++) = hexchar(*f);
1398 char *bus_path_unescape(const char *f) {
1403 /* Special case for the empty string */
1407 r = new(char, strlen(f) + 1);
1411 for (t = r; *f; f++) {
1416 if ((a = unhexchar(f[1])) < 0 ||
1417 (b = unhexchar(f[2])) < 0) {
1418 /* Invalid escape code, let's take it literal then */
1421 *(t++) = (char) ((a << 4) | b);
1433 char *ascii_strlower(char *t) {
1438 for (p = t; *p; p++)
1439 if (*p >= 'A' && *p <= 'Z')
1440 *p = *p - 'A' + 'a';
1445 static bool ignore_file_allow_backup(const char *filename) {
1449 filename[0] == '.' ||
1450 streq(filename, "lost+found") ||
1451 streq(filename, "aquota.user") ||
1452 streq(filename, "aquota.group") ||
1453 endswith(filename, ".rpmnew") ||
1454 endswith(filename, ".rpmsave") ||
1455 endswith(filename, ".rpmorig") ||
1456 endswith(filename, ".dpkg-old") ||
1457 endswith(filename, ".dpkg-new") ||
1458 endswith(filename, ".swp");
1461 bool ignore_file(const char *filename) {
1464 if (endswith(filename, "~"))
1467 return ignore_file_allow_backup(filename);
1470 int fd_nonblock(int fd, bool nonblock) {
1475 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1479 flags |= O_NONBLOCK;
1481 flags &= ~O_NONBLOCK;
1483 if (fcntl(fd, F_SETFL, flags) < 0)
1489 int fd_cloexec(int fd, bool cloexec) {
1494 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1498 flags |= FD_CLOEXEC;
1500 flags &= ~FD_CLOEXEC;
1502 if (fcntl(fd, F_SETFD, flags) < 0)
1508 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1511 assert(n_fdset == 0 || fdset);
1513 for (i = 0; i < n_fdset; i++)
1520 int close_all_fds(const int except[], unsigned n_except) {
1525 assert(n_except == 0 || except);
1527 d = opendir("/proc/self/fd");
1532 /* When /proc isn't available (for example in chroots)
1533 * the fallback is brute forcing through the fd
1536 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1537 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1539 if (fd_in_set(fd, except, n_except))
1542 if (close_nointr(fd) < 0)
1543 if (errno != EBADF && r == 0)
1550 while ((de = readdir(d))) {
1553 if (ignore_file(de->d_name))
1556 if (safe_atoi(de->d_name, &fd) < 0)
1557 /* Let's better ignore this, just in case */
1566 if (fd_in_set(fd, except, n_except))
1569 if (close_nointr(fd) < 0) {
1570 /* Valgrind has its own FD and doesn't want to have it closed */
1571 if (errno != EBADF && r == 0)
1580 bool chars_intersect(const char *a, const char *b) {
1583 /* Returns true if any of the chars in a are in b. */
1584 for (p = a; *p; p++)
1591 bool fstype_is_network(const char *fstype) {
1592 static const char table[] =
1601 return nulstr_contains(table, fstype);
1605 _cleanup_close_ int fd;
1607 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1613 TIOCL_GETKMSGREDIRECT,
1617 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1620 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1623 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1629 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1630 struct termios old_termios, new_termios;
1632 char line[LINE_MAX];
1637 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1638 new_termios = old_termios;
1640 new_termios.c_lflag &= ~ICANON;
1641 new_termios.c_cc[VMIN] = 1;
1642 new_termios.c_cc[VTIME] = 0;
1644 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1647 if (t != (usec_t) -1) {
1648 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1649 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1654 k = fread(&c, 1, 1, f);
1656 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1662 *need_nl = c != '\n';
1669 if (t != (usec_t) -1)
1670 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1673 if (!fgets(line, sizeof(line), f))
1678 if (strlen(line) != 1)
1688 int ask(char *ret, const char *replies, const char *text, ...) {
1698 bool need_nl = true;
1701 fputs(ANSI_HIGHLIGHT_ON, stdout);
1708 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1712 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1715 if (r == -EBADMSG) {
1716 puts("Bad input, please try again.");
1727 if (strchr(replies, c)) {
1732 puts("Read unexpected character, please try again.");
1736 int reset_terminal_fd(int fd, bool switch_to_text) {
1737 struct termios termios;
1740 /* Set terminal to some sane defaults */
1744 /* We leave locked terminal attributes untouched, so that
1745 * Plymouth may set whatever it wants to set, and we don't
1746 * interfere with that. */
1748 /* Disable exclusive mode, just in case */
1749 ioctl(fd, TIOCNXCL);
1751 /* Switch to text mode */
1753 ioctl(fd, KDSETMODE, KD_TEXT);
1755 /* Enable console unicode mode */
1756 ioctl(fd, KDSKBMODE, K_UNICODE);
1758 if (tcgetattr(fd, &termios) < 0) {
1763 /* We only reset the stuff that matters to the software. How
1764 * hardware is set up we don't touch assuming that somebody
1765 * else will do that for us */
1767 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1768 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1769 termios.c_oflag |= ONLCR;
1770 termios.c_cflag |= CREAD;
1771 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1773 termios.c_cc[VINTR] = 03; /* ^C */
1774 termios.c_cc[VQUIT] = 034; /* ^\ */
1775 termios.c_cc[VERASE] = 0177;
1776 termios.c_cc[VKILL] = 025; /* ^X */
1777 termios.c_cc[VEOF] = 04; /* ^D */
1778 termios.c_cc[VSTART] = 021; /* ^Q */
1779 termios.c_cc[VSTOP] = 023; /* ^S */
1780 termios.c_cc[VSUSP] = 032; /* ^Z */
1781 termios.c_cc[VLNEXT] = 026; /* ^V */
1782 termios.c_cc[VWERASE] = 027; /* ^W */
1783 termios.c_cc[VREPRINT] = 022; /* ^R */
1784 termios.c_cc[VEOL] = 0;
1785 termios.c_cc[VEOL2] = 0;
1787 termios.c_cc[VTIME] = 0;
1788 termios.c_cc[VMIN] = 1;
1790 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1794 /* Just in case, flush all crap out */
1795 tcflush(fd, TCIOFLUSH);
1800 int reset_terminal(const char *name) {
1803 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1807 r = reset_terminal_fd(fd, true);
1808 close_nointr_nofail(fd);
1813 int open_terminal(const char *name, int mode) {
1818 * If a TTY is in the process of being closed opening it might
1819 * cause EIO. This is horribly awful, but unlikely to be
1820 * changed in the kernel. Hence we work around this problem by
1821 * retrying a couple of times.
1823 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1827 fd = open(name, mode);
1834 /* Max 1s in total */
1838 usleep(50 * USEC_PER_MSEC);
1847 close_nointr_nofail(fd);
1852 close_nointr_nofail(fd);
1859 int flush_fd(int fd) {
1860 struct pollfd pollfd = {
1870 r = poll(&pollfd, 1, 0);
1880 l = read(fd, buf, sizeof(buf));
1886 if (errno == EAGAIN)
1895 int acquire_terminal(
1899 bool ignore_tiocstty_eperm,
1902 int fd = -1, notify = -1, r = 0, wd = -1;
1907 /* We use inotify to be notified when the tty is closed. We
1908 * create the watch before checking if we can actually acquire
1909 * it, so that we don't lose any event.
1911 * Note: strictly speaking this actually watches for the
1912 * device being closed, it does *not* really watch whether a
1913 * tty loses its controlling process. However, unless some
1914 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1915 * its tty otherwise this will not become a problem. As long
1916 * as the administrator makes sure not configure any service
1917 * on the same tty as an untrusted user this should not be a
1918 * problem. (Which he probably should not do anyway.) */
1920 if (timeout != (usec_t) -1)
1921 ts = now(CLOCK_MONOTONIC);
1923 if (!fail && !force) {
1924 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1930 wd = inotify_add_watch(notify, name, IN_CLOSE);
1938 struct sigaction sa_old, sa_new = {
1939 .sa_handler = SIG_IGN,
1940 .sa_flags = SA_RESTART,
1944 r = flush_fd(notify);
1949 /* We pass here O_NOCTTY only so that we can check the return
1950 * value TIOCSCTTY and have a reliable way to figure out if we
1951 * successfully became the controlling process of the tty */
1952 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1956 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1957 * if we already own the tty. */
1958 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1960 /* First, try to get the tty */
1961 if (ioctl(fd, TIOCSCTTY, force) < 0)
1964 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1966 /* Sometimes it makes sense to ignore TIOCSCTTY
1967 * returning EPERM, i.e. when very likely we already
1968 * are have this controlling terminal. */
1969 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1972 if (r < 0 && (force || fail || r != -EPERM)) {
1981 assert(notify >= 0);
1984 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1986 struct inotify_event *e;
1988 if (timeout != (usec_t) -1) {
1991 n = now(CLOCK_MONOTONIC);
1992 if (ts + timeout < n) {
1997 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2007 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2010 if (errno == EINTR || errno == EAGAIN)
2017 e = (struct inotify_event*) inotify_buffer;
2022 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2027 step = sizeof(struct inotify_event) + e->len;
2028 assert(step <= (size_t) l);
2030 e = (struct inotify_event*) ((uint8_t*) e + step);
2037 /* We close the tty fd here since if the old session
2038 * ended our handle will be dead. It's important that
2039 * we do this after sleeping, so that we don't enter
2040 * an endless loop. */
2041 close_nointr_nofail(fd);
2045 close_nointr_nofail(notify);
2047 r = reset_terminal_fd(fd, true);
2049 log_warning("Failed to reset terminal: %s", strerror(-r));
2055 close_nointr_nofail(fd);
2058 close_nointr_nofail(notify);
2063 int release_terminal(void) {
2065 struct sigaction sa_old, sa_new = {
2066 .sa_handler = SIG_IGN,
2067 .sa_flags = SA_RESTART,
2069 int _cleanup_close_ fd;
2071 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2075 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2076 * by our own TIOCNOTTY */
2077 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2079 if (ioctl(fd, TIOCNOTTY) < 0)
2082 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2087 int sigaction_many(const struct sigaction *sa, ...) {
2092 while ((sig = va_arg(ap, int)) > 0)
2093 if (sigaction(sig, sa, NULL) < 0)
2100 int ignore_signals(int sig, ...) {
2101 struct sigaction sa = {
2102 .sa_handler = SIG_IGN,
2103 .sa_flags = SA_RESTART,
2109 if (sigaction(sig, &sa, NULL) < 0)
2113 while ((sig = va_arg(ap, int)) > 0)
2114 if (sigaction(sig, &sa, NULL) < 0)
2121 int default_signals(int sig, ...) {
2122 struct sigaction sa = {
2123 .sa_handler = SIG_DFL,
2124 .sa_flags = SA_RESTART,
2129 if (sigaction(sig, &sa, NULL) < 0)
2133 while ((sig = va_arg(ap, int)) > 0)
2134 if (sigaction(sig, &sa, NULL) < 0)
2141 int close_pipe(int p[]) {
2147 a = close_nointr(p[0]);
2152 b = close_nointr(p[1]);
2156 return a < 0 ? a : b;
2159 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2168 while (nbytes > 0) {
2171 if ((k = read(fd, p, nbytes)) <= 0) {
2173 if (k < 0 && errno == EINTR)
2176 if (k < 0 && errno == EAGAIN && do_poll) {
2177 struct pollfd pollfd = {
2182 if (poll(&pollfd, 1, -1) < 0) {
2186 return n > 0 ? n : -errno;
2189 if (pollfd.revents != POLLIN)
2190 return n > 0 ? n : -EIO;
2195 return n > 0 ? n : (k < 0 ? -errno : 0);
2206 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2215 while (nbytes > 0) {
2218 k = write(fd, p, nbytes);
2221 if (k < 0 && errno == EINTR)
2224 if (k < 0 && errno == EAGAIN && do_poll) {
2225 struct pollfd pollfd = {
2230 if (poll(&pollfd, 1, -1) < 0) {
2234 return n > 0 ? n : -errno;
2237 if (pollfd.revents != POLLOUT)
2238 return n > 0 ? n : -EIO;
2243 return n > 0 ? n : (k < 0 ? -errno : 0);
2254 int parse_bytes(const char *t, off_t *bytes) {
2255 static const struct {
2261 { "M", 1024ULL*1024ULL },
2262 { "G", 1024ULL*1024ULL*1024ULL },
2263 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2264 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2265 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2282 l = strtoll(p, &e, 10);
2293 e += strspn(e, WHITESPACE);
2295 for (i = 0; i < ELEMENTSOF(table); i++)
2296 if (startswith(e, table[i].suffix)) {
2297 r += (off_t) l * table[i].factor;
2298 p = e + strlen(table[i].suffix);
2302 if (i >= ELEMENTSOF(table))
2312 int make_stdio(int fd) {
2317 r = dup3(fd, STDIN_FILENO, 0);
2318 s = dup3(fd, STDOUT_FILENO, 0);
2319 t = dup3(fd, STDERR_FILENO, 0);
2322 close_nointr_nofail(fd);
2324 if (r < 0 || s < 0 || t < 0)
2327 /* We rely here that the new fd has O_CLOEXEC not set */
2332 int make_null_stdio(void) {
2335 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2339 return make_stdio(null_fd);
2342 bool is_device_path(const char *path) {
2344 /* Returns true on paths that refer to a device, either in
2345 * sysfs or in /dev */
2348 path_startswith(path, "/dev/") ||
2349 path_startswith(path, "/sys/");
2352 int dir_is_empty(const char *path) {
2353 _cleanup_closedir_ DIR *d;
2362 union dirent_storage buf;
2364 r = readdir_r(d, &buf.de, &de);
2371 if (!ignore_file(de->d_name))
2376 char* dirname_malloc(const char *path) {
2377 char *d, *dir, *dir2;
2394 unsigned long long random_ull(void) {
2395 _cleanup_close_ int fd;
2399 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2403 r = loop_read(fd, &ull, sizeof(ull), true);
2404 if (r != sizeof(ull))
2410 return random() * RAND_MAX + random();
2413 void rename_process(const char name[8]) {
2416 /* This is a like a poor man's setproctitle(). It changes the
2417 * comm field, argv[0], and also the glibc's internally used
2418 * name of the process. For the first one a limit of 16 chars
2419 * applies, to the second one usually one of 10 (i.e. length
2420 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2421 * "systemd"). If you pass a longer string it will be
2424 prctl(PR_SET_NAME, name);
2426 if (program_invocation_name)
2427 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2429 if (saved_argc > 0) {
2433 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2435 for (i = 1; i < saved_argc; i++) {
2439 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2444 void sigset_add_many(sigset_t *ss, ...) {
2451 while ((sig = va_arg(ap, int)) > 0)
2452 assert_se(sigaddset(ss, sig) == 0);
2456 char* gethostname_malloc(void) {
2459 assert_se(uname(&u) >= 0);
2461 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2462 return strdup(u.nodename);
2464 return strdup(u.sysname);
2467 bool hostname_is_set(void) {
2470 assert_se(uname(&u) >= 0);
2472 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2475 static char *lookup_uid(uid_t uid) {
2478 _cleanup_free_ char *buf = NULL;
2479 struct passwd pwbuf, *pw = NULL;
2481 /* Shortcut things to avoid NSS lookups */
2483 return strdup("root");
2485 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2489 buf = malloc(bufsize);
2493 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2494 return strdup(pw->pw_name);
2496 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2502 char* getlogname_malloc(void) {
2506 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2511 return lookup_uid(uid);
2514 char *getusername_malloc(void) {
2521 return lookup_uid(getuid());
2524 int getttyname_malloc(int fd, char **r) {
2525 char path[PATH_MAX], *c;
2530 k = ttyname_r(fd, path, sizeof(path));
2536 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2544 int getttyname_harder(int fd, char **r) {
2548 k = getttyname_malloc(fd, &s);
2552 if (streq(s, "tty")) {
2554 return get_ctty(0, NULL, r);
2561 int get_ctty_devnr(pid_t pid, dev_t *d) {
2563 char line[LINE_MAX], *p, *fn;
2564 unsigned long ttynr;
2567 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2570 f = fopen(fn, "re");
2575 if (!fgets(line, sizeof(line), f)) {
2576 k = feof(f) ? -EIO : -errno;
2583 p = strrchr(line, ')');
2593 "%*d " /* session */
2598 if (major(ttynr) == 0 && minor(ttynr) == 0)
2605 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2607 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2612 k = get_ctty_devnr(pid, &devnr);
2616 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2618 k = readlink_malloc(fn, &s);
2624 /* This is an ugly hack */
2625 if (major(devnr) == 136) {
2626 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2636 /* Probably something like the ptys which have no
2637 * symlink in /dev/char. Let's return something
2638 * vaguely useful. */
2651 if (startswith(s, "/dev/"))
2653 else if (startswith(s, "../"))
2671 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2677 /* This returns the first error we run into, but nevertheless
2678 * tries to go on. This closes the passed fd. */
2682 close_nointr_nofail(fd);
2684 return errno == ENOENT ? 0 : -errno;
2689 union dirent_storage buf;
2690 bool is_dir, keep_around;
2694 r = readdir_r(d, &buf.de, &de);
2695 if (r != 0 && ret == 0) {
2703 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2706 if (de->d_type == DT_UNKNOWN ||
2708 (de->d_type == DT_DIR && root_dev)) {
2709 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2710 if (ret == 0 && errno != ENOENT)
2715 is_dir = S_ISDIR(st.st_mode);
2718 (st.st_uid == 0 || st.st_uid == getuid()) &&
2719 (st.st_mode & S_ISVTX);
2721 is_dir = de->d_type == DT_DIR;
2722 keep_around = false;
2728 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2729 if (root_dev && st.st_dev != root_dev->st_dev)
2732 subdir_fd = openat(fd, de->d_name,
2733 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2734 if (subdir_fd < 0) {
2735 if (ret == 0 && errno != ENOENT)
2740 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2741 if (r < 0 && ret == 0)
2745 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2746 if (ret == 0 && errno != ENOENT)
2750 } else if (!only_dirs && !keep_around) {
2752 if (unlinkat(fd, de->d_name, 0) < 0) {
2753 if (ret == 0 && errno != ENOENT)
2764 static int is_temporary_fs(struct statfs *s) {
2766 return s->f_type == TMPFS_MAGIC ||
2767 (long)s->f_type == (long)RAMFS_MAGIC;
2770 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2775 if (fstatfs(fd, &s) < 0) {
2776 close_nointr_nofail(fd);
2780 /* We refuse to clean disk file systems with this call. This
2781 * is extra paranoia just to be sure we never ever remove
2783 if (!is_temporary_fs(&s)) {
2784 log_error("Attempted to remove disk file system, and we can't allow that.");
2785 close_nointr_nofail(fd);
2789 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2792 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2798 /* We refuse to clean the root file system with this
2799 * call. This is extra paranoia to never cause a really
2800 * seriously broken system. */
2801 if (path_equal(path, "/")) {
2802 log_error("Attempted to remove entire root file system, and we can't allow that.");
2806 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2809 if (errno != ENOTDIR)
2813 if (statfs(path, &s) < 0)
2816 if (!is_temporary_fs(&s)) {
2817 log_error("Attempted to remove disk file system, and we can't allow that.");
2822 if (delete_root && !only_dirs)
2823 if (unlink(path) < 0 && errno != ENOENT)
2830 if (fstatfs(fd, &s) < 0) {
2831 close_nointr_nofail(fd);
2835 if (!is_temporary_fs(&s)) {
2836 log_error("Attempted to remove disk file system, and we can't allow that.");
2837 close_nointr_nofail(fd);
2842 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2845 if (honour_sticky && file_is_priv_sticky(path) > 0)
2848 if (rmdir(path) < 0 && errno != ENOENT) {
2857 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2858 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2861 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2862 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2865 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2868 /* Under the assumption that we are running privileged we
2869 * first change the access mode and only then hand out
2870 * ownership to avoid a window where access is too open. */
2872 if (mode != (mode_t) -1)
2873 if (chmod(path, mode) < 0)
2876 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2877 if (chown(path, uid, gid) < 0)
2883 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2886 /* Under the assumption that we are running privileged we
2887 * first change the access mode and only then hand out
2888 * ownership to avoid a window where access is too open. */
2890 if (fchmod(fd, mode) < 0)
2893 if (fchown(fd, uid, gid) < 0)
2899 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2903 /* Allocates the cpuset in the right size */
2906 if (!(r = CPU_ALLOC(n)))
2909 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2910 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2920 if (errno != EINVAL)
2927 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2928 static const char status_indent[] = " "; /* "[" STATUS "] " */
2929 _cleanup_free_ char *s = NULL;
2930 _cleanup_close_ int fd = -1;
2931 struct iovec iovec[6] = {};
2933 static bool prev_ephemeral;
2937 /* This is independent of logging, as status messages are
2938 * optional and go exclusively to the console. */
2940 if (vasprintf(&s, format, ap) < 0)
2943 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2956 sl = status ? sizeof(status_indent)-1 : 0;
2962 e = ellipsize(s, emax, 75);
2970 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2971 prev_ephemeral = ephemeral;
2974 if (!isempty(status)) {
2975 IOVEC_SET_STRING(iovec[n++], "[");
2976 IOVEC_SET_STRING(iovec[n++], status);
2977 IOVEC_SET_STRING(iovec[n++], "] ");
2979 IOVEC_SET_STRING(iovec[n++], status_indent);
2982 IOVEC_SET_STRING(iovec[n++], s);
2984 IOVEC_SET_STRING(iovec[n++], "\n");
2986 if (writev(fd, iovec, n) < 0)
2992 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2998 va_start(ap, format);
2999 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3005 int status_welcome(void) {
3007 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3009 r = parse_env_file("/etc/os-release", NEWLINE,
3010 "PRETTY_NAME", &pretty_name,
3011 "ANSI_COLOR", &ansi_color,
3013 if (r < 0 && r != -ENOENT)
3014 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3016 return status_printf(NULL, false, false,
3017 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3018 isempty(ansi_color) ? "1" : ansi_color,
3019 isempty(pretty_name) ? "Linux" : pretty_name);
3022 char *replace_env(const char *format, char **env) {
3029 const char *e, *word = format;
3034 for (e = format; *e; e ++) {
3045 if (!(k = strnappend(r, word, e-word-1)))
3054 } else if (*e == '$') {
3055 if (!(k = strnappend(r, word, e-word)))
3071 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3073 k = strappend(r, t);
3087 if (!(k = strnappend(r, word, e-word)))
3098 char **replace_env_argv(char **argv, char **env) {
3100 unsigned k = 0, l = 0;
3102 l = strv_length(argv);
3104 if (!(r = new(char*, l+1)))
3107 STRV_FOREACH(i, argv) {
3109 /* If $FOO appears as single word, replace it by the split up variable */
3110 if ((*i)[0] == '$' && (*i)[1] != '{') {
3115 e = strv_env_get(env, *i+1);
3118 if (!(m = strv_split_quoted(e))) {
3129 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3138 memcpy(r + k, m, q * sizeof(char*));
3146 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3147 if (!(r[k++] = replace_env(*i, env))) {
3157 int fd_columns(int fd) {
3158 struct winsize ws = {};
3160 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3169 unsigned columns(void) {
3173 if (_likely_(cached_columns > 0))
3174 return cached_columns;
3177 e = getenv("COLUMNS");
3182 c = fd_columns(STDOUT_FILENO);
3191 int fd_lines(int fd) {
3192 struct winsize ws = {};
3194 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3203 unsigned lines(void) {
3207 if (_likely_(cached_lines > 0))
3208 return cached_lines;
3211 e = getenv("LINES");
3216 l = fd_lines(STDOUT_FILENO);
3222 return cached_lines;
3225 /* intended to be used as a SIGWINCH sighandler */
3226 void columns_lines_cache_reset(int signum) {
3232 static int cached_on_tty = -1;
3234 if (_unlikely_(cached_on_tty < 0))
3235 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3237 return cached_on_tty;
3240 int running_in_chroot(void) {
3241 struct stat a = {}, b = {};
3243 /* Only works as root */
3244 if (stat("/proc/1/root", &a) < 0)
3247 if (stat("/", &b) < 0)
3251 a.st_dev != b.st_dev ||
3252 a.st_ino != b.st_ino;
3255 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3260 assert(percent <= 100);
3261 assert(new_length >= 3);
3263 if (old_length <= 3 || old_length <= new_length)
3264 return strndup(s, old_length);
3266 r = new0(char, new_length+1);
3270 x = (new_length * percent) / 100;
3272 if (x > new_length - 3)
3280 s + old_length - (new_length - x - 3),
3281 new_length - x - 3);
3286 char *ellipsize(const char *s, size_t length, unsigned percent) {
3287 return ellipsize_mem(s, strlen(s), length, percent);
3290 int touch(const char *path) {
3295 /* This just opens the file for writing, ensuring it
3296 * exists. It doesn't call utimensat() the way /usr/bin/touch
3299 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3303 close_nointr_nofail(fd);
3307 char *unquote(const char *s, const char* quotes) {
3311 /* This is rather stupid, simply removes the heading and
3312 * trailing quotes if there is one. Doesn't care about
3313 * escaping or anything. We should make this smarter one
3320 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3321 return strndup(s+1, l-2);
3326 char *normalize_env_assignment(const char *s) {
3327 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3330 eq = strchr(s, '=');
3342 memmove(r, t, strlen(t) + 1);
3346 name = strndup(s, eq - s);
3354 value = unquote(strstrip(p), QUOTES);
3358 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3364 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3375 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3387 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3394 r = wait_for_terminate(pid, &status);
3396 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3400 if (status.si_code == CLD_EXITED) {
3401 if (status.si_status != 0) {
3402 log_warning("%s failed with error code %i.", name, status.si_status);
3403 return status.si_status;
3406 log_debug("%s succeeded.", name);
3409 } else if (status.si_code == CLD_KILLED ||
3410 status.si_code == CLD_DUMPED) {
3412 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3416 log_warning("%s failed due to unknown reason.", name);
3420 _noreturn_ void freeze(void) {
3422 /* Make sure nobody waits for us on a socket anymore */
3423 close_all_fds(NULL, 0);
3431 bool null_or_empty(struct stat *st) {
3434 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3437 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3443 int null_or_empty_path(const char *fn) {
3448 if (stat(fn, &st) < 0)
3451 return null_or_empty(&st);
3454 DIR *xopendirat(int fd, const char *name, int flags) {
3458 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3464 close_nointr_nofail(nfd);
3471 int signal_from_string_try_harder(const char *s) {
3475 signo = signal_from_string(s);
3477 if (startswith(s, "SIG"))
3478 return signal_from_string(s+3);
3483 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3487 /* FIXME: to follow udev's logic 100% we need to leave valid
3488 * UTF8 chars unescaped */
3490 u = unquote(tagvalue, "\"\'");
3494 t = xescape(u, "/ ");
3500 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3509 char *fstab_node_to_udev_node(const char *p) {
3512 if (startswith(p, "LABEL="))
3513 return tag_to_udev_node(p+6, "label");
3515 if (startswith(p, "UUID="))
3516 return tag_to_udev_node(p+5, "uuid");
3518 if (startswith(p, "PARTUUID="))
3519 return tag_to_udev_node(p+9, "partuuid");
3521 if (startswith(p, "PARTLABEL="))
3522 return tag_to_udev_node(p+10, "partlabel");
3527 bool tty_is_vc(const char *tty) {
3530 if (startswith(tty, "/dev/"))
3533 return vtnr_from_tty(tty) >= 0;
3536 bool tty_is_console(const char *tty) {
3539 if (startswith(tty, "/dev/"))
3542 return streq(tty, "console");
3545 int vtnr_from_tty(const char *tty) {
3550 if (startswith(tty, "/dev/"))
3553 if (!startswith(tty, "tty") )
3556 if (tty[3] < '0' || tty[3] > '9')
3559 r = safe_atoi(tty+3, &i);
3563 if (i < 0 || i > 63)
3569 char *resolve_dev_console(char **active) {
3572 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3573 * (i.e. not read-only-mounted which is a sign for container setups) */
3575 if (path_is_read_only_fs("/sys") > 0)
3578 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3581 /* If multiple log outputs are configured the last one is what
3582 * /dev/console points to */
3583 tty = strrchr(*active, ' ');
3592 bool tty_is_vc_resolve(const char *tty) {
3593 char *active = NULL;
3598 if (startswith(tty, "/dev/"))
3601 if (streq(tty, "console")) {
3602 tty = resolve_dev_console(&active);
3613 const char *default_term_for_tty(const char *tty) {
3616 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3619 bool dirent_is_file(const struct dirent *de) {
3622 if (ignore_file(de->d_name))
3625 if (de->d_type != DT_REG &&
3626 de->d_type != DT_LNK &&
3627 de->d_type != DT_UNKNOWN)
3633 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3636 if (de->d_type != DT_REG &&
3637 de->d_type != DT_LNK &&
3638 de->d_type != DT_UNKNOWN)
3641 if (ignore_file_allow_backup(de->d_name))
3644 return endswith(de->d_name, suffix);
3647 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3650 Hashmap *pids = NULL;
3654 /* Executes all binaries in a directory in parallel and
3655 * waits for them to finish. */
3658 if (!(_d = opendir(directory))) {
3660 if (errno == ENOENT)
3663 log_error("Failed to enumerate directory %s: %m", directory);
3670 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3671 log_error("Failed to allocate set.");
3675 while ((de = readdir(d))) {
3680 if (!dirent_is_file(de))
3683 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3688 if ((pid = fork()) < 0) {
3689 log_error("Failed to fork: %m");
3707 log_error("Failed to execute %s: %m", path);
3708 _exit(EXIT_FAILURE);
3711 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3713 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3714 log_error("Failed to add PID to set: %s", strerror(-k));
3719 while (!hashmap_isempty(pids)) {
3720 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3724 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3729 log_error("waitid() failed: %m");
3733 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3734 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3735 if (si.si_code == CLD_EXITED)
3736 log_error("%s exited with exit status %i.", path, si.si_status);
3738 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3740 log_debug("%s exited successfully.", path);
3751 hashmap_free_free(pids);
3754 int kill_and_sigcont(pid_t pid, int sig) {
3757 r = kill(pid, sig) < 0 ? -errno : 0;
3765 bool nulstr_contains(const char*nulstr, const char *needle) {
3771 NULSTR_FOREACH(i, nulstr)
3772 if (streq(i, needle))
3778 bool plymouth_running(void) {
3779 return access("/run/plymouth/pid", F_OK) >= 0;
3782 char* strshorten(char *s, size_t l) {
3791 static bool hostname_valid_char(char c) {
3793 (c >= 'a' && c <= 'z') ||
3794 (c >= 'A' && c <= 'Z') ||
3795 (c >= '0' && c <= '9') ||
3801 bool hostname_is_valid(const char *s) {
3808 for (p = s, dot = true; *p; p++) {
3815 if (!hostname_valid_char(*p))
3825 if (p-s > HOST_NAME_MAX)
3831 char* hostname_cleanup(char *s) {
3834 for (p = s, d = s; *p; p++)
3835 if ((*p >= 'a' && *p <= 'z') ||
3836 (*p >= 'A' && *p <= 'Z') ||
3837 (*p >= '0' && *p <= '9') ||
3845 strshorten(s, HOST_NAME_MAX);
3849 int pipe_eof(int fd) {
3851 struct pollfd pollfd = {
3853 .events = POLLIN|POLLHUP,
3856 r = poll(&pollfd, 1, 0);
3863 return pollfd.revents & POLLHUP;
3866 int fd_wait_for_event(int fd, int event, usec_t t) {
3868 struct pollfd pollfd = {
3873 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3880 return pollfd.revents;
3883 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3894 t = new(char, strlen(path) + 1 + 6 + 1);
3898 fn = path_get_file_name(path);
3902 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3904 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3910 f = fdopen(fd, "we");
3923 int terminal_vhangup_fd(int fd) {
3926 if (ioctl(fd, TIOCVHANGUP) < 0)
3932 int terminal_vhangup(const char *name) {
3935 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3939 r = terminal_vhangup_fd(fd);
3940 close_nointr_nofail(fd);
3945 int vt_disallocate(const char *name) {
3949 /* Deallocate the VT if possible. If not possible
3950 * (i.e. because it is the active one), at least clear it
3951 * entirely (including the scrollback buffer) */
3953 if (!startswith(name, "/dev/"))
3956 if (!tty_is_vc(name)) {
3957 /* So this is not a VT. I guess we cannot deallocate
3958 * it then. But let's at least clear the screen */
3960 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3965 "\033[r" /* clear scrolling region */
3966 "\033[H" /* move home */
3967 "\033[2J", /* clear screen */
3969 close_nointr_nofail(fd);
3974 if (!startswith(name, "/dev/tty"))
3977 r = safe_atou(name+8, &u);
3984 /* Try to deallocate */
3985 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3989 r = ioctl(fd, VT_DISALLOCATE, u);
3990 close_nointr_nofail(fd);
3998 /* Couldn't deallocate, so let's clear it fully with
4000 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4005 "\033[r" /* clear scrolling region */
4006 "\033[H" /* move home */
4007 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4009 close_nointr_nofail(fd);
4014 int copy_file(const char *from, const char *to) {
4020 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4024 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4026 close_nointr_nofail(fdf);
4034 n = read(fdf, buf, sizeof(buf));
4038 close_nointr_nofail(fdf);
4049 k = loop_write(fdt, buf, n, false);
4051 r = k < 0 ? k : (errno ? -errno : -EIO);
4053 close_nointr_nofail(fdf);
4061 close_nointr_nofail(fdf);
4062 r = close_nointr(fdt);
4072 int symlink_atomic(const char *from, const char *to) {
4074 _cleanup_free_ char *t;
4077 unsigned long long ull;
4084 t = new(char, strlen(to) + 1 + 16 + 1);
4088 fn = path_get_file_name(to);
4092 x = stpcpy(t+k+1, fn);
4095 for (i = 0; i < 16; i++) {
4096 *(x++) = hexchar(ull & 0xF);
4102 if (symlink(from, t) < 0)
4105 if (rename(t, to) < 0) {
4114 bool display_is_local(const char *display) {
4118 display[0] == ':' &&
4119 display[1] >= '0' &&
4123 int socket_from_display(const char *display, char **path) {
4130 if (!display_is_local(display))
4133 k = strspn(display+1, "0123456789");
4135 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4139 c = stpcpy(f, "/tmp/.X11-unix/X");
4140 memcpy(c, display+1, k);
4149 const char **username,
4150 uid_t *uid, gid_t *gid,
4152 const char **shell) {
4160 /* We enforce some special rules for uid=0: in order to avoid
4161 * NSS lookups for root we hardcode its data. */
4163 if (streq(*username, "root") || streq(*username, "0")) {
4181 if (parse_uid(*username, &u) >= 0) {
4185 /* If there are multiple users with the same id, make
4186 * sure to leave $USER to the configured value instead
4187 * of the first occurrence in the database. However if
4188 * the uid was configured by a numeric uid, then let's
4189 * pick the real username from /etc/passwd. */
4191 *username = p->pw_name;
4194 p = getpwnam(*username);
4198 return errno > 0 ? -errno : -ESRCH;
4210 *shell = p->pw_shell;
4215 char* uid_to_name(uid_t uid) {
4220 return strdup("root");
4224 return strdup(p->pw_name);
4226 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4232 char* gid_to_name(gid_t gid) {
4237 return strdup("root");
4241 return strdup(p->gr_name);
4243 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4249 int get_group_creds(const char **groupname, gid_t *gid) {
4255 /* We enforce some special rules for gid=0: in order to avoid
4256 * NSS lookups for root we hardcode its data. */
4258 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4259 *groupname = "root";
4267 if (parse_gid(*groupname, &id) >= 0) {
4272 *groupname = g->gr_name;
4275 g = getgrnam(*groupname);
4279 return errno > 0 ? -errno : -ESRCH;
4287 int in_gid(gid_t gid) {
4289 int ngroups_max, r, i;
4291 if (getgid() == gid)
4294 if (getegid() == gid)
4297 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4298 assert(ngroups_max > 0);
4300 gids = alloca(sizeof(gid_t) * ngroups_max);
4302 r = getgroups(ngroups_max, gids);
4306 for (i = 0; i < r; i++)
4313 int in_group(const char *name) {
4317 r = get_group_creds(&name, &gid);
4324 int glob_exists(const char *path) {
4325 glob_t _cleanup_globfree_ g = {};
4331 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4333 if (k == GLOB_NOMATCH)
4335 else if (k == GLOB_NOSPACE)
4338 r = !strv_isempty(g.gl_pathv);
4340 r = errno ? -errno : -EIO;
4345 int dirent_ensure_type(DIR *d, struct dirent *de) {
4351 if (de->d_type != DT_UNKNOWN)
4354 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4358 S_ISREG(st.st_mode) ? DT_REG :
4359 S_ISDIR(st.st_mode) ? DT_DIR :
4360 S_ISLNK(st.st_mode) ? DT_LNK :
4361 S_ISFIFO(st.st_mode) ? DT_FIFO :
4362 S_ISSOCK(st.st_mode) ? DT_SOCK :
4363 S_ISCHR(st.st_mode) ? DT_CHR :
4364 S_ISBLK(st.st_mode) ? DT_BLK :
4370 int in_search_path(const char *path, char **search) {
4374 r = path_get_parent(path, &parent);
4380 STRV_FOREACH(i, search) {
4381 if (path_equal(parent, *i)) {
4392 int get_files_in_directory(const char *path, char ***list) {
4400 /* Returns all files in a directory in *list, and the number
4401 * of files as return value. If list is NULL returns only the
4410 union dirent_storage buf;
4413 k = readdir_r(d, &buf.de, &de);
4422 dirent_ensure_type(d, de);
4424 if (!dirent_is_file(de))
4428 if ((unsigned) r >= n) {
4432 t = realloc(l, sizeof(char*) * n);
4441 assert((unsigned) r < n);
4443 l[r] = strdup(de->d_name);
4467 char *strjoin(const char *x, ...) {
4481 t = va_arg(ap, const char *);
4486 if (n > ((size_t) -1) - l) {
4510 t = va_arg(ap, const char *);
4524 bool is_main_thread(void) {
4525 static __thread int cached = 0;
4527 if (_unlikely_(cached == 0))
4528 cached = getpid() == gettid() ? 1 : -1;
4533 int block_get_whole_disk(dev_t d, dev_t *ret) {
4540 /* If it has a queue this is good enough for us */
4541 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4544 r = access(p, F_OK);
4552 /* If it is a partition find the originating device */
4553 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4556 r = access(p, F_OK);
4562 /* Get parent dev_t */
4563 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4566 r = read_one_line_file(p, &s);
4572 r = sscanf(s, "%u:%u", &m, &n);
4578 /* Only return this if it is really good enough for us. */
4579 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4582 r = access(p, F_OK);
4586 *ret = makedev(m, n);
4593 int file_is_priv_sticky(const char *p) {
4598 if (lstat(p, &st) < 0)
4602 (st.st_uid == 0 || st.st_uid == getuid()) &&
4603 (st.st_mode & S_ISVTX);
4606 static const char *const ioprio_class_table[] = {
4607 [IOPRIO_CLASS_NONE] = "none",
4608 [IOPRIO_CLASS_RT] = "realtime",
4609 [IOPRIO_CLASS_BE] = "best-effort",
4610 [IOPRIO_CLASS_IDLE] = "idle"
4613 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4615 static const char *const sigchld_code_table[] = {
4616 [CLD_EXITED] = "exited",
4617 [CLD_KILLED] = "killed",
4618 [CLD_DUMPED] = "dumped",
4619 [CLD_TRAPPED] = "trapped",
4620 [CLD_STOPPED] = "stopped",
4621 [CLD_CONTINUED] = "continued",
4624 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4626 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4627 [LOG_FAC(LOG_KERN)] = "kern",
4628 [LOG_FAC(LOG_USER)] = "user",
4629 [LOG_FAC(LOG_MAIL)] = "mail",
4630 [LOG_FAC(LOG_DAEMON)] = "daemon",
4631 [LOG_FAC(LOG_AUTH)] = "auth",
4632 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4633 [LOG_FAC(LOG_LPR)] = "lpr",
4634 [LOG_FAC(LOG_NEWS)] = "news",
4635 [LOG_FAC(LOG_UUCP)] = "uucp",
4636 [LOG_FAC(LOG_CRON)] = "cron",
4637 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4638 [LOG_FAC(LOG_FTP)] = "ftp",
4639 [LOG_FAC(LOG_LOCAL0)] = "local0",
4640 [LOG_FAC(LOG_LOCAL1)] = "local1",
4641 [LOG_FAC(LOG_LOCAL2)] = "local2",
4642 [LOG_FAC(LOG_LOCAL3)] = "local3",
4643 [LOG_FAC(LOG_LOCAL4)] = "local4",
4644 [LOG_FAC(LOG_LOCAL5)] = "local5",
4645 [LOG_FAC(LOG_LOCAL6)] = "local6",
4646 [LOG_FAC(LOG_LOCAL7)] = "local7"
4649 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4651 static const char *const log_level_table[] = {
4652 [LOG_EMERG] = "emerg",
4653 [LOG_ALERT] = "alert",
4654 [LOG_CRIT] = "crit",
4656 [LOG_WARNING] = "warning",
4657 [LOG_NOTICE] = "notice",
4658 [LOG_INFO] = "info",
4659 [LOG_DEBUG] = "debug"
4662 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4664 static const char* const sched_policy_table[] = {
4665 [SCHED_OTHER] = "other",
4666 [SCHED_BATCH] = "batch",
4667 [SCHED_IDLE] = "idle",
4668 [SCHED_FIFO] = "fifo",
4672 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4674 static const char* const rlimit_table[] = {
4675 [RLIMIT_CPU] = "LimitCPU",
4676 [RLIMIT_FSIZE] = "LimitFSIZE",
4677 [RLIMIT_DATA] = "LimitDATA",
4678 [RLIMIT_STACK] = "LimitSTACK",
4679 [RLIMIT_CORE] = "LimitCORE",
4680 [RLIMIT_RSS] = "LimitRSS",
4681 [RLIMIT_NOFILE] = "LimitNOFILE",
4682 [RLIMIT_AS] = "LimitAS",
4683 [RLIMIT_NPROC] = "LimitNPROC",
4684 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4685 [RLIMIT_LOCKS] = "LimitLOCKS",
4686 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4687 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4688 [RLIMIT_NICE] = "LimitNICE",
4689 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4690 [RLIMIT_RTTIME] = "LimitRTTIME"
4693 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4695 static const char* const ip_tos_table[] = {
4696 [IPTOS_LOWDELAY] = "low-delay",
4697 [IPTOS_THROUGHPUT] = "throughput",
4698 [IPTOS_RELIABILITY] = "reliability",
4699 [IPTOS_LOWCOST] = "low-cost",
4702 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4704 static const char *const __signal_table[] = {
4721 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4732 [SIGVTALRM] = "VTALRM",
4734 [SIGWINCH] = "WINCH",
4740 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4742 const char *signal_to_string(int signo) {
4743 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4746 name = __signal_to_string(signo);
4750 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4751 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4753 snprintf(buf, sizeof(buf), "%d", signo);
4758 int signal_from_string(const char *s) {
4763 signo = __signal_from_string(s);
4767 if (startswith(s, "RTMIN+")) {
4771 if (safe_atou(s, &u) >= 0) {
4772 signo = (int) u + offset;
4773 if (signo > 0 && signo < _NSIG)
4779 bool kexec_loaded(void) {
4780 bool loaded = false;
4783 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4791 int strdup_or_null(const char *a, char **b) {
4809 int prot_from_flags(int flags) {
4811 switch (flags & O_ACCMODE) {
4820 return PROT_READ|PROT_WRITE;
4827 char *format_bytes(char *buf, size_t l, off_t t) {
4830 static const struct {
4834 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4835 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4836 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4837 { "G", 1024ULL*1024ULL*1024ULL },
4838 { "M", 1024ULL*1024ULL },
4842 for (i = 0; i < ELEMENTSOF(table); i++) {
4844 if (t >= table[i].factor) {
4847 (unsigned long long) (t / table[i].factor),
4848 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4855 snprintf(buf, l, "%lluB", (unsigned long long) t);
4863 void* memdup(const void *p, size_t l) {
4876 int fd_inc_sndbuf(int fd, size_t n) {
4878 socklen_t l = sizeof(value);
4880 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4882 l == sizeof(value) &&
4883 (size_t) value >= n*2)
4887 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4894 int fd_inc_rcvbuf(int fd, size_t n) {
4896 socklen_t l = sizeof(value);
4898 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4900 l == sizeof(value) &&
4901 (size_t) value >= n*2)
4905 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4912 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4913 pid_t parent_pid, agent_pid;
4915 bool stdout_is_tty, stderr_is_tty;
4923 parent_pid = getpid();
4925 /* Spawns a temporary TTY agent, making sure it goes away when
4932 if (agent_pid != 0) {
4939 * Make sure the agent goes away when the parent dies */
4940 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4941 _exit(EXIT_FAILURE);
4943 /* Check whether our parent died before we were able
4944 * to set the death signal */
4945 if (getppid() != parent_pid)
4946 _exit(EXIT_SUCCESS);
4948 /* Don't leak fds to the agent */
4949 close_all_fds(except, n_except);
4951 stdout_is_tty = isatty(STDOUT_FILENO);
4952 stderr_is_tty = isatty(STDERR_FILENO);
4954 if (!stdout_is_tty || !stderr_is_tty) {
4955 /* Detach from stdout/stderr. and reopen
4956 * /dev/tty for them. This is important to
4957 * ensure that when systemctl is started via
4958 * popen() or a similar call that expects to
4959 * read EOF we actually do generate EOF and
4960 * not delay this indefinitely by because we
4961 * keep an unused copy of stdin around. */
4962 fd = open("/dev/tty", O_WRONLY);
4964 log_error("Failed to open /dev/tty: %m");
4965 _exit(EXIT_FAILURE);
4969 dup2(fd, STDOUT_FILENO);
4972 dup2(fd, STDERR_FILENO);
4978 /* Count arguments */
4980 for (n = 0; va_arg(ap, char*); n++)
4985 l = alloca(sizeof(char *) * (n + 1));
4987 /* Fill in arguments */
4989 for (i = 0; i <= n; i++)
4990 l[i] = va_arg(ap, char*);
4994 _exit(EXIT_FAILURE);
4997 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4998 struct rlimit highest, fixed;
5002 if (setrlimit(resource, rlim) >= 0)
5008 /* So we failed to set the desired setrlimit, then let's try
5009 * to get as close as we can */
5010 assert_se(getrlimit(resource, &highest) == 0);
5012 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5013 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5015 if (setrlimit(resource, &fixed) < 0)
5021 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5022 char path[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/environ")], *value = NULL;
5034 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5036 f = fopen(path, "re");
5044 char line[LINE_MAX];
5047 for (i = 0; i < sizeof(line)-1; i++) {
5051 if (_unlikely_(c == EOF)) {
5061 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5062 value = strdup(line + l + 1);
5082 int can_sleep(const char *type) {
5086 _cleanup_free_ char *p = NULL;
5090 /* If /sys is read-only we cannot sleep */
5091 if (access("/sys/power/state", W_OK) < 0)
5094 r = read_one_line_file("/sys/power/state", &p);
5099 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5100 if (l == k && memcmp(w, type, l) == 0)
5106 int can_sleep_disk(const char *type) {
5110 _cleanup_free_ char *p = NULL;
5114 /* If /sys is read-only we cannot sleep */
5115 if (access("/sys/power/state", W_OK) < 0 ||
5116 access("/sys/power/disk", W_OK) < 0)
5119 r = read_one_line_file("/sys/power/disk", &p);
5124 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5125 if (l == k && memcmp(w, type, l) == 0)
5128 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5135 bool is_valid_documentation_url(const char *url) {
5138 if (startswith(url, "http://") && url[7])
5141 if (startswith(url, "https://") && url[8])
5144 if (startswith(url, "file:") && url[5])
5147 if (startswith(url, "info:") && url[5])
5150 if (startswith(url, "man:") && url[4])
5156 bool in_initrd(void) {
5157 static __thread int saved = -1;
5163 /* We make two checks here:
5165 * 1. the flag file /etc/initrd-release must exist
5166 * 2. the root file system must be a memory file system
5168 * The second check is extra paranoia, since misdetecting an
5169 * initrd can have bad bad consequences due the initrd
5170 * emptying when transititioning to the main systemd.
5173 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5174 statfs("/", &s) >= 0 &&
5175 is_temporary_fs(&s);
5180 void warn_melody(void) {
5181 _cleanup_close_ int fd = -1;
5183 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5187 /* Yeah, this is synchronous. Kinda sucks. But well... */
5189 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5190 usleep(125*USEC_PER_MSEC);
5192 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5193 usleep(125*USEC_PER_MSEC);
5195 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5196 usleep(125*USEC_PER_MSEC);
5198 ioctl(fd, KIOCSOUND, 0);
5201 int make_console_stdio(void) {
5204 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5206 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5208 log_error("Failed to acquire terminal: %s", strerror(-fd));
5214 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5221 int get_home_dir(char **_h) {
5229 /* Take the user specified one */
5240 /* Hardcode home directory for root to avoid NSS */
5243 h = strdup("/root");
5251 /* Check the database... */
5255 return errno ? -errno : -ESRCH;
5257 if (!path_is_absolute(p->pw_dir))
5260 h = strdup(p->pw_dir);
5268 void fclosep(FILE **f) {
5273 void pclosep(FILE **f) {
5278 void closep(int *fd) {
5280 close_nointr_nofail(*fd);
5283 void closedirp(DIR **d) {
5288 bool filename_is_safe(const char *p) {
5302 if (strlen(p) > FILENAME_MAX)
5308 bool string_is_safe(const char *p) {
5313 for (t = p; *t; t++) {
5314 if (*t > 0 && *t < ' ')
5317 if (strchr("\\\"\'", *t))
5324 bool string_has_cc(const char *p) {
5329 for (t = p; *t; t++)
5330 if (*t > 0 && *t < ' ')
5336 bool path_is_safe(const char *p) {
5341 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5344 if (strlen(p) > PATH_MAX)
5347 /* The following two checks are not really dangerous, but hey, they still are confusing */
5348 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5351 if (strstr(p, "//"))
5357 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5358 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5359 int (*compar) (const void *, const void *, void *), void *arg) {
5368 p = (void *)(((const char *) base) + (idx * size));
5369 comparison = compar(key, p, arg);
5372 else if (comparison > 0)
5380 bool is_locale_utf8(void) {
5382 static int cached_answer = -1;
5384 if (cached_answer >= 0)
5387 if (!setlocale(LC_ALL, "")) {
5388 cached_answer = true;
5392 set = nl_langinfo(CODESET);
5394 cached_answer = true;
5398 cached_answer = streq(set, "UTF-8");
5400 return (bool)cached_answer;
5403 const char *draw_special_char(DrawSpecialChar ch) {
5404 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5406 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5407 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5408 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5409 [DRAW_TREE_SPACE] = " ", /* */
5410 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5412 /* ASCII fallback */ {
5413 [DRAW_TREE_VERT] = "| ",
5414 [DRAW_TREE_BRANCH] = "|-",
5415 [DRAW_TREE_RIGHT] = "`-",
5416 [DRAW_TREE_SPACE] = " ",
5417 [DRAW_TRIANGULAR_BULLET] = "> ",
5421 return draw_table[!is_locale_utf8()][ch];
5424 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5427 size_t l, old_len, new_len;
5433 old_len = strlen(old_string);
5434 new_len = strlen(new_string);
5447 if (!startswith(f, old_string)) {
5453 nl = l - old_len + new_len;
5454 a = realloc(r, nl + 1);
5462 t = stpcpy(t, new_string);
5474 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5475 const char *i, *begin = NULL;
5480 } state = STATE_OTHER;
5482 size_t osz = 0, isz;
5488 /* Strips ANSI color and replaces TABs by 8 spaces */
5490 isz = _isz ? *_isz : strlen(*ibuf);
5492 f = open_memstream(&obuf, &osz);
5496 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5501 if (i >= *ibuf + isz) /* EOT */
5503 else if (*i == '\x1B')
5504 state = STATE_ESCAPE;
5505 else if (*i == '\t')
5512 if (i >= *ibuf + isz) { /* EOT */
5515 } else if (*i == '[') {
5516 state = STATE_BRACKET;
5521 state = STATE_OTHER;
5528 if (i >= *ibuf + isz || /* EOT */
5529 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5532 state = STATE_OTHER;
5534 } else if (*i == 'm')
5535 state = STATE_OTHER;
5557 int on_ac_power(void) {
5558 bool found_offline = false, found_online = false;
5559 _cleanup_closedir_ DIR *d = NULL;
5561 d = opendir("/sys/class/power_supply");
5567 union dirent_storage buf;
5568 _cleanup_close_ int fd = -1, device = -1;
5573 k = readdir_r(d, &buf.de, &de);
5580 if (ignore_file(de->d_name))
5583 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5585 if (errno == ENOENT || errno == ENOTDIR)
5591 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5593 if (errno == ENOENT)
5599 n = read(fd, contents, sizeof(contents));
5603 if (n != 6 || memcmp(contents, "Mains\n", 6))
5606 close_nointr_nofail(fd);
5607 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5609 if (errno == ENOENT)
5615 n = read(fd, contents, sizeof(contents));
5619 if (n != 2 || contents[1] != '\n')
5622 if (contents[0] == '1') {
5623 found_online = true;
5625 } else if (contents[0] == '0')
5626 found_offline = true;
5631 return found_online || !found_offline;
5634 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5641 if (!path_strv_canonicalize_uniq(search))
5644 STRV_FOREACH(i, search) {
5645 _cleanup_free_ char *p = NULL;
5648 p = strjoin(*i, "/", path, NULL);
5658 if (errno != ENOENT)
5665 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5666 _cleanup_strv_free_ char **copy = NULL;
5672 if (path_is_absolute(path)) {
5675 f = fopen(path, mode);
5684 copy = strv_copy((char**) search);
5688 return search_and_fopen_internal(path, mode, copy, _f);
5691 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5692 _cleanup_strv_free_ char **s = NULL;
5694 if (path_is_absolute(path)) {
5697 f = fopen(path, mode);
5706 s = strv_split_nulstr(search);
5710 return search_and_fopen_internal(path, mode, s, _f);
5713 int create_tmp_dir(char template[], char** dir_name) {
5719 RUN_WITH_UMASK(0077) {
5720 d = mkdtemp(template);
5723 log_error("Can't create directory %s: %m", template);
5727 dt = strjoin(d, "/tmp", NULL);
5733 RUN_WITH_UMASK(0000) {
5734 r = mkdir(dt, 0777);
5737 log_error("Can't create directory %s: %m", dt);
5741 log_debug("Created temporary directory %s", dt);
5743 r = chmod(dt, 0777 | S_ISVTX);
5745 log_error("Failed to chmod %s: %m", dt);
5749 log_debug("Set sticky bit on %s", dt);
5763 char *strextend(char **x, ...) {
5770 l = f = *x ? strlen(*x) : 0;
5777 t = va_arg(ap, const char *);
5782 if (n > ((size_t) -1) - l) {
5791 r = realloc(*x, l+1);
5801 t = va_arg(ap, const char *);
5815 char *strrep(const char *s, unsigned n) {
5823 p = r = malloc(l * n + 1);
5827 for (i = 0; i < n; i++)
5834 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5838 if (*allocated >= need)
5841 a = MAX(64u, need * 2);