HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/terminal-util.c

102,552 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 5623458dff231cd5b5e48a309e6a08afebf47c70

Lines 1001–2000 of 2,949

}
 
void reset_dev_console_fd(int fd, bool switch_to_text) {
        int r;
 
        assert(fd >= 0);
 
        _cleanup_close_ int lock_fd = lock_dev_console();
        if (lock_fd < 0)
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
 
        r = terminal_reset_ioctl(fd, switch_to_text);
        if (r < 0)
                log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
 
        unsigned rows, cols;
        r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
        if (r < 0)
                log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
        else if (r > 0) {
                r = terminal_set_size_fd(fd, NULL, rows, cols);
                if (r < 0)
                        log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
        } else
                (void) terminal_fix_size(fd, fd);
 
        r = terminal_reset_ansi_seq(fd);
        if (r < 0)
                log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
}
 
int lock_dev_console(void) {
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        /* NB: We do not use O_NOFOLLOW here, because some container managers might place a symlink to some
         * pty in /dev/console, in which case it should be fine to lock the target TTY. */
        fd = open_terminal("/dev/console", O_RDONLY|O_CLOEXEC|O_NOCTTY);
        if (fd < 0)
                return fd;
 
        r = lock_generic(fd, LOCK_BSD, LOCK_EX);
        if (r < 0)
                return r;
 
        return TAKE_FD(fd);
}
 
int make_console_stdio(bool switch_to_text) {
        int fd, r;
 
        /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
         * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
         * is specified on the kernel command line. */
 
        fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
        if (fd < 0) {
                log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
 
                r = make_null_stdio();
                if (r < 0)
                        return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
 
        } else {
                reset_dev_console_fd(fd, switch_to_text);
 
                r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
                if (r < 0)
                        return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
        }
 
        reset_terminal_feature_caches();
        return 0;
}
 
static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
        assert(tty);
 
        tty = skip_dev_prefix(tty);
 
        const char *e = startswith(tty, "tty");
        if (!e)
                return -EINVAL;
 
        return safe_atou(e, ret);
}
 
int vtnr_from_tty(const char *tty) {
        unsigned u;
        int r;
 
        assert(tty);
 
        r = vtnr_from_tty_raw(tty, &u);
        if (r < 0)
                return r;
        if (!vtnr_is_valid(u))
                return -ERANGE;
 
        return (int) u;
}
 
bool tty_is_vc(const char *tty) {
        assert(tty);
 
        /* NB: for >= 0 values no range check is conducted here, on the assumption that the caller will
         * either extract vtnr through vtnr_from_tty() later where ERANGE would be reported, or doesn't care
         * about whether it's strictly valid, but only asking "does this fall into the vt category?", for which
         * "yes" seems to be a better answer. */
 
        return vtnr_from_tty_raw(tty, /* ret= */ NULL) >= 0;
}
 
bool tty_is_console(const char *tty) {
        assert(tty);
 
        return streq(skip_dev_prefix(tty), "console");
}
 
int resolve_dev_console(char **ret) {
        int r;
 
        assert(ret);
 
        /* Resolve where /dev/console is pointing to. If /dev/console is a symlink (like in container
         * managers), we'll just resolve the symlink. If it's a real device node, we'll use if
         * /sys/class/tty/tty0/active, but only if /sys/ is actually ours (i.e. not read-only-mounted which
         * is a sign for container setups). */
 
        _cleanup_free_ char *chased = NULL;
        r = chase("/dev/console", /* root= */ NULL, /* flags= */ 0, &chased, /* ret_fd= */ NULL);
        if (r < 0)
                return r;
        if (!path_equal(chased, "/dev/console")) {
                *ret = TAKE_PTR(chased);
                return 0;
        }
 
        r = path_is_read_only_fs("/sys");
        if (r < 0)
                return r;
        if (r > 0)
                return -ENOMEDIUM;
 
        _cleanup_free_ char *active = NULL;
        r = read_one_line_file("/sys/class/tty/console/active", &active);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENXIO;
 
        /* If multiple log outputs are configured the last one is what /dev/console points to */
        const char *tty = strrchr(active, ' ');
        if (tty)
                tty++;
        else
                tty = active;
 
        if (streq(tty, "tty0")) {
                active = mfree(active);
 
                /* Get the active VC (e.g. tty1) */
                r = read_one_line_file("/sys/class/tty/tty0/active", &active);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -ENXIO;
 
                tty = active;
        }
 
        _cleanup_free_ char *path = NULL;
        path = path_join("/dev", tty);
        if (!path)
                return -ENOMEM;
 
        *ret = TAKE_PTR(path);
        return 0;
}
 
