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"
44 #include "user-util.h"
47 static volatile unsigned cached_columns
= 0;
48 static volatile unsigned cached_lines
= 0;
50 static volatile int cached_on_tty
= -1;
51 static volatile int cached_color_mode
= _COLOR_INVALID
;
52 static volatile int cached_underline_enabled
= -1;
55 _cleanup_close_
int fd
= -1;
57 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
58 * if that's configured. */
60 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
66 TIOCL_GETKMSGREDIRECT
,
70 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
73 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
76 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
82 int read_one_char(FILE *f
, char *ret
, usec_t t
, bool *need_nl
) {
83 _cleanup_free_
char *line
= NULL
;
84 struct termios old_termios
;
90 /* If this is a terminal, then switch canonical mode off, so that we can read a single
91 * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
94 if (fd
>= 0 && tcgetattr(fd
, &old_termios
) >= 0) {
95 struct termios new_termios
= old_termios
;
97 new_termios
.c_lflag
&= ~ICANON
;
98 new_termios
.c_cc
[VMIN
] = 1;
99 new_termios
.c_cc
[VTIME
] = 0;
101 if (tcsetattr(fd
, TCSADRAIN
, &new_termios
) >= 0) {
104 if (t
!= USEC_INFINITY
) {
105 if (fd_wait_for_event(fd
, POLLIN
, t
) <= 0) {
106 (void) tcsetattr(fd
, TCSADRAIN
, &old_termios
);
111 r
= safe_fgetc(f
, &c
);
112 (void) tcsetattr(fd
, TCSADRAIN
, &old_termios
);
119 *need_nl
= c
!= '\n';
126 if (t
!= USEC_INFINITY
&& fd
> 0) {
127 /* Let's wait the specified amount of time for input. When we have no fd we skip this, under
128 * the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
129 * anyway, as the data is either already in the stream or cannot possible be placed there
130 * while we access the stream */
132 if (fd_wait_for_event(fd
, POLLIN
, t
) <= 0)
136 /* If this is not a terminal, then read a full line instead */
138 r
= read_line(f
, 16, &line
); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
144 if (strlen(line
) != 1)
154 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
156 int ask_char(char *ret
, const char *replies
, const char *fmt
, ...) {
168 fputs(ansi_highlight(), stdout
);
176 fputs(ansi_normal(), stdout
);
180 r
= read_one_char(stdin
, &c
, DEFAULT_ASK_REFRESH_USEC
, &need_nl
);
187 puts("Bad input, please try again.");
198 if (strchr(replies
, c
)) {
203 puts("Read unexpected character, please try again.");
207 int ask_string(char **ret
, const char *text
, ...) {
208 _cleanup_free_
char *line
= NULL
;
215 fputs(ansi_highlight(), stdout
);
221 fputs(ansi_normal(), stdout
);
225 r
= read_line(stdin
, LONG_LINE_MAX
, &line
);
231 *ret
= TAKE_PTR(line
);
235 int reset_terminal_fd(int fd
, bool switch_to_text
) {
236 struct termios termios
;
239 /* Set terminal to some sane defaults */
244 return log_debug_errno(errno
, "Asked to reset a terminal that actually isn't a terminal: %m");
246 /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
247 * and we don't interfere with that. */
249 /* Disable exclusive mode, just in case */
250 if (ioctl(fd
, TIOCNXCL
) < 0)
251 log_debug_errno(errno
, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
253 /* Switch to text mode */
255 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
256 log_debug_errno(errno
, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
259 /* Set default keyboard mode */
260 (void) vt_reset_keyboard(fd
);
262 if (tcgetattr(fd
, &termios
) < 0) {
263 r
= log_debug_errno(errno
, "Failed to get terminal parameters: %m");
267 /* We only reset the stuff that matters to the software. How
268 * hardware is set up we don't touch assuming that somebody
269 * else will do that for us */
271 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
272 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
273 termios
.c_oflag
|= ONLCR
;
274 termios
.c_cflag
|= CREAD
;
275 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
277 termios
.c_cc
[VINTR
] = 03; /* ^C */
278 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
279 termios
.c_cc
[VERASE
] = 0177;
280 termios
.c_cc
[VKILL
] = 025; /* ^X */
281 termios
.c_cc
[VEOF
] = 04; /* ^D */
282 termios
.c_cc
[VSTART
] = 021; /* ^Q */
283 termios
.c_cc
[VSTOP
] = 023; /* ^S */
284 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
285 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
286 termios
.c_cc
[VWERASE
] = 027; /* ^W */
287 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
288 termios
.c_cc
[VEOL
] = 0;
289 termios
.c_cc
[VEOL2
] = 0;
291 termios
.c_cc
[VTIME
] = 0;
292 termios
.c_cc
[VMIN
] = 1;
294 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
298 /* Just in case, flush all crap out */
299 (void) tcflush(fd
, TCIOFLUSH
);
304 int reset_terminal(const char *name
) {
305 _cleanup_close_
int fd
= -1;
307 /* We open the terminal with O_NONBLOCK here, to ensure we
308 * don't block on carrier if this is a terminal with carrier
311 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
315 return reset_terminal_fd(fd
, true);
318 int open_terminal(const char *name
, int mode
) {
323 * If a TTY is in the process of being closed opening it might
324 * cause EIO. This is horribly awful, but unlikely to be
325 * changed in the kernel. Hence we work around this problem by
326 * retrying a couple of times.
328 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
335 fd
= open(name
, mode
, 0);
342 /* Max 1s in total */
346 usleep(50 * USEC_PER_MSEC
);
350 if (isatty(fd
) <= 0) {
358 int acquire_terminal(
360 AcquireTerminalFlags flags
,
363 _cleanup_close_
int notify
= -1, fd
= -1;
364 usec_t ts
= USEC_INFINITY
;
368 assert(IN_SET(flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
, ACQUIRE_TERMINAL_TRY
, ACQUIRE_TERMINAL_FORCE
, ACQUIRE_TERMINAL_WAIT
));
370 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
371 * acquire it, so that we don't lose any event.
373 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
374 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
375 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
376 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
377 * probably should not do anyway.) */
379 if ((flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_WAIT
) {
380 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= USEC_INFINITY
? IN_NONBLOCK
: 0));
384 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
388 if (timeout
!= USEC_INFINITY
)
389 ts
= now(CLOCK_MONOTONIC
);
393 struct sigaction sa_old
, sa_new
= {
394 .sa_handler
= SIG_IGN
,
395 .sa_flags
= SA_RESTART
,
399 r
= flush_fd(notify
);
404 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
405 * to figure out if we successfully became the controlling process of the tty */
406 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
410 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
411 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
413 /* First, try to get the tty */
414 r
= ioctl(fd
, TIOCSCTTY
,
415 (flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_FORCE
) < 0 ? -errno
: 0;
417 /* Reset signal handler to old value */
418 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
420 /* Success? Exit the loop now! */
424 /* Any failure besides -EPERM? Fail, regardless of the mode. */
428 if (flags
& ACQUIRE_TERMINAL_PERMISSIVE
) /* If we are in permissive mode, then EPERM is fine, turn this
429 * into a success. Note that EPERM is also returned if we
430 * already are the owner of the TTY. */
433 if (flags
!= ACQUIRE_TERMINAL_WAIT
) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
440 union inotify_event_buffer buffer
;
441 struct inotify_event
*e
;
444 if (timeout
!= USEC_INFINITY
) {
447 assert(ts
!= USEC_INFINITY
);
449 n
= usec_sub_unsigned(now(CLOCK_MONOTONIC
), ts
);
453 r
= fd_wait_for_event(notify
, POLLIN
, usec_sub_unsigned(timeout
, n
));
460 l
= read(notify
, &buffer
, sizeof(buffer
));
462 if (IN_SET(errno
, EINTR
, EAGAIN
))
468 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
469 if (e
->mask
& IN_Q_OVERFLOW
) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
472 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) /* Safety checks */
479 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
480 * we do this after sleeping, so that we don't enter an endless loop. */
487 int release_terminal(void) {
488 static const struct sigaction sa_new
= {
489 .sa_handler
= SIG_IGN
,
490 .sa_flags
= SA_RESTART
,
493 _cleanup_close_
int fd
= -1;
494 struct sigaction sa_old
;
497 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
501 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
502 * by our own TIOCNOTTY */
503 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
505 r
= ioctl(fd
, TIOCNOTTY
) < 0 ? -errno
: 0;
507 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
512 int terminal_vhangup_fd(int fd
) {
515 if (ioctl(fd
, TIOCVHANGUP
) < 0)
521 int terminal_vhangup(const char *name
) {
522 _cleanup_close_
int fd
= -1;
524 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
528 return terminal_vhangup_fd(fd
);
531 int vt_disallocate(const char *name
) {
535 /* Deallocate the VT if possible. If not possible
536 * (i.e. because it is the active one), at least clear it
537 * entirely (including the scrollback buffer). */
539 e
= path_startswith(name
, "/dev/");
543 if (tty_is_vc(name
)) {
544 _cleanup_close_
int fd
= -1;
548 n
= startswith(e
, "tty");
552 r
= safe_atou(n
, &u
);
559 /* Try to deallocate */
560 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
564 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
571 /* So this is not a VT (in which case we cannot deallocate it),
572 * or we failed to deallocate. Let's at least clear the screen. */
574 _cleanup_close_
int fd2
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
578 (void) loop_write(fd2
,
579 "\033[r" /* clear scrolling region */
580 "\033[H" /* move home */
581 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
586 int make_console_stdio(void) {
589 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
590 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
591 * is specified on the kernel command line. */
593 fd
= acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE
|ACQUIRE_TERMINAL_PERMISSIVE
, USEC_INFINITY
);
595 log_warning_errno(fd
, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
597 r
= make_null_stdio();
599 return log_error_errno(r
, "Failed to make /dev/null stdin/stdout/stderr: %m");
602 r
= reset_terminal_fd(fd
, true);
604 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
606 r
= rearrange_stdio(fd
, fd
, fd
); /* This invalidates 'fd' both on success and on failure. */
608 return log_error_errno(r
, "Failed to make terminal stdin/stdout/stderr: %m");
611 reset_terminal_feature_caches();
615 bool tty_is_vc(const char *tty
) {
618 return vtnr_from_tty(tty
) >= 0;
621 bool tty_is_console(const char *tty
) {
624 return streq(skip_dev_prefix(tty
), "console");
627 int vtnr_from_tty(const char *tty
) {
632 tty
= skip_dev_prefix(tty
);
634 if (!startswith(tty
, "tty") )
637 if (tty
[3] < '0' || tty
[3] > '9')
640 r
= safe_atoi(tty
+3, &i
);
650 int resolve_dev_console(char **ret
) {
651 _cleanup_free_
char *active
= NULL
;
657 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
658 * sign for container setups) */
660 if (path_is_read_only_fs("/sys") > 0)
663 r
= read_one_line_file("/sys/class/tty/console/active", &active
);
667 /* If multiple log outputs are configured the last one is what /dev/console points to */
668 tty
= strrchr(active
, ' ');
674 if (streq(tty
, "tty0")) {
675 active
= mfree(active
);
677 /* Get the active VC (e.g. tty1) */
678 r
= read_one_line_file("/sys/class/tty/tty0/active", &active
);
686 *ret
= TAKE_PTR(active
);
700 int get_kernel_consoles(char ***ret
) {
701 _cleanup_strv_free_
char **l
= NULL
;
702 _cleanup_free_
char *line
= NULL
;
708 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
709 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
710 if (path_is_read_only_fs("/sys") > 0)
713 r
= read_one_line_file("/sys/class/tty/console/active", &line
);
719 _cleanup_free_
char *tty
= NULL
, *path
= NULL
;
721 r
= extract_first_word(&p
, &tty
, NULL
, 0);
727 if (streq(tty
, "tty0")) {
729 r
= read_one_line_file("/sys/class/tty/tty0/active", &tty
);
734 path
= path_join("/dev", tty
);
738 if (access(path
, F_OK
) < 0) {
739 log_debug_errno(errno
, "Console device %s is not accessible, skipping: %m", path
);
743 r
= strv_consume(&l
, TAKE_PTR(path
));
748 if (strv_isempty(l
)) {
749 log_debug("No devices found for system console");
758 r
= strv_extend(&l
, "/dev/console");
767 bool tty_is_vc_resolve(const char *tty
) {
768 _cleanup_free_
char *resolved
= NULL
;
772 tty
= skip_dev_prefix(tty
);
774 if (streq(tty
, "console")) {
775 if (resolve_dev_console(&resolved
) < 0)
781 return tty_is_vc(tty
);
784 const char *default_term_for_tty(const char *tty
) {
785 return tty
&& tty_is_vc_resolve(tty
) ? "linux" : "vt220";
788 int fd_columns(int fd
) {
789 struct winsize ws
= {};
794 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
803 unsigned columns(void) {
807 if (cached_columns
> 0)
808 return cached_columns
;
811 e
= getenv("COLUMNS");
813 (void) safe_atoi(e
, &c
);
815 if (c
<= 0 || c
> USHRT_MAX
) {
816 c
= fd_columns(STDOUT_FILENO
);
822 return cached_columns
;
825 int fd_lines(int fd
) {
826 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_color_mode
= _COLOR_INVALID
;
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 openpt_allocate(int flags
, char **ret_slave
) {
1053 _cleanup_close_
int fd
= -1;
1054 _cleanup_free_
char *p
= NULL
;
1057 fd
= posix_openpt(flags
|O_NOCTTY
|O_CLOEXEC
);
1062 r
= ptsname_malloc(fd
, &p
);
1066 if (!path_startswith(p
, "/dev/pts/"))
1070 if (unlockpt(fd
) < 0)
1074 *ret_slave
= TAKE_PTR(p
);
1079 static int ptsname_namespace(int pty
, char **ret
) {
1082 /* Like ptsname(), but doesn't assume that the path is
1083 * accessible in the local namespace. */
1085 r
= ioctl(pty
, TIOCGPTN
, &no
);
1092 if (asprintf(ret
, "/dev/pts/%i", no
) < 0)
1098 int openpt_allocate_in_namespace(pid_t pid
, int flags
, char **ret_slave
) {
1099 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1, fd
= -1;
1100 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1106 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1110 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1113 r
= namespace_fork("(sd-openptns)", "(sd-openpt)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1114 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1118 pair
[0] = safe_close(pair
[0]);
1120 fd
= openpt_allocate(flags
, NULL
);
1122 _exit(EXIT_FAILURE
);
1124 if (send_one_fd(pair
[1], fd
, 0) < 0)
1125 _exit(EXIT_FAILURE
);
1127 _exit(EXIT_SUCCESS
);
1130 pair
[1] = safe_close(pair
[1]);
1132 r
= wait_for_terminate_and_check("(sd-openptns)", child
, 0);
1135 if (r
!= EXIT_SUCCESS
)
1138 fd
= receive_one_fd(pair
[0], 0);
1143 r
= ptsname_namespace(fd
, ret_slave
);
1151 int open_terminal_in_namespace(pid_t pid
, const char *name
, int mode
) {
1152 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
1153 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1157 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1161 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1164 r
= namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1165 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1171 pair
[0] = safe_close(pair
[0]);
1173 master
= open_terminal(name
, mode
|O_NOCTTY
|O_CLOEXEC
);
1175 _exit(EXIT_FAILURE
);
1177 if (send_one_fd(pair
[1], master
, 0) < 0)
1178 _exit(EXIT_FAILURE
);
1180 _exit(EXIT_SUCCESS
);
1183 pair
[1] = safe_close(pair
[1]);
1185 r
= wait_for_terminate_and_check("(sd-terminalns)", child
, 0);
1188 if (r
!= EXIT_SUCCESS
)
1191 return receive_one_fd(pair
[0], 0);
1194 static bool getenv_terminal_is_dumb(void) {
1201 return streq(e
, "dumb");
1204 bool terminal_is_dumb(void) {
1208 return getenv_terminal_is_dumb();
1211 static ColorMode
parse_systemd_colors(void) {
1215 e
= getenv("SYSTEMD_COLORS");
1217 return _COLOR_INVALID
;
1220 if (streq(e
, "256"))
1222 r
= parse_boolean(e
);
1224 return r
> 0 ? COLOR_ON
: COLOR_OFF
;
1225 return _COLOR_INVALID
;
1228 ColorMode
get_color_mode(void) {
1230 /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1231 * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors and COLOR_ON for unrestricted
1232 * color output. For that we check $SYSTEMD_COLORS first (which is the explicit way to
1233 * change the mode). If that didn't work we turn colors off unless we are on a TTY. And if we are on a TTY
1234 * we turn it off if $TERM is set to "dumb". There's one special tweak though: if we are PID 1 then we do not
1235 * check whether we are connected to a TTY, because we don't keep /dev/console open continuously due to fear
1236 * of SAK, and hence things are a bit weird. */
1239 if (cached_color_mode
< 0) {
1240 m
= parse_systemd_colors();
1242 cached_color_mode
= m
;
1243 else if (getenv("NO_COLOR"))
1244 /* We only check for the presence of the variable; value is ignored. */
1245 cached_color_mode
= COLOR_OFF
;
1247 else if (getpid_cached() == 1)
1248 /* PID1 outputs to the console without holding it open all the time.
1250 * Note that the Linux console can only display 16 colors. We still enable 256 color
1251 * mode even for PID1 output though (which typically goes to the Linux console),
1252 * since the Linux console is able to parse the 256 color sequences and automatically
1253 * map them to the closest color in the 16 color palette (since kernel 3.16). Doing
1254 * 256 colors is nice for people who invoke systemd in a container or via a serial
1255 * link or such, and use a true 256 color terminal to do so. */
1256 cached_color_mode
= getenv_terminal_is_dumb() ? COLOR_OFF
: COLOR_256
;
1258 cached_color_mode
= terminal_is_dumb() ? COLOR_OFF
: COLOR_256
;
1261 return cached_color_mode
;
1264 bool dev_console_colors_enabled(void) {
1265 _cleanup_free_
char *s
= NULL
;
1268 /* Returns true if we assume that color is supported on /dev/console.
1270 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1271 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1272 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1273 * colors_enabled() operates. */
1275 m
= parse_systemd_colors();
1279 if (getenv("NO_COLOR"))
1282 if (getenv_for_pid(1, "TERM", &s
) <= 0)
1283 (void) proc_cmdline_get_key("TERM", 0, &s
);
1285 return !streq_ptr(s
, "dumb");
1288 bool underline_enabled(void) {
1290 if (cached_underline_enabled
< 0) {
1292 /* The Linux console doesn't support underlining, turn it off, but only there. */
1294 if (colors_enabled())
1295 cached_underline_enabled
= !streq_ptr(getenv("TERM"), "linux");
1297 cached_underline_enabled
= false;
1300 return cached_underline_enabled
;
1303 int vt_default_utf8(void) {
1304 _cleanup_free_
char *b
= NULL
;
1307 /* Read the default VT UTF8 setting from the kernel */
1309 r
= read_one_line_file("/sys/module/vt/parameters/default_utf8", &b
);
1313 return parse_boolean(b
);
1316 int vt_reset_keyboard(int fd
) {
1319 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1320 kb
= vt_default_utf8() != 0 ? K_UNICODE
: K_XLATE
;
1322 if (ioctl(fd
, KDSKBMODE
, kb
) < 0)
1328 int vt_restore(int fd
) {
1329 static const struct vt_mode mode
= {
1335 return log_debug_errno(errno
, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
1337 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
1338 q
= log_debug_errno(errno
, "Failed to set VT in text mode, ignoring: %m");
1340 r
= vt_reset_keyboard(fd
);
1342 log_debug_errno(r
, "Failed to reset keyboard mode, ignoring: %m");
1347 if (ioctl(fd
, VT_SETMODE
, &mode
) < 0) {
1348 log_debug_errno(errno
, "Failed to set VT_AUTO mode, ignoring: %m");
1353 r
= fchmod_and_chown(fd
, TTY_MODE
, 0, GID_INVALID
);
1355 log_debug_errno(r
, "Failed to chmod()/chown() VT, ignoring: %m");
1363 int vt_release(int fd
, bool restore
) {
1366 /* This function releases the VT by acknowledging the VT-switch signal
1367 * sent by the kernel and optionally reset the VT in text and auto
1368 * VT-switching modes. */
1371 return log_debug_errno(errno
, "Asked to release the VT for an fd that does not refer to a terminal: %m");
1373 if (ioctl(fd
, VT_RELDISP
, 1) < 0)
1377 return vt_restore(fd
);
1382 void get_log_colors(int priority
, const char **on
, const char **off
, const char **highlight
) {
1383 /* Note that this will initialize output variables only when there's something to output.
1384 * The caller must pre-initialize to "" or NULL as appropriate. */
1386 if (priority
<= LOG_ERR
) {
1388 *on
= ansi_highlight_red();
1390 *off
= ansi_normal();
1392 *highlight
= ansi_highlight();
1394 } else if (priority
<= LOG_WARNING
) {
1396 *on
= ansi_highlight_yellow();
1398 *off
= ansi_normal();
1400 *highlight
= ansi_highlight();
1402 } else if (priority
<= LOG_NOTICE
) {
1404 *on
= ansi_highlight();
1406 *off
= ansi_normal();
1408 *highlight
= ansi_highlight_red();
1410 } else if (priority
>= LOG_DEBUG
) {
1414 *off
= ansi_normal();
1416 *highlight
= ansi_highlight_red();