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 2001–2949 of 2,949

 
        *ret_processed = size;
        return 0; /* all good, but not enough data yet */
}
 
int terminal_get_cursor_position(
                int input_fd,
                int output_fd,
                unsigned *ret_row,
                unsigned *ret_column) {
 
        _cleanup_close_ int nonblock_input_fd = -EBADF;
        int r;
 
        assert(input_fd >= 0);
        assert(output_fd >= 0);
 
        if (getenv_terminal_is_dumb())
                return -EOPNOTSUPP;
 
        r = terminal_verify_same(input_fd, output_fd);
        if (r < 0)
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
 
        /* Failure to reset the terminal is ignored here and in similar cases below.
         * We already have our result; if cleanup fails it doesn't change the validity of the result. */
        struct termios old_termios = TERMIOS_NULL;
        CLEANUP_TERMIOS_RESET(input_fd, old_termios);
 
        if (tcgetattr(input_fd, &old_termios) < 0)
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
 
        struct termios new_termios = old_termios;
        termios_disable_echo(&new_termios);
 
        if (tcsetattr(input_fd, TCSANOW, &new_termios) < 0)
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
 
        /* Request cursor position (DSR/CPR) */
        r = loop_write(output_fd, "\x1B[6n", SIZE_MAX);
        if (r < 0)
                return r;
 
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read() should someone
         * else process the POLLIN. */
 
        nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (r < 0)
                return r;
 
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
        size_t buf_full = 0;
        CursorPositionContext context = {};
 
        for (bool first = true;; first = false) {
                if (buf_full == 0) {
                        usec_t n = now(CLOCK_MONOTONIC);
                        if (n >= end)
                                return -EOPNOTSUPP;
 
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
                        if (r < 0)
                                return r;
                        if (r == 0)
                                return -EOPNOTSUPP;
 
                        /* On the first try, read multiple characters, i.e. the shortest valid
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
                         * unnecessarily drop too many characters from the input queue. */
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
                        if (l < 0) {
                                if (errno == EAGAIN)
                                        continue;
 
                                return -errno;
                        }
 
                        assert((size_t) l <= sizeof(buf));
                        buf_full = l;
                }
 
                size_t processed;
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
                if (r < 0)
                        return r;
 
                assert(processed <= buf_full);
                buf_full -= processed;
                memmove(buf, buf + processed, buf_full);
 
                if (r > 0) {
                        /* Superficial validity check */
                        if (context.row >= 32766 || context.column >= 32766)
                                return -ENODATA;
 
                        if (ret_row)
                                *ret_row = context.row;
                        if (ret_column)
                                *ret_column = context.column;
 
                        return 0;
                }
        }
}
 
int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
        int r = 0;
 
        assert(fd >= 0);
        assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
 
        /* Resets the terminal comprehensively, i.e. via both ioctl()s and via ANSI sequences, but do so only
         * if $TERM is unset or set to "dumb" */
 
        if (!isatty_safe(fd))
                return -ENOTTY;
 
        RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
 
        if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
            (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
                RET_GATHER(r, terminal_reset_ansi_seq(fd));
 
        return r;
}
 
int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
        assert(fd >= 0);
 
        _cleanup_close_ int lock_fd = lock_dev_console();
        if (lock_fd < 0)
                log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
 
        return terminal_reset_defensive(fd, flags);
}
 
void termios_disable_echo(struct termios *termios) {
        assert(termios);
 
        termios->c_lflag &= ~(ICANON|ECHO);
        termios->c_cc[VMIN] = 1;
        termios->c_cc[VTIME] = 0;
}
 
static bool termios_is_null(const struct termios *t) {
        if (!t)
                return true;
 
        return t->c_iflag == UINT_MAX &&
               t->c_oflag == UINT_MAX &&
               t->c_cflag == UINT_MAX &&
               t->c_lflag == UINT_MAX;
}
 
