1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 character */
90 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
91 struct termios new_termios
= old_termios
;
93 new_termios
.c_lflag
&= ~ICANON
;
94 new_termios
.c_cc
[VMIN
] = 1;
95 new_termios
.c_cc
[VTIME
] = 0;
97 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
100 if (t
!= USEC_INFINITY
) {
101 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0) {
102 (void) tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
107 r
= safe_fgetc(f
, &c
);
108 (void) tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
115 *need_nl
= c
!= '\n';
122 if (t
!= USEC_INFINITY
) {
123 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0)
127 /* If this is not a terminal, then read a full line instead */
129 r
= read_line(f
, 16, &line
); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
135 if (strlen(line
) != 1)
145 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
147 int ask_char(char *ret
, const char *replies
, const char *fmt
, ...) {
159 if (colors_enabled())
160 fputs(ANSI_HIGHLIGHT
, stdout
);
168 if (colors_enabled())
169 fputs(ANSI_NORMAL
, stdout
);
173 r
= read_one_char(stdin
, &c
, DEFAULT_ASK_REFRESH_USEC
, &need_nl
);
180 puts("Bad input, please try again.");
191 if (strchr(replies
, c
)) {
196 puts("Read unexpected character, please try again.");
200 int ask_string(char **ret
, const char *text
, ...) {
201 _cleanup_free_
char *line
= NULL
;
208 if (colors_enabled())
209 fputs(ANSI_HIGHLIGHT
, stdout
);
215 if (colors_enabled())
216 fputs(ANSI_NORMAL
, stdout
);
220 r
= read_line(stdin
, LONG_LINE_MAX
, &line
);
226 *ret
= TAKE_PTR(line
);
230 int reset_terminal_fd(int fd
, bool switch_to_text
) {
231 struct termios termios
;
234 /* Set terminal to some sane defaults */
238 /* We leave locked terminal attributes untouched, so that
239 * Plymouth may set whatever it wants to set, and we don't
240 * interfere with that. */
242 /* Disable exclusive mode, just in case */
243 (void) ioctl(fd
, TIOCNXCL
);
245 /* Switch to text mode */
247 (void) ioctl(fd
, KDSETMODE
, KD_TEXT
);
249 /* Set default keyboard mode */
250 (void) vt_reset_keyboard(fd
);
252 if (tcgetattr(fd
, &termios
) < 0) {
257 /* We only reset the stuff that matters to the software. How
258 * hardware is set up we don't touch assuming that somebody
259 * else will do that for us */
261 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
262 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
263 termios
.c_oflag
|= ONLCR
;
264 termios
.c_cflag
|= CREAD
;
265 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
267 termios
.c_cc
[VINTR
] = 03; /* ^C */
268 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
269 termios
.c_cc
[VERASE
] = 0177;
270 termios
.c_cc
[VKILL
] = 025; /* ^X */
271 termios
.c_cc
[VEOF
] = 04; /* ^D */
272 termios
.c_cc
[VSTART
] = 021; /* ^Q */
273 termios
.c_cc
[VSTOP
] = 023; /* ^S */
274 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
275 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
276 termios
.c_cc
[VWERASE
] = 027; /* ^W */
277 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
278 termios
.c_cc
[VEOL
] = 0;
279 termios
.c_cc
[VEOL2
] = 0;
281 termios
.c_cc
[VTIME
] = 0;
282 termios
.c_cc
[VMIN
] = 1;
284 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
288 /* Just in case, flush all crap out */
289 (void) tcflush(fd
, TCIOFLUSH
);
294 int reset_terminal(const char *name
) {
295 _cleanup_close_
int fd
= -1;
297 /* We open the terminal with O_NONBLOCK here, to ensure we
298 * don't block on carrier if this is a terminal with carrier
301 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
305 return reset_terminal_fd(fd
, true);
308 int open_terminal(const char *name
, int mode
) {
313 * If a TTY is in the process of being closed opening it might
314 * cause EIO. This is horribly awful, but unlikely to be
315 * changed in the kernel. Hence we work around this problem by
316 * retrying a couple of times.
318 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
325 fd
= open(name
, mode
, 0);
332 /* Max 1s in total */
336 usleep(50 * USEC_PER_MSEC
);
340 if (isatty(fd
) <= 0) {
348 int acquire_terminal(
350 AcquireTerminalFlags flags
,
353 _cleanup_close_
int notify
= -1, fd
= -1;
354 usec_t ts
= USEC_INFINITY
;
358 assert(IN_SET(flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
, ACQUIRE_TERMINAL_TRY
, ACQUIRE_TERMINAL_FORCE
, ACQUIRE_TERMINAL_WAIT
));
360 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
361 * acquire it, so that we don't lose any event.
363 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
364 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
365 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
366 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
367 * probably should not do anyway.) */
369 if ((flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_WAIT
) {
370 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= USEC_INFINITY
? IN_NONBLOCK
: 0));
374 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
378 if (timeout
!= USEC_INFINITY
)
379 ts
= now(CLOCK_MONOTONIC
);
383 struct sigaction sa_old
, sa_new
= {
384 .sa_handler
= SIG_IGN
,
385 .sa_flags
= SA_RESTART
,
389 r
= flush_fd(notify
);
394 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
395 * to figure out if we successfully became the controlling process of the tty */
396 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
400 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
401 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
403 /* First, try to get the tty */
404 r
= ioctl(fd
, TIOCSCTTY
,
405 (flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_FORCE
) < 0 ? -errno
: 0;
407 /* Reset signal handler to old value */
408 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
410 /* Success? Exit the loop now! */
414 /* Any failure besides -EPERM? Fail, regardless of the mode. */
418 if (flags
& ACQUIRE_TERMINAL_PERMISSIVE
) /* If we are in permissive mode, then EPERM is fine, turn this
419 * into a success. Note that EPERM is also returned if we
420 * already are the owner of the TTY. */
423 if (flags
!= ACQUIRE_TERMINAL_WAIT
) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
430 union inotify_event_buffer buffer
;
431 struct inotify_event
*e
;
434 if (timeout
!= USEC_INFINITY
) {
437 assert(ts
!= USEC_INFINITY
);
439 n
= now(CLOCK_MONOTONIC
);
440 if (ts
+ timeout
< n
)
443 r
= fd_wait_for_event(notify
, POLLIN
, ts
+ timeout
- n
);
450 l
= read(notify
, &buffer
, sizeof(buffer
));
452 if (IN_SET(errno
, EINTR
, EAGAIN
))
458 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
459 if (e
->mask
& IN_Q_OVERFLOW
) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
462 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) /* Safety checks */
469 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
470 * we do this after sleeping, so that we don't enter an endless loop. */
477 int release_terminal(void) {
478 static const struct sigaction sa_new
= {
479 .sa_handler
= SIG_IGN
,
480 .sa_flags
= SA_RESTART
,
483 _cleanup_close_
int fd
= -1;
484 struct sigaction sa_old
;
487 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
491 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
492 * by our own TIOCNOTTY */
493 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
495 r
= ioctl(fd
, TIOCNOTTY
) < 0 ? -errno
: 0;
497 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
502 int terminal_vhangup_fd(int fd
) {
505 if (ioctl(fd
, TIOCVHANGUP
) < 0)
511 int terminal_vhangup(const char *name
) {
512 _cleanup_close_
int fd
;
514 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
518 return terminal_vhangup_fd(fd
);
521 int vt_disallocate(const char *name
) {
525 /* Deallocate the VT if possible. If not possible
526 * (i.e. because it is the active one), at least clear it
527 * entirely (including the scrollback buffer). */
529 e
= path_startswith(name
, "/dev/");
533 if (tty_is_vc(name
)) {
534 _cleanup_close_
int fd
= -1;
538 n
= startswith(e
, "tty");
542 r
= safe_atou(n
, &u
);
549 /* Try to deallocate */
550 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
554 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
561 /* So this is not a VT (in which case we cannot deallocate it),
562 * or we failed to deallocate. Let's at least clear the screen. */
564 _cleanup_close_
int fd2
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
568 (void) loop_write(fd2
,
569 "\033[r" /* clear scrolling region */
570 "\033[H" /* move home */
571 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
576 int make_console_stdio(void) {
579 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
580 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
581 * is specified on the kernel command line. */
583 fd
= acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE
|ACQUIRE_TERMINAL_PERMISSIVE
, USEC_INFINITY
);
585 log_warning_errno(fd
, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
587 r
= make_null_stdio();
589 return log_error_errno(r
, "Failed to make /dev/null stdin/stdout/stderr: %m");
592 r
= reset_terminal_fd(fd
, true);
594 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
596 r
= rearrange_stdio(fd
, fd
, fd
); /* This invalidates 'fd' both on success and on failure. */
598 return log_error_errno(r
, "Failed to make terminal stdin/stdout/stderr: %m");
601 reset_terminal_feature_caches();
605 bool tty_is_vc(const char *tty
) {
608 return vtnr_from_tty(tty
) >= 0;
611 bool tty_is_console(const char *tty
) {
614 return streq(skip_dev_prefix(tty
), "console");
617 int vtnr_from_tty(const char *tty
) {
622 tty
= skip_dev_prefix(tty
);
624 if (!startswith(tty
, "tty") )
627 if (tty
[3] < '0' || tty
[3] > '9')
630 r
= safe_atoi(tty
+3, &i
);
640 int resolve_dev_console(char **ret
) {
641 _cleanup_free_
char *active
= NULL
;
647 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
648 * sign for container setups) */
650 if (path_is_read_only_fs("/sys") > 0)
653 r
= read_one_line_file("/sys/class/tty/console/active", &active
);
657 /* If multiple log outputs are configured the last one is what /dev/console points to */
658 tty
= strrchr(active
, ' ');
664 if (streq(tty
, "tty0")) {
665 active
= mfree(active
);
667 /* Get the active VC (e.g. tty1) */
668 r
= read_one_line_file("/sys/class/tty/tty0/active", &active
);
676 *ret
= TAKE_PTR(active
);
690 int get_kernel_consoles(char ***ret
) {
691 _cleanup_strv_free_
char **l
= NULL
;
692 _cleanup_free_
char *line
= NULL
;
698 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
699 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
700 if (path_is_read_only_fs("/sys") > 0)
703 r
= read_one_line_file("/sys/class/tty/console/active", &line
);
709 _cleanup_free_
char *tty
= NULL
, *path
= NULL
;
711 r
= extract_first_word(&p
, &tty
, NULL
, 0);
717 if (streq(tty
, "tty0")) {
719 r
= read_one_line_file("/sys/class/tty/tty0/active", &tty
);
724 path
= path_join("/dev", tty
);
728 if (access(path
, F_OK
) < 0) {
729 log_debug_errno(errno
, "Console device %s is not accessible, skipping: %m", path
);
733 r
= strv_consume(&l
, TAKE_PTR(path
));
738 if (strv_isempty(l
)) {
739 log_debug("No devices found for system console");
748 r
= strv_extend(&l
, "/dev/console");
757 bool tty_is_vc_resolve(const char *tty
) {
758 _cleanup_free_
char *resolved
= NULL
;
762 tty
= skip_dev_prefix(tty
);
764 if (streq(tty
, "console")) {
765 if (resolve_dev_console(&resolved
) < 0)
771 return tty_is_vc(tty
);
774 const char *default_term_for_tty(const char *tty
) {
775 return tty
&& tty_is_vc_resolve(tty
) ? "linux" : "vt220";
778 int fd_columns(int fd
) {
779 struct winsize ws
= {};
781 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
790 unsigned columns(void) {
794 if (cached_columns
> 0)
795 return cached_columns
;
798 e
= getenv("COLUMNS");
800 (void) safe_atoi(e
, &c
);
802 if (c
<= 0 || c
> USHRT_MAX
) {
803 c
= fd_columns(STDOUT_FILENO
);
809 return cached_columns
;
812 int fd_lines(int fd
) {
813 struct winsize ws
= {};
815 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
824 unsigned lines(void) {
828 if (cached_lines
> 0)
834 (void) safe_atoi(e
, &l
);
836 if (l
<= 0 || l
> USHRT_MAX
) {
837 l
= fd_lines(STDOUT_FILENO
);
846 /* intended to be used as a SIGWINCH sighandler */
847 void columns_lines_cache_reset(int signum
) {
852 void reset_terminal_feature_caches(void) {
856 cached_colors_enabled
= -1;
857 cached_underline_enabled
= -1;
863 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
864 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
865 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
866 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
867 * terminal functionality when outputting stuff, even if the input is piped to us. */
869 if (cached_on_tty
< 0)
871 isatty(STDOUT_FILENO
) > 0 &&
872 isatty(STDERR_FILENO
) > 0;
874 return cached_on_tty
;
877 int getttyname_malloc(int fd
, char **ret
) {
878 char path
[PATH_MAX
], *c
; /* PATH_MAX is counted *with* the trailing NUL byte */
884 r
= ttyname_r(fd
, path
, sizeof path
); /* positive error */
887 return -ENAMETOOLONG
;
891 c
= strdup(skip_dev_prefix(path
));
899 int getttyname_harder(int fd
, char **ret
) {
900 _cleanup_free_
char *s
= NULL
;
903 r
= getttyname_malloc(fd
, &s
);
908 return get_ctty(0, NULL
, ret
);
914 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
916 _cleanup_free_
char *line
= NULL
;
922 p
= procfs_file_alloca(pid
, "stat");
923 r
= read_one_line_file(p
, &line
);
927 p
= strrchr(line
, ')');
942 if (major(ttynr
) == 0 && minor(ttynr
) == 0)
951 int get_ctty(pid_t pid
, dev_t
*ret_devnr
, char **ret
) {
952 _cleanup_free_
char *fn
= NULL
, *b
= NULL
;
956 r
= get_ctty_devnr(pid
, &devnr
);
960 r
= device_path_make_canonical(S_IFCHR
, devnr
, &fn
);
962 if (r
!= -ENOENT
) /* No symlink for this in /dev/char/? */
965 if (major(devnr
) == 136) {
966 /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the
967 * Linux device model. This means we have no nice way to match them up against their actual
968 * device node. Let's hence do the check by the fixed, assigned major number. Normally we try
969 * to avoid such fixed major/minor matches, but there appears to nother nice way to handle
972 if (asprintf(&b
, "pts/%u", minor(devnr
)) < 0)
975 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
976 * something vaguely useful. */
978 r
= device_path_make_major_minor(S_IFCHR
, devnr
, &fn
);
987 w
= path_startswith(fn
, "/dev/");
1005 int ptsname_malloc(int fd
, char **ret
) {
1018 if (ptsname_r(fd
, c
, l
) == 0) {
1022 if (errno
!= ERANGE
) {
1029 if (l
> SIZE_MAX
/ 2)
1036 int openpt_allocate(int flags
, char **ret_slave
) {
1037 _cleanup_close_
int fd
= -1;
1038 _cleanup_free_
char *p
= NULL
;
1041 fd
= posix_openpt(flags
|O_NOCTTY
|O_CLOEXEC
);
1046 r
= ptsname_malloc(fd
, &p
);
1050 if (!path_startswith(p
, "/dev/pts/"))
1054 if (unlockpt(fd
) < 0)
1058 *ret_slave
= TAKE_PTR(p
);
1063 static int ptsname_namespace(int pty
, char **ret
) {
1066 /* Like ptsname(), but doesn't assume that the path is
1067 * accessible in the local namespace. */
1069 r
= ioctl(pty
, TIOCGPTN
, &no
);
1076 if (asprintf(ret
, "/dev/pts/%i", no
) < 0)
1082 int openpt_allocate_in_namespace(pid_t pid
, int flags
, char **ret_slave
) {
1083 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1, fd
= -1;
1084 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1090 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1094 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1097 r
= namespace_fork("(sd-openptns)", "(sd-openpt)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1098 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1102 pair
[0] = safe_close(pair
[0]);
1104 fd
= openpt_allocate(flags
, NULL
);
1106 _exit(EXIT_FAILURE
);
1108 if (send_one_fd(pair
[1], fd
, 0) < 0)
1109 _exit(EXIT_FAILURE
);
1111 _exit(EXIT_SUCCESS
);
1114 pair
[1] = safe_close(pair
[1]);
1116 r
= wait_for_terminate_and_check("(sd-openptns)", child
, 0);
1119 if (r
!= EXIT_SUCCESS
)
1122 fd
= receive_one_fd(pair
[0], 0);
1127 r
= ptsname_namespace(fd
, ret_slave
);
1135 int open_terminal_in_namespace(pid_t pid
, const char *name
, int mode
) {
1136 _cleanup_close_
int pidnsfd
= -1, mntnsfd
= -1, usernsfd
= -1, rootfd
= -1;
1137 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1141 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1145 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1148 r
= namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1149 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1155 pair
[0] = safe_close(pair
[0]);
1157 master
= open_terminal(name
, mode
|O_NOCTTY
|O_CLOEXEC
);
1159 _exit(EXIT_FAILURE
);
1161 if (send_one_fd(pair
[1], master
, 0) < 0)
1162 _exit(EXIT_FAILURE
);
1164 _exit(EXIT_SUCCESS
);
1167 pair
[1] = safe_close(pair
[1]);
1169 r
= wait_for_terminate_and_check("(sd-terminalns)", child
, 0);
1172 if (r
!= EXIT_SUCCESS
)
1175 return receive_one_fd(pair
[0], 0);
1178 static bool getenv_terminal_is_dumb(void) {
1185 return streq(e
, "dumb");
1188 bool terminal_is_dumb(void) {
1192 return getenv_terminal_is_dumb();
1195 bool colors_enabled(void) {
1197 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1198 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1199 * 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
1200 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1201 * continuously due to fear of SAK, and hence things are a bit weird. */
1203 if (cached_colors_enabled
< 0) {
1206 val
= getenv_bool("SYSTEMD_COLORS");
1208 cached_colors_enabled
= val
;
1210 else if (getenv("NO_COLOR"))
1211 /* We only check for the presence of the variable; value is ignored. */
1212 cached_colors_enabled
= false;
1214 else if (getpid_cached() == 1)
1215 /* PID1 outputs to the console without holding it open all the time */
1216 cached_colors_enabled
= !getenv_terminal_is_dumb();
1218 cached_colors_enabled
= !terminal_is_dumb();
1221 return cached_colors_enabled
;
1224 bool dev_console_colors_enabled(void) {
1225 _cleanup_free_
char *s
= NULL
;
1228 /* Returns true if we assume that color is supported on /dev/console.
1230 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1231 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1232 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1233 * colors_enabled() operates. */
1235 b
= getenv_bool("SYSTEMD_COLORS");
1239 if (getenv("NO_COLOR"))
1242 if (getenv_for_pid(1, "TERM", &s
) <= 0)
1243 (void) proc_cmdline_get_key("TERM", 0, &s
);
1245 return !streq_ptr(s
, "dumb");
1248 bool underline_enabled(void) {
1250 if (cached_underline_enabled
< 0) {
1252 /* The Linux console doesn't support underlining, turn it off, but only there. */
1254 if (colors_enabled())
1255 cached_underline_enabled
= !streq_ptr(getenv("TERM"), "linux");
1257 cached_underline_enabled
= false;
1260 return cached_underline_enabled
;
1263 int vt_default_utf8(void) {
1264 _cleanup_free_
char *b
= NULL
;
1267 /* Read the default VT UTF8 setting from the kernel */
1269 r
= read_one_line_file("/sys/module/vt/parameters/default_utf8", &b
);
1273 return parse_boolean(b
);
1276 int vt_reset_keyboard(int fd
) {
1279 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1280 kb
= vt_default_utf8() != 0 ? K_UNICODE
: K_XLATE
;
1282 if (ioctl(fd
, KDSKBMODE
, kb
) < 0)
1288 int vt_restore(int fd
) {
1289 static const struct vt_mode mode
= {
1294 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
1295 q
= log_debug_errno(errno
, "Failed to set VT in text mode, ignoring: %m");
1297 r
= vt_reset_keyboard(fd
);
1299 log_debug_errno(r
, "Failed to reset keyboard mode, ignoring: %m");
1304 if (ioctl(fd
, VT_SETMODE
, &mode
) < 0) {
1305 log_debug_errno(errno
, "Failed to set VT_AUTO mode, ignoring: %m");
1310 r
= fchmod_and_chown(fd
, TTY_MODE
, 0, (gid_t
) -1);
1312 log_debug_errno(r
, "Failed to chmod()/chown() VT, ignoring: %m");
1320 int vt_release(int fd
, bool restore
) {
1323 /* This function releases the VT by acknowledging the VT-switch signal
1324 * sent by the kernel and optionally reset the VT in text and auto
1325 * VT-switching modes. */
1327 if (ioctl(fd
, VT_RELDISP
, 1) < 0)
1331 return vt_restore(fd
);
1336 void get_log_colors(int priority
, const char **on
, const char **off
, const char **highlight
) {
1337 /* Note that this will initialize output variables only when there's something to output.
1338 * The caller must pre-initalize to "" or NULL as appropriate. */
1340 if (priority
<= LOG_ERR
) {
1342 *on
= ANSI_HIGHLIGHT_RED
;
1346 *highlight
= ANSI_HIGHLIGHT
;
1348 } else if (priority
<= LOG_WARNING
) {
1350 *on
= ANSI_HIGHLIGHT_YELLOW
;
1354 *highlight
= ANSI_HIGHLIGHT
;
1356 } else if (priority
<= LOG_NOTICE
) {
1358 *on
= ANSI_HIGHLIGHT
;
1362 *highlight
= ANSI_HIGHLIGHT_RED
;
1364 } else if (priority
>= LOG_DEBUG
) {
1370 *highlight
= ANSI_HIGHLIGHT_RED
;