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 1–1000 of 2,949

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/kd.h>
#include <linux/magic.h>
#include <linux/tiocl.h>
#include <linux/vt.h>
#include <poll.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
 
#include "alloc-util.h"
#include "ansi-color.h"
#include "chase.h"
#include "devnum-util.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "hexdecoct.h"
#include "inotify-util.h"
#include "io-util.h"
#include "log.h"
#include "namespace-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidref.h"
#include "proc-cmdline.h"
#include "process-util.h"
#include "signal-util.h"
#include "socket-util.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "time-util.h"
#include "utf8.h"
 
/* How much to wait when reading/writing ANSI sequences from/to the console */
#define CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC (333 * USEC_PER_MSEC)
 
static volatile unsigned cached_columns = 0;
static volatile unsigned cached_lines = 0;
 
static volatile int cached_on_tty = -1;
static volatile int cached_on_dev_null = -1;
 
bool isatty_safe(int fd) {
        assert(fd >= 0);
 
        if (isatty(fd))
                return true;
 
        /* Linux/glibc returns EIO for hung up TTY on isatty(). Which is wrong, the thing doesn't stop being
         * a TTY after all, just because it is temporarily hung up. Let's work around this here, until this
         * is fixed in glibc. See: https://sourceware.org/bugzilla/show_bug.cgi?id=32103 */
        if (errno == EIO)
                return true;
 
        /* Be resilient if we're working on stdio, since they're set up by parent process. */
        assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
 
        return false;
}
 
int chvt(int vt) {
        _cleanup_close_ int fd = -EBADF;
 
        /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
         * if that's configured. */
 
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd < 0)
                return fd;
 
        if (vt <= 0) {
                int tiocl[2] = {
                        TIOCL_GETKMSGREDIRECT,
                        0
                };
 
                if (ioctl(fd, TIOCLINUX, tiocl) < 0)
                        return -errno;
 
                vt = tiocl[0] <= 0 ? 1 : tiocl[0];
        }
 
        return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
}
 
int read_one_char(FILE *f, char *ret, usec_t t, bool echo, bool *need_nl) {
        _cleanup_free_ char *line = NULL;
        struct termios old_termios;
        int r, fd;
 
        assert(ret);
 
        if (!f)
                f = stdin;
 
        /* If this is a terminal, then switch canonical mode off, so that we can read a single
         * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
         * nicely.) If 'echo' is false we'll also disable ECHO mode so that the pressed key is not made
         * visible to the user. */
        fd = fileno(f);
        if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
                struct termios new_termios = old_termios;
 
                new_termios.c_lflag &= ~(ICANON|(echo ? 0 : ECHO));
                new_termios.c_cc[VMIN] = 1;
                new_termios.c_cc[VTIME] = 0;
 
                if (tcsetattr(fd, TCSANOW, &new_termios) >= 0) {
                        char c;
 
                        if (t != USEC_INFINITY) {
                                if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
                                        (void) tcsetattr(fd, TCSANOW, &old_termios);
                                        return -ETIMEDOUT;
                                }
                        }
 
                        r = safe_fgetc(f, &c);
                        (void) tcsetattr(fd, TCSANOW, &old_termios);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                return -EIO;
 
                        if (need_nl)
                                *need_nl = c != '\n';
 
                        *ret = c;
                        return 0;
                }
        }
 
        if (t != USEC_INFINITY && fd >= 0) {
                /* Let's wait the specified amount of time for input. When we have no fd we skip this, under
                 * the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
                 * anyway, as the data is either already in the stream or cannot possible be placed there
                 * while we access the stream */
 
                if (fd_wait_for_event(fd, POLLIN, t) <= 0)
                        return -ETIMEDOUT;
        }
 
        /* If this is not a terminal, then read a full line instead */
 
        r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
        if (r < 0)
                return r;
        if (r == 0)
                return -EIO;
 
        if (strlen(line) != 1)
                return -EBADMSG;
 
        if (need_nl)
                *need_nl = false;
 
        *ret = line[0];
        return 0;
}
 
#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
 