void termios_reset(const TermiosResetContext *c) {
        assert(c);
 
        PROTECT_ERRNO;
 
        if (c->fd && *c->fd >= 0 && !termios_is_null(c->termios))
                (void) tcsetattr(*c->fd, TCSANOW, c->termios);
}
 
typedef enum BackgroundColorState {
        BACKGROUND_TEXT,
        BACKGROUND_ESCAPE,
        BACKGROUND_BRACKET,
        BACKGROUND_FIRST_ONE,
        BACKGROUND_SECOND_ONE,
        BACKGROUND_SEMICOLON,
        BACKGROUND_R,
        BACKGROUND_G,
        BACKGROUND_B,
        BACKGROUND_RED,
        BACKGROUND_GREEN,
        BACKGROUND_BLUE,
        BACKGROUND_STRING_TERMINATOR,
} BackgroundColorState;
 
typedef struct BackgroundColorContext {
        BackgroundColorState state;
        uint32_t red, green, blue;
        unsigned red_bits, green_bits, blue_bits;
} BackgroundColorContext;
 
static int scan_background_color_response(
                BackgroundColorContext *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 BACKGROUND_TEXT:
                        context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_ESCAPE:
                        context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_BRACKET:
                        context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_FIRST_ONE:
                        context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_SECOND_ONE:
                        context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_SEMICOLON:
                        context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_R:
                        context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_G:
                        context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_B:
                        context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
                        break;
 
                case BACKGROUND_RED:
                        if (c == '/')
                                context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
                        else {
                                int d = unhexchar(c);
                                if (d < 0 || context->red_bits >= sizeof(context->red)*8)
                                        context->state = BACKGROUND_TEXT;
                                else {
                                        context->red = (context->red << 4) | d;
                                        context->red_bits += 4;
                                }
                        }
                        break;
 
                case BACKGROUND_GREEN:
                        if (c == '/')
                                context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
                        else {
                                int d = unhexchar(c);
                                if (d < 0 || context->green_bits >= sizeof(context->green)*8)
                                        context->state = BACKGROUND_TEXT;
                                else {
                                        context->green = (context->green << 4) | d;
                                        context->green_bits += 4;
                                }
                        }
                        break;
 
                case BACKGROUND_BLUE:
                        if (c == '\x07') {
                                if (context->blue_bits > 0) {
                                        *ret_processed = i + 1;
                                        return 1; /* success! */
                                }
 
                                context->state = BACKGROUND_TEXT;
                        } else if (c == '\x1b')
                                context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
                        else {
                                int d = unhexchar(c);
                                if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
                                        context->state = BACKGROUND_TEXT;
                                else {
                                        context->blue = (context->blue << 4) | d;
                                        context->blue_bits += 4;
                                }
                        }
                        break;
 
                case BACKGROUND_STRING_TERMINATOR:
                        if (c == '\\') {
                                *ret_processed = i + 1;
                                return 1; /* success! */
                        }
 
                        context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
                        break;
 
                }
 
                /* Reset any colors we might have picked up */
                if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
                        /* reset color */
                        context->red = context->green = context->blue = 0;
                        context->red_bits = context->green_bits = context->blue_bits = 0;
                }
        }
 
        *ret_processed = size;
        return 0; /* all good, but not enough data yet */
}
 