int get_kernel_consoles(char ***ret) {
        _cleanup_strv_free_ char **l = NULL;
        _cleanup_free_ char *line = NULL;
        int r;
 
        assert(ret);
 
        /* If /sys/ is mounted read-only this means we are running in some kind of container environment.
         * In that case /sys/ would reflect the host system, not us, hence ignore the data we can read from it. */
        if (path_is_read_only_fs("/sys") > 0)
                goto fallback;
 
        r = read_one_line_file("/sys/class/tty/console/active", &line);
        if (r < 0)
                return r;
 
        for (const char *p = line;;) {
                _cleanup_free_ char *tty = NULL, *path = NULL;
 
                r = extract_first_word(&p, &tty, NULL, 0);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                if (streq(tty, "tty0")) {
                        tty = mfree(tty);
                        r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
                        if (r < 0)
                                return r;
                        if (r == 0) {
                                log_debug("No VT active, skipping /dev/tty0.");
                                continue;
                        }
                }
 
                path = path_join("/dev", tty);
                if (!path)
                        return -ENOMEM;
 
                if (access(path, F_OK) < 0) {
                        log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
                        continue;
                }
 
                r = strv_consume(&l, TAKE_PTR(path));
                if (r < 0)
                        return r;
        }
 
        if (strv_isempty(l)) {
                log_debug("No devices found for system console");
                goto fallback;
        }
 
        *ret = TAKE_PTR(l);
        return strv_length(*ret);
 
fallback:
        r = strv_extend(&l, "/dev/console");
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(l);
        return 0;
}
 
bool tty_is_vc_resolve(const char *tty) {
        _cleanup_free_ char *resolved = NULL;
 
        assert(tty);
 
        if (streq(skip_dev_prefix(tty), "console")) {
                if (resolve_dev_console(&resolved) < 0)
                        return false;
 
                tty = resolved;
        }
 
        return tty_is_vc(tty);
}
 
int fd_columns(int fd) {
        struct winsize ws = {};
 
        if (fd < 0)
                return -EBADF;
 
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
                return -errno;
 
        if (ws.ws_col <= 0)
                return -ENODATA; /* some tty types come up with invalid row/column initially, return a recognizable error for that */
 
        return ws.ws_col;
}
 
int getenv_columns(void) {
        int r;
 
        const char *e = getenv("COLUMNS");
        if (!e)
                return -ENXIO;
 
        unsigned c;
        r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
        if (r < 0)
                return r;
 
        return (int) c;
}
 
unsigned columns(void) {
 
        if (cached_columns > 0)
                return cached_columns;
 
        int c = getenv_columns();
        if (c < 0) {
                c = fd_columns(STDOUT_FILENO);
                if (c < 0)
                        c = 80;
        }
 
        assert(c > 0);
 
        cached_columns = c;
        return cached_columns;
}
 
int fd_lines(int fd) {
        struct winsize ws = {};
 
        if (fd < 0)
                return -EBADF;
 
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
                return -errno;
 
        if (ws.ws_row <= 0)
                return -ENODATA; /* some tty types come up with invalid row/column initially, return a recognizable error for that */
 
        return ws.ws_row;
}
 
unsigned lines(void) {
        const char *e;
        int l;
 
        if (cached_lines > 0)
                return cached_lines;
 
        l = 0;
        e = getenv("LINES");
        if (e)
                (void) safe_atoi(e, &l);
 
        if (l <= 0 || l > USHRT_MAX) {
                l = fd_lines(STDOUT_FILENO);
                if (l <= 0)
                        l = 24;
        }
 
        cached_lines = l;
        return cached_lines;
}
 