int ask_char(char *ret, const char *replies, const char *fmt, ...) {
        int r;
 
        assert(ret);
        assert(replies);
        assert(fmt);
 
        for (;;) {
                va_list ap;
                char c;
                bool need_nl = true;
 
                fputs(ansi_highlight(), stdout);
 
                putchar('\r');
 
                va_start(ap, fmt);
                vprintf(fmt, ap);
                va_end(ap);
 
                fputs(ansi_normal(), stdout);
 
                fflush(stdout);
 
                r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, /* echo= */ true, &need_nl);
                if (r < 0) {
 
                        if (r == -ETIMEDOUT)
                                continue;
 
                        if (r == -EBADMSG) {
                                puts("Bad input, please try again.");
                                continue;
                        }
 
                        putchar('\n');
                        return r;
                }
 
                if (need_nl)
                        putchar('\n');
 
                if (strchr(replies, c)) {
                        *ret = c;
                        return 0;
                }
 
                puts("Read unexpected character, please try again.");
        }
}
 
typedef enum CompletionResult{
        COMPLETION_ALREADY,       /* the input string is already complete */
        COMPLETION_FULL,          /* completed the input string to be complete now */
        COMPLETION_PARTIAL,       /* completed the input string so that is still incomplete */
        COMPLETION_NONE,          /* found no matching completion */
        _COMPLETION_RESULT_MAX,
        _COMPLETION_RESULT_INVALID = -EINVAL,
        _COMPLETION_RESULT_ERRNO_MAX = -ERRNO_MAX,
} CompletionResult;
 
static CompletionResult pick_completion(const char *string, char *const*completions, char **ret) {
        _cleanup_free_ char *found = NULL;
        bool partial = false;
 
        assert(ret);
 
        string = strempty(string);
 
        STRV_FOREACH(c, completions) {
 
                /* Ignore entries that are not actually completions */
                if (!startswith(*c, string))
                        continue;
 
                /* Store first completion that matches */
                if (!found) {
                        found = strdup(*c);
                        if (!found)
                                return -ENOMEM;
 
                        continue;
                }
 
                /* If there's another completion that works truncate the one we already found by common
                 * prefix */
                size_t n = str_common_prefix(found, *c);
                if (n == SIZE_MAX)
                        continue;
 
                found[n] = 0;
                partial = true;
        }
 
        *ret = TAKE_PTR(found);
 
        if (!*ret)
                return COMPLETION_NONE;
        if (partial)
                return COMPLETION_PARTIAL;
 
        return streq(string, *ret) ? COMPLETION_ALREADY : COMPLETION_FULL;
}
 
static void clear_by_backspace(size_t n) {
        /* Erase the specified number of character cells backwards on the terminal */
        for (size_t i = 0; i < n; i++)
                fputs("\b \b", stdout);
}
 