int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
        int r;
 
        assert(ret_red);
        assert(ret_green);
        assert(ret_blue);
 
        if (!colors_enabled())
                return -EOPNOTSUPP;
 
        r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
        if (r < 0)
                return r;
 
        if (streq_ptr(getenv("TERM"), "linux")) {
                /* Linux console is black */
                *ret_red = *ret_green = *ret_blue = 0.0;
                return 0;
        }
 
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (r < 0)
                return r;
 
        struct termios old_termios = TERMIOS_NULL;
        CLEANUP_TERMIOS_RESET(nonblock_input_fd, old_termios);
 
        if (tcgetattr(nonblock_input_fd, &old_termios) < 0)
                return -errno;
 
        struct termios new_termios = old_termios;
        termios_disable_echo(&new_termios);
 
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
                return -errno;
 
        r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
        if (r < 0)
                return r;
 
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
        size_t buf_full = 0;
        BackgroundColorContext context = {};
 
        for (bool first = true;; first = false) {
                if (buf_full == 0) {
                        usec_t n = now(CLOCK_MONOTONIC);
                        if (n >= end)
                                return -EOPNOTSUPP;
 
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
                        if (r < 0)
                                return r;
                        if (r == 0)
                                return -EOPNOTSUPP;
 
                        /* On the first try, read multiple characters, i.e. the shortest valid
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
                         * unnecessarily drop too many characters from the input queue. */
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
                        if (l < 0) {
                                if (errno == EAGAIN)
                                        continue;
                                return -errno;
                        }
 
                        assert((size_t) l <= sizeof(buf));
                        buf_full = l;
                }
 
                size_t processed;
                r = scan_background_color_response(&context, buf, buf_full, &processed);
                if (r < 0)
                        return r;
 
                assert(processed <= buf_full);
                buf_full -= processed;
                memmove(buf, buf + processed, buf_full);
 
                if (r > 0) {
                        assert(context.red_bits > 0);
                        *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
                        assert(context.green_bits > 0);
                        *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
                        assert(context.blue_bits > 0);
                        *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
                        return 0;
                }
        }
}
 
/* Determine terminal dimensions by means of ANSI sequences: save the cursor via DECSC, position it far
 * to the bottom right (clamped to actual terminal dimensions), read back via DSR where we ended up, and
 * restore cursor via DECRC. Only needs a single DSR round-trip, and always restores the cursor regardless
 * of whether the response is received.
 *
 * Caller must have already opened a non-blocking input fd and configured termios (echo/icanon off). */
static int terminal_query_size_by_dsr(
                int nonblock_input_fd,
                int output_fd,
                unsigned *ret_rows,
                unsigned *ret_columns) {
 
        int r;
 
        assert(nonblock_input_fd >= 0);
        assert(output_fd >= 0);
 
        /* Use DECSC/DECRC to save/restore cursor instead of querying position via DSR. This way the cursor
         * is always restored — even on timeout — and we only need one DSR response instead of two. */
        r = loop_write_full(output_fd,
                            "\x1B" "7"              /* DECSC: save cursor position */
                            "\x1B[32766;32766H"     /* CUP: position cursor far to the right and to the bottom, staying within 16bit signed range */
                            "\x1B[6n"               /* DSR: request cursor position (CPR) */
                            "\x1B" "8",             /* DECRC: restore cursor position */
                            SIZE_MAX,
                            CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        if (r < 0)
                return r;
 
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
        size_t buf_full = 0;
        CursorPositionContext context = {};
 
        for (bool first = true;; first = false) {
                if (buf_full == 0) {
                        usec_t n = now(CLOCK_MONOTONIC);
                        if (n >= end)
                                return -EOPNOTSUPP;
 
                        r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
                        if (r < 0)
                                return r;
                        if (r == 0)
                                return -EOPNOTSUPP;
 
                        /* On the first try, read multiple characters, i.e. the shortest valid
                         * reply. Afterwards read byte-wise, since we don't want to read too much, and
                         * unnecessarily drop too many characters from the input queue. */
                        ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
                        if (l < 0) {
                                if (errno == EAGAIN)
                                        continue;
 
                                return -errno;
                        }
 
                        assert((size_t) l <= sizeof(buf));
                        buf_full = l;
                }
 
                size_t processed;
                r = scan_cursor_position_response(&context, buf, buf_full, &processed);
                if (r < 0)
                        return r;
 
                assert(processed <= buf_full);
                buf_full -= processed;
                memmove(buf, buf + processed, buf_full);
 
                if (r > 0) {
                        /* Superficial validity checks (no particular reason to check for < 4, it's
                         * just a way to look for unreasonably small values) */
                        if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766)
                                return -ENODATA;
 
                        if (ret_rows)
                                *ret_rows = context.row;
                        if (ret_columns)
                                *ret_columns = context.column;
 
                        return 0;
                }
        }
}
 
