1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
71 #include "path-util.h"
72 #include "exit-status.h"
78 char **saved_argv = NULL;
80 static volatile unsigned cached_columns = 0;
81 static volatile unsigned cached_lines = 0;
83 #define PROCFS_PATH_LEN (sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t))
85 #define FORMAT_PROCFS_PATH(buffer, path, pid) \
87 assert_cc(sizeof(buffer) == (PROCFS_PATH_LEN + 1 + sizeof(path))); \
88 snprintf(buffer, sizeof(buffer) - 1, "/proc/%lu/%s", (unsigned long) pid, path); \
89 char_array_0(buffer); \
93 size_t page_size(void) {
94 static __thread size_t pgsz = 0;
97 if (_likely_(pgsz > 0))
100 r = sysconf(_SC_PAGESIZE);
107 bool streq_ptr(const char *a, const char *b) {
109 /* Like streq(), but tries to make sense of NULL pointers */
120 char* endswith(const char *s, const char *postfix) {
127 pl = strlen(postfix);
130 return (char*) s + sl;
135 if (memcmp(s + sl - pl, postfix, pl) != 0)
138 return (char*) s + sl - pl;
141 char* startswith(const char *s, const char *prefix) {
158 char* startswith_no_case(const char *s, const char *prefix) {
168 if (tolower(*a) != tolower(*b))
175 bool first_word(const char *s, const char *word) {
190 if (memcmp(s, word, wl) != 0)
194 strchr(WHITESPACE, s[wl]);
197 int close_nointr(int fd) {
203 /* Just ignore EINTR; a retry loop is the wrong
204 * thing to do on Linux.
206 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
207 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
208 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
209 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
211 if (_unlikely_(r < 0 && errno == EINTR))
219 void close_nointr_nofail(int fd) {
222 /* like close_nointr() but cannot fail, and guarantees errno
225 assert_se(close_nointr(fd) == 0);
228 void close_many(const int fds[], unsigned n_fd) {
231 assert(fds || n_fd <= 0);
233 for (i = 0; i < n_fd; i++)
234 close_nointr_nofail(fds[i]);
237 int parse_boolean(const char *v) {
240 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
242 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
248 int parse_pid(const char *s, pid_t* ret_pid) {
249 unsigned long ul = 0;
256 r = safe_atolu(s, &ul);
262 if ((unsigned long) pid != ul)
272 int parse_uid(const char *s, uid_t* ret_uid) {
273 unsigned long ul = 0;
280 r = safe_atolu(s, &ul);
286 if ((unsigned long) uid != ul)
293 int safe_atou(const char *s, unsigned *ret_u) {
301 l = strtoul(s, &x, 0);
303 if (!x || x == s || *x || errno)
304 return errno > 0 ? -errno : -EINVAL;
306 if ((unsigned long) (unsigned) l != l)
309 *ret_u = (unsigned) l;
313 int safe_atoi(const char *s, int *ret_i) {
321 l = strtol(s, &x, 0);
323 if (!x || x == s || *x || errno)
324 return errno > 0 ? -errno : -EINVAL;
326 if ((long) (int) l != l)
333 int safe_atollu(const char *s, long long unsigned *ret_llu) {
335 unsigned long long l;
341 l = strtoull(s, &x, 0);
343 if (!x || x == s || *x || errno)
344 return errno ? -errno : -EINVAL;
350 int safe_atolli(const char *s, long long int *ret_lli) {
358 l = strtoll(s, &x, 0);
360 if (!x || x == s || *x || errno)
361 return errno ? -errno : -EINVAL;
367 int safe_atod(const char *s, double *ret_d) {
377 if (!x || x == s || *x || errno)
378 return errno ? -errno : -EINVAL;
384 /* Split a string into words. */
385 char *split(const char *c, size_t *l, const char *separator, char **state) {
388 current = *state ? *state : (char*) c;
390 if (!*current || *c == 0)
393 current += strspn(current, separator);
394 *l = strcspn(current, separator);
397 return (char*) current;
400 /* Split a string into words, but consider strings enclosed in '' and
401 * "" as words even if they include spaces. */
402 char *split_quoted(const char *c, size_t *l, char **state) {
404 bool escaped = false;
406 current = *state ? *state : (char*) c;
408 if (!*current || *c == 0)
411 current += strspn(current, WHITESPACE);
413 if (*current == '\'') {
416 for (e = current; *e; e++) {
426 *state = *e == 0 ? e : e+1;
427 } else if (*current == '\"') {
430 for (e = current; *e; e++) {
440 *state = *e == 0 ? e : e+1;
442 for (e = current; *e; e++) {
447 else if (strchr(WHITESPACE, *e))
454 return (char*) current;
457 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
459 _cleanup_fclose_ FILE *f = NULL;
460 char fn[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/stat")], line[LINE_MAX], *p;
466 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
472 if (!fgets(line, sizeof(line), f)) {
473 r = feof(f) ? -EIO : -errno;
477 /* Let's skip the pid and comm fields. The latter is enclosed
478 * in () but does not escape any () in its value, so let's
479 * skip over it manually */
481 p = strrchr(line, ')');
493 if ((long unsigned) (pid_t) ppid != ppid)
496 *_ppid = (pid_t) ppid;
501 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
502 _cleanup_fclose_ FILE *f = NULL;
503 char fn[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/stat")], line[LINE_MAX], *p;
508 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
514 if (!fgets(line, sizeof(line), f)) {
521 /* Let's skip the pid and comm fields. The latter is enclosed
522 * in () but does not escape any () in its value, so let's
523 * skip over it manually */
525 p = strrchr(line, ')');
547 "%*d " /* priority */
549 "%*d " /* num_threads */
550 "%*d " /* itrealvalue */
551 "%llu " /* starttime */,
558 int fchmod_umask(int fd, mode_t m) {
563 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
569 char *truncate_nl(char *s) {
572 s[strcspn(s, NEWLINE)] = 0;
576 int get_process_comm(pid_t pid, char **name) {
582 r = read_one_line_file("/proc/self/comm", name);
584 char path[PROCFS_PATH_LEN + sizeof("/comm")];
585 FORMAT_PROCFS_PATH(path, "comm", pid);
586 r = read_one_line_file(path, name);
592 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
600 f = fopen("/proc/self/cmdline", "re");
602 char path[PROCFS_PATH_LEN + sizeof("/cmdline")];
603 FORMAT_PROCFS_PATH(path, "cmdline", pid);
604 f = fopen(path, "re");
609 if (max_length == 0) {
611 while ((c = getc(f)) != EOF) {
612 k = realloc(r, len+1);
619 r[len-1] = isprint(c) ? c : ' ';
626 r = new(char, max_length);
634 while ((c = getc(f)) != EOF) {
656 size_t n = MIN(left-1, 3U);
665 /* Kernel threads have no argv[] */
666 if (r == NULL || r[0] == 0) {
675 h = get_process_comm(pid, &t);
679 r = strjoin("[", t, "]", NULL);
690 int is_kernel_thread(pid_t pid) {
691 char path[PROCFS_PATH_LEN + sizeof("/cmdline")];
700 FORMAT_PROCFS_PATH(path, "cmdline", pid);
701 f = fopen(path, "re");
706 count = fread(&c, 1, 1, f);
710 /* Kernel threads have an empty cmdline */
713 return eof ? 1 : -errno;
718 int get_process_exe(pid_t pid, char **name) {
724 r = readlink_malloc("/proc/self/exe", name);
726 char path[PROCFS_PATH_LEN + sizeof("/exe")];
727 FORMAT_PROCFS_PATH(path, "exe", pid);
728 r = readlink_malloc(path, name);
734 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
735 _cleanup_fclose_ FILE *f = NULL;
736 char path[PROCFS_PATH_LEN + sizeof("/status")];
745 FORMAT_PROCFS_PATH(path, "status", pid);
746 f = fopen(path, "re");
750 FOREACH_LINE(line, f, return -errno) {
755 if (startswith(l, field)) {
757 l += strspn(l, WHITESPACE);
759 l[strcspn(l, WHITESPACE)] = 0;
761 return parse_uid(l, uid);
768 int get_process_uid(pid_t pid, uid_t *uid) {
769 return get_process_id(pid, "Uid:", uid);
772 int get_process_gid(pid_t pid, gid_t *gid) {
773 return get_process_id(pid, "Gid:", gid);
776 char *strnappend(const char *s, const char *suffix, size_t b) {
784 return strndup(suffix, b);
793 if (b > ((size_t) -1) - a)
796 r = new(char, a+b+1);
801 memcpy(r+a, suffix, b);
807 char *strappend(const char *s, const char *suffix) {
808 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
811 int readlink_malloc(const char *p, char **r) {
821 if (!(c = new(char, l)))
824 if ((n = readlink(p, c, l-1)) < 0) {
830 if ((size_t) n < l-1) {
841 int readlink_and_make_absolute(const char *p, char **r) {
848 if ((j = readlink_malloc(p, &target)) < 0)
851 k = file_in_same_dir(p, target);
861 int readlink_and_canonicalize(const char *p, char **r) {
868 j = readlink_and_make_absolute(p, &t);
872 s = canonicalize_file_name(t);
879 path_kill_slashes(*r);
884 int reset_all_signal_handlers(void) {
887 for (sig = 1; sig < _NSIG; sig++) {
888 struct sigaction sa = {
889 .sa_handler = SIG_DFL,
890 .sa_flags = SA_RESTART,
893 if (sig == SIGKILL || sig == SIGSTOP)
896 /* On Linux the first two RT signals are reserved by
897 * glibc, and sigaction() will return EINVAL for them. */
898 if ((sigaction(sig, &sa, NULL) < 0))
906 char *strstrip(char *s) {
909 /* Drops trailing whitespace. Modifies the string in
910 * place. Returns pointer to first non-space character */
912 s += strspn(s, WHITESPACE);
914 for (e = strchr(s, 0); e > s; e --)
915 if (!strchr(WHITESPACE, e[-1]))
923 char *delete_chars(char *s, const char *bad) {
926 /* Drops all whitespace, regardless where in the string */
928 for (f = s, t = s; *f; f++) {
940 bool in_charset(const char *s, const char* charset) {
947 if (!strchr(charset, *i))
953 char *file_in_same_dir(const char *path, const char *filename) {
960 /* This removes the last component of path and appends
961 * filename, unless the latter is absolute anyway or the
964 if (path_is_absolute(filename))
965 return strdup(filename);
967 if (!(e = strrchr(path, '/')))
968 return strdup(filename);
970 k = strlen(filename);
971 if (!(r = new(char, e-path+1+k+1)))
974 memcpy(r, path, e-path+1);
975 memcpy(r+(e-path)+1, filename, k+1);
980 int rmdir_parents(const char *path, const char *stop) {
989 /* Skip trailing slashes */
990 while (l > 0 && path[l-1] == '/')
996 /* Skip last component */
997 while (l > 0 && path[l-1] != '/')
1000 /* Skip trailing slashes */
1001 while (l > 0 && path[l-1] == '/')
1007 if (!(t = strndup(path, l)))
1010 if (path_startswith(stop, t)) {
1019 if (errno != ENOENT)
1026 char hexchar(int x) {
1027 static const char table[16] = "0123456789abcdef";
1029 return table[x & 15];
1032 int unhexchar(char c) {
1034 if (c >= '0' && c <= '9')
1037 if (c >= 'a' && c <= 'f')
1038 return c - 'a' + 10;
1040 if (c >= 'A' && c <= 'F')
1041 return c - 'A' + 10;
1046 char *hexmem(const void *p, size_t l) {
1050 z = r = malloc(l * 2 + 1);
1054 for (x = p; x < (const uint8_t*) p + l; x++) {
1055 *(z++) = hexchar(*x >> 4);
1056 *(z++) = hexchar(*x & 15);
1063 void *unhexmem(const char *p, size_t l) {
1069 z = r = malloc((l + 1) / 2 + 1);
1073 for (x = p; x < p + l; x += 2) {
1076 a = unhexchar(x[0]);
1078 b = unhexchar(x[1]);
1082 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1089 char octchar(int x) {
1090 return '0' + (x & 7);
1093 int unoctchar(char c) {
1095 if (c >= '0' && c <= '7')
1101 char decchar(int x) {
1102 return '0' + (x % 10);
1105 int undecchar(char c) {
1107 if (c >= '0' && c <= '9')
1113 char *cescape(const char *s) {
1119 /* Does C style string escaping. */
1121 r = new(char, strlen(s)*4 + 1);
1125 for (f = s, t = r; *f; f++)
1171 /* For special chars we prefer octal over
1172 * hexadecimal encoding, simply because glib's
1173 * g_strescape() does the same */
1174 if ((*f < ' ') || (*f >= 127)) {
1176 *(t++) = octchar((unsigned char) *f >> 6);
1177 *(t++) = octchar((unsigned char) *f >> 3);
1178 *(t++) = octchar((unsigned char) *f);
1189 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1196 /* Undoes C style string escaping, and optionally prefixes it. */
1198 pl = prefix ? strlen(prefix) : 0;
1200 r = new(char, pl+length+1);
1205 memcpy(r, prefix, pl);
1207 for (f = s, t = r + pl; f < s + length; f++) {
1250 /* This is an extension of the XDG syntax files */
1255 /* hexadecimal encoding */
1258 a = unhexchar(f[1]);
1259 b = unhexchar(f[2]);
1261 if (a < 0 || b < 0) {
1262 /* Invalid escape code, let's take it literal then */
1266 *(t++) = (char) ((a << 4) | b);
1281 /* octal encoding */
1284 a = unoctchar(f[0]);
1285 b = unoctchar(f[1]);
1286 c = unoctchar(f[2]);
1288 if (a < 0 || b < 0 || c < 0) {
1289 /* Invalid escape code, let's take it literal then */
1293 *(t++) = (char) ((a << 6) | (b << 3) | c);
1301 /* premature end of string.*/
1306 /* Invalid escape code, let's take it literal then */
1318 char *cunescape_length(const char *s, size_t length) {
1319 return cunescape_length_with_prefix(s, length, NULL);
1322 char *cunescape(const char *s) {
1325 return cunescape_length(s, strlen(s));
1328 char *xescape(const char *s, const char *bad) {
1332 /* Escapes all chars in bad, in addition to \ and all special
1333 * chars, in \xFF style escaping. May be reversed with
1336 r = new(char, strlen(s) * 4 + 1);
1340 for (f = s, t = r; *f; f++) {
1342 if ((*f < ' ') || (*f >= 127) ||
1343 (*f == '\\') || strchr(bad, *f)) {
1346 *(t++) = hexchar(*f >> 4);
1347 *(t++) = hexchar(*f);
1357 char *bus_path_escape(const char *s) {
1363 /* Escapes all chars that D-Bus' object path cannot deal
1364 * with. Can be reverse with bus_path_unescape(). We special
1365 * case the empty string. */
1370 r = new(char, strlen(s)*3 + 1);
1374 for (f = s, t = r; *f; f++) {
1376 /* Escape everything that is not a-zA-Z0-9. We also
1377 * escape 0-9 if it's the first character */
1379 if (!(*f >= 'A' && *f <= 'Z') &&
1380 !(*f >= 'a' && *f <= 'z') &&
1381 !(f > s && *f >= '0' && *f <= '9')) {
1383 *(t++) = hexchar(*f >> 4);
1384 *(t++) = hexchar(*f);
1394 char *bus_path_unescape(const char *f) {
1399 /* Special case for the empty string */
1403 r = new(char, strlen(f) + 1);
1407 for (t = r; *f; f++) {
1412 if ((a = unhexchar(f[1])) < 0 ||
1413 (b = unhexchar(f[2])) < 0) {
1414 /* Invalid escape code, let's take it literal then */
1417 *(t++) = (char) ((a << 4) | b);
1429 char *ascii_strlower(char *t) {
1434 for (p = t; *p; p++)
1435 if (*p >= 'A' && *p <= 'Z')
1436 *p = *p - 'A' + 'a';
1441 static bool ignore_file_allow_backup(const char *filename) {
1445 filename[0] == '.' ||
1446 streq(filename, "lost+found") ||
1447 streq(filename, "aquota.user") ||
1448 streq(filename, "aquota.group") ||
1449 endswith(filename, ".rpmnew") ||
1450 endswith(filename, ".rpmsave") ||
1451 endswith(filename, ".rpmorig") ||
1452 endswith(filename, ".dpkg-old") ||
1453 endswith(filename, ".dpkg-new") ||
1454 endswith(filename, ".swp");
1457 bool ignore_file(const char *filename) {
1460 if (endswith(filename, "~"))
1463 return ignore_file_allow_backup(filename);
1466 int fd_nonblock(int fd, bool nonblock) {
1471 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1475 flags |= O_NONBLOCK;
1477 flags &= ~O_NONBLOCK;
1479 if (fcntl(fd, F_SETFL, flags) < 0)
1485 int fd_cloexec(int fd, bool cloexec) {
1490 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1494 flags |= FD_CLOEXEC;
1496 flags &= ~FD_CLOEXEC;
1498 if (fcntl(fd, F_SETFD, flags) < 0)
1504 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1507 assert(n_fdset == 0 || fdset);
1509 for (i = 0; i < n_fdset; i++)
1516 int close_all_fds(const int except[], unsigned n_except) {
1521 assert(n_except == 0 || except);
1523 d = opendir("/proc/self/fd");
1528 /* When /proc isn't available (for example in chroots)
1529 * the fallback is brute forcing through the fd
1532 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1533 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1535 if (fd_in_set(fd, except, n_except))
1538 if (close_nointr(fd) < 0)
1539 if (errno != EBADF && r == 0)
1546 while ((de = readdir(d))) {
1549 if (ignore_file(de->d_name))
1552 if (safe_atoi(de->d_name, &fd) < 0)
1553 /* Let's better ignore this, just in case */
1562 if (fd_in_set(fd, except, n_except))
1565 if (close_nointr(fd) < 0) {
1566 /* Valgrind has its own FD and doesn't want to have it closed */
1567 if (errno != EBADF && r == 0)
1576 bool chars_intersect(const char *a, const char *b) {
1579 /* Returns true if any of the chars in a are in b. */
1580 for (p = a; *p; p++)
1587 bool fstype_is_network(const char *fstype) {
1588 static const char table[] =
1597 return nulstr_contains(table, fstype);
1601 _cleanup_close_ int fd;
1603 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1609 TIOCL_GETKMSGREDIRECT,
1613 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1616 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1619 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1625 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1626 struct termios old_termios, new_termios;
1628 char line[LINE_MAX];
1633 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1634 new_termios = old_termios;
1636 new_termios.c_lflag &= ~ICANON;
1637 new_termios.c_cc[VMIN] = 1;
1638 new_termios.c_cc[VTIME] = 0;
1640 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1643 if (t != (usec_t) -1) {
1644 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1645 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1650 k = fread(&c, 1, 1, f);
1652 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1658 *need_nl = c != '\n';
1665 if (t != (usec_t) -1)
1666 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1669 if (!fgets(line, sizeof(line), f))
1674 if (strlen(line) != 1)
1684 int ask(char *ret, const char *replies, const char *text, ...) {
1694 bool need_nl = true;
1697 fputs(ANSI_HIGHLIGHT_ON, stdout);
1704 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1708 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1711 if (r == -EBADMSG) {
1712 puts("Bad input, please try again.");
1723 if (strchr(replies, c)) {
1728 puts("Read unexpected character, please try again.");
1732 int reset_terminal_fd(int fd, bool switch_to_text) {
1733 struct termios termios;
1736 /* Set terminal to some sane defaults */
1740 /* We leave locked terminal attributes untouched, so that
1741 * Plymouth may set whatever it wants to set, and we don't
1742 * interfere with that. */
1744 /* Disable exclusive mode, just in case */
1745 ioctl(fd, TIOCNXCL);
1747 /* Switch to text mode */
1749 ioctl(fd, KDSETMODE, KD_TEXT);
1751 /* Enable console unicode mode */
1752 ioctl(fd, KDSKBMODE, K_UNICODE);
1754 if (tcgetattr(fd, &termios) < 0) {
1759 /* We only reset the stuff that matters to the software. How
1760 * hardware is set up we don't touch assuming that somebody
1761 * else will do that for us */
1763 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1764 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1765 termios.c_oflag |= ONLCR;
1766 termios.c_cflag |= CREAD;
1767 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1769 termios.c_cc[VINTR] = 03; /* ^C */
1770 termios.c_cc[VQUIT] = 034; /* ^\ */
1771 termios.c_cc[VERASE] = 0177;
1772 termios.c_cc[VKILL] = 025; /* ^X */
1773 termios.c_cc[VEOF] = 04; /* ^D */
1774 termios.c_cc[VSTART] = 021; /* ^Q */
1775 termios.c_cc[VSTOP] = 023; /* ^S */
1776 termios.c_cc[VSUSP] = 032; /* ^Z */
1777 termios.c_cc[VLNEXT] = 026; /* ^V */
1778 termios.c_cc[VWERASE] = 027; /* ^W */
1779 termios.c_cc[VREPRINT] = 022; /* ^R */
1780 termios.c_cc[VEOL] = 0;
1781 termios.c_cc[VEOL2] = 0;
1783 termios.c_cc[VTIME] = 0;
1784 termios.c_cc[VMIN] = 1;
1786 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1790 /* Just in case, flush all crap out */
1791 tcflush(fd, TCIOFLUSH);
1796 int reset_terminal(const char *name) {
1799 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1803 r = reset_terminal_fd(fd, true);
1804 close_nointr_nofail(fd);
1809 int open_terminal(const char *name, int mode) {
1814 * If a TTY is in the process of being closed opening it might
1815 * cause EIO. This is horribly awful, but unlikely to be
1816 * changed in the kernel. Hence we work around this problem by
1817 * retrying a couple of times.
1819 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1823 fd = open(name, mode);
1830 /* Max 1s in total */
1834 usleep(50 * USEC_PER_MSEC);
1843 close_nointr_nofail(fd);
1848 close_nointr_nofail(fd);
1855 int flush_fd(int fd) {
1856 struct pollfd pollfd = {
1866 r = poll(&pollfd, 1, 0);
1876 l = read(fd, buf, sizeof(buf));
1882 if (errno == EAGAIN)
1891 int acquire_terminal(
1895 bool ignore_tiocstty_eperm,
1898 int fd = -1, notify = -1, r = 0, wd = -1;
1903 /* We use inotify to be notified when the tty is closed. We
1904 * create the watch before checking if we can actually acquire
1905 * it, so that we don't lose any event.
1907 * Note: strictly speaking this actually watches for the
1908 * device being closed, it does *not* really watch whether a
1909 * tty loses its controlling process. However, unless some
1910 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1911 * its tty otherwise this will not become a problem. As long
1912 * as the administrator makes sure not configure any service
1913 * on the same tty as an untrusted user this should not be a
1914 * problem. (Which he probably should not do anyway.) */
1916 if (timeout != (usec_t) -1)
1917 ts = now(CLOCK_MONOTONIC);
1919 if (!fail && !force) {
1920 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1926 wd = inotify_add_watch(notify, name, IN_CLOSE);
1934 struct sigaction sa_old, sa_new = {
1935 .sa_handler = SIG_IGN,
1936 .sa_flags = SA_RESTART,
1940 r = flush_fd(notify);
1945 /* We pass here O_NOCTTY only so that we can check the return
1946 * value TIOCSCTTY and have a reliable way to figure out if we
1947 * successfully became the controlling process of the tty */
1948 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1952 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1953 * if we already own the tty. */
1954 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1956 /* First, try to get the tty */
1957 if (ioctl(fd, TIOCSCTTY, force) < 0)
1960 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1962 /* Sometimes it makes sense to ignore TIOCSCTTY
1963 * returning EPERM, i.e. when very likely we already
1964 * are have this controlling terminal. */
1965 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1968 if (r < 0 && (force || fail || r != -EPERM)) {
1977 assert(notify >= 0);
1980 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1982 struct inotify_event *e;
1984 if (timeout != (usec_t) -1) {
1987 n = now(CLOCK_MONOTONIC);
1988 if (ts + timeout < n) {
1993 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2003 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2006 if (errno == EINTR || errno == EAGAIN)
2013 e = (struct inotify_event*) inotify_buffer;
2018 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2023 step = sizeof(struct inotify_event) + e->len;
2024 assert(step <= (size_t) l);
2026 e = (struct inotify_event*) ((uint8_t*) e + step);
2033 /* We close the tty fd here since if the old session
2034 * ended our handle will be dead. It's important that
2035 * we do this after sleeping, so that we don't enter
2036 * an endless loop. */
2037 close_nointr_nofail(fd);
2041 close_nointr_nofail(notify);
2043 r = reset_terminal_fd(fd, true);
2045 log_warning("Failed to reset terminal: %s", strerror(-r));
2051 close_nointr_nofail(fd);
2054 close_nointr_nofail(notify);
2059 int release_terminal(void) {
2061 struct sigaction sa_old, sa_new = {
2062 .sa_handler = SIG_IGN,
2063 .sa_flags = SA_RESTART,
2065 int _cleanup_close_ fd;
2067 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2071 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2072 * by our own TIOCNOTTY */
2073 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2075 if (ioctl(fd, TIOCNOTTY) < 0)
2078 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2083 int sigaction_many(const struct sigaction *sa, ...) {
2088 while ((sig = va_arg(ap, int)) > 0)
2089 if (sigaction(sig, sa, NULL) < 0)
2096 int ignore_signals(int sig, ...) {
2097 struct sigaction sa = {
2098 .sa_handler = SIG_IGN,
2099 .sa_flags = SA_RESTART,
2105 if (sigaction(sig, &sa, NULL) < 0)
2109 while ((sig = va_arg(ap, int)) > 0)
2110 if (sigaction(sig, &sa, NULL) < 0)
2117 int default_signals(int sig, ...) {
2118 struct sigaction sa = {
2119 .sa_handler = SIG_DFL,
2120 .sa_flags = SA_RESTART,
2125 if (sigaction(sig, &sa, NULL) < 0)
2129 while ((sig = va_arg(ap, int)) > 0)
2130 if (sigaction(sig, &sa, NULL) < 0)
2137 int close_pipe(int p[]) {
2143 a = close_nointr(p[0]);
2148 b = close_nointr(p[1]);
2152 return a < 0 ? a : b;
2155 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2164 while (nbytes > 0) {
2167 if ((k = read(fd, p, nbytes)) <= 0) {
2169 if (k < 0 && errno == EINTR)
2172 if (k < 0 && errno == EAGAIN && do_poll) {
2173 struct pollfd pollfd = {
2178 if (poll(&pollfd, 1, -1) < 0) {
2182 return n > 0 ? n : -errno;
2185 if (pollfd.revents != POLLIN)
2186 return n > 0 ? n : -EIO;
2191 return n > 0 ? n : (k < 0 ? -errno : 0);
2202 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2211 while (nbytes > 0) {
2214 k = write(fd, p, nbytes);
2217 if (k < 0 && errno == EINTR)
2220 if (k < 0 && errno == EAGAIN && do_poll) {
2221 struct pollfd pollfd = {
2226 if (poll(&pollfd, 1, -1) < 0) {
2230 return n > 0 ? n : -errno;
2233 if (pollfd.revents != POLLOUT)
2234 return n > 0 ? n : -EIO;
2239 return n > 0 ? n : (k < 0 ? -errno : 0);
2250 int parse_bytes(const char *t, off_t *bytes) {
2251 static const struct {
2257 { "M", 1024ULL*1024ULL },
2258 { "G", 1024ULL*1024ULL*1024ULL },
2259 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2260 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2261 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2278 l = strtoll(p, &e, 10);
2289 e += strspn(e, WHITESPACE);
2291 for (i = 0; i < ELEMENTSOF(table); i++)
2292 if (startswith(e, table[i].suffix)) {
2293 r += (off_t) l * table[i].factor;
2294 p = e + strlen(table[i].suffix);
2298 if (i >= ELEMENTSOF(table))
2308 int make_stdio(int fd) {
2313 r = dup3(fd, STDIN_FILENO, 0);
2314 s = dup3(fd, STDOUT_FILENO, 0);
2315 t = dup3(fd, STDERR_FILENO, 0);
2318 close_nointr_nofail(fd);
2320 if (r < 0 || s < 0 || t < 0)
2323 /* We rely here that the new fd has O_CLOEXEC not set */
2328 int make_null_stdio(void) {
2331 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2335 return make_stdio(null_fd);
2338 bool is_device_path(const char *path) {
2340 /* Returns true on paths that refer to a device, either in
2341 * sysfs or in /dev */
2344 path_startswith(path, "/dev/") ||
2345 path_startswith(path, "/sys/");
2348 int dir_is_empty(const char *path) {
2349 _cleanup_closedir_ DIR *d;
2358 union dirent_storage buf;
2360 r = readdir_r(d, &buf.de, &de);
2367 if (!ignore_file(de->d_name))
2372 char* dirname_malloc(const char *path) {
2373 char *d, *dir, *dir2;
2390 unsigned long long random_ull(void) {
2391 _cleanup_close_ int fd;
2395 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2399 r = loop_read(fd, &ull, sizeof(ull), true);
2400 if (r != sizeof(ull))
2406 return random() * RAND_MAX + random();
2409 void rename_process(const char name[8]) {
2412 /* This is a like a poor man's setproctitle(). It changes the
2413 * comm field, argv[0], and also the glibc's internally used
2414 * name of the process. For the first one a limit of 16 chars
2415 * applies, to the second one usually one of 10 (i.e. length
2416 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2417 * "systemd"). If you pass a longer string it will be
2420 prctl(PR_SET_NAME, name);
2422 if (program_invocation_name)
2423 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2425 if (saved_argc > 0) {
2429 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2431 for (i = 1; i < saved_argc; i++) {
2435 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2440 void sigset_add_many(sigset_t *ss, ...) {
2447 while ((sig = va_arg(ap, int)) > 0)
2448 assert_se(sigaddset(ss, sig) == 0);
2452 char* gethostname_malloc(void) {
2455 assert_se(uname(&u) >= 0);
2457 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2458 return strdup(u.nodename);
2460 return strdup(u.sysname);
2463 bool hostname_is_set(void) {
2466 assert_se(uname(&u) >= 0);
2468 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2471 static char *lookup_uid(uid_t uid) {
2474 _cleanup_free_ char *buf = NULL;
2475 struct passwd pwbuf, *pw = NULL;
2477 /* Shortcut things to avoid NSS lookups */
2479 return strdup("root");
2481 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2485 buf = malloc(bufsize);
2489 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2490 return strdup(pw->pw_name);
2492 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2498 char* getlogname_malloc(void) {
2502 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2507 return lookup_uid(uid);
2510 char *getusername_malloc(void) {
2517 return lookup_uid(getuid());
2520 int getttyname_malloc(int fd, char **r) {
2521 char path[PATH_MAX], *c;
2526 k = ttyname_r(fd, path, sizeof(path));
2532 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2540 int getttyname_harder(int fd, char **r) {
2544 k = getttyname_malloc(fd, &s);
2548 if (streq(s, "tty")) {
2550 return get_ctty(0, NULL, r);
2557 int get_ctty_devnr(pid_t pid, dev_t *d) {
2559 char line[LINE_MAX], *p, *fn;
2560 unsigned long ttynr;
2563 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2566 f = fopen(fn, "re");
2571 if (!fgets(line, sizeof(line), f)) {
2572 k = feof(f) ? -EIO : -errno;
2579 p = strrchr(line, ')');
2589 "%*d " /* session */
2594 if (major(ttynr) == 0 && minor(ttynr) == 0)
2601 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2603 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2608 k = get_ctty_devnr(pid, &devnr);
2612 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2614 k = readlink_malloc(fn, &s);
2620 /* This is an ugly hack */
2621 if (major(devnr) == 136) {
2622 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2632 /* Probably something like the ptys which have no
2633 * symlink in /dev/char. Let's return something
2634 * vaguely useful. */
2647 if (startswith(s, "/dev/"))
2649 else if (startswith(s, "../"))
2667 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2673 /* This returns the first error we run into, but nevertheless
2674 * tries to go on. This closes the passed fd. */
2678 close_nointr_nofail(fd);
2680 return errno == ENOENT ? 0 : -errno;
2685 union dirent_storage buf;
2686 bool is_dir, keep_around;
2690 r = readdir_r(d, &buf.de, &de);
2691 if (r != 0 && ret == 0) {
2699 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2702 if (de->d_type == DT_UNKNOWN ||
2704 (de->d_type == DT_DIR && root_dev)) {
2705 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2706 if (ret == 0 && errno != ENOENT)
2711 is_dir = S_ISDIR(st.st_mode);
2714 (st.st_uid == 0 || st.st_uid == getuid()) &&
2715 (st.st_mode & S_ISVTX);
2717 is_dir = de->d_type == DT_DIR;
2718 keep_around = false;
2724 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2725 if (root_dev && st.st_dev != root_dev->st_dev)
2728 subdir_fd = openat(fd, de->d_name,
2729 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2730 if (subdir_fd < 0) {
2731 if (ret == 0 && errno != ENOENT)
2736 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2737 if (r < 0 && ret == 0)
2741 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2742 if (ret == 0 && errno != ENOENT)
2746 } else if (!only_dirs && !keep_around) {
2748 if (unlinkat(fd, de->d_name, 0) < 0) {
2749 if (ret == 0 && errno != ENOENT)
2760 static int is_temporary_fs(struct statfs *s) {
2762 return s->f_type == TMPFS_MAGIC ||
2763 (long)s->f_type == (long)RAMFS_MAGIC;
2766 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2771 if (fstatfs(fd, &s) < 0) {
2772 close_nointr_nofail(fd);
2776 /* We refuse to clean disk file systems with this call. This
2777 * is extra paranoia just to be sure we never ever remove
2779 if (!is_temporary_fs(&s)) {
2780 log_error("Attempted to remove disk file system, and we can't allow that.");
2781 close_nointr_nofail(fd);
2785 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2788 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2794 /* We refuse to clean the root file system with this
2795 * call. This is extra paranoia to never cause a really
2796 * seriously broken system. */
2797 if (path_equal(path, "/")) {
2798 log_error("Attempted to remove entire root file system, and we can't allow that.");
2802 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2805 if (errno != ENOTDIR)
2809 if (statfs(path, &s) < 0)
2812 if (!is_temporary_fs(&s)) {
2813 log_error("Attempted to remove disk file system, and we can't allow that.");
2818 if (delete_root && !only_dirs)
2819 if (unlink(path) < 0 && errno != ENOENT)
2826 if (fstatfs(fd, &s) < 0) {
2827 close_nointr_nofail(fd);
2831 if (!is_temporary_fs(&s)) {
2832 log_error("Attempted to remove disk file system, and we can't allow that.");
2833 close_nointr_nofail(fd);
2838 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2841 if (honour_sticky && file_is_priv_sticky(path) > 0)
2844 if (rmdir(path) < 0 && errno != ENOENT) {
2853 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2854 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2857 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2858 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2861 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2864 /* Under the assumption that we are running privileged we
2865 * first change the access mode and only then hand out
2866 * ownership to avoid a window where access is too open. */
2868 if (mode != (mode_t) -1)
2869 if (chmod(path, mode) < 0)
2872 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2873 if (chown(path, uid, gid) < 0)
2879 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2882 /* Under the assumption that we are running privileged we
2883 * first change the access mode and only then hand out
2884 * ownership to avoid a window where access is too open. */
2886 if (fchmod(fd, mode) < 0)
2889 if (fchown(fd, uid, gid) < 0)
2895 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2899 /* Allocates the cpuset in the right size */
2902 if (!(r = CPU_ALLOC(n)))
2905 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2906 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2916 if (errno != EINVAL)
2923 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2924 static const char status_indent[] = " "; /* "[" STATUS "] " */
2925 _cleanup_free_ char *s = NULL;
2926 _cleanup_close_ int fd = -1;
2927 struct iovec iovec[6] = {};
2929 static bool prev_ephemeral;
2933 /* This is independent of logging, as status messages are
2934 * optional and go exclusively to the console. */
2936 if (vasprintf(&s, format, ap) < 0)
2939 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2952 sl = status ? sizeof(status_indent)-1 : 0;
2958 e = ellipsize(s, emax, 75);
2966 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2967 prev_ephemeral = ephemeral;
2970 if (!isempty(status)) {
2971 IOVEC_SET_STRING(iovec[n++], "[");
2972 IOVEC_SET_STRING(iovec[n++], status);
2973 IOVEC_SET_STRING(iovec[n++], "] ");
2975 IOVEC_SET_STRING(iovec[n++], status_indent);
2978 IOVEC_SET_STRING(iovec[n++], s);
2980 IOVEC_SET_STRING(iovec[n++], "\n");
2982 if (writev(fd, iovec, n) < 0)
2988 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2994 va_start(ap, format);
2995 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3001 int status_welcome(void) {
3003 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3005 r = parse_env_file("/etc/os-release", NEWLINE,
3006 "PRETTY_NAME", &pretty_name,
3007 "ANSI_COLOR", &ansi_color,
3009 if (r < 0 && r != -ENOENT)
3010 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3012 return status_printf(NULL, false, false,
3013 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3014 isempty(ansi_color) ? "1" : ansi_color,
3015 isempty(pretty_name) ? "Linux" : pretty_name);
3018 char *replace_env(const char *format, char **env) {
3025 const char *e, *word = format;
3030 for (e = format; *e; e ++) {
3041 if (!(k = strnappend(r, word, e-word-1)))
3050 } else if (*e == '$') {
3051 if (!(k = strnappend(r, word, e-word)))
3067 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3069 k = strappend(r, t);
3083 if (!(k = strnappend(r, word, e-word)))
3094 char **replace_env_argv(char **argv, char **env) {
3096 unsigned k = 0, l = 0;
3098 l = strv_length(argv);
3100 if (!(r = new(char*, l+1)))
3103 STRV_FOREACH(i, argv) {
3105 /* If $FOO appears as single word, replace it by the split up variable */
3106 if ((*i)[0] == '$' && (*i)[1] != '{') {
3111 e = strv_env_get(env, *i+1);
3114 if (!(m = strv_split_quoted(e))) {
3125 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3134 memcpy(r + k, m, q * sizeof(char*));
3142 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3143 if (!(r[k++] = replace_env(*i, env))) {
3153 int fd_columns(int fd) {
3154 struct winsize ws = {};
3156 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3165 unsigned columns(void) {
3169 if (_likely_(cached_columns > 0))
3170 return cached_columns;
3173 e = getenv("COLUMNS");
3178 c = fd_columns(STDOUT_FILENO);
3187 int fd_lines(int fd) {
3188 struct winsize ws = {};
3190 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3199 unsigned lines(void) {
3203 if (_likely_(cached_lines > 0))
3204 return cached_lines;
3207 e = getenv("LINES");
3212 l = fd_lines(STDOUT_FILENO);
3218 return cached_lines;
3221 /* intended to be used as a SIGWINCH sighandler */
3222 void columns_lines_cache_reset(int signum) {
3228 static int cached_on_tty = -1;
3230 if (_unlikely_(cached_on_tty < 0))
3231 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3233 return cached_on_tty;
3236 int running_in_chroot(void) {
3237 struct stat a = {}, b = {};
3239 /* Only works as root */
3240 if (stat("/proc/1/root", &a) < 0)
3243 if (stat("/", &b) < 0)
3247 a.st_dev != b.st_dev ||
3248 a.st_ino != b.st_ino;
3251 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3256 assert(percent <= 100);
3257 assert(new_length >= 3);
3259 if (old_length <= 3 || old_length <= new_length)
3260 return strndup(s, old_length);
3262 r = new0(char, new_length+1);
3266 x = (new_length * percent) / 100;
3268 if (x > new_length - 3)
3276 s + old_length - (new_length - x - 3),
3277 new_length - x - 3);
3282 char *ellipsize(const char *s, size_t length, unsigned percent) {
3283 return ellipsize_mem(s, strlen(s), length, percent);
3286 int touch(const char *path) {
3291 /* This just opens the file for writing, ensuring it
3292 * exists. It doesn't call utimensat() the way /usr/bin/touch
3295 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3299 close_nointr_nofail(fd);
3303 char *unquote(const char *s, const char* quotes) {
3307 /* This is rather stupid, simply removes the heading and
3308 * trailing quotes if there is one. Doesn't care about
3309 * escaping or anything. We should make this smarter one
3316 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3317 return strndup(s+1, l-2);
3322 char *normalize_env_assignment(const char *s) {
3323 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3326 eq = strchr(s, '=');
3338 memmove(r, t, strlen(t) + 1);
3342 name = strndup(s, eq - s);
3350 value = unquote(strstrip(p), QUOTES);
3354 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3360 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3371 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3383 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3390 r = wait_for_terminate(pid, &status);
3392 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3396 if (status.si_code == CLD_EXITED) {
3397 if (status.si_status != 0) {
3398 log_warning("%s failed with error code %i.", name, status.si_status);
3399 return status.si_status;
3402 log_debug("%s succeeded.", name);
3405 } else if (status.si_code == CLD_KILLED ||
3406 status.si_code == CLD_DUMPED) {
3408 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3412 log_warning("%s failed due to unknown reason.", name);
3416 _noreturn_ void freeze(void) {
3418 /* Make sure nobody waits for us on a socket anymore */
3419 close_all_fds(NULL, 0);
3427 bool null_or_empty(struct stat *st) {
3430 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3433 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3439 int null_or_empty_path(const char *fn) {
3444 if (stat(fn, &st) < 0)
3447 return null_or_empty(&st);
3450 DIR *xopendirat(int fd, const char *name, int flags) {
3454 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3460 close_nointr_nofail(nfd);
3467 int signal_from_string_try_harder(const char *s) {
3471 signo = signal_from_string(s);
3473 if (startswith(s, "SIG"))
3474 return signal_from_string(s+3);
3479 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3483 /* FIXME: to follow udev's logic 100% we need to leave valid
3484 * UTF8 chars unescaped */
3486 u = unquote(tagvalue, "\"\'");
3490 t = xescape(u, "/ ");
3496 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3505 char *fstab_node_to_udev_node(const char *p) {
3508 if (startswith(p, "LABEL="))
3509 return tag_to_udev_node(p+6, "label");
3511 if (startswith(p, "UUID="))
3512 return tag_to_udev_node(p+5, "uuid");
3514 if (startswith(p, "PARTUUID="))
3515 return tag_to_udev_node(p+9, "partuuid");
3517 if (startswith(p, "PARTLABEL="))
3518 return tag_to_udev_node(p+10, "partlabel");
3523 bool tty_is_vc(const char *tty) {
3526 if (startswith(tty, "/dev/"))
3529 return vtnr_from_tty(tty) >= 0;
3532 bool tty_is_console(const char *tty) {
3535 if (startswith(tty, "/dev/"))
3538 return streq(tty, "console");
3541 int vtnr_from_tty(const char *tty) {
3546 if (startswith(tty, "/dev/"))
3549 if (!startswith(tty, "tty") )
3552 if (tty[3] < '0' || tty[3] > '9')
3555 r = safe_atoi(tty+3, &i);
3559 if (i < 0 || i > 63)
3565 char *resolve_dev_console(char **active) {
3568 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3569 * (i.e. not read-only-mounted which is a sign for container setups) */
3571 if (path_is_read_only_fs("/sys") > 0)
3574 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3577 /* If multiple log outputs are configured the last one is what
3578 * /dev/console points to */
3579 tty = strrchr(*active, ' ');
3588 bool tty_is_vc_resolve(const char *tty) {
3589 char *active = NULL;
3594 if (startswith(tty, "/dev/"))
3597 if (streq(tty, "console")) {
3598 tty = resolve_dev_console(&active);
3609 const char *default_term_for_tty(const char *tty) {
3612 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3615 bool dirent_is_file(const struct dirent *de) {
3618 if (ignore_file(de->d_name))
3621 if (de->d_type != DT_REG &&
3622 de->d_type != DT_LNK &&
3623 de->d_type != DT_UNKNOWN)
3629 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3632 if (de->d_type != DT_REG &&
3633 de->d_type != DT_LNK &&
3634 de->d_type != DT_UNKNOWN)
3637 if (ignore_file_allow_backup(de->d_name))
3640 return endswith(de->d_name, suffix);
3643 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3646 Hashmap *pids = NULL;
3650 /* Executes all binaries in a directory in parallel and
3651 * waits for them to finish. */
3654 if (!(_d = opendir(directory))) {
3656 if (errno == ENOENT)
3659 log_error("Failed to enumerate directory %s: %m", directory);
3666 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3667 log_error("Failed to allocate set.");
3671 while ((de = readdir(d))) {
3676 if (!dirent_is_file(de))
3679 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3684 if ((pid = fork()) < 0) {
3685 log_error("Failed to fork: %m");
3703 log_error("Failed to execute %s: %m", path);
3704 _exit(EXIT_FAILURE);
3707 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3709 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3710 log_error("Failed to add PID to set: %s", strerror(-k));
3715 while (!hashmap_isempty(pids)) {
3716 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3720 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3725 log_error("waitid() failed: %m");
3729 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3730 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3731 if (si.si_code == CLD_EXITED)
3732 log_error("%s exited with exit status %i.", path, si.si_status);
3734 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3736 log_debug("%s exited successfully.", path);
3747 hashmap_free_free(pids);
3750 int kill_and_sigcont(pid_t pid, int sig) {
3753 r = kill(pid, sig) < 0 ? -errno : 0;
3761 bool nulstr_contains(const char*nulstr, const char *needle) {
3767 NULSTR_FOREACH(i, nulstr)
3768 if (streq(i, needle))
3774 bool plymouth_running(void) {
3775 return access("/run/plymouth/pid", F_OK) >= 0;
3778 char* strshorten(char *s, size_t l) {
3787 static bool hostname_valid_char(char c) {
3789 (c >= 'a' && c <= 'z') ||
3790 (c >= 'A' && c <= 'Z') ||
3791 (c >= '0' && c <= '9') ||
3797 bool hostname_is_valid(const char *s) {
3804 for (p = s, dot = true; *p; p++) {
3811 if (!hostname_valid_char(*p))
3821 if (p-s > HOST_NAME_MAX)
3827 char* hostname_cleanup(char *s) {
3830 for (p = s, d = s; *p; p++)
3831 if ((*p >= 'a' && *p <= 'z') ||
3832 (*p >= 'A' && *p <= 'Z') ||
3833 (*p >= '0' && *p <= '9') ||
3841 strshorten(s, HOST_NAME_MAX);
3845 int pipe_eof(int fd) {
3847 struct pollfd pollfd = {
3849 .events = POLLIN|POLLHUP,
3852 r = poll(&pollfd, 1, 0);
3859 return pollfd.revents & POLLHUP;
3862 int fd_wait_for_event(int fd, int event, usec_t t) {
3864 struct pollfd pollfd = {
3869 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3876 return pollfd.revents;
3879 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3890 t = new(char, strlen(path) + 1 + 6 + 1);
3894 fn = path_get_file_name(path);
3898 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3900 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3906 f = fdopen(fd, "we");
3919 int terminal_vhangup_fd(int fd) {
3922 if (ioctl(fd, TIOCVHANGUP) < 0)
3928 int terminal_vhangup(const char *name) {
3931 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3935 r = terminal_vhangup_fd(fd);
3936 close_nointr_nofail(fd);
3941 int vt_disallocate(const char *name) {
3945 /* Deallocate the VT if possible. If not possible
3946 * (i.e. because it is the active one), at least clear it
3947 * entirely (including the scrollback buffer) */
3949 if (!startswith(name, "/dev/"))
3952 if (!tty_is_vc(name)) {
3953 /* So this is not a VT. I guess we cannot deallocate
3954 * it then. But let's at least clear the screen */
3956 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3961 "\033[r" /* clear scrolling region */
3962 "\033[H" /* move home */
3963 "\033[2J", /* clear screen */
3965 close_nointr_nofail(fd);
3970 if (!startswith(name, "/dev/tty"))
3973 r = safe_atou(name+8, &u);
3980 /* Try to deallocate */
3981 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3985 r = ioctl(fd, VT_DISALLOCATE, u);
3986 close_nointr_nofail(fd);
3994 /* Couldn't deallocate, so let's clear it fully with
3996 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4001 "\033[r" /* clear scrolling region */
4002 "\033[H" /* move home */
4003 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4005 close_nointr_nofail(fd);
4010 int copy_file(const char *from, const char *to) {
4016 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4020 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4022 close_nointr_nofail(fdf);
4030 n = read(fdf, buf, sizeof(buf));
4034 close_nointr_nofail(fdf);
4045 k = loop_write(fdt, buf, n, false);
4047 r = k < 0 ? k : (errno ? -errno : -EIO);
4049 close_nointr_nofail(fdf);
4057 close_nointr_nofail(fdf);
4058 r = close_nointr(fdt);
4068 int symlink_atomic(const char *from, const char *to) {
4070 _cleanup_free_ char *t;
4073 unsigned long long ull;
4080 t = new(char, strlen(to) + 1 + 16 + 1);
4084 fn = path_get_file_name(to);
4088 x = stpcpy(t+k+1, fn);
4091 for (i = 0; i < 16; i++) {
4092 *(x++) = hexchar(ull & 0xF);
4098 if (symlink(from, t) < 0)
4101 if (rename(t, to) < 0) {
4110 bool display_is_local(const char *display) {
4114 display[0] == ':' &&
4115 display[1] >= '0' &&
4119 int socket_from_display(const char *display, char **path) {
4126 if (!display_is_local(display))
4129 k = strspn(display+1, "0123456789");
4131 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4135 c = stpcpy(f, "/tmp/.X11-unix/X");
4136 memcpy(c, display+1, k);
4145 const char **username,
4146 uid_t *uid, gid_t *gid,
4148 const char **shell) {
4156 /* We enforce some special rules for uid=0: in order to avoid
4157 * NSS lookups for root we hardcode its data. */
4159 if (streq(*username, "root") || streq(*username, "0")) {
4177 if (parse_uid(*username, &u) >= 0) {
4181 /* If there are multiple users with the same id, make
4182 * sure to leave $USER to the configured value instead
4183 * of the first occurrence in the database. However if
4184 * the uid was configured by a numeric uid, then let's
4185 * pick the real username from /etc/passwd. */
4187 *username = p->pw_name;
4190 p = getpwnam(*username);
4194 return errno > 0 ? -errno : -ESRCH;
4206 *shell = p->pw_shell;
4211 char* uid_to_name(uid_t uid) {
4216 return strdup("root");
4220 return strdup(p->pw_name);
4222 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4228 char* gid_to_name(gid_t gid) {
4233 return strdup("root");
4237 return strdup(p->gr_name);
4239 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4245 int get_group_creds(const char **groupname, gid_t *gid) {
4251 /* We enforce some special rules for gid=0: in order to avoid
4252 * NSS lookups for root we hardcode its data. */
4254 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4255 *groupname = "root";
4263 if (parse_gid(*groupname, &id) >= 0) {
4268 *groupname = g->gr_name;
4271 g = getgrnam(*groupname);
4275 return errno > 0 ? -errno : -ESRCH;
4283 int in_gid(gid_t gid) {
4285 int ngroups_max, r, i;
4287 if (getgid() == gid)
4290 if (getegid() == gid)
4293 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4294 assert(ngroups_max > 0);
4296 gids = alloca(sizeof(gid_t) * ngroups_max);
4298 r = getgroups(ngroups_max, gids);
4302 for (i = 0; i < r; i++)
4309 int in_group(const char *name) {
4313 r = get_group_creds(&name, &gid);
4320 int glob_exists(const char *path) {
4321 glob_t _cleanup_globfree_ g = {};
4327 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4329 if (k == GLOB_NOMATCH)
4331 else if (k == GLOB_NOSPACE)
4334 r = !strv_isempty(g.gl_pathv);
4336 r = errno ? -errno : -EIO;
4341 int dirent_ensure_type(DIR *d, struct dirent *de) {
4347 if (de->d_type != DT_UNKNOWN)
4350 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4354 S_ISREG(st.st_mode) ? DT_REG :
4355 S_ISDIR(st.st_mode) ? DT_DIR :
4356 S_ISLNK(st.st_mode) ? DT_LNK :
4357 S_ISFIFO(st.st_mode) ? DT_FIFO :
4358 S_ISSOCK(st.st_mode) ? DT_SOCK :
4359 S_ISCHR(st.st_mode) ? DT_CHR :
4360 S_ISBLK(st.st_mode) ? DT_BLK :
4366 int in_search_path(const char *path, char **search) {
4370 r = path_get_parent(path, &parent);
4376 STRV_FOREACH(i, search) {
4377 if (path_equal(parent, *i)) {
4388 int get_files_in_directory(const char *path, char ***list) {
4396 /* Returns all files in a directory in *list, and the number
4397 * of files as return value. If list is NULL returns only the
4406 union dirent_storage buf;
4409 k = readdir_r(d, &buf.de, &de);
4418 dirent_ensure_type(d, de);
4420 if (!dirent_is_file(de))
4424 if ((unsigned) r >= n) {
4428 t = realloc(l, sizeof(char*) * n);
4437 assert((unsigned) r < n);
4439 l[r] = strdup(de->d_name);
4463 char *strjoin(const char *x, ...) {
4477 t = va_arg(ap, const char *);
4482 if (n > ((size_t) -1) - l) {
4506 t = va_arg(ap, const char *);
4520 bool is_main_thread(void) {
4521 static __thread int cached = 0;
4523 if (_unlikely_(cached == 0))
4524 cached = getpid() == gettid() ? 1 : -1;
4529 int block_get_whole_disk(dev_t d, dev_t *ret) {
4536 /* If it has a queue this is good enough for us */
4537 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4540 r = access(p, F_OK);
4548 /* If it is a partition find the originating device */
4549 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4552 r = access(p, F_OK);
4558 /* Get parent dev_t */
4559 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4562 r = read_one_line_file(p, &s);
4568 r = sscanf(s, "%u:%u", &m, &n);
4574 /* Only return this if it is really good enough for us. */
4575 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4578 r = access(p, F_OK);
4582 *ret = makedev(m, n);
4589 int file_is_priv_sticky(const char *p) {
4594 if (lstat(p, &st) < 0)
4598 (st.st_uid == 0 || st.st_uid == getuid()) &&
4599 (st.st_mode & S_ISVTX);
4602 static const char *const ioprio_class_table[] = {
4603 [IOPRIO_CLASS_NONE] = "none",
4604 [IOPRIO_CLASS_RT] = "realtime",
4605 [IOPRIO_CLASS_BE] = "best-effort",
4606 [IOPRIO_CLASS_IDLE] = "idle"
4609 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4611 static const char *const sigchld_code_table[] = {
4612 [CLD_EXITED] = "exited",
4613 [CLD_KILLED] = "killed",
4614 [CLD_DUMPED] = "dumped",
4615 [CLD_TRAPPED] = "trapped",
4616 [CLD_STOPPED] = "stopped",
4617 [CLD_CONTINUED] = "continued",
4620 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4622 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4623 [LOG_FAC(LOG_KERN)] = "kern",
4624 [LOG_FAC(LOG_USER)] = "user",
4625 [LOG_FAC(LOG_MAIL)] = "mail",
4626 [LOG_FAC(LOG_DAEMON)] = "daemon",
4627 [LOG_FAC(LOG_AUTH)] = "auth",
4628 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4629 [LOG_FAC(LOG_LPR)] = "lpr",
4630 [LOG_FAC(LOG_NEWS)] = "news",
4631 [LOG_FAC(LOG_UUCP)] = "uucp",
4632 [LOG_FAC(LOG_CRON)] = "cron",
4633 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4634 [LOG_FAC(LOG_FTP)] = "ftp",
4635 [LOG_FAC(LOG_LOCAL0)] = "local0",
4636 [LOG_FAC(LOG_LOCAL1)] = "local1",
4637 [LOG_FAC(LOG_LOCAL2)] = "local2",
4638 [LOG_FAC(LOG_LOCAL3)] = "local3",
4639 [LOG_FAC(LOG_LOCAL4)] = "local4",
4640 [LOG_FAC(LOG_LOCAL5)] = "local5",
4641 [LOG_FAC(LOG_LOCAL6)] = "local6",
4642 [LOG_FAC(LOG_LOCAL7)] = "local7"
4645 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4647 static const char *const log_level_table[] = {
4648 [LOG_EMERG] = "emerg",
4649 [LOG_ALERT] = "alert",
4650 [LOG_CRIT] = "crit",
4652 [LOG_WARNING] = "warning",
4653 [LOG_NOTICE] = "notice",
4654 [LOG_INFO] = "info",
4655 [LOG_DEBUG] = "debug"
4658 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4660 static const char* const sched_policy_table[] = {
4661 [SCHED_OTHER] = "other",
4662 [SCHED_BATCH] = "batch",
4663 [SCHED_IDLE] = "idle",
4664 [SCHED_FIFO] = "fifo",
4668 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4670 static const char* const rlimit_table[] = {
4671 [RLIMIT_CPU] = "LimitCPU",
4672 [RLIMIT_FSIZE] = "LimitFSIZE",
4673 [RLIMIT_DATA] = "LimitDATA",
4674 [RLIMIT_STACK] = "LimitSTACK",
4675 [RLIMIT_CORE] = "LimitCORE",
4676 [RLIMIT_RSS] = "LimitRSS",
4677 [RLIMIT_NOFILE] = "LimitNOFILE",
4678 [RLIMIT_AS] = "LimitAS",
4679 [RLIMIT_NPROC] = "LimitNPROC",
4680 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4681 [RLIMIT_LOCKS] = "LimitLOCKS",
4682 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4683 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4684 [RLIMIT_NICE] = "LimitNICE",
4685 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4686 [RLIMIT_RTTIME] = "LimitRTTIME"
4689 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4691 static const char* const ip_tos_table[] = {
4692 [IPTOS_LOWDELAY] = "low-delay",
4693 [IPTOS_THROUGHPUT] = "throughput",
4694 [IPTOS_RELIABILITY] = "reliability",
4695 [IPTOS_LOWCOST] = "low-cost",
4698 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4700 static const char *const __signal_table[] = {
4717 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4728 [SIGVTALRM] = "VTALRM",
4730 [SIGWINCH] = "WINCH",
4736 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4738 const char *signal_to_string(int signo) {
4739 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4742 name = __signal_to_string(signo);
4746 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4747 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4749 snprintf(buf, sizeof(buf), "%d", signo);
4754 int signal_from_string(const char *s) {
4759 signo = __signal_from_string(s);
4763 if (startswith(s, "RTMIN+")) {
4767 if (safe_atou(s, &u) >= 0) {
4768 signo = (int) u + offset;
4769 if (signo > 0 && signo < _NSIG)
4775 bool kexec_loaded(void) {
4776 bool loaded = false;
4779 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4787 int strdup_or_null(const char *a, char **b) {
4805 int prot_from_flags(int flags) {
4807 switch (flags & O_ACCMODE) {
4816 return PROT_READ|PROT_WRITE;
4823 char *format_bytes(char *buf, size_t l, off_t t) {
4826 static const struct {
4830 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4831 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4832 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4833 { "G", 1024ULL*1024ULL*1024ULL },
4834 { "M", 1024ULL*1024ULL },
4838 for (i = 0; i < ELEMENTSOF(table); i++) {
4840 if (t >= table[i].factor) {
4843 (unsigned long long) (t / table[i].factor),
4844 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4851 snprintf(buf, l, "%lluB", (unsigned long long) t);
4859 void* memdup(const void *p, size_t l) {
4872 int fd_inc_sndbuf(int fd, size_t n) {
4874 socklen_t l = sizeof(value);
4876 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4878 l == sizeof(value) &&
4879 (size_t) value >= n*2)
4883 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4890 int fd_inc_rcvbuf(int fd, size_t n) {
4892 socklen_t l = sizeof(value);
4894 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4896 l == sizeof(value) &&
4897 (size_t) value >= n*2)
4901 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4908 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4909 pid_t parent_pid, agent_pid;
4911 bool stdout_is_tty, stderr_is_tty;
4919 parent_pid = getpid();
4921 /* Spawns a temporary TTY agent, making sure it goes away when
4928 if (agent_pid != 0) {
4935 * Make sure the agent goes away when the parent dies */
4936 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4937 _exit(EXIT_FAILURE);
4939 /* Check whether our parent died before we were able
4940 * to set the death signal */
4941 if (getppid() != parent_pid)
4942 _exit(EXIT_SUCCESS);
4944 /* Don't leak fds to the agent */
4945 close_all_fds(except, n_except);
4947 stdout_is_tty = isatty(STDOUT_FILENO);
4948 stderr_is_tty = isatty(STDERR_FILENO);
4950 if (!stdout_is_tty || !stderr_is_tty) {
4951 /* Detach from stdout/stderr. and reopen
4952 * /dev/tty for them. This is important to
4953 * ensure that when systemctl is started via
4954 * popen() or a similar call that expects to
4955 * read EOF we actually do generate EOF and
4956 * not delay this indefinitely by because we
4957 * keep an unused copy of stdin around. */
4958 fd = open("/dev/tty", O_WRONLY);
4960 log_error("Failed to open /dev/tty: %m");
4961 _exit(EXIT_FAILURE);
4965 dup2(fd, STDOUT_FILENO);
4968 dup2(fd, STDERR_FILENO);
4974 /* Count arguments */
4976 for (n = 0; va_arg(ap, char*); n++)
4981 l = alloca(sizeof(char *) * (n + 1));
4983 /* Fill in arguments */
4985 for (i = 0; i <= n; i++)
4986 l[i] = va_arg(ap, char*);
4990 _exit(EXIT_FAILURE);
4993 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4994 struct rlimit highest, fixed;
4998 if (setrlimit(resource, rlim) >= 0)
5004 /* So we failed to set the desired setrlimit, then let's try
5005 * to get as close as we can */
5006 assert_se(getrlimit(resource, &highest) == 0);
5008 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5009 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5011 if (setrlimit(resource, &fixed) < 0)
5017 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5018 char path[sizeof("/proc/")-1 + DECIMAL_STR_MAX(pid_t) + sizeof("/environ")], *value = NULL;
5030 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5032 f = fopen(path, "re");
5040 char line[LINE_MAX];
5043 for (i = 0; i < sizeof(line)-1; i++) {
5047 if (_unlikely_(c == EOF)) {
5057 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5058 value = strdup(line + l + 1);
5078 int can_sleep(const char *type) {
5082 _cleanup_free_ char *p = NULL;
5086 /* If /sys is read-only we cannot sleep */
5087 if (access("/sys/power/state", W_OK) < 0)
5090 r = read_one_line_file("/sys/power/state", &p);
5095 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5096 if (l == k && memcmp(w, type, l) == 0)
5102 int can_sleep_disk(const char *type) {
5106 _cleanup_free_ char *p = NULL;
5110 /* If /sys is read-only we cannot sleep */
5111 if (access("/sys/power/state", W_OK) < 0 ||
5112 access("/sys/power/disk", W_OK) < 0)
5115 r = read_one_line_file("/sys/power/disk", &p);
5120 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5121 if (l == k && memcmp(w, type, l) == 0)
5124 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5131 bool is_valid_documentation_url(const char *url) {
5134 if (startswith(url, "http://") && url[7])
5137 if (startswith(url, "https://") && url[8])
5140 if (startswith(url, "file:") && url[5])
5143 if (startswith(url, "info:") && url[5])
5146 if (startswith(url, "man:") && url[4])
5152 bool in_initrd(void) {
5153 static __thread int saved = -1;
5159 /* We make two checks here:
5161 * 1. the flag file /etc/initrd-release must exist
5162 * 2. the root file system must be a memory file system
5164 * The second check is extra paranoia, since misdetecting an
5165 * initrd can have bad bad consequences due the initrd
5166 * emptying when transititioning to the main systemd.
5169 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5170 statfs("/", &s) >= 0 &&
5171 is_temporary_fs(&s);
5176 void warn_melody(void) {
5177 _cleanup_close_ int fd = -1;
5179 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5183 /* Yeah, this is synchronous. Kinda sucks. But well... */
5185 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5186 usleep(125*USEC_PER_MSEC);
5188 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5189 usleep(125*USEC_PER_MSEC);
5191 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5192 usleep(125*USEC_PER_MSEC);
5194 ioctl(fd, KIOCSOUND, 0);
5197 int make_console_stdio(void) {
5200 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5202 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5204 log_error("Failed to acquire terminal: %s", strerror(-fd));
5210 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5217 int get_home_dir(char **_h) {
5225 /* Take the user specified one */
5236 /* Hardcode home directory for root to avoid NSS */
5239 h = strdup("/root");
5247 /* Check the database... */
5251 return errno ? -errno : -ESRCH;
5253 if (!path_is_absolute(p->pw_dir))
5256 h = strdup(p->pw_dir);
5264 void fclosep(FILE **f) {
5269 void pclosep(FILE **f) {
5274 void closep(int *fd) {
5276 close_nointr_nofail(*fd);
5279 void closedirp(DIR **d) {
5284 bool filename_is_safe(const char *p) {
5298 if (strlen(p) > FILENAME_MAX)
5304 bool string_is_safe(const char *p) {
5309 for (t = p; *t; t++) {
5310 if (*t > 0 && *t < ' ')
5313 if (strchr("\\\"\'", *t))
5320 bool string_has_cc(const char *p) {
5325 for (t = p; *t; t++)
5326 if (*t > 0 && *t < ' ')
5332 bool path_is_safe(const char *p) {
5337 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5340 if (strlen(p) > PATH_MAX)
5343 /* The following two checks are not really dangerous, but hey, they still are confusing */
5344 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5347 if (strstr(p, "//"))
5353 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5354 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5355 int (*compar) (const void *, const void *, void *), void *arg) {
5364 p = (void *)(((const char *) base) + (idx * size));
5365 comparison = compar(key, p, arg);
5368 else if (comparison > 0)
5376 bool is_locale_utf8(void) {
5378 static int cached_answer = -1;
5380 if (cached_answer >= 0)
5383 if (!setlocale(LC_ALL, "")) {
5384 cached_answer = true;
5388 set = nl_langinfo(CODESET);
5390 cached_answer = true;
5394 cached_answer = streq(set, "UTF-8");
5396 return (bool)cached_answer;
5399 const char *draw_special_char(DrawSpecialChar ch) {
5400 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5402 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5403 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5404 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5405 [DRAW_TREE_SPACE] = " ", /* */
5406 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5408 /* ASCII fallback */ {
5409 [DRAW_TREE_VERT] = "| ",
5410 [DRAW_TREE_BRANCH] = "|-",
5411 [DRAW_TREE_RIGHT] = "`-",
5412 [DRAW_TREE_SPACE] = " ",
5413 [DRAW_TRIANGULAR_BULLET] = "> ",
5417 return draw_table[!is_locale_utf8()][ch];
5420 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5423 size_t l, old_len, new_len;
5429 old_len = strlen(old_string);
5430 new_len = strlen(new_string);
5443 if (!startswith(f, old_string)) {
5449 nl = l - old_len + new_len;
5450 a = realloc(r, nl + 1);
5458 t = stpcpy(t, new_string);
5470 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5471 const char *i, *begin = NULL;
5476 } state = STATE_OTHER;
5478 size_t osz = 0, isz;
5484 /* Strips ANSI color and replaces TABs by 8 spaces */
5486 isz = _isz ? *_isz : strlen(*ibuf);
5488 f = open_memstream(&obuf, &osz);
5492 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5497 if (i >= *ibuf + isz) /* EOT */
5499 else if (*i == '\x1B')
5500 state = STATE_ESCAPE;
5501 else if (*i == '\t')
5508 if (i >= *ibuf + isz) { /* EOT */
5511 } else if (*i == '[') {
5512 state = STATE_BRACKET;
5517 state = STATE_OTHER;
5524 if (i >= *ibuf + isz || /* EOT */
5525 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5528 state = STATE_OTHER;
5530 } else if (*i == 'm')
5531 state = STATE_OTHER;
5553 int on_ac_power(void) {
5554 bool found_offline = false, found_online = false;
5555 _cleanup_closedir_ DIR *d = NULL;
5557 d = opendir("/sys/class/power_supply");
5563 union dirent_storage buf;
5564 _cleanup_close_ int fd = -1, device = -1;
5569 k = readdir_r(d, &buf.de, &de);
5576 if (ignore_file(de->d_name))
5579 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5581 if (errno == ENOENT || errno == ENOTDIR)
5587 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5589 if (errno == ENOENT)
5595 n = read(fd, contents, sizeof(contents));
5599 if (n != 6 || memcmp(contents, "Mains\n", 6))
5602 close_nointr_nofail(fd);
5603 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5605 if (errno == ENOENT)
5611 n = read(fd, contents, sizeof(contents));
5615 if (n != 2 || contents[1] != '\n')
5618 if (contents[0] == '1') {
5619 found_online = true;
5621 } else if (contents[0] == '0')
5622 found_offline = true;
5627 return found_online || !found_offline;
5630 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5637 if (!path_strv_canonicalize_uniq(search))
5640 STRV_FOREACH(i, search) {
5641 _cleanup_free_ char *p = NULL;
5644 p = strjoin(*i, "/", path, NULL);
5654 if (errno != ENOENT)
5661 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5662 _cleanup_strv_free_ char **copy = NULL;
5668 if (path_is_absolute(path)) {
5671 f = fopen(path, mode);
5680 copy = strv_copy((char**) search);
5684 return search_and_fopen_internal(path, mode, copy, _f);
5687 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5688 _cleanup_strv_free_ char **s = NULL;
5690 if (path_is_absolute(path)) {
5693 f = fopen(path, mode);
5702 s = strv_split_nulstr(search);
5706 return search_and_fopen_internal(path, mode, s, _f);
5709 int create_tmp_dir(char template[], char** dir_name) {
5715 RUN_WITH_UMASK(0077) {
5716 d = mkdtemp(template);
5719 log_error("Can't create directory %s: %m", template);
5723 dt = strjoin(d, "/tmp", NULL);
5729 RUN_WITH_UMASK(0000) {
5730 r = mkdir(dt, 0777);
5733 log_error("Can't create directory %s: %m", dt);
5737 log_debug("Created temporary directory %s", dt);
5739 r = chmod(dt, 0777 | S_ISVTX);
5741 log_error("Failed to chmod %s: %m", dt);
5745 log_debug("Set sticky bit on %s", dt);
5759 char *strextend(char **x, ...) {
5766 l = f = *x ? strlen(*x) : 0;
5773 t = va_arg(ap, const char *);
5778 if (n > ((size_t) -1) - l) {
5787 r = realloc(*x, l+1);
5797 t = va_arg(ap, const char *);
5811 char *strrep(const char *s, unsigned n) {
5819 p = r = malloc(l * n + 1);
5823 for (i = 0; i < n; i++)
5830 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5834 if (*allocated >= need)
5837 a = MAX(64u, need * 2);