int ask_string_full(
                char **ret,
                const char *prefill,
                GetCompletionsCallback get_completions,
                void *userdata,
                const char *text, ...) {
 
        va_list ap;
        int r;
 
        assert(ret);
        assert(text);
 
        _cleanup_free_ char *string = NULL;
        size_t n = 0;
 
        if (prefill) {
                /* Prefill query with explicit data if specified */
 
                string = strdup(prefill);
                if (!string)
                        return -ENOMEM;
 
                n = strlen(string);
 
        } else if (get_completions) {
                /* Otherwise, figure out what string to preselect the query with */
                _cleanup_strv_free_ char **completions = NULL;
                r = get_completions("", GET_COMPLETIONS_PRESELECT, &completions, userdata);
                if (r < 0)
                        return r;
 
                CompletionResult cr = pick_completion(string, completions, &string);
                if (cr < 0)
                        return cr;
 
                n = strlen_ptr(string);
        }
 
        /* Output the prompt */
        fputs(ansi_highlight(), stdout);
        va_start(ap, text);
        vprintf(text, ap);
        va_end(ap);
        fputs(ansi_normal(), stdout);
        if (string)
                fputs(string, stdout);
        fflush(stdout);
 
        /* Do interactive logic only if stdin + stdout are connected to the same place. And yes, we could use
         * STDIN_FILENO and STDOUT_FILENO here, but let's be overly correct for once, after all libc allows
         * swapping out stdin/stdout. */
        int fd_input = fileno(stdin);
        int fd_output = fileno(stdout);
        struct termios old_termios = TERMIOS_NULL;
        CLEANUP_TERMIOS_RESET(fd_input, old_termios);
 
        if (fd_input < 0 || fd_output < 0 || same_fd(fd_input, fd_output) <= 0)
                goto fallback;
 
        /* Try to disable echo, which also tells us if this even is a terminal */
        if (tcgetattr(fd_input, &old_termios) < 0) {
                old_termios = TERMIOS_NULL;
                goto fallback;
        }
 
        struct termios new_termios = old_termios;
        termios_disable_echo(&new_termios);
        if (tcsetattr(fd_input, TCSANOW, &new_termios) < 0)
                return -errno;
 
        for (;;) {
                int c = fgetc(stdin);
 
                /* On EOF or NUL, end the request, don't output anything anymore */
                if (IN_SET(c, EOF, 0))
                        break;
 
                /* On Return also end the request, but make this visible */
                if (IN_SET(c, '\n', '\r')) {
                        fputc('\n', stdout);
                        break;
                }
 
                if (c == '\t') {
                        /* Tab */
 
                        _cleanup_strv_free_ char **completions = NULL;
                        if (get_completions) {
                                r = get_completions(string, /* flags= */ 0, &completions, userdata);
                                if (r < 0)
                                        return r;
                        }
 
                        _cleanup_free_ char *new_string = NULL;
                        CompletionResult cr = pick_completion(string, completions, &new_string);
                        if (cr < 0)
                                return cr;
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_FULL)) {
                                /* Output the new suffix we learned */
                                fputs(ASSERT_PTR(startswith(new_string, strempty(string))), stdout);
 
                                /* And update the whole string */
                                free_and_replace(string, new_string);
                                n = strlen(string);
                        }
                        if (cr == COMPLETION_NONE)
                                fputc('\a', stdout); /* BEL */
 
                        if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_ALREADY)) {
                                /* If this worked only partially, or if the user hit TAB even though we were
                                 * complete already, then show the remaining options (in the latter case just
                                 * the one). */
                                fputc('\n', stdout);
 
                                _cleanup_strv_free_ char **filtered = strv_filter_prefix(completions, string);
                                if (!filtered)
                                        return -ENOMEM;
 
                                r = show_menu(filtered,
                                              /* n_columns= */ SIZE_MAX,
                                              /* column_width= */ SIZE_MAX,
                                              /* ellipsize_percentage= */ 0,
                                              /* grey_prefix= */ string,
                                              /* with_numbers= */ false);
                                if (r < 0)
                                        return r;
 
                                /* Show the prompt again */
                                fputs(ansi_highlight(), stdout);
                                va_start(ap, text);
                                vprintf(text, ap);
                                va_end(ap);
                                fputs(ansi_normal(), stdout);
                                fputs(string, stdout);
                        }
 
                } else if (IN_SET(c, '\b', 127)) {
                        /* Backspace */
 
                        if (n == 0)
                                fputc('\a', stdout); /* BEL */
                        else {
                                size_t m = utf8_last_length(string, n);
 
                                char *e = string + n - m;
                                clear_by_backspace(utf8_console_width(e));
 
                                *e = 0;
                                n -= m;
                        }
 
                } else if (c == 21) {
                        /* Ctrl-u → erase all input */
 
                        clear_by_backspace(utf8_console_width(string));
                        if (string)
                                string[n = 0] = 0;
                        else
                                assert(n == 0);
 
                } else if (c == 4) {
                        /* Ctrl-d → cancel this field input */
 
                        return -ECANCELED;
 
                } else if (char_is_cc(c) || n >= LINE_MAX)
                        /* refuse control characters and too long strings */
                        fputc('\a', stdout); /* BEL */
                else {
                        /* Regular char */
 
                        if (!GREEDY_REALLOC(string, n+2))
                                return -ENOMEM;
 
                        string[n++] = (char) c;
                        string[n] = 0;
 
                        fputc(c, stdout);
                }
 
                fflush(stdout);
        }
 
        if (!string) {
                string = strdup("");
                if (!string)
                        return -ENOMEM;
        }
 
        *ret = TAKE_PTR(string);
        return 0;
 
fallback:
        /* A simple fallback without TTY magic */
        string = mfree(string);
        r = read_line(stdin, LONG_LINE_MAX, &string);
        if (r < 0)
                return r;
        if (r == 0)
                return -EIO;
 
        *ret = TAKE_PTR(string);
        return 0;
}
 