/* Common setup for ANSI terminal queries: validate the fds, open a non-blocking input fd, and configure
 * termios with echo and canonical mode disabled. Caller must restore termios and close the fd when done. */
static int terminal_prepare_query(
                int input_fd,
                int output_fd,
                int *ret_nonblock_fd,
                struct termios *ret_saved_termios) {
 
        int r;
 
        assert(input_fd >= 0);
        assert(output_fd >= 0);
        assert(ret_nonblock_fd);
        assert(ret_saved_termios);
 
        /* Use getenv_terminal_is_dumb() instead of terminal_is_dumb() here since we operate on an
         * explicitly passed fd, not on stdio. terminal_is_dumb() additionally checks on_tty() which
         * tests whether *stderr* is a tty — that's irrelevant when we're querying a directly opened
         * terminal such as /dev/console. */
        if (getenv_terminal_is_dumb())
                return -EOPNOTSUPP;
 
        r = terminal_verify_same(input_fd, output_fd);
        if (r < 0)
                return log_debug_errno(r, "Called with distinct input/output fds: %m");
 
        /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
         * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
        _cleanup_close_ int nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (r < 0)
                return r;
 
        if (tcgetattr(nonblock_input_fd, ret_saved_termios) < 0)
                return log_debug_errno(errno, "Failed to get terminal settings: %m");
 
        struct termios new_termios = *ret_saved_termios;
        termios_disable_echo(&new_termios);
 
        if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
                return log_debug_errno(errno, "Failed to set new terminal settings: %m");
 
        *ret_nonblock_fd = TAKE_FD(nonblock_input_fd);
        return 0;
}
 
/*
 * See https://terminalguide.namepad.de/seq/csi_st-18/,
 * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_.
 */
#define CSI18_Q  "\x1B[18t"               /* Report the size of the text area in characters */
#define CSI18_Rp "\x1B[8;"                /* Reply prefix */
#define CSI18_R0 CSI18_Rp "1;1t"          /* Shortest reply */
#define CSI18_R1 CSI18_Rp "32766;32766t"  /* Longest reply */
 
static int scan_text_area_size_response(
                const char *buf,
                size_t size,
                unsigned *ret_rows,
                unsigned *ret_columns) {
 
        assert(buf);
        assert(ret_rows);
        assert(ret_columns);
 
        /* Check if we have enough space for the shortest possible answer. */
        if (size < STRLEN(CSI18_R0))
                return -EAGAIN;
 
        /* Check if the terminating sequence is present */
        if (buf[size - 1] != 't')
                return -EAGAIN;
 
        unsigned short rows, columns;
        if (sscanf(buf, CSI18_Rp "%hu;%hut", &rows, &columns) != 2)
                return -EINVAL;
 
        *ret_rows = rows;
        *ret_columns = columns;
        return 0;
}
 
/* Determine terminal dimensions by means of an ANSI CSI 18 sequence.
 *
 * Caller must have already opened a non-blocking input fd and configured termios (echo/icanon off). */