int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
        struct winsize ws;
 
        assert(fd >= 0);
 
        if (!ident)
                ident = "TTY";
 
        if (rows == UINT_MAX && cols == UINT_MAX)
                return 0;
 
        if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
                return log_debug_errno(errno,
                                       "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
                                       ident);
 
        if (rows == UINT_MAX)
                rows = ws.ws_row;
        else if (rows > USHRT_MAX)
                rows = USHRT_MAX;
 
        if (cols == UINT_MAX)
                cols = ws.ws_col;
        else if (cols > USHRT_MAX)
                cols = USHRT_MAX;
 
        if (rows == ws.ws_row && cols == ws.ws_col)
                return 0;
 
        ws.ws_row = rows;
        ws.ws_col = cols;
 
        if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
                return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident);
 
        return 0;
}
 
int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
        unsigned rows = UINT_MAX, cols = UINT_MAX;
        int r;
 
        assert(tty);
 
        if (!ret_rows && !ret_cols)
                return 0;
 
        tty = skip_dev_prefix(tty);
        if (path_startswith(tty, "pts/"))
                return -EMEDIUMTYPE;
        if (!in_charset(tty, ALPHANUMERICAL))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
 
        rowskey = strjoin("systemd.tty.rows.", tty);
        if (!rowskey)
                return -ENOMEM;
 
        colskey = strjoin("systemd.tty.columns.", tty);
        if (!colskey)
                return -ENOMEM;
 
        r = proc_cmdline_get_key_many(/* flags= */ 0,
                                      rowskey, &rowsvalue,
                                      colskey, &colsvalue);
        if (r < 0)
                return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
 
        if (rowsvalue) {
                r = safe_atou(rowsvalue, &rows);
                if (r < 0)
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
        }
 
        if (colsvalue) {
                r = safe_atou(colsvalue, &cols);
                if (r < 0)
                        return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
        }
 
        if (ret_rows)
                *ret_rows = rows;
        if (ret_cols)
                *ret_cols = cols;
 
        return rows != UINT_MAX || cols != UINT_MAX;
}
 
/* intended to be used as a SIGWINCH sighandler */
void columns_lines_cache_reset(int signum) {
        cached_columns = 0;
        cached_lines = 0;
}
 
void reset_terminal_feature_caches(void) {
        cached_columns = 0;
        cached_lines = 0;
 
        cached_on_tty = -1;
        cached_on_dev_null = -1;
 
        reset_ansi_feature_caches();
}
 
bool on_tty(void) {
 
        /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
         * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
         * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
         * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
         * terminal functionality when outputting stuff, even if the input is piped to us. */
 
        if (cached_on_tty < 0)
                cached_on_tty =
                        isatty_safe(STDOUT_FILENO) &&
                        isatty_safe(STDERR_FILENO);
 
        return cached_on_tty;
}
 
int getttyname_malloc(int fd, char **ret) {
        char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
        int r;
 
        assert(fd >= 0);
        assert(ret);
 
        r = ttyname_r(fd, path, sizeof path); /* positive error */
        assert(r >= 0);
        if (r == ERANGE)
                return -ENAMETOOLONG;
        if (r > 0)
                return -r;
 
        return strdup_to(ret, skip_dev_prefix(path));
}
 
int getttyname_harder(int fd, char **ret) {
        _cleanup_free_ char *s = NULL;
        int r;
 
        assert(ret);
 
        r = getttyname_malloc(fd, &s);
        if (r < 0)
                return r;
 
        if (streq(s, "tty"))
                return get_ctty(0, NULL, ret);
 
        *ret = TAKE_PTR(s);
        return 0;
}
 