bool any_key_to_proceed(void) {
 
        /* Insert a new line here as well as to when the user inputs, as this is also used during the boot up
         * sequence when status messages may be interleaved with the current program output. This ensures
         * that the status messages aren't appended on the same line as this message. */
 
        fputc('\n', stdout);
        fputs(ansi_highlight_magenta(), stdout);
        fputs("-- Press any key to proceed --", stdout);
        fputs(ansi_normal(), stdout);
        fputc('\n', stdout);
        fflush(stdout);
 
        char key = 0;
        (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
 
        fputc('\n', stdout);
        fflush(stdout);
 
        return key != 'q';
}
 
static size_t widest_list_element(char *const*l) {
        size_t w = 0;
 
        /* Returns the largest console width of all elements in 'l' */
 
        STRV_FOREACH(i, l)
                w = MAX(w, utf8_console_width(*i));
 
        return w;
}
 
int show_menu(char **x,
              size_t n_columns,
              size_t column_width,
              unsigned ellipsize_percentage,
              const char *grey_prefix,
              bool with_numbers) {
 
        assert(n_columns > 0);
        assert(column_width > 0);
 
        if (n_columns == SIZE_MAX)
                n_columns = 3;
 
        if (column_width == SIZE_MAX) {
                size_t widest = widest_list_element(x);
 
                /* If not specified, derive column width from screen width */
                size_t column_max = (columns()-1) / n_columns;
 
                /* Subtract room for numbers */
                if (with_numbers)
                        column_max = LESS_BY(column_max, 6U);
 
                /* If columns would get too tight let's make this a linear list instead. */
                if (column_max < 10 && widest > 10) {
                        n_columns = 1;
                        column_max = columns()-1;
 
                        if (with_numbers)
                                column_max = LESS_BY(column_max, 6U);
                }
 
                /* Never make this narrower than 10 characters */
                column_max = MAX(column_max, 10U);
                column_width = CLAMP(widest+1, 10U, column_max);
        }
 
        size_t n = strv_length(x);
        size_t per_column = DIV_ROUND_UP(n, n_columns);
 
        size_t break_lines = lines();
        if (break_lines > 2)
                break_lines--;
 
        /* The first page gets two extra lines, since we want to show a title */
        size_t break_modulo = break_lines;
        if (break_modulo > 3)
                break_modulo -= 3;
 
        for (size_t i = 0; i < per_column; i++) {
 
                for (size_t j = 0; j < n_columns; j++) {
                        _cleanup_free_ char *e = NULL;
 
                        size_t p = j * per_column + i;
                        if (p >= n)
                                break;
 
                        e = ellipsize(x[p], column_width, ellipsize_percentage);
                        if (!e)
                                return -ENOMEM;
 
                        if (with_numbers)
                                printf("%s%4zu)%s ",
                                       ansi_grey(),
                                       p + 1,
                                       ansi_normal());
 
                        if (grey_prefix && startswith(e, grey_prefix)) {
                                size_t k = MIN(strlen(grey_prefix), column_width);
                                printf("%s%.*s%s",
                                       ansi_grey(),
                                       (int) k, e,
                                       ansi_normal());
                                printf("%-*s",
                                       (int) (column_width - k), e+k);
                        } else
                                printf("%-*s", (int) column_width, e);
                }
 
                putchar('\n');
 
                /* on the first screen we reserve 2 extra lines for the title */
                if (i % break_lines == break_modulo)
                        if (!any_key_to_proceed())
                                return 0;
        }
 
        return 0;
}
 
int open_terminal(const char *name, int mode) {
        _cleanup_close_ int fd = -EBADF;
 
        /*
         * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
         * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
         * times.
         *
         * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
         */
 
        assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
 
        for (unsigned c = 0;; c++) {
                fd = open(name, mode, 0);
                if (fd >= 0)
                        break;
 
                if (errno != EIO)
                        return -errno;
 
                /* Max 1s in total */
                if (c >= 20)
                        return -EIO;
 
                (void) usleep_safe(50 * USEC_PER_MSEC);
        }
 
        if (!isatty_safe(fd))
                return -ENOTTY;
 
        return TAKE_FD(fd);
}
 
int acquire_terminal(
                const char *name,
                AcquireTerminalFlags flags,
                usec_t timeout) {
 
        _cleanup_close_ int notify = -EBADF, fd = -EBADF;
        usec_t ts = USEC_INFINITY;
        int r, wd = -1;
 
        assert(name);
 
        AcquireTerminalFlags mode = flags & _ACQUIRE_TERMINAL_MODE_MASK;
        assert(IN_SET(mode, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
        assert(mode == ACQUIRE_TERMINAL_WAIT || !FLAGS_SET(flags, ACQUIRE_TERMINAL_WATCH_SIGTERM));
 
        /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
         * acquire it, so that we don't lose any event.
         *
         * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
         * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
         * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
         * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
         * probably should not do anyway.) */
 
        if (mode == ACQUIRE_TERMINAL_WAIT) {
                notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
                if (notify < 0)
                        return -errno;
 
                wd = inotify_add_watch(notify, name, IN_CLOSE);
                if (wd < 0)
                        return -errno;
 
                if (timeout != USEC_INFINITY)
                        ts = now(CLOCK_MONOTONIC);
        }
 
        /* If we are called with ACQUIRE_TERMINAL_WATCH_SIGTERM we'll unblock SIGTERM during ppoll() temporarily */
        sigset_t poll_ss;
        assert_se(sigprocmask(SIG_SETMASK, /* newset= */ NULL, &poll_ss) >= 0);
        if (flags & ACQUIRE_TERMINAL_WATCH_SIGTERM) {
                assert_se(sigismember(&poll_ss, SIGTERM) > 0);
                assert_se(sigdelset(&poll_ss, SIGTERM) >= 0);
        }
 
        for (;;) {
                if (notify >= 0) {
                        r = flush_fd(notify);
                        if (r < 0)
                                return r;
                }
 
                /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
                 * to figure out if we successfully became the controlling process of the tty */
                fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
                if (fd < 0)
                        return fd;
 
                /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
                struct sigaction sa_old;
                assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
 
                /* First, try to get the tty */
                r = RET_NERRNO(ioctl(fd, TIOCSCTTY, mode == ACQUIRE_TERMINAL_FORCE));
 
                /* Reset signal handler to old value */
                assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
 
                /* Success? Exit the loop now! */
                if (r >= 0)
                        break;
 
                /* Any failure besides -EPERM? Fail, regardless of the mode. */
                if (r != -EPERM)
                        return r;
 
                if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
                                                          * into a success. Note that EPERM is also returned if we
                                                          * already are the owner of the TTY. */
                        break;
 
                if (mode != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
                        return r;
 
                assert(notify >= 0);
                assert(wd >= 0);
 
                for (;;) {
                        usec_t left;
                        if (timeout == USEC_INFINITY)
                                left = USEC_INFINITY;
                        else {
                                assert(ts != USEC_INFINITY);
 
                                usec_t n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
                                if (n >= timeout)
                                        return -ETIMEDOUT;
 
                                left = timeout - n;
                        }
 
                        r = ppoll_usec_full(
                                        &(struct pollfd) {
                                                .fd = notify,
                                                .events = POLLIN,
                                        },
                                        /* n_fds= */ 1,
                                        left,
                                        &poll_ss);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                return -ETIMEDOUT;
 
                        union inotify_event_buffer buffer;
                        ssize_t l;
                        l = read(notify, &buffer, sizeof(buffer));
                        if (l < 0) {
                                if (ERRNO_IS_TRANSIENT(errno))
                                        continue;
 
                                return -errno;
                        }
 
                        FOREACH_INOTIFY_EVENT(e, buffer, l) {
                                if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
                                        break;
 
                                if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
                                        return -EIO;
                        }
 
                        break;
                }
 
                /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
                 * we do this after sleeping, so that we don't enter an endless loop. */
                fd = safe_close(fd);
        }
 
        return TAKE_FD(fd);
}
 
int release_terminal(void) {
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd < 0)
                return -errno;
 
        /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
         * by our own TIOCNOTTY */
        struct sigaction sa_old;
        assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
 
        r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
 
        assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
 
        return r;
}
 
int terminal_new_session(void) {
 
        /* Make us the new session leader, and set stdin tty to be our controlling terminal.
         *
         * Why stdin? Well, the ctty logic is relevant for signal delivery mostly, i.e. if people hit C-c
         * or the line is hung up. Such events are basically just a form of input, via a side channel
         * (that side channel being signal delivery, i.e. SIGINT, SIGHUP et al). Hence we focus on input,
         * not output here. */
 
        if (!isatty_safe(STDIN_FILENO))
                return -ENXIO;
 
        (void) setsid();
        return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
}
 
void terminal_detach_session(void) {
        (void) setsid();
        (void) release_terminal();
}
 
int terminal_vhangup_fd(int fd) {
        assert(fd >= 0);
        return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
}
 
int terminal_vhangup(const char *tty) {
        _cleanup_close_ int fd = -EBADF;
 
        assert(tty);
 
        fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return fd;
 
        return terminal_vhangup_fd(fd);
}
 
int vt_disallocate(const char *tty_path) {
        assert(tty_path);
 
        /* Deallocate the VT if possible. If not possible (i.e. because it is the active one), at least clear
         * it entirely (including the scrollback buffer). */
 
        int ttynr = vtnr_from_tty(tty_path);
        if (ttynr > 0) {
                _cleanup_close_ int fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
                if (fd < 0)
                        return fd;
 
                /* Try to deallocate */
                if (ioctl(fd, VT_DISALLOCATE, ttynr) >= 0)
                        return 0;
                if (errno != EBUSY)
                        return -errno;
        }
 
        /* So this is not a VT (in which case we cannot deallocate it), or we failed to deallocate. Let's at
         * least clear the screen. */
 
        _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (fd2 < 0)
                return fd2;
 
        return loop_write_full(fd2,
                               "\033[r"   /* clear scrolling region */
                               "\033[H"   /* move home */
                               "\033[3J"  /* clear screen including scrollback, requires Linux 2.6.40 */
                               "\033c",   /* reset to initial state */
                               SIZE_MAX,
                               CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
}
 
static int vt_default_utf8(void) {
        /* Read the default VT UTF8 setting from the kernel */
        return read_boolean_file("/sys/module/vt/parameters/default_utf8");
}
 
static int vt_reset_keyboard(int fd) {
        int r, kb;
 
        assert(fd >= 0);
 
        /* If we can't read the default, then default to Unicode. It's 2024 after all. */
        r = vt_default_utf8();
        if (r < 0)
                log_debug_errno(r, "Failed to determine kernel VT UTF-8 mode, assuming enabled: %m");
 
        kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
        return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
}
 
static int terminal_reset_ioctl(int fd, bool switch_to_text) {
        struct termios termios;
        int r;
 
        /* Set terminal to some sane defaults */
 
        assert(fd >= 0);
 
        /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
         * and we don't interfere with that. */
 
        /* Disable exclusive mode, just in case */
        if (ioctl(fd, TIOCNXCL) < 0)
                log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
 
        /* Switch to text mode */
        if (switch_to_text)
                if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
                        log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
 
        /* Set default keyboard mode */
        r = vt_reset_keyboard(fd);
        if (r < 0)
                log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
 
        if (tcgetattr(fd, &termios) < 0) {
                r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
                goto finish;
        }
 
        /* We only reset the stuff that matters to the software. How
         * hardware is set up we don't touch assuming that somebody
         * else will do that for us */
 
        termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
        termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
        termios.c_oflag |= ONLCR | OPOST;
        termios.c_cflag |= CREAD;
        termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
 
        termios.c_cc[VINTR]    =   03;  /* ^C */
        termios.c_cc[VQUIT]    =  034;  /* ^\ */
        termios.c_cc[VERASE]   = 0177;
        termios.c_cc[VKILL]    =  025;  /* ^X */
        termios.c_cc[VEOF]     =   04;  /* ^D */
        termios.c_cc[VSTART]   =  021;  /* ^Q */
        termios.c_cc[VSTOP]    =  023;  /* ^S */
        termios.c_cc[VSUSP]    =  032;  /* ^Z */
        termios.c_cc[VLNEXT]   =  026;  /* ^V */
        termios.c_cc[VWERASE]  =  027;  /* ^W */
        termios.c_cc[VREPRINT] =  022;  /* ^R */
        termios.c_cc[VEOL]     =    0;
        termios.c_cc[VEOL2]    =    0;
 
        termios.c_cc[VTIME]  = 0;
        termios.c_cc[VMIN]   = 1;
 
        r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
        if (r < 0)
                log_debug_errno(r, "Failed to set terminal parameters: %m");
 
finish:
        /* Just in case, flush all crap out */
        (void) tcflush(fd, TCIOFLUSH);
 
        return r;
}
 
int terminal_reset_ansi_seq(int fd) {
        _cleanup_(nonblock_resetp) int nonblock_reset = -EBADF;
        int r;
 
        assert(fd >= 0);
 
        if (getenv_terminal_is_dumb())
                return 0;
 
        r = fd_nonblock(fd, true);
        if (r < 0)
                return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
        if (r > 0)
                nonblock_reset = fd;
 
        r = loop_write_full(fd,
                            "\033[!p"              /* soft terminal reset */
                            ANSI_OSC "104" ANSI_ST /* reset color palette via OSC 104 */
                            ANSI_NORMAL            /* reset colors */
                            "\033[?7h"             /* enable line-wrapping */
                            "\033[1G"              /* place cursor at beginning of current line */
                            "\033[0J",             /* erase till end of screen */
                            SIZE_MAX,
                            CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
        if (r < 0)
                log_debug_errno(r, "Failed to reset terminal through ANSI sequences: %m");
 
        return r;