static int terminal_query_size_by_csi18(
                int nonblock_input_fd,
                int output_fd,
                unsigned *ret_rows,
                unsigned *ret_columns) {
 
        int r;
 
        assert(nonblock_input_fd >= 0);
        assert(output_fd >= 0);
 
        r = loop_write_full(output_fd, CSI18_Q, SIZE_MAX, CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        if (r < 0)
                return r;
 
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        char buf[STRLEN(CSI18_R1)];
        size_t bytes = 0;
 
        for (;;) {
                usec_t n = now(CLOCK_MONOTONIC);
                if (n >= end)
                        return -EOPNOTSUPP;
 
                r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
                if (r < 0)
                        return r;
                if (r == 0)
                        return -EOPNOTSUPP;
 
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
                 * read byte by byte, since we don't want to read too much and drop characters from the input
                 * queue. */
                ssize_t l = read(nonblock_input_fd, buf + bytes, bytes == 0 ? STRLEN(CSI18_R0) : 1);
                if (l < 0) {
                        if (errno == EAGAIN)
                                continue;
                        return -errno;
                }
 
                assert((size_t) l <= sizeof(buf) - bytes);
                bytes += l;
 
                r = scan_text_area_size_response(buf, bytes, ret_rows, ret_columns);
                if (r != -EAGAIN)
                        return r;
 
                if (bytes == sizeof(buf))
                        return -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
                                             * answer with a terminator in the allotted space. Something is
                                             * wrong, possibly some unrelated bytes got injected into the
                                             * answer. */
        }
}
 
int terminal_get_size(
                int input_fd,
                int output_fd,
                unsigned *ret_rows,
                unsigned *ret_columns,
                bool try_dsr,
                bool try_csi18) {
 
        _cleanup_close_ int nonblock_input_fd = -EBADF;
        struct termios old_termios = TERMIOS_NULL;
        CLEANUP_TERMIOS_RESET(nonblock_input_fd, old_termios);
        _cleanup_(nonblock_resetp) int nonblock_reset = -EBADF;
        int r;
 
        assert(try_dsr || try_csi18);
 
        r = terminal_prepare_query(input_fd, output_fd, &nonblock_input_fd, &old_termios);
        if (r < 0)
                return r;
 
        /* Put the output fd in non-blocking mode with a write timeout, to avoid blocking indefinitely on
         * write if the terminal is not consuming data (e.g. serial console with flow control). */
        r = fd_nonblock(output_fd, true);
        if (r < 0)
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
        if (r > 0)
                nonblock_reset = output_fd;
 
        /* Flush any stale input that might confuse the response parsers. */
        (void) tcflush(nonblock_input_fd, TCIFLUSH);
 
        if (try_csi18) {
                r = terminal_query_size_by_csi18(nonblock_input_fd, output_fd, ret_rows, ret_columns);
                if (r >= 0)
                        return r;
 
                /* Query failed. Flush any outstanding input. */
                (void) tcflush(nonblock_input_fd, TCIFLUSH);
 
                if (!IN_SET(r, -EOPNOTSUPP, -EINVAL))
                        return r;
        }
 
        if (try_dsr) {
                r = terminal_query_size_by_dsr(nonblock_input_fd, output_fd, ret_rows, ret_columns);
                if (r >= 0)
                        return r;
 
                /* Query failed. Flush any outstanding input. */
                (void) tcflush(nonblock_input_fd, TCIFLUSH);
        }
 
        return r;
}
 
static int fd_is_vc(int fd) {
        _cleanup_free_ char *name = NULL;
        int r;
 
        assert(fd >= 0);
 
        r = getttyname_harder(fd, &name);
        if (r < 0)
                return r;
 
        return tty_is_vc_resolve(name);
}
 
int terminal_fix_size(int input_fd, int output_fd) {
        unsigned rows, columns;
        int r;
 
        /* Don't ask a virtual console at all. There is no intermediary here that could be wrong about the
         * dimensions: the kernel renders the screen itself, so its winsize is authoritative. */
        r = fd_is_vc(input_fd);
        if (r < 0)
                log_debug_errno(r, "Failed to determine whether terminal is a virtual console, assuming it is not: %m");
        else if (r > 0) {
                log_debug("Not querying dimensions of a virtual console, kernel dimensions are authoritative.");
                return 0;
        }
 
        struct winsize ws = {};
        if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
                return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
 
        r = terminal_get_size(input_fd, output_fd, &rows, &columns, /* try_dsr= */ true, /* try_csi18= */ true);
        if (r < 0)
                return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
 
        if (ws.ws_row == rows && ws.ws_col == columns) {
                log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
                return 0;
        }
 
        ws.ws_col = columns;
        ws.ws_row = rows;
 
        if (ioctl(output_fd, TIOCSWINSZ, &ws) < 0)
                return log_debug_errno(errno, "Failed to update terminal dimensions, ignoring: %m");
 
        log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
        return 1;
}
 
#define MAX_TERMINFO_LENGTH 64
/* python -c 'print("".join(hex(ord(i))[2:] for i in "name").upper())' */
#define DCS_TERMINFO_Q ANSI_DCS "+q" "6E616D65" ANSI_ST
/* The answer is either 0+r… (invalid) or 1+r… (OK). */
#define DCS_TERMINFO_R0 ANSI_DCS "0+r" ANSI_ST
#define DCS_TERMINFO_R1 ANSI_DCS "1+r" "6E616D65" "=" /* This is followed by Pt ST. */
assert_cc(STRLEN(DCS_TERMINFO_R0) <= STRLEN(DCS_TERMINFO_R1 ANSI_ST));
 
static int scan_terminfo_response(
                const char *buf,
                size_t size,
                char **ret_name) {
        int r;
 
        assert(buf);
        assert(ret_name);
 
        /* Check if we have enough space for the shortest possible answer. */
        if (size < STRLEN(DCS_TERMINFO_R0))
                return -EAGAIN;
 
        /* Check if the terminating sequence is present */
        if (memcmp(buf + size - STRLEN(ANSI_ST), ANSI_ST, STRLEN(ANSI_ST)) != 0)
                return -EAGAIN;
 
        if (size <= STRLEN(DCS_TERMINFO_R1 ANSI_ST))
                return -EINVAL;  /* The answer is invalid or empty */
 
        if (memcmp(buf, DCS_TERMINFO_R1, STRLEN(DCS_TERMINFO_R1)) != 0)
                return -EINVAL;  /* The answer is not valid */
 
        _cleanup_free_ void *dec = NULL;
        size_t dec_size;
        r = unhexmem_full(buf + STRLEN(DCS_TERMINFO_R1), size - STRLEN(DCS_TERMINFO_R1 ANSI_ST),
                          /* secure= */ false,
                          &dec, &dec_size);
        if (r < 0)
                return r;
 
        assert(((const char *) dec)[dec_size] == '\0'); /* unhexmem appends NUL for our convenience */
        if (memchr(dec, '\0', dec_size) || string_has_cc(dec, NULL) || !filename_is_valid(dec))
                return -EUCLEAN;
 
        *ret_name = TAKE_PTR(dec);
        return 0;
}
 
int terminal_get_terminfo_by_dcs(int fd, char **ret_name) {
        int r;
 
        assert(fd >= 0);
        assert(ret_name);
 
        /* Note: fd must be in non-blocking read-write mode! */
 
        struct termios old_termios = TERMIOS_NULL;
        CLEANUP_TERMIOS_RESET(fd, old_termios);
 
        if (tcgetattr(fd, &old_termios) < 0)
                return -errno;
 
        struct termios new_termios = old_termios;
        termios_disable_echo(&new_termios);
 
        if (tcsetattr(fd, TCSANOW, &new_termios) < 0)
                return -errno;
 
        r = loop_write(fd, DCS_TERMINFO_Q, SIZE_MAX);
        if (r < 0)
                return r;
 
        usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        char buf[STRLEN(DCS_TERMINFO_R1) + MAX_TERMINFO_LENGTH + STRLEN(ANSI_ST)];
        size_t bytes = 0;
 
        for (;;) {
                usec_t n = now(CLOCK_MONOTONIC);
                if (n >= end)
                        return -EOPNOTSUPP;
 
                r = fd_wait_for_event(fd, POLLIN, usec_sub_unsigned(end, n));
                if (r < 0)
                        return r;
                if (r == 0)
                        return -EOPNOTSUPP;
 
                /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
                 * read byte by byte, since we don't want to read too much and drop characters from the input
                 * queue. */
                ssize_t l = read(fd, buf + bytes, bytes == 0 ? STRLEN(DCS_TERMINFO_R0) : 1);
                if (l < 0) {
                        if (errno == EAGAIN)
                                continue;
                        return -errno;
                }
 
                assert((size_t) l <= sizeof(buf) - bytes);
                bytes += l;
 
                r = scan_terminfo_response(buf, bytes, ret_name);
                if (r != -EAGAIN)
                        return r;
 
                if (bytes == sizeof(buf))
                        return -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
                                             * answer with a terminator in the allotted space. Something is
                                             * wrong, possibly some unrelated bytes got injected into the
                                             * answer. */
        }
}
 
int have_terminfo_file(const char *name) {
        /* This is a heuristic check if we have the file, using the directory layout used on
         * current Linux systems. Checks for other layouts can be added later if appropriate. */
        int r;
 
        assert(filename_is_valid(name));
 
        _cleanup_free_ char *p = path_join("/usr/share/terminfo", CHAR_TO_STR(name[0]), name);
        if (!p)
                return log_oom_debug();
 
        r = RET_NERRNO(access(p, F_OK));
        if (r == -ENOENT)
                return false;
        if (r < 0)
                return r;
        return true;
}
 
int query_term_for_tty(const char *tty, char **ret_term) {
        _cleanup_free_ char *dcs_term = NULL;
        int r;
 
        assert(tty);
        assert(ret_term);
 
        if (tty_is_vc_resolve(tty))
                return strdup_to(ret_term, "linux");
 
        /* Try to query the terminal implementation that we're on. This will not work in all
         * cases, which is fine, since this is intended to be used as a fallback. */
 
        _cleanup_close_ int tty_fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (tty_fd < 0)
                return log_debug_errno(tty_fd, "Failed to open %s to query terminfo: %m", tty);
 
        r = terminal_get_terminfo_by_dcs(tty_fd, &dcs_term);
        if (r < 0)
                return log_debug_errno(r, "Failed to query %s for terminfo: %m", tty);
 
        r = have_terminfo_file(dcs_term);
        if (r < 0)
                return log_debug_errno(r, "Failed to look for terminfo %s: %m", dcs_term);
        if (r == 0)
                return log_info_errno(SYNTHETIC_ERRNO(ENODATA),
                                      "Terminfo %s not found for %s.", dcs_term, tty);
 
        *ret_term = TAKE_PTR(dcs_term);
        return 0;
}
 
int terminal_is_pty_fd(int fd) {
        int r;
 
        assert(fd >= 0);
 
        /* Returns true if we are looking at a pty, i.e. if it's backed by the /dev/pts/ file system */
 
        if (!isatty_safe(fd))
                return false;
 
        r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
        if (r != 0)
                return r;
 
        /* The ptmx device is weird, it exists twice, once inside and once outside devpts. To detect the
         * latter case, let's fire off an ioctl() that only works on ptmx devices. */
 
        int v;
        if (ioctl(fd, TIOCGPKT, &v) < 0) {
                if (ERRNO_IS_NOT_SUPPORTED(errno))
                        return false;
 
                return -errno;
        }
 
        return true;
}
 
int pty_open_peer(int fd, int mode) {
        assert(fd >= 0);
 
        /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
         *
         * This is safe to be called on TTYs from other namespaces. */
 
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
 
        /* This replicates the EIO retry logic of open_terminal() in a modified way. */
        for (unsigned c = 0;; c++) {
                int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
                if (peer_fd >= 0)
                        return peer_fd;
 
                if (errno != EIO)
                        return -errno;
 
                /* Max 1s in total */
                if (c >= 20)
                        return -EIO;
 
                (void) usleep_safe(50 * USEC_PER_MSEC);
        }
}