1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include <linux/tiocl.h>
15 #include <sys/inotify.h>
16 #include <sys/ioctl.h>
17 #include <sys/socket.h>
18 #include <sys/sysmacros.h>
20 #include <sys/types.h>
21 #include <sys/utsname.h>
25 #include "alloc-util.h"
35 #include "namespace-util.h"
36 #include "parse-util.h"
37 #include "path-util.h"
38 #include "proc-cmdline.h"
39 #include "process-util.h"
40 #include "socket-util.h"
41 #include "stat-util.h"
42 #include "string-util.h"
44 #include "terminal-util.h"
45 #include "time-util.h"
48 static volatile unsigned cached_columns
= 0;
49 static volatile unsigned cached_lines
= 0;
51 static volatile int cached_on_tty
= -1;
52 static volatile int cached_colors_enabled
= -1;
53 static volatile int cached_underline_enabled
= -1;
56 _cleanup_close_
int fd
;
58 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
59 * if that's configured. */
61 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
67 TIOCL_GETKMSGREDIRECT
,
71 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
74 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
77 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
83 int read_one_char(FILE *f
, char *ret
, usec_t t
, bool *need_nl
) {
84 _cleanup_free_
char *line
= NULL
;
85 struct termios old_termios
;
91 /* If this is a terminal, then switch canonical mode off, so that we can read a single character */
92 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
93 struct termios new_termios
= old_termios
;
95 new_termios
.c_lflag
&= ~ICANON
;
96 new_termios
.c_cc
[VMIN
] = 1;
97 new_termios
.c_cc
[VTIME
] = 0;
99 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
102 if (t
!= USEC_INFINITY
) {
103 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0) {
104 (void) tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
109 r
= safe_fgetc(f
, &c
);
110 (void) tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
117 *need_nl
= c
!= '\n';
124 if (t
!= USEC_INFINITY
) {
125 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0)
129 /* If this is not a terminal, then read a full line instead */
131 r
= read_line(f
, 16, &line
); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
137 if (strlen(line
) != 1)
147 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
149 int ask_char(char *ret
, const char *replies
, const char *fmt
, ...) {
161 if (colors_enabled())
162 fputs(ANSI_HIGHLIGHT
, stdout
);
170 if (colors_enabled())
171 fputs(ANSI_NORMAL
, stdout
);
175 r
= read_one_char(stdin
, &c
, DEFAULT_ASK_REFRESH_USEC
, &need_nl
);
182 puts("Bad input, please try again.");
193 if (strchr(replies
, c
)) {
198 puts("Read unexpected character, please try again.");
202 int ask_string(char **ret
, const char *text
, ...) {
209 _cleanup_free_
char *line
= NULL
;
212 if (colors_enabled())
213 fputs(ANSI_HIGHLIGHT
, stdout
);
219 if (colors_enabled())
220 fputs(ANSI_NORMAL
, stdout
);
224 r
= read_line(stdin
, LONG_LINE_MAX
, &line
);
230 if (!isempty(line
)) {
231 *ret
= TAKE_PTR(line
);
237 int reset_terminal_fd(int fd
, bool switch_to_text
) {
238 struct termios termios
;
241 /* Set terminal to some sane defaults */
245 /* We leave locked terminal attributes untouched, so that
246 * Plymouth may set whatever it wants to set, and we don't
247 * interfere with that. */
249 /* Disable exclusive mode, just in case */
250 (void) ioctl(fd
, TIOCNXCL
);
252 /* Switch to text mode */
254 (void) ioctl(fd
, KDSETMODE
, KD_TEXT
);
256 /* Set default keyboard mode */
257 (void) vt_reset_keyboard(fd
);
259 if (tcgetattr(fd
, &termios
) < 0) {
264 /* We only reset the stuff that matters to the software. How
265 * hardware is set up we don't touch assuming that somebody
266 * else will do that for us */
268 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
269 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
270 termios
.c_oflag
|= ONLCR
;
271 termios
.c_cflag
|= CREAD
;
272 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
274 termios
.c_cc
[VINTR
] = 03; /* ^C */
275 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
276 termios
.c_cc
[VERASE
] = 0177;
277 termios
.c_cc
[VKILL
] = 025; /* ^X */
278 termios
.c_cc
[VEOF
] = 04; /* ^D */
279 termios
.c_cc
[VSTART
] = 021; /* ^Q */
280 termios
.c_cc
[VSTOP
] = 023; /* ^S */
281 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
282 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
283 termios
.c_cc
[VWERASE
] = 027; /* ^W */
284 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
285 termios
.c_cc
[VEOL
] = 0;
286 termios
.c_cc
[VEOL2
] = 0;
288 termios
.c_cc
[VTIME
] = 0;
289 termios
.c_cc
[VMIN
] = 1;
291 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
295 /* Just in case, flush all crap out */
296 (void) tcflush(fd
, TCIOFLUSH
);
301 int reset_terminal(const char *name
) {
302 _cleanup_close_
int fd
= -1;
304 /* We open the terminal with O_NONBLOCK here, to ensure we
305 * don't block on carrier if this is a terminal with carrier
308 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
312 return reset_terminal_fd(fd
, true);
315 int open_terminal(const char *name
, int mode
) {
320 * If a TTY is in the process of being closed opening it might
321 * cause EIO. This is horribly awful, but unlikely to be
322 * changed in the kernel. Hence we work around this problem by
323 * retrying a couple of times.
325 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
332 fd
= open(name
, mode
, 0);
339 /* Max 1s in total */
343 usleep(50 * USEC_PER_MSEC
);
347 if (isatty(fd
) <= 0) {
355 int acquire_terminal(
357 AcquireTerminalFlags flags
,
360 _cleanup_close_
int notify
= -1, fd
= -1;
361 usec_t ts
= USEC_INFINITY
;
365 assert(IN_SET(flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
, ACQUIRE_TERMINAL_TRY
, ACQUIRE_TERMINAL_FORCE
, ACQUIRE_TERMINAL_WAIT
));
367 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
368 * acquire it, so that we don't lose any event.
370 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
371 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
372 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
373 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
374 * probably should not do anyway.) */
376 if ((flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_WAIT
) {
377 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= USEC_INFINITY
? IN_NONBLOCK
: 0));
381 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
385 if (timeout
!= USEC_INFINITY
)
386 ts
= now(CLOCK_MONOTONIC
);
390 struct sigaction sa_old
, sa_new
= {
391 .sa_handler
= SIG_IGN
,
392 .sa_flags
= SA_RESTART
,
396 r
= flush_fd(notify
);
401 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
402 * to figure out if we successfully became the controlling process of the tty */
403 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
407 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
408 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
410 /* First, try to get the tty */
411 r
= ioctl(fd
, TIOCSCTTY
,
412 (flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_FORCE
) < 0 ? -errno
: 0;
414 /* Reset signal handler to old value */
415 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
417 /* Success? Exit the loop now! */
421 /* Any failure besides -EPERM? Fail, regardless of the mode. */
425 if (flags
& ACQUIRE_TERMINAL_PERMISSIVE
) /* If we are in permissive mode, then EPERM is fine, turn this
426 * into a success. Note that EPERM is also returned if we
427 * already are the owner of the TTY. */
430 if (flags
!= ACQUIRE_TERMINAL_WAIT
) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
437 union inotify_event_buffer buffer
;
438 struct inotify_event
*e
;
441 if (timeout
!= USEC_INFINITY
) {
444 assert(ts
!= USEC_INFINITY
);
446 n
= now(CLOCK_MONOTONIC
);
447 if (ts
+ timeout
< n
)
450 r
= fd_wait_for_event(notify
, POLLIN
, ts
+ timeout
- n
);
457 l
= read(notify
, &buffer
, sizeof(buffer
));
459 if (IN_SET(errno
, EINTR
, EAGAIN
))
465 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
466 if (e
->mask
& IN_Q_OVERFLOW
) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
469 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) /* Safety checks */
476 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
477 * we do this after sleeping, so that we don't enter an endless loop. */
484 int release_terminal(void) {
485 static const struct sigaction sa_new
= {
486 .sa_handler
= SIG_IGN
,
487 .sa_flags
= SA_RESTART
,
490 _cleanup_close_
int fd
= -1;
491 struct sigaction sa_old
;
494 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
498 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
499 * by our own TIOCNOTTY */
500 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
502 r
= ioctl(fd
, TIOCNOTTY
) < 0 ? -errno
: 0;
504 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
509 int terminal_vhangup_fd(int fd
) {
512 if (ioctl(fd
, TIOCVHANGUP
) < 0)
518 int terminal_vhangup(const char *name
) {
519 _cleanup_close_
int fd
;
521 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
525 return terminal_vhangup_fd(fd
);
528 int vt_disallocate(const char *name
) {
529 _cleanup_close_
int fd
= -1;
534 /* Deallocate the VT if possible. If not possible
535 * (i.e. because it is the active one), at least clear it
536 * entirely (including the scrollback buffer) */
538 e
= path_startswith(name
, "/dev/");
542 if (!tty_is_vc(name
)) {
543 /* So this is not a VT. I guess we cannot deallocate
544 * it then. But let's at least clear the screen */
546 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
551 "\033[r" /* clear scrolling region */
552 "\033[H" /* move home */
553 "\033[2J", /* clear screen */
558 n
= startswith(e
, "tty");
562 r
= safe_atou(n
, &u
);
569 /* Try to deallocate */
570 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
574 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
583 /* Couldn't deallocate, so let's clear it fully with
585 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
590 "\033[r" /* clear scrolling region */
591 "\033[H" /* move home */
592 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
597 int make_console_stdio(void) {
600 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
602 fd
= acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE
|ACQUIRE_TERMINAL_PERMISSIVE
, USEC_INFINITY
);
604 return log_error_errno(fd
, "Failed to acquire terminal: %m");
606 r
= reset_terminal_fd(fd
, true);
608 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
610 r
= rearrange_stdio(fd
, fd
, fd
); /* This invalidates 'fd' both on success and on failure. */
612 return log_error_errno(r
, "Failed to make terminal stdin/stdout/stderr: %m");
614 reset_terminal_feature_caches();
619 bool tty_is_vc(const char *tty
) {
622 return vtnr_from_tty(tty
) >= 0;
625 bool tty_is_console(const char *tty
) {
628 return streq(skip_dev_prefix(tty
), "console");
631 int vtnr_from_tty(const char *tty
) {
636 tty
= skip_dev_prefix(tty
);
638 if (!startswith(tty
, "tty") )
641 if (tty
[3] < '0' || tty
[3] > '9')
644 r
= safe_atoi(tty
+3, &i
);
654 int resolve_dev_console(char **ret
) {
655 _cleanup_free_
char *active
= NULL
;
661 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
662 * sign for container setups) */
664 if (path_is_read_only_fs("/sys") > 0)
667 r
= read_one_line_file("/sys/class/tty/console/active", &active
);
671 /* If multiple log outputs are configured the last one is what /dev/console points to */
672 tty
= strrchr(active
, ' ');
678 if (streq(tty
, "tty0")) {
679 active
= mfree(active
);
681 /* Get the active VC (e.g. tty1) */
682 r
= read_one_line_file("/sys/class/tty/tty0/active", &active
);
690 *ret
= TAKE_PTR(active
);
704 int get_kernel_consoles(char ***ret
) {
705 _cleanup_strv_free_
char **l
= NULL
;
706 _cleanup_free_
char *line
= NULL
;
712 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
713 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
714 if (path_is_read_only_fs("/sys") > 0)
717 r
= read_one_line_file("/sys/class/tty/console/active", &line
);
723 _cleanup_free_
char *tty
= NULL
;
726 r
= extract_first_word(&p
, &tty
, NULL
, 0);
732 if (streq(tty
, "tty0")) {
734 r
= read_one_line_file("/sys/class/tty/tty0/active", &tty
);
739 path
= strappend("/dev/", tty
);
743 if (access(path
, F_OK
) < 0) {
744 log_debug_errno(errno
, "Console device %s is not accessible, skipping: %m", path
);
749 r
= strv_consume(&l
, path
);
754 if (strv_isempty(l
)) {
755 log_debug("No devices found for system console");
764 r
= strv_extend(&l
, "/dev/console");
773 bool tty_is_vc_resolve(const char *tty
) {
774 _cleanup_free_
char *resolved
= NULL
;
778 tty
= skip_dev_prefix(tty
);
780 if (streq(tty
, "console")) {
781 if (resolve_dev_console(&resolved
) < 0)
787 return tty_is_vc(tty
);
790 const char *default_term_for_tty(const char *tty
) {
791 return tty
&& tty_is_vc_resolve(tty
) ? "linux" : "vt220";
794 int fd_columns(int fd
) {
795 struct winsize ws
= {};
797 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
806 unsigned columns(void) {
810 if (cached_columns
> 0)
811 return cached_columns
;
814 e
= getenv("COLUMNS");
816 (void) safe_atoi(e
, &c
);
818 if (c
<= 0 || c
> USHRT_MAX
) {
819 c
= fd_columns(STDOUT_FILENO
);
825 return cached_columns
;
828 int fd_lines(int fd
) {
829 struct winsize ws
= {};
831 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
840 unsigned lines(void) {
844 if (cached_lines
> 0)
850 (void) safe_atoi(e
, &l
);
852 if (l
<= 0 || l
> USHRT_MAX
) {
853 l
= fd_lines(STDOUT_FILENO
);
862 /* intended to be used as a SIGWINCH sighandler */
863 void columns_lines_cache_reset(int signum
) {
868 void reset_terminal_feature_caches(void) {
872 cached_colors_enabled
= -1;
873 cached_underline_enabled
= -1;
879 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
880 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
881 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
882 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
883 * terminal functionality when outputting stuff, even if the input is piped to us. */
885 if (cached_on_tty
< 0)
887 isatty(STDOUT_FILENO
) > 0 &&
888 isatty(STDERR_FILENO
) > 0;
890 return cached_on_tty
;
893 int getttyname_malloc(int fd
, char **ret
) {
894 char path
[PATH_MAX
], *c
; /* PATH_MAX is counted *with* the trailing NUL byte */
900 r
= ttyname_r(fd
, path
, sizeof path
); /* positive error */
903 return -ENAMETOOLONG
;
907 c
= strdup(skip_dev_prefix(path
));
915 int getttyname_harder(int fd
, char **ret
) {
916 _cleanup_free_
char *s
= NULL
;
919 r
= getttyname_malloc(fd
, &s
);
924 return get_ctty(0, NULL
, ret
);
930 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
932 _cleanup_free_
char *line
= NULL
;
938 p
= procfs_file_alloca(pid
, "stat");
939 r
= read_one_line_file(p
, &line
);
943 p
= strrchr(line
, ')');
958 if (major(ttynr
) == 0 && minor(ttynr
) == 0)
967 int get_ctty(pid_t pid
, dev_t
*ret_devnr
, char **ret
) {
968 _cleanup_free_
char *fn
= NULL
, *b
= NULL
;
972 r
= get_ctty_devnr(pid
, &devnr
);
976 r
= device_path_make_canonical(S_IFCHR
, devnr
, &fn
);
978 if (r
!= -ENOENT
) /* No symlink for this in /dev/char/? */
981 if (major(devnr
) == 136) {
982 /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the
983 * Linux device model. This means we have no nice way to match them up against their actual
984 * device node. Let's hence do the check by the fixed, assigned major number. Normally we try
985 * to avoid such fixed major/minor matches, but there appears to nother nice way to handle
988 if (asprintf(&b
, "pts/%u", minor(devnr
)) < 0)
991 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
992 * something vaguely useful. */
994 r
= device_path_make_major_minor(S_IFCHR
, devnr
, &fn
);
1003 w
= path_startswith(fn
, "/dev/");
1021 int ptsname_malloc(int fd
, char **ret
) {
1034 if (ptsname_r(fd
, c
, l
) == 0) {
1038 if (errno
!= ERANGE
) {
1045 if (l
> SIZE_MAX
/ 2)
1052 int ptsname_namespace(int pty
, char **ret
) {
1055 /* Like ptsname(), but doesn't assume that the path is
1056 * accessible in the local namespace. */
1058 r
= ioctl(pty
, TIOCGPTN
, &no
);
1065 if (asprintf(ret
, "/dev/pts/%i", no
) < 0)
1071 int openpt_in_namespace(pid_t pid
, int flags
) {
1072 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
1073 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1079 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1083 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1086 r
= namespace_fork("(sd-openptns)", "(sd-openpt)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1087 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1093 pair
[0] = safe_close(pair
[0]);
1095 master
= posix_openpt(flags
|O_NOCTTY
|O_CLOEXEC
);
1097 _exit(EXIT_FAILURE
);
1099 if (unlockpt(master
) < 0)
1100 _exit(EXIT_FAILURE
);
1102 if (send_one_fd(pair
[1], master
, 0) < 0)
1103 _exit(EXIT_FAILURE
);
1105 _exit(EXIT_SUCCESS
);
1108 pair
[1] = safe_close(pair
[1]);
1110 r
= wait_for_terminate_and_check("(sd-openptns)", child
, 0);
1113 if (r
!= EXIT_SUCCESS
)
1116 return receive_one_fd(pair
[0], 0);
1119 int open_terminal_in_namespace(pid_t pid
, const char *name
, int mode
) {
1120 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
1121 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1125 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1129 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1132 r
= namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1133 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1139 pair
[0] = safe_close(pair
[0]);
1141 master
= open_terminal(name
, mode
|O_NOCTTY
|O_CLOEXEC
);
1143 _exit(EXIT_FAILURE
);
1145 if (send_one_fd(pair
[1], master
, 0) < 0)
1146 _exit(EXIT_FAILURE
);
1148 _exit(EXIT_SUCCESS
);
1151 pair
[1] = safe_close(pair
[1]);
1153 r
= wait_for_terminate_and_check("(sd-terminalns)", child
, 0);
1156 if (r
!= EXIT_SUCCESS
)
1159 return receive_one_fd(pair
[0], 0);
1162 static bool getenv_terminal_is_dumb(void) {
1169 return streq(e
, "dumb");
1172 bool terminal_is_dumb(void) {
1176 return getenv_terminal_is_dumb();
1179 bool colors_enabled(void) {
1181 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1182 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1183 * TTY. And if we are on a TTY we turn it off if $TERM is set to "dumb". There's one special tweak though: if
1184 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1185 * continously due to fear of SAK, and hence things are a bit weird. */
1187 if (cached_colors_enabled
< 0) {
1190 val
= getenv_bool("SYSTEMD_COLORS");
1192 cached_colors_enabled
= val
;
1193 else if (getpid_cached() == 1)
1194 /* PID1 outputs to the console without holding it open all the time */
1195 cached_colors_enabled
= !getenv_terminal_is_dumb();
1197 cached_colors_enabled
= !terminal_is_dumb();
1200 return cached_colors_enabled
;
1203 bool dev_console_colors_enabled(void) {
1204 _cleanup_free_
char *s
= NULL
;
1207 /* Returns true if we assume that color is supported on /dev/console.
1209 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1210 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1211 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1212 * colors_enabled() operates. */
1214 b
= getenv_bool("SYSTEMD_COLORS");
1218 if (getenv_for_pid(1, "TERM", &s
) <= 0)
1219 (void) proc_cmdline_get_key("TERM", 0, &s
);
1221 return !streq_ptr(s
, "dumb");
1224 bool underline_enabled(void) {
1226 if (cached_underline_enabled
< 0) {
1228 /* The Linux console doesn't support underlining, turn it off, but only there. */
1230 if (colors_enabled())
1231 cached_underline_enabled
= !streq_ptr(getenv("TERM"), "linux");
1233 cached_underline_enabled
= false;
1236 return cached_underline_enabled
;
1239 int vt_default_utf8(void) {
1240 _cleanup_free_
char *b
= NULL
;
1243 /* Read the default VT UTF8 setting from the kernel */
1245 r
= read_one_line_file("/sys/module/vt/parameters/default_utf8", &b
);
1249 return parse_boolean(b
);
1252 int vt_verify_kbmode(int fd
) {
1256 * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.
1257 * Otherwise we would (likely) interfere with X11's processing of the
1260 * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html
1263 if (ioctl(fd
, KDGKBMODE
, &curr_mode
) < 0)
1266 return IN_SET(curr_mode
, K_XLATE
, K_UNICODE
) ? 0 : -EBUSY
;
1269 int vt_reset_keyboard(int fd
) {
1272 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1273 kb
= vt_default_utf8() != 0 ? K_UNICODE
: K_XLATE
;
1275 r
= vt_verify_kbmode(fd
);
1277 log_debug_errno(r
, "Keyboard is not in XLATE or UNICODE mode, not resetting: %m");
1282 if (ioctl(fd
, KDSKBMODE
, kb
) < 0)
1288 int vt_restore(int fd
) {
1289 static const struct vt_mode mode
= {
1294 r
= ioctl(fd
, KDSETMODE
, KD_TEXT
);
1296 q
= log_debug_errno(errno
, "Failed to set VT in text mode, ignoring: %m");
1298 r
= vt_reset_keyboard(fd
);
1300 log_debug_errno(r
, "Failed to reset keyboard mode, ignoring: %m");
1305 r
= ioctl(fd
, VT_SETMODE
, &mode
);
1307 log_debug_errno(errno
, "Failed to set VT_AUTO mode, ignoring: %m");
1312 r
= fchown(fd
, 0, (gid_t
) -1);
1314 log_debug_errno(errno
, "Failed to chown VT, ignoring: %m");
1322 int vt_release(int fd
, bool restore
) {
1325 /* This function releases the VT by acknowledging the VT-switch signal
1326 * sent by the kernel and optionally reset the VT in text and auto
1327 * VT-switching modes. */
1329 if (ioctl(fd
, VT_RELDISP
, 1) < 0)
1333 return vt_restore(fd
);