int get_ctty_devnr(pid_t pid, dev_t *ret) {
        _cleanup_free_ char *line = NULL;
        unsigned long ttynr;
        const char *p;
        int r;
 
        assert(pid >= 0);
 
        p = procfs_file_alloca(pid, "stat");
        r = read_one_line_file(p, &line);
        if (r < 0)
                return r;
 
        p = strrchr(line, ')');
        if (!p)
                return -EIO;
 
        p++;
 
        if (sscanf(p, " "
                   "%*c "  /* state */
                   "%*d "  /* ppid */
                   "%*d "  /* pgrp */
                   "%*d "  /* session */
                   "%lu ", /* ttynr */
                   &ttynr) != 1)
                return -EIO;
 
        if (devnum_is_zero(ttynr))
                return -ENXIO;
 
        if (ret)
                *ret = (dev_t) ttynr;
 
        return 0;
}
 
int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
        char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
        _cleanup_free_ char *buf = NULL;
        const char *fn = NULL, *w;
        dev_t devnr;
        int r;
 
        r = get_ctty_devnr(pid, &devnr);
        if (r < 0)
                return r;
 
        r = device_path_make_canonical(S_IFCHR, devnr, &buf);
        if (r < 0) {
                struct stat st;
 
                if (r != -ENOENT) /* No symlink for this in /dev/char/? */
                        return r;
 
                /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
                 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
                 * assume this is a PTY for a moment, and check if the device node this would then map to in
                 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
                 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
                 * the minor number of the pty. */
                xsprintf(pty, "/dev/pts/%u", minor(devnr));
 
                if (stat(pty, &st) < 0) {
                        if (errno != ENOENT)
                                return -errno;
 
                } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
                        fn = pty;
 
                if (!fn) {
                        /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
                         * symlink in /dev/char/. Let's return something vaguely useful. */
                        r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
                        if (r < 0)
                                return r;
 
                        fn = buf;
                }
        } else
                fn = buf;
 
        w = path_startswith(fn, "/dev/");
        if (!w)
                return -EINVAL;
 
        if (ret) {
                r = strdup_to(ret, w);
                if (r < 0)
                        return r;
        }
 
        if (ret_devnr)
                *ret_devnr = devnr;
 
        return 0;
}
 
int ptsname_malloc(int fd, char **ret) {
        assert(fd >= 0);
        assert(ret);
 
        for (size_t l = 50;;) {
                _cleanup_free_ char *c = NULL;
 
                c = new(char, l);
                if (!c)
                        return -ENOMEM;
 
                if (ptsname_r(fd, c, l) >= 0) {
                        *ret = TAKE_PTR(c);
                        return 0;
                }
                if (errno != ERANGE)
                        return -errno;
 
                if (!MUL_ASSIGN_SAFE(&l, 2))
                        return -ENOMEM;
        }
}
 
int openpt_allocate(int flags, char **ret_peer_path) {
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return -errno;
 
        _cleanup_free_ char *p = NULL;
        if (ret_peer_path) {
                r = ptsname_malloc(fd, &p);
                if (r < 0)
                        return r;
 
                if (!path_startswith(p, "/dev/pts/"))
                        return -EINVAL;
        }
 
        if (unlockpt(fd) < 0)
                return -errno;
 
        if (ret_peer_path)
                *ret_peer_path = TAKE_PTR(p);
 
        return TAKE_FD(fd);
}
 
static int ptsname_namespace(int pty, char **ret) {
        int no = -1;
 
        assert(pty >= 0);
        assert(ret);
 
        /* Like ptsname(), but doesn't assume that the path is
         * accessible in the local namespace. */
 
        if (ioctl(pty, TIOCGPTN, &no) < 0)
                return -errno;
 
        if (no < 0)
                return -EIO;
 
        if (asprintf(ret, "/dev/pts/%i", no) < 0)
                return -ENOMEM;
 
        return 0;
}
 
