1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <linux/tiocl.h>
14 #include <sys/inotify.h>
15 #include <sys/ioctl.h>
16 #include <sys/sysmacros.h>
18 #include <sys/types.h>
19 #include <sys/utsname.h>
23 #include "alloc-util.h"
33 #include "namespace-util.h"
34 #include "parse-util.h"
35 #include "path-util.h"
36 #include "proc-cmdline.h"
37 #include "process-util.h"
38 #include "socket-util.h"
39 #include "stat-util.h"
40 #include "string-util.h"
42 #include "terminal-util.h"
43 #include "time-util.h"
46 static volatile unsigned cached_columns
= 0;
47 static volatile unsigned cached_lines
= 0;
49 static volatile int cached_on_tty
= -1;
50 static volatile int cached_colors_enabled
= -1;
51 static volatile int cached_underline_enabled
= -1;
54 _cleanup_close_
int fd
;
56 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
57 * if that's configured. */
59 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
65 TIOCL_GETKMSGREDIRECT
,
69 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
72 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
75 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
81 int read_one_char(FILE *f
, char *ret
, usec_t t
, bool *need_nl
) {
82 _cleanup_free_
char *line
= NULL
;
83 struct termios old_termios
;
89 /* If this is a terminal, then switch canonical mode off, so that we can read a single
90 * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
93 if (fd
>= 0 && tcgetattr(fd
, &old_termios
) >= 0) {
94 struct termios new_termios
= old_termios
;
96 new_termios
.c_lflag
&= ~ICANON
;
97 new_termios
.c_cc
[VMIN
] = 1;
98 new_termios
.c_cc
[VTIME
] = 0;
100 if (tcsetattr(fd
, TCSADRAIN
, &new_termios
) >= 0) {
103 if (t
!= USEC_INFINITY
) {
104 if (fd_wait_for_event(fd
, POLLIN
, t
) <= 0) {
105 (void) tcsetattr(fd
, TCSADRAIN
, &old_termios
);
110 r
= safe_fgetc(f
, &c
);
111 (void) tcsetattr(fd
, TCSADRAIN
, &old_termios
);
118 *need_nl
= c
!= '\n';
125 if (t
!= USEC_INFINITY
&& fd
> 0) {
126 /* Let's wait the specified amount of time for input. When we have no fd we skip this, under
127 * the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
128 * anyway, as the data is either already in the stream or cannot possible be placed there
129 * while we access the stream */
131 if (fd_wait_for_event(fd
, POLLIN
, t
) <= 0)
135 /* If this is not a terminal, then read a full line instead */
137 r
= read_line(f
, 16, &line
); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
143 if (strlen(line
) != 1)
153 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
155 int ask_char(char *ret
, const char *replies
, const char *fmt
, ...) {
167 if (colors_enabled())
168 fputs(ANSI_HIGHLIGHT
, stdout
);
176 if (colors_enabled())
177 fputs(ANSI_NORMAL
, stdout
);
181 r
= read_one_char(stdin
, &c
, DEFAULT_ASK_REFRESH_USEC
, &need_nl
);
188 puts("Bad input, please try again.");
199 if (strchr(replies
, c
)) {
204 puts("Read unexpected character, please try again.");
208 int ask_string(char **ret
, const char *text
, ...) {
209 _cleanup_free_
char *line
= NULL
;
216 if (colors_enabled())
217 fputs(ANSI_HIGHLIGHT
, stdout
);
223 if (colors_enabled())
224 fputs(ANSI_NORMAL
, stdout
);
228 r
= read_line(stdin
, LONG_LINE_MAX
, &line
);
234 *ret
= TAKE_PTR(line
);
238 int reset_terminal_fd(int fd
, bool switch_to_text
) {
239 struct termios termios
;
242 /* Set terminal to some sane defaults */
246 /* We leave locked terminal attributes untouched, so that
247 * Plymouth may set whatever it wants to set, and we don't
248 * interfere with that. */
250 /* Disable exclusive mode, just in case */
251 (void) ioctl(fd
, TIOCNXCL
);
253 /* Switch to text mode */
255 (void) ioctl(fd
, KDSETMODE
, KD_TEXT
);
257 /* Set default keyboard mode */
258 (void) vt_reset_keyboard(fd
);
260 if (tcgetattr(fd
, &termios
) < 0) {
265 /* We only reset the stuff that matters to the software. How
266 * hardware is set up we don't touch assuming that somebody
267 * else will do that for us */
269 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
270 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
271 termios
.c_oflag
|= ONLCR
;
272 termios
.c_cflag
|= CREAD
;
273 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
275 termios
.c_cc
[VINTR
] = 03; /* ^C */
276 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
277 termios
.c_cc
[VERASE
] = 0177;
278 termios
.c_cc
[VKILL
] = 025; /* ^X */
279 termios
.c_cc
[VEOF
] = 04; /* ^D */
280 termios
.c_cc
[VSTART
] = 021; /* ^Q */
281 termios
.c_cc
[VSTOP
] = 023; /* ^S */
282 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
283 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
284 termios
.c_cc
[VWERASE
] = 027; /* ^W */
285 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
286 termios
.c_cc
[VEOL
] = 0;
287 termios
.c_cc
[VEOL2
] = 0;
289 termios
.c_cc
[VTIME
] = 0;
290 termios
.c_cc
[VMIN
] = 1;
292 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
296 /* Just in case, flush all crap out */
297 (void) tcflush(fd
, TCIOFLUSH
);
302 int reset_terminal(const char *name
) {
303 _cleanup_close_
int fd
= -1;
305 /* We open the terminal with O_NONBLOCK here, to ensure we
306 * don't block on carrier if this is a terminal with carrier
309 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
313 return reset_terminal_fd(fd
, true);
316 int open_terminal(const char *name
, int mode
) {
321 * If a TTY is in the process of being closed opening it might
322 * cause EIO. This is horribly awful, but unlikely to be
323 * changed in the kernel. Hence we work around this problem by
324 * retrying a couple of times.
326 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
333 fd
= open(name
, mode
, 0);
340 /* Max 1s in total */
344 usleep(50 * USEC_PER_MSEC
);
348 if (isatty(fd
) <= 0) {
356 int acquire_terminal(
358 AcquireTerminalFlags flags
,
361 _cleanup_close_
int notify
= -1, fd
= -1;
362 usec_t ts
= USEC_INFINITY
;
366 assert(IN_SET(flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
, ACQUIRE_TERMINAL_TRY
, ACQUIRE_TERMINAL_FORCE
, ACQUIRE_TERMINAL_WAIT
));
368 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
369 * acquire it, so that we don't lose any event.
371 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
372 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
373 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
374 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
375 * probably should not do anyway.) */
377 if ((flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_WAIT
) {
378 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= USEC_INFINITY
? IN_NONBLOCK
: 0));
382 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
386 if (timeout
!= USEC_INFINITY
)
387 ts
= now(CLOCK_MONOTONIC
);
391 struct sigaction sa_old
, sa_new
= {
392 .sa_handler
= SIG_IGN
,
393 .sa_flags
= SA_RESTART
,
397 r
= flush_fd(notify
);
402 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
403 * to figure out if we successfully became the controlling process of the tty */
404 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
408 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
409 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
411 /* First, try to get the tty */
412 r
= ioctl(fd
, TIOCSCTTY
,
413 (flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_FORCE
) < 0 ? -errno
: 0;
415 /* Reset signal handler to old value */
416 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
418 /* Success? Exit the loop now! */
422 /* Any failure besides -EPERM? Fail, regardless of the mode. */
426 if (flags
& ACQUIRE_TERMINAL_PERMISSIVE
) /* If we are in permissive mode, then EPERM is fine, turn this
427 * into a success. Note that EPERM is also returned if we
428 * already are the owner of the TTY. */
431 if (flags
!= ACQUIRE_TERMINAL_WAIT
) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
438 union inotify_event_buffer buffer
;
439 struct inotify_event
*e
;
442 if (timeout
!= USEC_INFINITY
) {
445 assert(ts
!= USEC_INFINITY
);
447 n
= now(CLOCK_MONOTONIC
);
448 if (ts
+ timeout
< n
)
451 r
= fd_wait_for_event(notify
, POLLIN
, ts
+ timeout
- n
);
458 l
= read(notify
, &buffer
, sizeof(buffer
));
460 if (IN_SET(errno
, EINTR
, EAGAIN
))
466 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
467 if (e
->mask
& IN_Q_OVERFLOW
) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
470 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) /* Safety checks */
477 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
478 * we do this after sleeping, so that we don't enter an endless loop. */
485 int release_terminal(void) {
486 static const struct sigaction sa_new
= {
487 .sa_handler
= SIG_IGN
,
488 .sa_flags
= SA_RESTART
,
491 _cleanup_close_
int fd
= -1;
492 struct sigaction sa_old
;
495 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
499 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
500 * by our own TIOCNOTTY */
501 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
503 r
= ioctl(fd
, TIOCNOTTY
) < 0 ? -errno
: 0;
505 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
510 int terminal_vhangup_fd(int fd
) {
513 if (ioctl(fd
, TIOCVHANGUP
) < 0)
519 int terminal_vhangup(const char *name
) {
520 _cleanup_close_
int fd
;
522 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
526 return terminal_vhangup_fd(fd
);
529 int vt_disallocate(const char *name
) {
533 /* Deallocate the VT if possible. If not possible
534 * (i.e. because it is the active one), at least clear it
535 * entirely (including the scrollback buffer). */
537 e
= path_startswith(name
, "/dev/");
541 if (tty_is_vc(name
)) {
542 _cleanup_close_
int fd
= -1;
546 n
= startswith(e
, "tty");
550 r
= safe_atou(n
, &u
);
557 /* Try to deallocate */
558 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
562 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
569 /* So this is not a VT (in which case we cannot deallocate it),
570 * or we failed to deallocate. Let's at least clear the screen. */
572 _cleanup_close_
int fd2
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
576 (void) loop_write(fd2
,
577 "\033[r" /* clear scrolling region */
578 "\033[H" /* move home */
579 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
584 int make_console_stdio(void) {
587 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
588 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
589 * is specified on the kernel command line. */
591 fd
= acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE
|ACQUIRE_TERMINAL_PERMISSIVE
, USEC_INFINITY
);
593 log_warning_errno(fd
, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
595 r
= make_null_stdio();
597 return log_error_errno(r
, "Failed to make /dev/null stdin/stdout/stderr: %m");
600 r
= reset_terminal_fd(fd
, true);
602 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
604 r
= rearrange_stdio(fd
, fd
, fd
); /* This invalidates 'fd' both on success and on failure. */
606 return log_error_errno(r
, "Failed to make terminal stdin/stdout/stderr: %m");
609 reset_terminal_feature_caches();
613 bool tty_is_vc(const char *tty
) {
616 return vtnr_from_tty(tty
) >= 0;
619 bool tty_is_console(const char *tty
) {
622 return streq(skip_dev_prefix(tty
), "console");
625 int vtnr_from_tty(const char *tty
) {
630 tty
= skip_dev_prefix(tty
);
632 if (!startswith(tty
, "tty") )
635 if (tty
[3] < '0' || tty
[3] > '9')
638 r
= safe_atoi(tty
+3, &i
);
648 int resolve_dev_console(char **ret
) {
649 _cleanup_free_
char *active
= NULL
;
655 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
656 * sign for container setups) */
658 if (path_is_read_only_fs("/sys") > 0)
661 r
= read_one_line_file("/sys/class/tty/console/active", &active
);
665 /* If multiple log outputs are configured the last one is what /dev/console points to */
666 tty
= strrchr(active
, ' ');
672 if (streq(tty
, "tty0")) {
673 active
= mfree(active
);
675 /* Get the active VC (e.g. tty1) */
676 r
= read_one_line_file("/sys/class/tty/tty0/active", &active
);
684 *ret
= TAKE_PTR(active
);
698 int get_kernel_consoles(char ***ret
) {
699 _cleanup_strv_free_
char **l
= NULL
;
700 _cleanup_free_
char *line
= NULL
;
706 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
707 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
708 if (path_is_read_only_fs("/sys") > 0)
711 r
= read_one_line_file("/sys/class/tty/console/active", &line
);
717 _cleanup_free_
char *tty
= NULL
, *path
= NULL
;
719 r
= extract_first_word(&p
, &tty
, NULL
, 0);
725 if (streq(tty
, "tty0")) {
727 r
= read_one_line_file("/sys/class/tty/tty0/active", &tty
);
732 path
= path_join("/dev", tty
);
736 if (access(path
, F_OK
) < 0) {
737 log_debug_errno(errno
, "Console device %s is not accessible, skipping: %m", path
);
741 r
= strv_consume(&l
, TAKE_PTR(path
));
746 if (strv_isempty(l
)) {
747 log_debug("No devices found for system console");
756 r
= strv_extend(&l
, "/dev/console");
765 bool tty_is_vc_resolve(const char *tty
) {
766 _cleanup_free_
char *resolved
= NULL
;
770 tty
= skip_dev_prefix(tty
);
772 if (streq(tty
, "console")) {
773 if (resolve_dev_console(&resolved
) < 0)
779 return tty_is_vc(tty
);
782 const char *default_term_for_tty(const char *tty
) {
783 return tty
&& tty_is_vc_resolve(tty
) ? "linux" : "vt220";
786 int fd_columns(int fd
) {
787 struct winsize ws
= {};
792 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
801 unsigned columns(void) {
805 if (cached_columns
> 0)
806 return cached_columns
;
809 e
= getenv("COLUMNS");
811 (void) safe_atoi(e
, &c
);
813 if (c
<= 0 || c
> USHRT_MAX
) {
814 c
= fd_columns(STDOUT_FILENO
);
820 return cached_columns
;
823 int fd_lines(int fd
) {
824 struct winsize ws
= {};
829 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
838 unsigned lines(void) {
842 if (cached_lines
> 0)
848 (void) safe_atoi(e
, &l
);
850 if (l
<= 0 || l
> USHRT_MAX
) {
851 l
= fd_lines(STDOUT_FILENO
);
860 /* intended to be used as a SIGWINCH sighandler */
861 void columns_lines_cache_reset(int signum
) {
866 void reset_terminal_feature_caches(void) {
870 cached_colors_enabled
= -1;
871 cached_underline_enabled
= -1;
877 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
878 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
879 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
880 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
881 * terminal functionality when outputting stuff, even if the input is piped to us. */
883 if (cached_on_tty
< 0)
885 isatty(STDOUT_FILENO
) > 0 &&
886 isatty(STDERR_FILENO
) > 0;
888 return cached_on_tty
;
891 int getttyname_malloc(int fd
, char **ret
) {
892 char path
[PATH_MAX
], *c
; /* PATH_MAX is counted *with* the trailing NUL byte */
898 r
= ttyname_r(fd
, path
, sizeof path
); /* positive error */
901 return -ENAMETOOLONG
;
905 c
= strdup(skip_dev_prefix(path
));
913 int getttyname_harder(int fd
, char **ret
) {
914 _cleanup_free_
char *s
= NULL
;
917 r
= getttyname_malloc(fd
, &s
);
922 return get_ctty(0, NULL
, ret
);
928 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
930 _cleanup_free_
char *line
= NULL
;
936 p
= procfs_file_alloca(pid
, "stat");
937 r
= read_one_line_file(p
, &line
);
941 p
= strrchr(line
, ')');
956 if (major(ttynr
) == 0 && minor(ttynr
) == 0)
965 int get_ctty(pid_t pid
, dev_t
*ret_devnr
, char **ret
) {
966 _cleanup_free_
char *fn
= NULL
, *b
= NULL
;
970 r
= get_ctty_devnr(pid
, &devnr
);
974 r
= device_path_make_canonical(S_IFCHR
, devnr
, &fn
);
976 if (r
!= -ENOENT
) /* No symlink for this in /dev/char/? */
979 if (major(devnr
) == 136) {
980 /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the
981 * Linux device model. This means we have no nice way to match them up against their actual
982 * device node. Let's hence do the check by the fixed, assigned major number. Normally we try
983 * to avoid such fixed major/minor matches, but there appears to nother nice way to handle
986 if (asprintf(&b
, "pts/%u", minor(devnr
)) < 0)
989 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
990 * something vaguely useful. */
992 r
= device_path_make_major_minor(S_IFCHR
, devnr
, &fn
);
1001 w
= path_startswith(fn
, "/dev/");
1019 int ptsname_malloc(int fd
, char **ret
) {
1032 if (ptsname_r(fd
, c
, l
) == 0) {
1036 if (errno
!= ERANGE
) {
1043 if (l
> SIZE_MAX
/ 2)
1050 int openpt_allocate(int flags
, char **ret_slave
) {
1051 _cleanup_close_
int fd
= -1;
1052 _cleanup_free_
char *p
= NULL
;
1055 fd
= posix_openpt(flags
|O_NOCTTY
|O_CLOEXEC
);
1060 r
= ptsname_malloc(fd
, &p
);
1064 if (!path_startswith(p
, "/dev/pts/"))
1068 if (unlockpt(fd
) < 0)
1072 *ret_slave
= TAKE_PTR(p
);
1077 static int ptsname_namespace(int pty
, char **ret
) {
1080 /* Like ptsname(), but doesn't assume that the path is
1081 * accessible in the local namespace. */
1083 r
= ioctl(pty
, TIOCGPTN
, &no
);
1090 if (asprintf(ret
, "/dev/pts/%i", no
) < 0)
1096 int openpt_allocate_in_namespace(pid_t pid
, int flags
, char **ret_slave
) {
1097 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1, fd
= -1;
1098 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1104 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1108 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1111 r
= namespace_fork("(sd-openptns)", "(sd-openpt)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1112 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1116 pair
[0] = safe_close(pair
[0]);
1118 fd
= openpt_allocate(flags
, NULL
);
1120 _exit(EXIT_FAILURE
);
1122 if (send_one_fd(pair
[1], fd
, 0) < 0)
1123 _exit(EXIT_FAILURE
);
1125 _exit(EXIT_SUCCESS
);
1128 pair
[1] = safe_close(pair
[1]);
1130 r
= wait_for_terminate_and_check("(sd-openptns)", child
, 0);
1133 if (r
!= EXIT_SUCCESS
)
1136 fd
= receive_one_fd(pair
[0], 0);
1141 r
= ptsname_namespace(fd
, ret_slave
);
1149 int open_terminal_in_namespace(pid_t pid
, const char *name
, int mode
) {
1150 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
1151 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1155 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1159 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1162 r
= namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1163 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1169 pair
[0] = safe_close(pair
[0]);
1171 master
= open_terminal(name
, mode
|O_NOCTTY
|O_CLOEXEC
);
1173 _exit(EXIT_FAILURE
);
1175 if (send_one_fd(pair
[1], master
, 0) < 0)
1176 _exit(EXIT_FAILURE
);
1178 _exit(EXIT_SUCCESS
);
1181 pair
[1] = safe_close(pair
[1]);
1183 r
= wait_for_terminate_and_check("(sd-terminalns)", child
, 0);
1186 if (r
!= EXIT_SUCCESS
)
1189 return receive_one_fd(pair
[0], 0);
1192 static bool getenv_terminal_is_dumb(void) {
1199 return streq(e
, "dumb");
1202 bool terminal_is_dumb(void) {
1206 return getenv_terminal_is_dumb();
1209 bool colors_enabled(void) {
1211 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1212 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1213 * 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
1214 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1215 * continuously due to fear of SAK, and hence things are a bit weird. */
1217 if (cached_colors_enabled
< 0) {
1220 val
= getenv_bool("SYSTEMD_COLORS");
1222 cached_colors_enabled
= val
;
1224 else if (getenv("NO_COLOR"))
1225 /* We only check for the presence of the variable; value is ignored. */
1226 cached_colors_enabled
= false;
1228 else if (getpid_cached() == 1)
1229 /* PID1 outputs to the console without holding it open all the time */
1230 cached_colors_enabled
= !getenv_terminal_is_dumb();
1232 cached_colors_enabled
= !terminal_is_dumb();
1235 return cached_colors_enabled
;
1238 bool dev_console_colors_enabled(void) {
1239 _cleanup_free_
char *s
= NULL
;
1242 /* Returns true if we assume that color is supported on /dev/console.
1244 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1245 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1246 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1247 * colors_enabled() operates. */
1249 b
= getenv_bool("SYSTEMD_COLORS");
1253 if (getenv("NO_COLOR"))
1256 if (getenv_for_pid(1, "TERM", &s
) <= 0)
1257 (void) proc_cmdline_get_key("TERM", 0, &s
);
1259 return !streq_ptr(s
, "dumb");
1262 bool underline_enabled(void) {
1264 if (cached_underline_enabled
< 0) {
1266 /* The Linux console doesn't support underlining, turn it off, but only there. */
1268 if (colors_enabled())
1269 cached_underline_enabled
= !streq_ptr(getenv("TERM"), "linux");
1271 cached_underline_enabled
= false;
1274 return cached_underline_enabled
;
1277 int vt_default_utf8(void) {
1278 _cleanup_free_
char *b
= NULL
;
1281 /* Read the default VT UTF8 setting from the kernel */
1283 r
= read_one_line_file("/sys/module/vt/parameters/default_utf8", &b
);
1287 return parse_boolean(b
);
1290 int vt_reset_keyboard(int fd
) {
1293 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1294 kb
= vt_default_utf8() != 0 ? K_UNICODE
: K_XLATE
;
1296 if (ioctl(fd
, KDSKBMODE
, kb
) < 0)
1302 int vt_restore(int fd
) {
1303 static const struct vt_mode mode
= {
1308 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
1309 q
= log_debug_errno(errno
, "Failed to set VT in text mode, ignoring: %m");
1311 r
= vt_reset_keyboard(fd
);
1313 log_debug_errno(r
, "Failed to reset keyboard mode, ignoring: %m");
1318 if (ioctl(fd
, VT_SETMODE
, &mode
) < 0) {
1319 log_debug_errno(errno
, "Failed to set VT_AUTO mode, ignoring: %m");
1324 r
= fchmod_and_chown(fd
, TTY_MODE
, 0, (gid_t
) -1);
1326 log_debug_errno(r
, "Failed to chmod()/chown() VT, ignoring: %m");
1334 int vt_release(int fd
, bool restore
) {
1337 /* This function releases the VT by acknowledging the VT-switch signal
1338 * sent by the kernel and optionally reset the VT in text and auto
1339 * VT-switching modes. */
1341 if (ioctl(fd
, VT_RELDISP
, 1) < 0)
1345 return vt_restore(fd
);
1350 void get_log_colors(int priority
, const char **on
, const char **off
, const char **highlight
) {
1351 /* Note that this will initialize output variables only when there's something to output.
1352 * The caller must pre-initialize to "" or NULL as appropriate. */
1354 if (priority
<= LOG_ERR
) {
1356 *on
= ANSI_HIGHLIGHT_RED
;
1360 *highlight
= ANSI_HIGHLIGHT
;
1362 } else if (priority
<= LOG_WARNING
) {
1364 *on
= ANSI_HIGHLIGHT_YELLOW
;
1368 *highlight
= ANSI_HIGHLIGHT
;
1370 } else if (priority
<= LOG_NOTICE
) {
1372 *on
= ANSI_HIGHLIGHT
;
1376 *highlight
= ANSI_HIGHLIGHT_RED
;
1378 } else if (priority
>= LOG_DEBUG
) {
1384 *highlight
= ANSI_HIGHLIGHT_RED
;