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_color_mode
= _COLOR_INVALID
;
53 static volatile int cached_underline_enabled
= -1;
56 _cleanup_close_
int fd
= -EBADF
;
58 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
59 * if that's configured. */
61 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
67 TIOCL_GETKMSGREDIRECT
,
71 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
74 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
77 return RET_NERRNO(ioctl(fd
, VT_ACTIVATE
, vt
));
80 int read_one_char(FILE *f
, char *ret
, usec_t t
, bool *need_nl
) {
81 _cleanup_free_
char *line
= NULL
;
82 struct termios old_termios
;
88 /* If this is a terminal, then switch canonical mode off, so that we can read a single
89 * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
92 if (fd
>= 0 && tcgetattr(fd
, &old_termios
) >= 0) {
93 struct termios new_termios
= old_termios
;
95 new_termios
.c_lflag
&= ~ICANON
;
96 new_termios
.c_cc
[VMIN
] = 1;
97 new_termios
.c_cc
[VTIME
] = 0;
99 if (tcsetattr(fd
, TCSADRAIN
, &new_termios
) >= 0) {
102 if (t
!= USEC_INFINITY
) {
103 if (fd_wait_for_event(fd
, POLLIN
, t
) <= 0) {
104 (void) tcsetattr(fd
, TCSADRAIN
, &old_termios
);
109 r
= safe_fgetc(f
, &c
);
110 (void) tcsetattr(fd
, TCSADRAIN
, &old_termios
);
117 *need_nl
= c
!= '\n';
124 if (t
!= USEC_INFINITY
&& fd
> 0) {
125 /* Let's wait the specified amount of time for input. When we have no fd we skip this, under
126 * the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
127 * anyway, as the data is either already in the stream or cannot possible be placed there
128 * while we access the stream */
130 if (fd_wait_for_event(fd
, POLLIN
, t
) <= 0)
134 /* If this is not a terminal, then read a full line instead */
136 r
= read_line(f
, 16, &line
); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
142 if (strlen(line
) != 1)
152 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
154 int ask_char(char *ret
, const char *replies
, const char *fmt
, ...) {
166 fputs(ansi_highlight(), stdout
);
174 fputs(ansi_normal(), stdout
);
178 r
= read_one_char(stdin
, &c
, DEFAULT_ASK_REFRESH_USEC
, &need_nl
);
185 puts("Bad input, please try again.");
196 if (strchr(replies
, c
)) {
201 puts("Read unexpected character, please try again.");
205 int ask_string(char **ret
, const char *text
, ...) {
206 _cleanup_free_
char *line
= NULL
;
213 fputs(ansi_highlight(), stdout
);
219 fputs(ansi_normal(), stdout
);
223 r
= read_line(stdin
, LONG_LINE_MAX
, &line
);
229 *ret
= TAKE_PTR(line
);
233 int reset_terminal_fd(int fd
, bool switch_to_text
) {
234 struct termios termios
;
237 /* Set terminal to some sane defaults */
242 return log_debug_errno(errno
, "Asked to reset a terminal that actually isn't a terminal: %m");
244 /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
245 * and we don't interfere with that. */
247 /* Disable exclusive mode, just in case */
248 if (ioctl(fd
, TIOCNXCL
) < 0)
249 log_debug_errno(errno
, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
251 /* Switch to text mode */
253 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
254 log_debug_errno(errno
, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
257 /* Set default keyboard mode */
258 (void) vt_reset_keyboard(fd
);
260 if (tcgetattr(fd
, &termios
) < 0) {
261 r
= log_debug_errno(errno
, "Failed to get terminal parameters: %m");
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
| OPOST
;
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
= -EBADF
;
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
) {
317 _cleanup_close_
int fd
= -EBADF
;
321 * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
322 * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
325 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
332 fd
= open(name
, mode
, 0);
339 /* Max 1s in total */
343 (void) usleep(50 * USEC_PER_MSEC
);
348 return negative_errno();
353 int acquire_terminal(
355 AcquireTerminalFlags flags
,
358 _cleanup_close_
int notify
= -EBADF
, fd
= -EBADF
;
359 usec_t ts
= USEC_INFINITY
;
363 assert(IN_SET(flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
, ACQUIRE_TERMINAL_TRY
, ACQUIRE_TERMINAL_FORCE
, ACQUIRE_TERMINAL_WAIT
));
365 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
366 * acquire it, so that we don't lose any event.
368 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
369 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
370 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
371 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
372 * probably should not do anyway.) */
374 if ((flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_WAIT
) {
375 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= USEC_INFINITY
? IN_NONBLOCK
: 0));
379 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
383 if (timeout
!= USEC_INFINITY
)
384 ts
= now(CLOCK_MONOTONIC
);
388 struct sigaction sa_old
, sa_new
= {
389 .sa_handler
= SIG_IGN
,
390 .sa_flags
= SA_RESTART
,
394 r
= flush_fd(notify
);
399 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
400 * to figure out if we successfully became the controlling process of the tty */
401 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
405 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
406 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
408 /* First, try to get the tty */
409 r
= RET_NERRNO(ioctl(fd
, TIOCSCTTY
, (flags
& ~ACQUIRE_TERMINAL_PERMISSIVE
) == ACQUIRE_TERMINAL_FORCE
));
411 /* Reset signal handler to old value */
412 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
414 /* Success? Exit the loop now! */
418 /* Any failure besides -EPERM? Fail, regardless of the mode. */
422 if (flags
& ACQUIRE_TERMINAL_PERMISSIVE
) /* If we are in permissive mode, then EPERM is fine, turn this
423 * into a success. Note that EPERM is also returned if we
424 * already are the owner of the TTY. */
427 if (flags
!= ACQUIRE_TERMINAL_WAIT
) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
434 union inotify_event_buffer buffer
;
437 if (timeout
!= USEC_INFINITY
) {
440 assert(ts
!= USEC_INFINITY
);
442 n
= usec_sub_unsigned(now(CLOCK_MONOTONIC
), ts
);
446 r
= fd_wait_for_event(notify
, POLLIN
, usec_sub_unsigned(timeout
, n
));
453 l
= read(notify
, &buffer
, sizeof(buffer
));
455 if (ERRNO_IS_TRANSIENT(errno
))
461 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
462 if (e
->mask
& IN_Q_OVERFLOW
) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
465 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) /* Safety checks */
472 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
473 * we do this after sleeping, so that we don't enter an endless loop. */
480 int release_terminal(void) {
481 static const struct sigaction sa_new
= {
482 .sa_handler
= SIG_IGN
,
483 .sa_flags
= SA_RESTART
,
486 _cleanup_close_
int fd
= -EBADF
;
487 struct sigaction sa_old
;
490 fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
494 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
495 * by our own TIOCNOTTY */
496 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
498 r
= RET_NERRNO(ioctl(fd
, TIOCNOTTY
));
500 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
505 int terminal_vhangup_fd(int fd
) {
507 return RET_NERRNO(ioctl(fd
, TIOCVHANGUP
));
510 int terminal_vhangup(const char *name
) {
511 _cleanup_close_
int fd
= -EBADF
;
513 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
517 return terminal_vhangup_fd(fd
);
520 int vt_disallocate(const char *name
) {
524 /* Deallocate the VT if possible. If not possible
525 * (i.e. because it is the active one), at least clear it
526 * entirely (including the scrollback buffer). */
528 e
= path_startswith(name
, "/dev/");
532 if (tty_is_vc(name
)) {
533 _cleanup_close_
int fd
= -EBADF
;
537 n
= startswith(e
, "tty");
541 r
= safe_atou(n
, &u
);
548 /* Try to deallocate */
549 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
553 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
560 /* So this is not a VT (in which case we cannot deallocate it),
561 * or we failed to deallocate. Let's at least clear the screen. */
563 _cleanup_close_
int fd2
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
567 (void) loop_write(fd2
,
568 "\033[r" /* clear scrolling region */
569 "\033[H" /* move home */
570 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
575 int make_console_stdio(void) {
578 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
579 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
580 * is specified on the kernel command line. */
582 fd
= acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE
|ACQUIRE_TERMINAL_PERMISSIVE
, USEC_INFINITY
);
584 log_warning_errno(fd
, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
586 r
= make_null_stdio();
588 return log_error_errno(r
, "Failed to make /dev/null stdin/stdout/stderr: %m");
591 r
= reset_terminal_fd(fd
, true);
593 log_warning_errno(r
, "Failed to reset terminal, ignoring: %m");
595 r
= rearrange_stdio(fd
, fd
, fd
); /* This invalidates 'fd' both on success and on failure. */
597 return log_error_errno(r
, "Failed to make terminal stdin/stdout/stderr: %m");
600 reset_terminal_feature_caches();
604 bool tty_is_vc(const char *tty
) {
607 return vtnr_from_tty(tty
) >= 0;
610 bool tty_is_console(const char *tty
) {
613 return streq(skip_dev_prefix(tty
), "console");
616 int vtnr_from_tty(const char *tty
) {
621 tty
= skip_dev_prefix(tty
);
623 if (!startswith(tty
, "tty") )
626 if (!ascii_isdigit(tty
[3]))
629 r
= safe_atoi(tty
+3, &i
);
639 int resolve_dev_console(char **ret
) {
640 _cleanup_free_
char *active
= NULL
;
646 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
647 * sign for container setups) */
649 if (path_is_read_only_fs("/sys") > 0)
652 r
= read_one_line_file("/sys/class/tty/console/active", &active
);
656 /* If multiple log outputs are configured the last one is what /dev/console points to */
657 tty
= strrchr(active
, ' ');
663 if (streq(tty
, "tty0")) {
664 active
= mfree(active
);
666 /* Get the active VC (e.g. tty1) */
667 r
= read_one_line_file("/sys/class/tty/tty0/active", &active
);
675 *ret
= TAKE_PTR(active
);
689 int get_kernel_consoles(char ***ret
) {
690 _cleanup_strv_free_
char **l
= NULL
;
691 _cleanup_free_
char *line
= NULL
;
697 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
698 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
699 if (path_is_read_only_fs("/sys") > 0)
702 r
= read_one_line_file("/sys/class/tty/console/active", &line
);
708 _cleanup_free_
char *tty
= NULL
, *path
= NULL
;
710 r
= extract_first_word(&p
, &tty
, NULL
, 0);
716 if (streq(tty
, "tty0")) {
718 r
= read_one_line_file("/sys/class/tty/tty0/active", &tty
);
723 path
= path_join("/dev", tty
);
727 if (access(path
, F_OK
) < 0) {
728 log_debug_errno(errno
, "Console device %s is not accessible, skipping: %m", path
);
732 r
= strv_consume(&l
, TAKE_PTR(path
));
737 if (strv_isempty(l
)) {
738 log_debug("No devices found for system console");
747 r
= strv_extend(&l
, "/dev/console");
756 bool tty_is_vc_resolve(const char *tty
) {
757 _cleanup_free_
char *resolved
= NULL
;
761 tty
= skip_dev_prefix(tty
);
763 if (streq(tty
, "console")) {
764 if (resolve_dev_console(&resolved
) < 0)
770 return tty_is_vc(tty
);
773 const char *default_term_for_tty(const char *tty
) {
774 return tty
&& tty_is_vc_resolve(tty
) ? "linux" : "vt220";
777 int fd_columns(int fd
) {
778 struct winsize ws
= {};
783 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
792 unsigned columns(void) {
796 if (cached_columns
> 0)
797 return cached_columns
;
800 e
= getenv("COLUMNS");
802 (void) safe_atoi(e
, &c
);
804 if (c
<= 0 || c
> USHRT_MAX
) {
805 c
= fd_columns(STDOUT_FILENO
);
811 return cached_columns
;
814 int fd_lines(int fd
) {
815 struct winsize ws
= {};
820 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
829 unsigned lines(void) {
833 if (cached_lines
> 0)
839 (void) safe_atoi(e
, &l
);
841 if (l
<= 0 || l
> USHRT_MAX
) {
842 l
= fd_lines(STDOUT_FILENO
);
851 int terminal_set_size_fd(int fd
, const char *ident
, unsigned rows
, unsigned cols
) {
854 if (rows
== UINT_MAX
&& cols
== UINT_MAX
)
857 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
858 return log_debug_errno(errno
,
859 "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
862 if (rows
== UINT_MAX
)
864 else if (rows
> USHRT_MAX
)
867 if (cols
== UINT_MAX
)
869 else if (cols
> USHRT_MAX
)
872 if (rows
== ws
.ws_row
&& cols
== ws
.ws_col
)
878 if (ioctl(fd
, TIOCSWINSZ
, &ws
) < 0)
879 return log_debug_errno(errno
, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident
?: "TTY");
884 /* intended to be used as a SIGWINCH sighandler */
885 void columns_lines_cache_reset(int signum
) {
890 void reset_terminal_feature_caches(void) {
894 cached_color_mode
= _COLOR_INVALID
;
895 cached_underline_enabled
= -1;
901 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
902 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
903 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
904 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
905 * terminal functionality when outputting stuff, even if the input is piped to us. */
907 if (cached_on_tty
< 0)
909 isatty(STDOUT_FILENO
) > 0 &&
910 isatty(STDERR_FILENO
) > 0;
912 return cached_on_tty
;
915 int getttyname_malloc(int fd
, char **ret
) {
916 char path
[PATH_MAX
], *c
; /* PATH_MAX is counted *with* the trailing NUL byte */
922 r
= ttyname_r(fd
, path
, sizeof path
); /* positive error */
925 return -ENAMETOOLONG
;
929 c
= strdup(skip_dev_prefix(path
));
937 int getttyname_harder(int fd
, char **ret
) {
938 _cleanup_free_
char *s
= NULL
;
941 r
= getttyname_malloc(fd
, &s
);
946 return get_ctty(0, NULL
, ret
);
952 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
954 _cleanup_free_
char *line
= NULL
;
960 p
= procfs_file_alloca(pid
, "stat");
961 r
= read_one_line_file(p
, &line
);
965 p
= strrchr(line
, ')');
980 if (major(ttynr
) == 0 && minor(ttynr
) == 0)
989 int get_ctty(pid_t pid
, dev_t
*ret_devnr
, char **ret
) {
990 char pty
[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t
) + 1];
991 _cleanup_free_
char *buf
= NULL
;
992 const char *fn
= NULL
, *w
;
996 r
= get_ctty_devnr(pid
, &devnr
);
1000 r
= device_path_make_canonical(S_IFCHR
, devnr
, &buf
);
1004 if (r
!= -ENOENT
) /* No symlink for this in /dev/char/? */
1007 /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
1008 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
1009 * assume this is a PTY for a moment, and check if the device node this would then map to in
1010 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
1011 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
1012 * the minor number of the pty. */
1013 xsprintf(pty
, "/dev/pts/%u", minor(devnr
));
1015 if (stat(pty
, &st
) < 0) {
1016 if (errno
!= ENOENT
)
1019 } else if (S_ISCHR(st
.st_mode
) && devnr
== st
.st_rdev
) /* Bingo! */
1023 /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1024 * symlink in /dev/char/. Let's return something vaguely useful. */
1025 r
= device_path_make_major_minor(S_IFCHR
, devnr
, &buf
);
1034 w
= path_startswith(fn
, "/dev/");
1039 _cleanup_free_
char *b
= NULL
;
1054 int ptsname_malloc(int fd
, char **ret
) {
1067 if (ptsname_r(fd
, c
, l
) == 0) {
1071 if (errno
!= ERANGE
) {
1078 if (l
> SIZE_MAX
/ 2)
1085 int openpt_allocate(int flags
, char **ret_slave
) {
1086 _cleanup_close_
int fd
= -EBADF
;
1087 _cleanup_free_
char *p
= NULL
;
1090 fd
= posix_openpt(flags
|O_NOCTTY
|O_CLOEXEC
);
1095 r
= ptsname_malloc(fd
, &p
);
1099 if (!path_startswith(p
, "/dev/pts/"))
1103 if (unlockpt(fd
) < 0)
1107 *ret_slave
= TAKE_PTR(p
);
1112 static int ptsname_namespace(int pty
, char **ret
) {
1115 /* Like ptsname(), but doesn't assume that the path is
1116 * accessible in the local namespace. */
1118 r
= ioctl(pty
, TIOCGPTN
, &no
);
1125 if (asprintf(ret
, "/dev/pts/%i", no
) < 0)
1131 int openpt_allocate_in_namespace(pid_t pid
, int flags
, char **ret_slave
) {
1132 _cleanup_close_
int pidnsfd
= -EBADF
, mntnsfd
= -EBADF
, usernsfd
= -EBADF
, rootfd
= -EBADF
, fd
= -EBADF
;
1133 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1139 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1143 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1146 r
= namespace_fork("(sd-openptns)", "(sd-openpt)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1147 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1151 pair
[0] = safe_close(pair
[0]);
1153 fd
= openpt_allocate(flags
, NULL
);
1155 _exit(EXIT_FAILURE
);
1157 if (send_one_fd(pair
[1], fd
, 0) < 0)
1158 _exit(EXIT_FAILURE
);
1160 _exit(EXIT_SUCCESS
);
1163 pair
[1] = safe_close(pair
[1]);
1165 r
= wait_for_terminate_and_check("(sd-openptns)", child
, 0);
1168 if (r
!= EXIT_SUCCESS
)
1171 fd
= receive_one_fd(pair
[0], 0);
1176 r
= ptsname_namespace(fd
, ret_slave
);
1184 int open_terminal_in_namespace(pid_t pid
, const char *name
, int mode
) {
1185 _cleanup_close_
int pidnsfd
= -EBADF
, mntnsfd
= -EBADF
, usernsfd
= -EBADF
, rootfd
= -EBADF
;
1186 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1190 r
= namespace_open(pid
, &pidnsfd
, &mntnsfd
, NULL
, &usernsfd
, &rootfd
);
1194 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, pair
) < 0)
1197 r
= namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL
, 0, FORK_RESET_SIGNALS
|FORK_DEATHSIG
,
1198 pidnsfd
, mntnsfd
, -1, usernsfd
, rootfd
, &child
);
1204 pair
[0] = safe_close(pair
[0]);
1206 master
= open_terminal(name
, mode
|O_NOCTTY
|O_CLOEXEC
);
1208 _exit(EXIT_FAILURE
);
1210 if (send_one_fd(pair
[1], master
, 0) < 0)
1211 _exit(EXIT_FAILURE
);
1213 _exit(EXIT_SUCCESS
);
1216 pair
[1] = safe_close(pair
[1]);
1218 r
= wait_for_terminate_and_check("(sd-terminalns)", child
, 0);
1221 if (r
!= EXIT_SUCCESS
)
1224 return receive_one_fd(pair
[0], 0);
1227 static bool getenv_terminal_is_dumb(void) {
1234 return streq(e
, "dumb");
1237 bool terminal_is_dumb(void) {
1241 return getenv_terminal_is_dumb();
1244 static ColorMode
parse_systemd_colors(void) {
1248 e
= getenv("SYSTEMD_COLORS");
1250 return _COLOR_INVALID
;
1253 if (streq(e
, "256"))
1255 r
= parse_boolean(e
);
1257 return r
> 0 ? COLOR_ON
: COLOR_OFF
;
1258 return _COLOR_INVALID
;
1261 ColorMode
get_color_mode(void) {
1263 /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1264 * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors and COLOR_ON for unrestricted
1265 * color output. For that we check $SYSTEMD_COLORS first (which is the explicit way to
1266 * 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
1267 * 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
1268 * check whether we are connected to a TTY, because we don't keep /dev/console open continuously due to fear
1269 * of SAK, and hence things are a bit weird. */
1272 if (cached_color_mode
< 0) {
1273 m
= parse_systemd_colors();
1275 cached_color_mode
= m
;
1276 else if (getenv("NO_COLOR"))
1277 /* We only check for the presence of the variable; value is ignored. */
1278 cached_color_mode
= COLOR_OFF
;
1280 else if (getpid_cached() == 1) {
1281 /* PID1 outputs to the console without holding it open all the time.
1283 * Note that the Linux console can only display 16 colors. We still enable 256 color
1284 * mode even for PID1 output though (which typically goes to the Linux console),
1285 * since the Linux console is able to parse the 256 color sequences and automatically
1286 * map them to the closest color in the 16 color palette (since kernel 3.16). Doing
1287 * 256 colors is nice for people who invoke systemd in a container or via a serial
1288 * link or such, and use a true 256 color terminal to do so. */
1289 if (getenv_terminal_is_dumb())
1290 cached_color_mode
= COLOR_OFF
;
1292 if (terminal_is_dumb())
1293 cached_color_mode
= COLOR_OFF
;
1296 if (cached_color_mode
< 0) {
1297 /* We failed to figure out any reason to *disable* colors.
1298 * Let's see how many colors we shall use. */
1299 if (STRPTR_IN_SET(getenv("COLORTERM"),
1302 cached_color_mode
= COLOR_24BIT
;
1304 cached_color_mode
= COLOR_256
;
1308 return cached_color_mode
;
1311 bool dev_console_colors_enabled(void) {
1312 _cleanup_free_
char *s
= NULL
;
1315 /* Returns true if we assume that color is supported on /dev/console.
1317 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1318 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1319 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1320 * colors_enabled() operates. */
1322 m
= parse_systemd_colors();
1326 if (getenv("NO_COLOR"))
1329 if (getenv_for_pid(1, "TERM", &s
) <= 0)
1330 (void) proc_cmdline_get_key("TERM", 0, &s
);
1332 return !streq_ptr(s
, "dumb");
1335 bool underline_enabled(void) {
1337 if (cached_underline_enabled
< 0) {
1339 /* The Linux console doesn't support underlining, turn it off, but only there. */
1341 if (colors_enabled())
1342 cached_underline_enabled
= !streq_ptr(getenv("TERM"), "linux");
1344 cached_underline_enabled
= false;
1347 return cached_underline_enabled
;
1350 int vt_default_utf8(void) {
1351 _cleanup_free_
char *b
= NULL
;
1354 /* Read the default VT UTF8 setting from the kernel */
1356 r
= read_one_line_file("/sys/module/vt/parameters/default_utf8", &b
);
1360 return parse_boolean(b
);
1363 int vt_reset_keyboard(int fd
) {
1366 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1367 kb
= vt_default_utf8() != 0 ? K_UNICODE
: K_XLATE
;
1369 return RET_NERRNO(ioctl(fd
, KDSKBMODE
, kb
));
1372 int vt_restore(int fd
) {
1373 static const struct vt_mode mode
= {
1379 return log_debug_errno(errno
, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
1381 if (ioctl(fd
, KDSETMODE
, KD_TEXT
) < 0)
1382 q
= log_debug_errno(errno
, "Failed to set VT in text mode, ignoring: %m");
1384 r
= vt_reset_keyboard(fd
);
1386 log_debug_errno(r
, "Failed to reset keyboard mode, ignoring: %m");
1391 if (ioctl(fd
, VT_SETMODE
, &mode
) < 0) {
1392 log_debug_errno(errno
, "Failed to set VT_AUTO mode, ignoring: %m");
1397 r
= fchmod_and_chown(fd
, TTY_MODE
, 0, GID_INVALID
);
1399 log_debug_errno(r
, "Failed to chmod()/chown() VT, ignoring: %m");
1407 int vt_release(int fd
, bool restore
) {
1410 /* This function releases the VT by acknowledging the VT-switch signal
1411 * sent by the kernel and optionally reset the VT in text and auto
1412 * VT-switching modes. */
1415 return log_debug_errno(errno
, "Asked to release the VT for an fd that does not refer to a terminal: %m");
1417 if (ioctl(fd
, VT_RELDISP
, 1) < 0)
1421 return vt_restore(fd
);
1426 void get_log_colors(int priority
, const char **on
, const char **off
, const char **highlight
) {
1427 /* Note that this will initialize output variables only when there's something to output.
1428 * The caller must pre-initialize to "" or NULL as appropriate. */
1430 if (priority
<= LOG_ERR
) {
1432 *on
= ansi_highlight_red();
1434 *off
= ansi_normal();
1436 *highlight
= ansi_highlight();
1438 } else if (priority
<= LOG_WARNING
) {
1440 *on
= ansi_highlight_yellow();
1442 *off
= ansi_normal();
1444 *highlight
= ansi_highlight();
1446 } else if (priority
<= LOG_NOTICE
) {
1448 *on
= ansi_highlight();
1450 *off
= ansi_normal();
1452 *highlight
= ansi_highlight_red();
1454 } else if (priority
>= LOG_DEBUG
) {
1458 *off
= ansi_normal();
1460 *highlight
= ansi_highlight_red();