int openpt_allocate_in_namespace(
                const PidRef *pidref,
                int flags,
                char **ret_peer_path) {
 
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
        int r;
 
        assert(pidref);
 
        r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd= */ NULL, &usernsfd, &rootfd);
        if (r < 0)
                return log_debug_errno(r, "Failed to open namespaces of PID "PID_FMT": %m", pidref->pid);
 
        if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
                return -errno;
 
        r = namespace_fork(
                        "(sd-openptns)",
                        "(sd-openpt)",
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
                        pidnsfd,
                        mntnsfd,
                        /* netns_fd= */ -EBADF,
                        usernsfd,
                        rootfd,
                        /* ret= */ NULL);
        if (r < 0)
                return r;
        if (r == 0) {
                pair[0] = safe_close(pair[0]);
 
                fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
                if (fd < 0)
                        _exit(EXIT_FAILURE);
 
                if (send_one_fd(pair[1], fd, 0) < 0)
                        _exit(EXIT_FAILURE);
 
                _exit(EXIT_SUCCESS);
        }
 
        pair[1] = safe_close(pair[1]);
 
        fd = receive_one_fd(pair[0], 0);
        if (fd < 0)
                return fd;
 
        if (ret_peer_path) {
                r = ptsname_namespace(fd, ret_peer_path);
                if (r < 0)
                        return r;
        }
 
        return TAKE_FD(fd);
}
 
static bool on_dev_null(void) {
        struct stat dst, ost, est;
 
        if (cached_on_dev_null >= 0)
                return cached_on_dev_null;
 
        if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
                cached_on_dev_null = false;
        else
                cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
 
        return cached_on_dev_null;
}
 
bool term_env_valid(const char *term) {
        /* Checks if the specified $TERM value is suitable for propagation, i.e. is not empty, not set to
         * "unknown" (as is common in CI), and only contains characters valid in terminal type names.
         * Valid $TERM values are things like "xterm-256color", "linux", "screen.xterm-256color", i.e.
         * alphanumeric characters, hyphens, underscores, dots, and plus signs. */
        return !isempty(term) &&
                !streq(term, "unknown") &&
                in_charset(term, ALPHANUMERICAL "-_+.");
}
 
bool getenv_terminal_is_dumb(void) {
        const char *e;
 
        e = getenv("TERM");
        if (!e)
                return true;
 
        return streq(e, "dumb");
}
 
bool terminal_is_dumb(void) {
        if (!on_tty() && !on_dev_null())
                return true;
 
        return getenv_terminal_is_dumb();
}
 
bool dev_console_colors_enabled(void) {
        _cleanup_free_ char *s = NULL;
        ColorMode m;
 
        /* Returns true if we assume that color is supported on /dev/console.
         *
         * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
         * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
         * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
         * colors_enabled() operates. */
 
        m = parse_systemd_colors();
        if (m >= 0)
                return m;
 
        if (getenv("NO_COLOR"))
                return false;
 
        if (getenv_for_pid(1, "TERM", &s) <= 0)
                (void) proc_cmdline_get_key("TERM", 0, &s);
 
        return !streq_ptr(s, "dumb");
}
 
int vt_restore(int fd) {
 
        static const struct vt_mode mode = {
                .mode = VT_AUTO,
        };
 
        int r, ret = 0;
 
        assert(fd >= 0);
 
        if (!isatty_safe(fd))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTTY), "Asked to restore the VT for an fd that does not refer to a terminal.");
 
        if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
                RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT to text mode, ignoring: %m"));
 
        r = vt_reset_keyboard(fd);
        if (r < 0)
                RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
 
        if (ioctl(fd, VT_SETMODE, &mode) < 0)
                RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m"));
 
        r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
        if (r < 0)
                RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
 
        return ret;
}
 
int vt_release(int fd, bool restore) {
        assert(fd >= 0);
 
        /* This function releases the VT by acknowledging the VT-switch signal
         * sent by the kernel and optionally reset the VT in text and auto
         * VT-switching modes. */
 
        if (!isatty_safe(fd))
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTTY), "Asked to release the VT for an fd that does not refer to a terminal.");
 
        if (ioctl(fd, VT_RELDISP, 1) < 0)
                return -errno;
 
        if (restore)
                return vt_restore(fd);
 
        return 0;
}
 
