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"
24 #include "constants.h"
25 #include "devnum-util.h"
30 #include "inotify-util.h"
34 #include "namespace-util.h"
35 #include "parse-util.h"
36 #include "path-util.h"
37 #include "proc-cmdline.h"
38 #include "process-util.h"
39 #include "socket-util.h"
40 #include "stat-util.h"
41 #include "stdio-util.h"
42 #include "string-util.h"
44 #include "terminal-util.h"
45 #include "time-util.h"
46 #include "user-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_on_dev_null
= -1;
53 static volatile int cached_color_mode
= _COLOR_INVALID
;
54 static volatile int cached_underline_enabled
= -1;
57 _cleanup_close_
int fd
= -EBADF
;
59 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
60 * if that's configured. */
62 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
68 TIOCL_GETKMSGREDIRECT
,
72 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
75 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
78 return RET_NERRNO(ioctl(fd
, VT_ACTIVATE
, vt
));
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 fputs(ansi_highlight(), stdout
);
175 fputs(ansi_normal(), stdout
);
179 r
= read_one_char(stdin
, &c
, DEFAULT_ASK_REFRESH_USEC
, &need_nl
);
186 puts("Bad input, please try again.");
197 if (strchr(replies
, c
)) {
202 puts("Read unexpected character, please try again.");
206 int ask_string(char **ret
, const char *text
, ...) {
207 _cleanup_free_
char *line
= NULL
;
214 fputs(ansi_highlight(), stdout
);
220 fputs(ansi_normal(), stdout
);
224 r
= read_line(stdin
, LONG_LINE_MAX
, &line
);
230 *ret
= TAKE_PTR(line
);
234 int reset_terminal_fd(int fd
, bool switch_to_text
) {
235 struct termios termios
;
238 /* Set terminal to some sane defaults */
243 return log_debug_errno(errno
, "Asked to reset a terminal that actually isn't a terminal: %m");
245 /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
246 * and we don't interfere with that. */
248 /* Disable exclusive mode, just in case */
249 if (ioctl(fd
, TIOCNXCL
) < 0)
250 log_debug_errno(errno
, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
252 /* Switch to text mode */
254 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
255 log_debug_errno(errno
, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
258 /* Set default keyboard mode */
259 r
= vt_reset_keyboard(fd
);
261 log_debug_errno(r
, "Failed to reset VT keyboard, ignoring: %m");
263 if (tcgetattr(fd
, &termios
) < 0) {
264 r
= log_debug_errno(errno
, "Failed to get terminal parameters: %m");
268 /* We only reset the stuff that matters to the software. How
269 * hardware is set up we don't touch assuming that somebody
270 * else will do that for us */
272 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
273 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
274 termios
.c_oflag
|= ONLCR
| OPOST
;
275 termios
.c_cflag
|= CREAD
;
276 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOKE
;
278 termios
.c_cc
[VINTR
] = 03; /* ^C */
279 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
280 termios
.c_cc
[VERASE
] = 0177;
281 termios
.c_cc
[VKILL
] = 025; /* ^X */
282 termios
.c_cc
[VEOF
] = 04; /* ^D */
283 termios
.c_cc
[VSTART
] = 021; /* ^Q */
284 termios
.c_cc
[VSTOP
] = 023; /* ^S */
285 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
286 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
287 termios
.c_cc
[VWERASE
] = 027; /* ^W */
288 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
289 termios
.c_cc
[VEOL
] = 0;
290 termios
.c_cc
[VEOL2
] = 0;
292 termios
.c_cc
[VTIME
] = 0;
293 termios
.c_cc
[VMIN
] = 1;
295 r
= RET_NERRNO(tcsetattr(fd
, TCSANOW
, &termios
));
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
= -EBADF
;
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
) {
319 _cleanup_close_
int fd
= -EBADF
;
323 * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
324 * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
327 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
334 fd
= open(name
, mode
, 0);
341 /* Max 1s in total */
345 (void) usleep_safe(50 * USEC_PER_MSEC
);
350 return negative_errno();
355 int acquire_terminal(
357 AcquireTerminalFlags flags
,
360 _cleanup_close_
int notify
= -EBADF
, fd
= -EBADF
;
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
= RET_NERRNO(ioctl(fd
, TIOCSCTTY
, (flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_FORCE
));
413 /* Reset signal handler to old value */
414 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
416 /* Success? Exit the loop now! */
420 /* Any failure besides -EPERM? Fail, regardless of the mode. */
424 if (flags
& ACQUIRE_TERMINAL_PERMISSIVE
) /* If we are in permissive mode, then EPERM is fine, turn this
425 * into a success. Note that EPERM is also returned if we
426 * already are the owner of the TTY. */
429 if (flags
!= ACQUIRE_TERMINAL_WAIT
) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
436 union inotify_event_buffer buffer
;
439 if (timeout
!= USEC_INFINITY
) {
442 assert(ts
!= USEC_INFINITY
);
444 n
= usec_sub_unsigned(now(CLOCK_MONOTONIC
), ts
);
448 r
= fd_wait_for_event(notify
, POLLIN
, usec_sub_unsigned(timeout
, n
));
455 l
= read(notify
, &buffer
, sizeof(buffer
));
457 if (ERRNO_IS_TRANSIENT(errno
))
463 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
464 if (e
->mask
& IN_Q_OVERFLOW
) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
467 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) /* Safety checks */
474 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
475 * we do this after sleeping, so that we don't enter an endless loop. */
482 int release_terminal(void) {
483 static const struct sigaction sa_new
= {
484 .sa_handler
= SIG_IGN
,
485 .sa_flags
= SA_RESTART
,
488 _cleanup_close_
int fd
= -EBADF
;
489 struct sigaction sa_old
;
492 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
496 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
497 * by our own TIOCNOTTY */
498 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
500 r
= RET_NERRNO(ioctl(fd
, TIOCNOTTY
));
502 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
507 int terminal_vhangup_fd(int fd
) {
509 return RET_NERRNO(ioctl(fd
, TIOCVHANGUP
));
512 int terminal_vhangup(const char *name
) {
513 _cleanup_close_
int fd
= -EBADF
;
515 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
519 return terminal_vhangup_fd(fd
);
522 int vt_disallocate(const char *name
) {
526 /* Deallocate the VT if possible. If not possible
527 * (i.e. because it is the active one), at least clear it
528 * entirely (including the scrollback buffer). */
530 e
= path_startswith(name
, "/dev/");
534 if (tty_is_vc(name
)) {
535 _cleanup_close_
int fd
= -EBADF
;
539 n
= startswith(e
, "tty");
543 r
= safe_atou(n
, &u
);
550 /* Try to deallocate */
551 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
555 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
562 /* So this is not a VT (in which case we cannot deallocate it),
563 * or we failed to deallocate. Let's at least clear the screen. */
565 _cleanup_close_
int fd2
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
569 (void) loop_write(fd2
,
570 "\033[r" /* clear scrolling region */
571 "\033[H" /* move home */
572 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
577 int make_console_stdio(void) {
580 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
581 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
582 * is specified on the kernel command line. */
584 fd
= acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE
|ACQUIRE_TERMINAL_PERMISSIVE
, USEC_INFINITY
);
586 log_warning_errno(fd
, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
588 r
= make_null_stdio();
590 return log_error_errno(r
, "Failed to make /dev/null stdin/stdout/stderr: %m");
595 r
= reset_terminal_fd(fd
, /* switch_to_text= */ true);
597 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
599 r
= proc_cmdline_tty_size("/dev/console", &rows
, &cols
);
601 log_warning_errno(r
, "Failed to get terminal size, ignoring: %m");
603 r
= terminal_set_size_fd(fd
, NULL
, rows
, cols
);
605 log_warning_errno(r
, "Failed to set terminal size, ignoring: %m");
608 r
= rearrange_stdio(fd
, fd
, fd
); /* This invalidates 'fd' both on success and on failure. */
610 return log_error_errno(r
, "Failed to make terminal stdin/stdout/stderr: %m");
613 reset_terminal_feature_caches();
617 bool tty_is_vc(const char *tty
) {
620 return vtnr_from_tty(tty
) >= 0;
623 bool tty_is_console(const char *tty
) {
626 return streq(skip_dev_prefix(tty
), "console");
629 int vtnr_from_tty(const char *tty
) {
634 tty
= skip_dev_prefix(tty
);
636 if (!startswith(tty
, "tty") )
639 if (!ascii_isdigit(tty
[3]))
642 r
= safe_atoi(tty
+3, &i
);
652 int resolve_dev_console(char **ret
) {
653 _cleanup_free_
char *active
= NULL
;
659 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
660 * sign for container setups) */
662 if (path_is_read_only_fs("/sys") > 0)
665 r
= read_one_line_file("/sys/class/tty/console/active", &active
);
669 /* If multiple log outputs are configured the last one is what /dev/console points to */
670 tty
= strrchr(active
, ' ');
676 if (streq(tty
, "tty0")) {
677 active
= mfree(active
);
679 /* Get the active VC (e.g. tty1) */
680 r
= read_one_line_file("/sys/class/tty/tty0/active", &active
);
688 *ret
= TAKE_PTR(active
);
702 int get_kernel_consoles(char ***ret
) {
703 _cleanup_strv_free_
char **l
= NULL
;
704 _cleanup_free_
char *line
= NULL
;
710 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
711 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
712 if (path_is_read_only_fs("/sys") > 0)
715 r
= read_one_line_file("/sys/class/tty/console/active", &line
);
721 _cleanup_free_
char *tty
= NULL
, *path
= NULL
;
723 r
= extract_first_word(&p
, &tty
, NULL
, 0);
729 if (streq(tty
, "tty0")) {
731 r
= read_one_line_file("/sys/class/tty/tty0/active", &tty
);
736 path
= path_join("/dev", tty
);
740 if (access(path
, F_OK
) < 0) {
741 log_debug_errno(errno
, "Console device %s is not accessible, skipping: %m", path
);
745 r
= strv_consume(&l
, TAKE_PTR(path
));
750 if (strv_isempty(l
)) {
751 log_debug("No devices found for system console");
760 r
= strv_extend(&l
, "/dev/console");
769 bool tty_is_vc_resolve(const char *tty
) {
770 _cleanup_free_
char *resolved
= NULL
;
774 tty
= skip_dev_prefix(tty
);
776 if (streq(tty
, "console")) {
777 if (resolve_dev_console(&resolved
) < 0)
783 return tty_is_vc(tty
);
786 const char *default_term_for_tty(const char *tty
) {
787 return tty
&& tty_is_vc_resolve(tty
) ? "linux" : "vt220";
790 int fd_columns(int fd
) {
791 struct winsize ws
= {};
796 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
805 unsigned columns(void) {
809 if (cached_columns
> 0)
810 return cached_columns
;
813 e
= getenv("COLUMNS");
815 (void) safe_atoi(e
, &c
);
817 if (c
<= 0 || c
> USHRT_MAX
) {
818 c
= fd_columns(STDOUT_FILENO
);
824 return cached_columns
;
827 int fd_lines(int fd
) {
828 struct winsize ws
= {};
833 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
842 unsigned lines(void) {
846 if (cached_lines
> 0)
852 (void) safe_atoi(e
, &l
);
854 if (l
<= 0 || l
> USHRT_MAX
) {
855 l
= fd_lines(STDOUT_FILENO
);
864 int terminal_set_size_fd(int fd
, const char *ident
, unsigned rows
, unsigned cols
) {
867 if (rows
== UINT_MAX
&& cols
== UINT_MAX
)
870 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
871 return log_debug_errno(errno
,
872 "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
875 if (rows
== UINT_MAX
)
877 else if (rows
> USHRT_MAX
)
880 if (cols
== UINT_MAX
)
882 else if (cols
> USHRT_MAX
)
885 if (rows
== ws
.ws_row
&& cols
== ws
.ws_col
)
891 if (ioctl(fd
, TIOCSWINSZ
, &ws
) < 0)
892 return log_debug_errno(errno
, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident
?: "TTY");
897 int proc_cmdline_tty_size(const char *tty
, unsigned *ret_rows
, unsigned *ret_cols
) {
898 _cleanup_free_
char *rowskey
= NULL
, *rowsvalue
= NULL
, *colskey
= NULL
, *colsvalue
= NULL
;
899 unsigned rows
= UINT_MAX
, cols
= UINT_MAX
;
904 if (!ret_rows
&& !ret_cols
)
907 tty
= skip_dev_prefix(tty
);
908 if (!in_charset(tty
, ALPHANUMERICAL
))
909 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "%s contains non-alphanumeric characters", tty
);
911 rowskey
= strjoin("systemd.tty.rows.", tty
);
915 colskey
= strjoin("systemd.tty.columns.", tty
);
919 r
= proc_cmdline_get_key_many(/* flags = */ 0,
921 colskey
, &colsvalue
);
923 return log_debug_errno(r
, "Failed to read TTY size of %s from kernel cmdline: %m", tty
);
926 r
= safe_atou(rowsvalue
, &rows
);
928 return log_debug_errno(r
, "Failed to parse %s=%s: %m", rowskey
, rowsvalue
);
932 r
= safe_atou(colsvalue
, &cols
);
934 return log_debug_errno(r
, "Failed to parse %s=%s: %m", colskey
, colsvalue
);
945 /* intended to be used as a SIGWINCH sighandler */
946 void columns_lines_cache_reset(int signum
) {
951 void reset_terminal_feature_caches(void) {
955 cached_color_mode
= _COLOR_INVALID
;
956 cached_underline_enabled
= -1;
958 cached_on_dev_null
= -1;
963 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
964 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
965 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
966 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
967 * terminal functionality when outputting stuff, even if the input is piped to us. */
969 if (cached_on_tty
< 0)
971 isatty(STDOUT_FILENO
) > 0 &&
972 isatty(STDERR_FILENO
) > 0;
974 return cached_on_tty
;
977 int getttyname_malloc(int fd
, char **ret
) {
978 char path
[PATH_MAX
], *c
; /* PATH_MAX is counted *with* the trailing NUL byte */
984 r
= ttyname_r(fd
, path
, sizeof path
); /* positive error */
987 return -ENAMETOOLONG
;
991 c
= strdup(skip_dev_prefix(path
));
999 int getttyname_harder(int fd
, char **ret
) {
1000 _cleanup_free_
char *s
= NULL
;
1003 r
= getttyname_malloc(fd
, &s
);
1007 if (streq(s
, "tty"))
1008 return get_ctty(0, NULL
, ret
);
1014 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
1016 _cleanup_free_
char *line
= NULL
;
1018 unsigned long ttynr
;
1022 p
= procfs_file_alloca(pid
, "stat");
1023 r
= read_one_line_file(p
, &line
);
1027 p
= strrchr(line
, ')');
1037 "%*d " /* session */
1042 if (devnum_is_zero(ttynr
))
1051 int get_ctty(pid_t pid
, dev_t
*ret_devnr
, char **ret
) {
1052 char pty
[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t
) + 1];
1053 _cleanup_free_
char *buf
= NULL
;
1054 const char *fn
= NULL
, *w
;
1058 r
= get_ctty_devnr(pid
, &devnr
);
1062 r
= device_path_make_canonical(S_IFCHR
, devnr
, &buf
);
1066 if (r
!= -ENOENT
) /* No symlink for this in /dev/char/? */
1069 /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
1070 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
1071 * assume this is a PTY for a moment, and check if the device node this would then map to in
1072 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
1073 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
1074 * the minor number of the pty. */
1075 xsprintf(pty
, "/dev/pts/%u", minor(devnr
));
1077 if (stat(pty
, &st
) < 0) {
1078 if (errno
!= ENOENT
)
1081 } else if (S_ISCHR(st
.st_mode
) && devnr
== st
.st_rdev
) /* Bingo! */
1085 /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1086 * symlink in /dev/char/. Let's return something vaguely useful. */
1087 r
= device_path_make_major_minor(S_IFCHR
, devnr
, &buf
);
1096 w
= path_startswith(fn
, "/dev/");
1101 _cleanup_free_
char *b
= NULL
;
1116 int ptsname_malloc(int fd
, char **ret
) {
1129 if (ptsname_r(fd
, c
, l
) == 0) {
1133 if (errno
!= ERANGE
) {
1140 if (l
> SIZE_MAX
/ 2)
1147 int openpt_allocate(int flags
, char **ret_slave
) {
1148 _cleanup_close_
int fd
= -EBADF
;
1149 _cleanup_free_
char *p
= NULL
;
1152 fd
= posix_openpt(flags
|O_NOCTTY
|O_CLOEXEC
);
1157 r
= ptsname_malloc(fd
, &p
);
1161 if (!path_startswith(p
, "/dev/pts/"))
1165 if (unlockpt(fd
) < 0)
1169 *ret_slave
= TAKE_PTR(p
);
1174 static int ptsname_namespace(int pty
, char **ret
) {
1177 /* Like ptsname(), but doesn't assume that the path is
1178 * accessible in the local namespace. */
1180 r
= ioctl(pty
, TIOCGPTN
, &no
);
1187 if (asprintf(ret
, "/dev/pts/%i", no
) < 0)
1193 int openpt_allocate_in_namespace(pid_t pid
, int flags
, char **ret_slave
) {
1194 _cleanup_close_
int pidnsfd
= -EBADF
, mntnsfd
= -EBADF
, usernsfd
= -EBADF
, rootfd
= -EBADF
, fd
= -EBADF
;
1195 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
1201 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1205 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1208 r
= namespace_fork("(sd-openptns)", "(sd-openpt)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGKILL
,
1209 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1213 pair
[0] = safe_close(pair
[0]);
1215 fd
= openpt_allocate(flags
, NULL
);
1217 _exit(EXIT_FAILURE
);
1219 if (send_one_fd(pair
[1], fd
, 0) < 0)
1220 _exit(EXIT_FAILURE
);
1222 _exit(EXIT_SUCCESS
);
1225 pair
[1] = safe_close(pair
[1]);
1227 r
= wait_for_terminate_and_check("(sd-openptns)", child
, 0);
1230 if (r
!= EXIT_SUCCESS
)
1233 fd
= receive_one_fd(pair
[0], 0);
1238 r
= ptsname_namespace(fd
, ret_slave
);
1246 int open_terminal_in_namespace(pid_t pid
, const char *name
, int mode
) {
1247 _cleanup_close_
int pidnsfd
= -EBADF
, mntnsfd
= -EBADF
, usernsfd
= -EBADF
, rootfd
= -EBADF
;
1248 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
1252 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1256 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1259 r
= namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGKILL
,
1260 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1266 pair
[0] = safe_close(pair
[0]);
1268 master
= open_terminal(name
, mode
|O_NOCTTY
|O_CLOEXEC
);
1270 _exit(EXIT_FAILURE
);
1272 if (send_one_fd(pair
[1], master
, 0) < 0)
1273 _exit(EXIT_FAILURE
);
1275 _exit(EXIT_SUCCESS
);
1278 pair
[1] = safe_close(pair
[1]);
1280 r
= wait_for_terminate_and_check("(sd-terminalns)", child
, 0);
1283 if (r
!= EXIT_SUCCESS
)
1286 return receive_one_fd(pair
[0], 0);
1289 static bool on_dev_null(void) {
1290 struct stat dst
, ost
, est
;
1292 if (cached_on_dev_null
>= 0)
1293 return cached_on_dev_null
;
1295 if (stat("/dev/null", &dst
) < 0 || fstat(STDOUT_FILENO
, &ost
) < 0 || fstat(STDERR_FILENO
, &est
) < 0)
1296 cached_on_dev_null
= false;
1298 cached_on_dev_null
= stat_inode_same(&dst
, &ost
) && stat_inode_same(&dst
, &est
);
1300 return cached_on_dev_null
;
1303 static bool getenv_terminal_is_dumb(void) {
1310 return streq(e
, "dumb");
1313 bool terminal_is_dumb(void) {
1314 if (!on_tty() && !on_dev_null())
1317 return getenv_terminal_is_dumb();
1320 static ColorMode
parse_systemd_colors(void) {
1324 e
= getenv("SYSTEMD_COLORS");
1326 return _COLOR_INVALID
;
1329 if (streq(e
, "256"))
1331 r
= parse_boolean(e
);
1333 return r
> 0 ? COLOR_ON
: COLOR_OFF
;
1334 return _COLOR_INVALID
;
1337 ColorMode
get_color_mode(void) {
1339 /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1340 * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors and COLOR_ON for unrestricted
1341 * color output. For that we check $SYSTEMD_COLORS first (which is the explicit way to
1342 * 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
1343 * 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
1344 * check whether we are connected to a TTY, because we don't keep /dev/console open continuously due to fear
1345 * of SAK, and hence things are a bit weird. */
1348 if (cached_color_mode
< 0) {
1349 m
= parse_systemd_colors();
1351 cached_color_mode
= m
;
1352 else if (getenv("NO_COLOR"))
1353 /* We only check for the presence of the variable; value is ignored. */
1354 cached_color_mode
= COLOR_OFF
;
1356 else if (getpid_cached() == 1) {
1357 /* PID1 outputs to the console without holding it open all the time.
1359 * Note that the Linux console can only display 16 colors. We still enable 256 color
1360 * mode even for PID1 output though (which typically goes to the Linux console),
1361 * since the Linux console is able to parse the 256 color sequences and automatically
1362 * map them to the closest color in the 16 color palette (since kernel 3.16). Doing
1363 * 256 colors is nice for people who invoke systemd in a container or via a serial
1364 * link or such, and use a true 256 color terminal to do so. */
1365 if (getenv_terminal_is_dumb())
1366 cached_color_mode
= COLOR_OFF
;
1368 if (terminal_is_dumb())
1369 cached_color_mode
= COLOR_OFF
;
1372 if (cached_color_mode
< 0) {
1373 /* We failed to figure out any reason to *disable* colors.
1374 * Let's see how many colors we shall use. */
1375 if (STRPTR_IN_SET(getenv("COLORTERM"),
1378 cached_color_mode
= COLOR_24BIT
;
1380 cached_color_mode
= COLOR_256
;
1384 return cached_color_mode
;
1387 bool dev_console_colors_enabled(void) {
1388 _cleanup_free_
char *s
= NULL
;
1391 /* Returns true if we assume that color is supported on /dev/console.
1393 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1394 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1395 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1396 * colors_enabled() operates. */
1398 m
= parse_systemd_colors();
1402 if (getenv("NO_COLOR"))
1405 if (getenv_for_pid(1, "TERM", &s
) <= 0)
1406 (void) proc_cmdline_get_key("TERM", 0, &s
);
1408 return !streq_ptr(s
, "dumb");
1411 bool underline_enabled(void) {
1413 if (cached_underline_enabled
< 0) {
1415 /* The Linux console doesn't support underlining, turn it off, but only there. */
1417 if (colors_enabled())
1418 cached_underline_enabled
= !streq_ptr(getenv("TERM"), "linux");
1420 cached_underline_enabled
= false;
1423 return cached_underline_enabled
;
1426 int vt_default_utf8(void) {
1427 _cleanup_free_
char *b
= NULL
;
1430 /* Read the default VT UTF8 setting from the kernel */
1432 r
= read_one_line_file("/sys/module/vt/parameters/default_utf8", &b
);
1436 return parse_boolean(b
);
1439 int vt_reset_keyboard(int fd
) {
1442 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1443 kb
= vt_default_utf8() != 0 ? K_UNICODE
: K_XLATE
;
1445 return RET_NERRNO(ioctl(fd
, KDSKBMODE
, kb
));
1448 int vt_restore(int fd
) {
1449 static const struct vt_mode mode
= {
1455 return log_debug_errno(errno
, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
1457 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
1458 q
= log_debug_errno(errno
, "Failed to set VT in text mode, ignoring: %m");
1460 r
= vt_reset_keyboard(fd
);
1462 log_debug_errno(r
, "Failed to reset keyboard mode, ignoring: %m");
1467 if (ioctl(fd
, VT_SETMODE
, &mode
) < 0) {
1468 log_debug_errno(errno
, "Failed to set VT_AUTO mode, ignoring: %m");
1473 r
= fchmod_and_chown(fd
, TTY_MODE
, 0, GID_INVALID
);
1475 log_debug_errno(r
, "Failed to chmod()/chown() VT, ignoring: %m");
1483 int vt_release(int fd
, bool restore
) {
1486 /* This function releases the VT by acknowledging the VT-switch signal
1487 * sent by the kernel and optionally reset the VT in text and auto
1488 * VT-switching modes. */
1491 return log_debug_errno(errno
, "Asked to release the VT for an fd that does not refer to a terminal: %m");
1493 if (ioctl(fd
, VT_RELDISP
, 1) < 0)
1497 return vt_restore(fd
);
1502 void get_log_colors(int priority
, const char **on
, const char **off
, const char **highlight
) {
1503 /* Note that this will initialize output variables only when there's something to output.
1504 * The caller must pre-initialize to "" or NULL as appropriate. */
1506 if (priority
<= LOG_ERR
) {
1508 *on
= ansi_highlight_red();
1510 *off
= ansi_normal();
1512 *highlight
= ansi_highlight();
1514 } else if (priority
<= LOG_WARNING
) {
1516 *on
= ansi_highlight_yellow();
1518 *off
= ansi_normal();
1520 *highlight
= ansi_highlight();
1522 } else if (priority
<= LOG_NOTICE
) {
1524 *on
= ansi_highlight();
1526 *off
= ansi_normal();
1528 *highlight
= ansi_highlight_red();
1530 } else if (priority
>= LOG_DEBUG
) {
1534 *off
= ansi_normal();
1536 *highlight
= ansi_highlight_red();
1540 int set_terminal_cursor_position(int fd
, unsigned int row
, unsigned int column
) {
1542 char cursor_position
[STRLEN("\x1B[") + DECIMAL_STR_MAX(int) * 2 + STRLEN(";H") + 1];
1546 xsprintf(cursor_position
, "\x1B[%u;%uH", row
, column
);
1548 r
= loop_write(fd
, cursor_position
, SIZE_MAX
);
1550 return log_warning_errno(r
, "Failed to set cursor position, ignoring: %m");