void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
        /* Note that this will initialize output variables only when there's something to output.
         * The caller must pre-initialize to "" or NULL as appropriate. */
 
        if (priority <= LOG_ERR) {
                if (on)
                        *on = ansi_highlight_red();
                if (off)
                        *off = ansi_normal();
                if (highlight)
                        *highlight = ansi_highlight();
 
        } else if (priority <= LOG_WARNING) {
                if (on)
                        *on = ansi_highlight_yellow();
                if (off)
                        *off = ansi_normal();
                if (highlight)
                        *highlight = ansi_highlight();
 
        } else if (priority <= LOG_NOTICE) {
                if (on)
                        *on = ansi_highlight();
                if (off)
                        *off = ansi_normal();
                if (highlight)
                        *highlight = ansi_highlight_red();
 
        } else if (priority >= LOG_DEBUG) {
                if (on)
                        *on = ansi_grey();
                if (off)
                        *off = ansi_normal();
                if (highlight)
                        *highlight = ansi_highlight_red();
        }
}
 
int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
        assert(fd >= 0);
 
        char cursor_position[STRLEN("\x1B[" ";" "H") + DECIMAL_STR_MAX(unsigned) * 2 + 1];
        xsprintf(cursor_position, "\x1B[%u;%uH", row, column);
 
        return loop_write(fd, cursor_position, SIZE_MAX);
}
 
static int terminal_verify_same(int input_fd, int output_fd) {
        int r;
 
        assert(input_fd >= 0);
        assert(output_fd >= 0);
 
        /* Validates that the specified fds reference the same TTY */
 
        if (input_fd != output_fd) {
                struct stat sti;
                if (fstat(input_fd, &sti) < 0)
                        return -errno;
 
                r = stat_verify_char(&sti); /* TTYs are character devices */
                if (r < 0)
                        return r;
 
                struct stat sto;
                if (fstat(output_fd, &sto) < 0)
                        return -errno;
 
                r = stat_verify_char(&sto);
                if (r < 0)
                        return r;
 
                if (sti.st_rdev != sto.st_rdev)
                        return -ENOLINK;
        }
 
        if (!isatty_safe(input_fd)) /* The check above was just for char device, but now let's ensure it's actually a tty */
                return -ENOTTY;
 
        return 0;
}
 
typedef enum CursorPositionState {
        CURSOR_TEXT,
        CURSOR_ESCAPE,
        CURSOR_ROW,
        CURSOR_COLUMN,
} CursorPositionState;
 
typedef struct CursorPositionContext {
        CursorPositionState state;
        unsigned row, column;
} CursorPositionContext;
 
static int scan_cursor_position_response(
                CursorPositionContext *context,
                const char *buf,
                size_t size,
                size_t *ret_processed) {
 
        assert(context);
        assert(buf);
        assert(ret_processed);
 
        for (size_t i = 0; i < size; i++) {
                char c = buf[i];
 
                switch (context->state) {
 
                case CURSOR_TEXT:
                        context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
                        break;
 
                case CURSOR_ESCAPE:
                        context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
                        break;
 
                case CURSOR_ROW:
                        if (c == ';')
                                context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
                        else {
                                int d = undecchar(c);
 
                                /* We read a decimal character, let's suffix it to the number we so far read,
                                 * but let's do an overflow check first. */
                                if (d < 0 || context->row > (UINT_MAX-d)/10)
                                        context->state = CURSOR_TEXT;
                                else
                                        context->row = context->row * 10 + d;
                        }
                        break;
 
                case CURSOR_COLUMN:
                        if (c == 'R') {
                                if (context->column > 0) {
                                        *ret_processed = i + 1;
                                        return 1; /* success! */
                                }
 
                                context->state = CURSOR_TEXT;
                        } else {
                                int d = undecchar(c);
 
                                /* As above, add the decimal character to our column number */
                                if (d < 0 || context->column > (UINT_MAX-d)/10)
                                        context->state = CURSOR_TEXT;
                                else
                                        context->column = context->column * 10 + d;
                        }
 
                        break;
                }
 
                /* Reset any positions we might have picked up */
                if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
                        context->row = context->column = 0;
        }